当前位置:网站首页>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
边栏推荐
- For instruction, uploading pictures and display effect optimization of simple wechat applet development
- Wechat applet + Alibaba IOT platform + Hezhou air724ug built with server version system analysis
- Téléchargement et installation du client Filezilla
- pytorch项目怎么跑?
- Hutool动态添加定时任务
- [Apple Push] IMessage group sending condition document (push certificate) development tool pushnotification
- Makefile demo
- SAP ui5 application development tutorial 105 - detailed introduction to the linkage effect implementation of SAP ui5 master detail layout mode
- IPv6 transition technology-6to4 manual tunnel configuration experiment -- Kuige of Shangwen network
- Hutool dynamically adds scheduled tasks
猜你喜欢

IPv6过渡技术-6to4手工隧道配置实验--尚文网络奎哥
![[MySQL] the difference between left join, right join and join](/img/d4/8684cd59cd1bd77e70bd4d7c7074c3.jpg)
[MySQL] the difference between left join, right join and join

Docker install and start MySQL service

递归:深度优先搜索

Cnopendata China Customs Statistics

编译文件时报错:错误: 编码GBK的不可映射字符

2022 polymerization process examination questions and polymerization process examination skills

Recursion: depth first search
![[home push IMessage] software installation virtual host rental tothebuddy delay](/img/e7/eb20a773e4b674962f856d179a3769.jpg)
[home push IMessage] software installation virtual host rental tothebuddy delay

FileZilla client download and installation
随机推荐
2022-07-02:以下go语言代码输出什么?A:编译错误;B:Panic;C:NaN。 package main import “fmt“ func main() { var a =
Pytorch multi card distributed training distributeddataparallel usage
How to move towards IPv6: IPv6 Transition Technology - Shangwen network quigo
Message queue addition failure
记一次 .NET 差旅管理后台 CPU 爆高分析
递归使用和多维数组对象变一维数组对象
阿洛对自己的思考
Hutool动态添加定时任务
C language hashtable/hashset library summary
C语言HashTable/HashSet库汇总
[Blue Bridge Road -- bug free code] DS18B20 temperature reading code analysis
2022deepbrainchain biweekly report no. 104 (01.16-02.15)
Mysql Mac版下载安装教程
Is pytorch open source?
ffmpeg之 一张/多张图片合成视频
【刷题篇】接雨水(一维)
2022 P cylinder filling examination content and P cylinder filling practice examination video
2022 tea master (intermediate) examination questions and analysis and tea master (intermediate) practical examination video
Recursive use and multi-dimensional array object to one-dimensional array object
Basic operations of mongodb [add, delete, modify, query]