In this article, we will use an example to explain the expect command to realize Shell automated interaction. We can implement simple control flow functions through Shell, such as: looping, judgment, etc. The following article mainly introduces you to the relevant information about using the expect command to realize shell automated interaction. The article introduces it in great detail through sample code. Friends in need can refer to it. Let’s take a look together.
Background
There are many scenarios in Linux scripts for remote operations, such as remote login ssh, remote copy scp, file transfer sftp, etc. These commands will involve entering a security password. Normal use of the command requires manual input of the password and acceptance of security verification. In order to achieve automated remote operations, we can borrow the functionality of expect.
expect is a free programming tool language used to implement automated and interactive tasks to communicate without human intervention. Expect is constantly evolving. As time goes by, its functions become more and more powerful, and it has become a powerful assistant for system administrators. Expect requires the support of the Tcl programming language. To run expect on the system, Tcl must first be installed.
Installation of expect
expect is created based on Tcl, so we should install Tcl before installing expect.
(1) Tcl installation
Home page: http://www.tcl.tk
Download address: http://www.tcl .tk/software/tcltk/downloadnow84.tml
1. Download the source code package
wget http://nchc.dl.sourceforge.net/sourceforge/tcl/tcl8.4.11-src.tar.gz
2. Unzip the source code package
tar xfvz tcl8.4.11-src.tar.gz
3. Installation configuration
cd tcl8.4.11/unix ./configure --prefix=/usr/tcl --enable-shared make make install
Note:
1. After the installation is completed, enter the root directory of the tcl source code and copy tclUnixPort.h under the subdirectory unix to the subdirectory generic.
2. Do not delete the tcl source code yet, because it is still needed for the expect installation process.
(2) expect installation (requires Tcl library)
Home page: http://expect.nist.gov/
1. Download Source package
wget http://sourceforge.net/projects/expect/files/Expect/5.45/expect5.45.tar.gz/download
2. Unzip the source package
tar xzvf expect5.45.tar.gz
3. Installation and configuration
cd expect5.45 ./configure --prefix=/usr/expect --with-tcl=/usr/tcl/lib --with-tclinclude=../tcl8.4.11/generic make make install ln -s /usr/tcl/bin/expect /usr/expect/bin/expect
expect
The core of expect is spawn and expect , send, set.
spawn calls the command to be executed
#expect waits for the command prompt message to appear, that is, to capture the user input prompt:
send sends values that require interaction, replacing the user's manual input
#set sets the variable value
interact After execution is completed Maintain the interactive state and give control to the console. At this time, you can operate manually. If there is no such sentence, it will exit after the login is completed, instead of staying on the remote terminal.
expect eof This must be added, and corresponds to spawn to indicate the termination of capturing terminal output information, similar to if....endif
expect The script must end with interact or expect eof. Expect eof is usually enough to perform automated tasks.
Other settings
Set expect to never timeout set timeout -1
Set expect 300 Second timeout, if no expect content appears after more than 300, exit set timeout 300
expect writing syntax
expect uses tcl syntax
A Tcl command consists of words separated by spaces. Among them, the first word is the command name, and the rest are command parameters
cmd arg arg arg
$foo
[cmd arg]
"some stuff"
{some stuff}
#!/usr/bin/expect -f ########################################################## # 通过SSH登陆和执行命令 #参数:1.Use_Type [check/execute] # 2.SSHServerIp # 3.SSHUser # 4.SSHPassword # 5.CommandList [多个命令间以;间隔] #返回值: # 0 成功 # 1 参数个数不正确 # 2 SSH 服务器服务没有打开 # 3 SSH 用户密码不正确 # 4 连接SSH服务器超时 ########################################################## proc usage {} { regsub ".*/" $::argv0 "" name send_user "Usage:\n" send_user " $name Use_Type SSHServerIp SSHUser SSHPassword CommandList\n" exit 1 } ## 判断参数个数 if {[llength $argv] != 5} { usage } #设置变量值 set Use_Type [lindex $argv 0] set SSHServerIp [lindex $argv 1] set SSHUser [lindex $argv 2] set SSHPassword [lindex $argv 3] set CommandList [lindex $argv 4] #spawn ping ${SSHServerIp} -w 5 #expect { # -nocase -re "100% packet loss" { # send_error "Ping ${SSHServerIp} is unreachable, Please check the IP address.\n" # exit 1 # } #} set timeout 360 set resssh 0 #定义变量标记ssh连接时是否输入yes确认 set inputYes 0 set ok_string LOGIN_SUCCESS if {$Use_Type=="check"} { #激活ssh连接,如果要需要输入yes确认,输入yes,设置inputYes为1,否则输入ssh密码 spawn ssh ${SSHUser}@${SSHServerIp} "echo $ok_string" } else { spawn ssh ${SSHUser}@${SSHServerIp} "$CommandList" } expect { -nocase -re "yes/no" { send -- "yes\n" set inputYes 1 } -nocase -re "assword: " { send -- "${SSHPassword}\n" set resssh 1 } #-nocase -re "Last login: " { # send -- "${CommandList}\n" #} $ok_string {} -nocase -re "Connection refused" { send_error "SSH services at ${SSHServerIp} is not active.\n" exit 2 } timeout { send_error "Connect to SSH server ${SSHUser}@${SSHServerIp} timeout(10s).\n" exit 4 } } #如果输入了yes确认,输入ssh密码 if {$inputYes==1} { expect { -nocase -re "assword: " { send -- "${SSHPassword}\n" set resssh 1 } } } #如果出现try again或者password:提示,说明输入的用户密码错误,直接退出。 if {$resssh==1} { expect { -nocase -re "try again" { send_error "SSH user:${SSHUser} passwd error.\n" exit 3 } -nocase -re "assword:" { send_error "SSH user:${SSHUser} passwd error.\n" exit 3 } eof {} } } send_error -- "$expect_out(buffer)" #-nocase -re "No such user" { # send_error "No such user.\n" # exit 5 # } #exit
Linux Shell production recording and playback function script
Python realizes the simple function of shell sed replacement
Linux shell ftp method to download files according to date
The above is the detailed content of Examples to explain the expect command to implement Shell automated interaction. For more information, please follow other related articles on the PHP Chinese website!