当前位置:网站首页>Interaction free shell programming
Interaction free shell programming
2022-07-03 03:54:00 【Old man, take you 1v5】
Catalog
1、Here Document No interaction
(2)Here Document Precautions for use
1、Here Document No interaction
(1)Here Document summary
■ Use I/O The list of commands is provided to the interactive program by redirection
■ An alternative to standard input
■ Grammar format
command << Mark
...
...
Mark
(2)Here Document Precautions for use
■ Tags can use any legal character
■ The ending mark must be written in the top case , There can't be any characters in front of it
■ There can't be any characters after the tag at the end ( Including Spaces )
■ Spaces before and after the opening mark are omitted
(3 ) Example
1、
2、 utilize read The command accepts input and prints
3、 utilize passwd Add password to user
4、 Variable to replace : Echo and replace variables with actual values when writing files , combining cat Command complete write
5、 Whole assignment to variable , And then through echo The command prints out the value of the variable
6、 Turn off the variable replacement function , stay EOF With single quotation mark , It will directly output the variable name of the called variable
7、 Remove the front of each line TAB character
No addition -
8、 Multiline comment
Bash The default comment for is “#”, This annotation method only supports single line annotations , stay shekk In the work of the script ,“#” Any string on the right ,bash Will be ignored .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 .
2、Expect Free of charge
(1)Expect summary
● Based on the tcl A tool on top of
● For automatic control and testing
● solve shell Interaction related issues in scripts
(2)Expect install
[[email protected] ~]# yum -y install expect
[[email protected]~]#rpm -qa]grep expect
expect-5.45-14.el7_1.x86_64
[[email protected] ~]# rpm -qa]grep tcl
tcl-8.5.13-8.el7.x86_64
(3) Basic commands
(1)expect
● Judge whether the last output result contains the specified string , If so, return immediately , Otherwise, it will wait for the timeout to return
● Can only be captured by spawn The output of the started process
● Used to receive output after command execution , And then match the expected string
(2)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 )
(3)spawn
spawn Usually followed by a Linux Carry out orders , Open a conversation 、 Start the process , And track subsequent interaction information .
example :spawn passwd root
(4) Terminator
●expect eof( Performing automated tasks usually uses expect eof)
For example, switch to root user ,expect The script default is to wait 10s, After executing the completion command , Default stay 10s after , Automatically switched back to the original user
Waiting for execution to end
●interact
Keep interactive after execution , Give control to the console , Will stay at the target terminal without returning to the original terminal , This time
Then you can operate it manually ,interact The last order doesn't work , such as interact Add exit, It's not going to quit root use
Household . And if not interact Will exit after login , Instead of staying on the remote terminal .
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 .
Be careful :expect eof And interact You can only choose one .
(5)set
● Set timeout , If it expires, continue to execute subsequent instructions
● The unit is seconds
●timeout -1 Means never time out
● By default ,timeout yes 10 second
(6)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_continmue Similar to... In a control statement continue sentence . It means to allow expect Continue down the instruction .
for example : The following example will determine if there is yes/no or *password. If the match yes/no The output yes And execute judgment again ; If the match *password The output abc123 And end the paragraph expect sentence .
expect {
" (yes/no) " { send "yeslr"; exp _continue ; }
"*password" { set timeout 300; send "abc123\r"; }
Be careful : Use exp continue when , If tracking is like passwd This is the command to end the process after entering the password ,expect(} Don't add expect eof because spawn At the end of the process, it will default to expect send out eof, It will lead to the following expect eof Error report in execution
notes : Indicates that users are allowed to interact , Always keep the session connected
(7)send_user
● Echo command , amount to echo
(8) Accept parameters
●expect Scripts can accept from bash Parameters passed
● have access to [lindex %argv n] get
●n from 0 Start , They are the first 、 the second 、 Third ... Parameters
(4) Example
use expect Write a script
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 , Pay attention to the format !
"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
[rootesjserver ~] # ./expect.sh
spawn ssh [email protected]@192.168.100.100's password:
Last login: Mon Jul 27 23:31:00 2020 from 192.168.100.120
example 2
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] Need a blank line
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.211set pass 123456
Reference location variable
# !/ usr/bin/expectset 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"
#interact
expect eof
[[email protected] ~]# ./expect.sh 192.168.245.211123456 // 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 l/1 Output information for the screen ,0 Is not output
ssh Another way to write free login
#!/usr/bin/expec
tset timeout 60
log_file test.log
log_user 1
set ip [lindex $argv 0]
set password [lindex $argv 1]
spawn ssh [email protected]$ {ip}
expect {
" (yes/no) "
{send "yes\r"; exp_continuel "*password"
{ send "$password\r"}
}
interact
[[email protected]~]#sh expect.sh 192.168.10.20 111111
Embedded execution patterns , take expect Process integration shell among , Easy to execute and handle
stay shell Call in script expect
1、 Create users and set user passwords 1:
#!/bin/bash
username=$1
useradd $username
/usr/bin/expecti <<-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 "123456\r" ;exp_continue}
" The new code "
{ send "123456\r"; }
EOF
![]()
Another way
# ! /bin/bashuser=$1
password=$2
useradd $user
expect <<EOF
spawn passwd $user # Start a process trace passwd command ,expect Only the process information can be captured
expect " new *" # Match output information " new * sichuan I
send "$ {password} \r" # Automatic password input
expect" again *:" # Match output information " again *"
send "$ {password} \r" # Automatic password input
expect eof; # Wait for the end tag
EOF
ssh Remote to server list
#!/bin/bash
expect -c " // Need to use expect -c call expect Program
spawn ssh [email protected]
expect \ "password: \" { send \ "123456\r\" }
interact
"
[[email protected] ~]# vim expects.sh // Not only stay but also give orders to quit
# !/bin/bashexpect -c "
spawn ssh root192.168.245.211expect \ "password: \" {send \ "123456\r\"}
expect \"]# \"{ send \"ifconfig\r\"}
expect \"]#\" {send \ "exit\r\ "}expect eof
utilize expect complete FTP Login process
# ! /usr/bin/expect -fset timeout 10
spawn ftp 192.168.8.33
expect "Name*"
send "ftp\r"
expect "Password:*"
send "\r"
expect "ftp>*"
interact
expect eof
summary
■Here Document Usage method
■Expect Basic commands
■Expect Usage method
边栏推荐
- 105. Detailed introduction of linkage effect realization of SAP ui5 master detail layout mode
- Dynamic programming: longest common substring and longest common subsequence
- Mongodb replication set [master-slave replication]
- Web会话管理安全问题
- [mathematical logic] propositions and connectives (propositions | propositional symbolization | truth connectives | no | conjunction | disjunction | non truth connectives | implication | equivalence)
- 基于Pytorch和RDKit的QSAR模型建立脚本
- golang xxx. Go code template
- 小程序获取用户头像和昵称
- 可分离债券与可转债
- 【刷题篇】 找出第 K 小的数对距离
猜你喜欢
MySQL MAC download and installation tutorial
What can learning pytorch do?
学会pytorch能干什么?
Table structure of Navicat export database
numpy之 警告VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences
navicat 导出数据库的表结构
2022 polymerization process examination questions and polymerization process examination skills
npm : 无法将“npm”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确,然后再试一次。
pytorch是什么?pytorch是一个软件吗?
Introduction to mongodb
随机推荐
node,npm以及yarn下载安装
C language hashtable/hashset library summary
Error c2694 "void logger:: log (nvinfer1:: ilogger:: severity, const char *)": rewrite the restrictive exception specification of virtual functions than base class virtual member functions
IPv6 transition technology-6to4 manual tunnel configuration experiment -- Kuige of Shangwen network
PHP generates PDF tcpdf
Mongodb master profile
golang xxx. Go code template
User value is the last word in the competition of mobile phone market
第十届中国云计算大会·中国站:展望未来十年科技走向
leetcode:297. 二叉树的序列化与反序列化
shardingsphere动态数据源
FileZilla Client下載安裝
Recursion: one dimensional linked lists and arrays
@The difference between Autowired, @qualifier, @resource
IPv6 foundation construction experiment
2022 P cylinder filling examination content and P cylinder filling practice examination video
pytorch是什么?pytorch是一个软件吗?
MySQL MAC download and installation tutorial
Web会话管理安全问题
How does the pytorch project run?