Examples to explain the expect command to implement Shell automated interaction

小云云
Release: 2017-12-22 09:19:26
Original
2814 people have browsed it

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
Copy after login

2. Unzip the source code package

tar xfvz tcl8.4.11-src.tar.gz
Copy after login

3. Installation configuration

cd tcl8.4.11/unix 
./configure --prefix=/usr/tcl --enable-shared 
make 
make install
Copy after login

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
Copy after login

2. Unzip the source package

tar xzvf expect5.45.tar.gz
Copy after login

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
Copy after login

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

  • # The
  • ##$ symbol represents the value of a variable. In this example, the variable name is foo.

    $foo

  • The square brackets execute a nested command. For example, If you want to pass the results of one command as an argument to another command, then you use the notation

    [cmd arg]

  • double quotes to mark the phrase as an argument to the command. The "$" symbol and square brackets are still interpreted inside double quotes

    "some stuff"

  • Braces also mark a phrase as an argument to a command. However, other symbols are Curly brackets are not interpreted

    {some stuff}

  • The backslash symbol is used to quote special symbols. For example: n represents a newline. The backslash symbol is also used Close the special meanings of the "$" symbol, quotation marks, square brackets and curly brackets


Example


login.exp is dedicated to remote login, shortcut Usage: login.exp "exclude" "${remote_ip}" "${remote_user}" "${remote_passwd}" "${remote_command}"

#!/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
Copy after login
Have you learned it yet? I hope that after reading this article, you will have a deeper understanding of shell automation interaction.

Related recommendations:

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!