当前位置:网站首页>Here document interaction free and expect automatic interaction
Here document interaction free and expect automatic interaction
2022-06-26 13:22:00 【C chord~】
Catalog
One .Here Document No interaction
2. No interactive way to achieve the number of rows statistics
3. adopt read Commands receive input and print
4. Set the password for the user
5. Support variable replacement
6. Turn off the function of variable replacement
7. Remove the front of each line TAB character
Two 、Expect Automated interaction
introduction
In our work, we need to realize shell Automation of scripts , This will reduce our workload , And in the shell We need to use interaction in the script .
One .Here Document No interaction
- Use I/0 The list of commands is provided to the interactive program by redirection
- Is a substitute for standard input
1. Grammar format
command << Mark
......
......
Mark
notes : The tag can be any character ( Usually use EOF), There can be spaces before and after the opening mark ( Will be ignored ), The ending mark must be written in the top case , There can't be any characters in front of it ( Including Spaces )
2. No interactive way to achieve the number of rows statistics
Put the content to be counted in the tag “EOF” Between , Direct the content to wc -l To statistics
3. adopt read Commands receive input and print
The input value is two EOF The part between the marks , As a variable i Value
4. Set the password for the user
5. Support variable replacement
When you write to a file, you first replace the variable with the actual value , combining cat Command complete write
6. Turn off the function of variable replacement
Output the characters as they are , Without any modification or replacement
Not closed :
closed :
7. Remove the front of each line TAB character
8. Multiline comment
- Bash The default comment for is “#”, This annotation method only supports single line annotations :Here Document It solves the problem of multi line annotation .
- ":" It's an empty order to do nothing . The contents of the middle marked area are not executed , Will be bash Ignore , So it can achieve the effect of batch annotation .
Two 、Expect Automated interaction
- tand at tcl A tool based on language , It is often used for automatic control and testing , solve shell Interaction related issues in scripts
rpm -q expect
rpm -q tcl
yum -y install tcl expect #yum Or CD-ROM installation
1、 Basic commands
Script interpreter :
- expect The script first introduces the file , Indicate which one is used shell.
#!/usr/bin/expect
- spawn Usually followed by a Linux Carry out orders , Open a conversation 、 Start the process , And track subsequent interaction information .
example : spawn passwd root ## Track and start the process of changing user password
Interactive information
expect:
- Judge whether the last output result contains the specified string , If so, return immediately , Otherwise, it will wait for the timeout to return ;
- Used to receive output after command execution , And then match the expected string .
- Can only be captured by spawn The output of the started process ;
send:
- Send string to process , Used to simulate user input ; This command does not automatically enter to wrap lines , Generally, we need to add \r( enter ) perhaps \n.
Mode one :
expect " password " {send "abc123\r"} # The same line send There should be {}
Mode two :
expect " password "
send "abc123\r" # Line break send Part of it doesn't need to have {}
Mode three :
expect Supports multiple branches
expect # Just match one of the cases , Execute corresponding send Statement to exit the expect sentence
{
" password 1" {send "abc123\r"}
" password 2" {send "123456\r"}
" password 3" {send "123123\r"}
}
Terminator :
- expect eof
Indicates the end of the interaction , Waiting for execution to end , Return to the original user , And spawn Corresponding .
For example, switch to root user ,expect The script default is to wait 10s, When the command is finished , Default stay 10s after , Automatically switched back to the original user
interact
1、 Keep interactive after execution , Give control to the console , Will stay at the target terminal without returning to the original terminal , At this time, it can be operated by hand .
interact The last order doesn't work , such as interact Add exit, It's not going to quit root user .
And if not interact Will exit after login , Instead of staying on the remote terminal .
2、 Use interact Will remain in the terminal and will not return to the original terminal , For example, switch to root user , Will always be root In user state ;
such as ssh To another server , Will always be on the target server terminal , Instead of switching back to the original server .
3、 Be careful :expect eof And interact You can only choose one .
set
- expect The default timeout is 10 second , adopt set Command to set the session timeout , If the timeout is not limited, it should be set to -1.
exp_continue
- exp_continue Attached to a expect After the judgment , After the item is matched , Can continue to match the expect Determine other items in the statement .
- exp_continue Similar to... In a control statement continue sentence . It means to allow expect Continue down the instruction .
send_user
- send_ user Represents the echo command , amount to echo
Receiving parameters
- expect Scripts can accept from bash Parameters passed from the command line , Use [lindex $argv n] get , among n from 0 Start , They are the first , the second , Third …
set hostname [ lindex $argv 0]
amount to hostname=$1
set password [ lindex $argv 1]
amount to password=$2
example 1:ssh No interactive login to the remote server
[[email protected] ~]# vim expect.sh
#!/usr/bin/expect // You need to use expect Own interpreter , Be careful not to write bash Otherwise, I can't recognize
spawn ssh [email protected] // Open a program , This program is ssh Remote login
expect { // Capture content , When there is a password When , Will send the password to the program , The default is no line break , So we need to \r Carriage returns , Multiple conditions need to be enclosed in curly braces !
"password:"
{ send "123456\r"; }
}
interact // Interaction , Otherwise, it will exit the remote server directly
[[email protected] ~]# chmod +x expect.sh // Need to add Execution Authority
[[email protected] ~]# ./expect.sh
spawn ssh [email protected]
[email protected]'s password:
Last login: Mon Jul 27 23:31:00 2020 from 192.168.100.120
If you want to do something on the other server before exiting, you can execute the following script
[[email protected] ~]# vim expect.sh
#!/usr/bin/expect
spawn ssh [email protected]
expect {
"password:"
{ send "123456\r"; }
}
expect "#" // When you catch # When
send "ls\r" // perform ls command
send "ifconfig ens33\r" // perform ifconfig ens33 command
send "exit\r" // After execution exit Exit login
expect eof // No need for interaction , It means the end expect Program , If you don't write, you won't execute the operation and exit directly ; If you don't write , Write interact You can't execute commands on the other machine ,eof Can replace
Define and reference variables
use set Keywords define variables , The variable name and the value of the variable are separated by a space , Other usage and shell The script is consistent
#!/usr/bin/expect
set user root
set ip 192.168.245.211
set pass 123456
Reference location variable
#!/usr/bin/expect
set user root
set ip [lindex $argv 0] // Set the first position variable to ip
set pass [lindex $argv 1] // Set the second location variable to login password
spawn ssh [email protected]$ip
expect {
"password:"
{ send "$pass\r"; }
}
expect "#"
send "ls\r"
send "ifconfig ens33\r"
send "exit\r"
expect eof
[[email protected] ~]# ./expect.sh 192.168.245.211 123456 // Position variables need to be added during execution
You can also define other parameters , For example, time-out , Log etc.
# Timeout time
set timeout 20 // Login timeout how many seconds to exit
# Open the log file
log_file test.log // Logging operations
# display information
log_user 1 //1 Output information for the screen ,0 Is not output
stay shell Call in script expect
Create user and set user password
Case study 1:
#!/bin/bash
username=$1
useradd $username
/usr/bin/expect <<-EOF
spawn passwd $username
expect {
" password " // Be careful : The obtained content and the sent content cannot be on the same line, otherwise the execution will not succeed
{send "123321\r";exp_continue}
" The new code "
{send "123321\r";}
}
EOF
The verification results :
[[email protected] ~]# . user.sh ab
spawn passwd ab
Change user ab Password .
new password :
Invalid password : The password is less than 8 Characters
Reenter the new password :
passwd: All authentication tokens have been successfully updated .
summary :
Use expect Commands that handle interactions , It can improve the work efficiency of system managers , Reduce the pressure of our work , It can be said that it is a good helper for our operation and maintenance personnel .
边栏推荐
- Echart stack histogram: add white spacing effect setting between color blocks
- Electron official docs series: Contributing
- Nlp-d60-nlp competition D29
- Opencv high speed download
- What are the common categories of software testing?
- First pass! Baidu AI Cloud Xiling platform has obtained the authoritative certification of digital human ability evaluation from the Institute of information technology
- Word document export (using fixed template)
- Use the script to crawl the beautiful sentences of the sentence fan website and store them locally (blessed are those who like to excerpt!)
- 【Spark】. Explanation of several icons of scala file in idea
- IDC report: the AI cloud market share of Baidu AI Cloud ranks first for six consecutive times
猜你喜欢
Update and download of Beifu EtherCAT XML description file
Hdu1724[Simpson formula for integral]ellipse
原型模式(prototype)
Bifu divides EtherCAT module into multiple synchronization units for operation -- use of sync units
Word document export (using fixed template)
Dark horse notes - Common APIs
Chapter 01_ Installation and use of MySQL under Linux
Beifu PLC based on NT_ Shutdown to realize automatic shutdown and restart of controller
Thinking caused by the error < note: candidate expectations 1 argument, 0 provided >
[how to connect the network] Chapter 2 (next): receiving a network packet
随机推荐
Machine learning notes - seasonality of time series
Processsing function random
sed编辑器
Detailed practical sharing, two hours of funny videos after work, earning more than 7000 a month
Mysql database explanation (6)
scrapy——爬取漫画自定义存储路径下载到本地
A primary multithreaded server model
Update and download of Beifu EtherCAT XML description file
Aesthetic experience (episode 238) Luo Guozheng
7-16 monetary system I
Learn how to develop owl components by hand (7): practical use of owl projects
MySQL数据库讲解(六)
Digital signal processing -- Design of linear phase type (Ⅰ, Ⅲ) FIR filter (1)
What features are added to Photoshop 2022 23.4.1? Do you know anything
B - Bridging signals
Word document export (using fixed template)
8. [STM32] timer (TIM) -- interrupt, PWM, input capture experiment (proficient in timer)
Analysis of state transition diagram of Beifu NC axis
Processing random generation line animation
D - 滑雪