search
HomeOperation and MaintenanceLinux Operation and MaintenanceExamples to explain the expect command to implement Shell automated interaction

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

  • # 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
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!

Statement
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
The Building Blocks of Linux: Key Components ExplainedThe Building Blocks of Linux: Key Components ExplainedApr 30, 2025 am 12:26 AM

The core components of the Linux system include the kernel, file system, and user space. 1. The kernel manages hardware resources and provides basic services. 2. The file system is responsible for data storage and organization. 3. Run user programs and services in the user space.

Using Maintenance Mode: Troubleshooting and Repairing LinuxUsing Maintenance Mode: Troubleshooting and Repairing LinuxApr 29, 2025 am 12:28 AM

Maintenance mode is a special operating level entered in Linux systems through single-user mode or rescue mode, and is used for system maintenance and repair. 1. Enter maintenance mode and use the command "sudosystemctlisolaterscue.target". 2. In maintenance mode, you can check and repair the file system and use the command "fsck/dev/sda1". 3. Advanced usage includes resetting the root user password, mounting the file system in read and write mode and editing the password file.

Linux Maintenance Mode: Understanding the PurposeLinux Maintenance Mode: Understanding the PurposeApr 28, 2025 am 12:01 AM

Maintenance mode is used for system maintenance and repair, allowing administrators to work in a simplified environment. 1. System Repair: Repair corrupt file system and boot loader. 2. Password reset: reset the root user password. 3. Package management: Install, update or delete software packages. By modifying the GRUB configuration or entering maintenance mode with specific keys, you can safely exit after performing maintenance tasks.

Linux Operations: Networking and Network ConfigurationLinux Operations: Networking and Network ConfigurationApr 27, 2025 am 12:09 AM

Linux network configuration can be completed through the following steps: 1. Configure the network interface, use the ip command to temporarily set or edit the configuration file persistence settings. 2. Set up a static IP, suitable for devices that require a fixed IP. 3. Manage the firewall and use the iptables or firewalld tools to control network traffic.

Maintenance Mode in Linux: A System Administrator's GuideMaintenance Mode in Linux: A System Administrator's GuideApr 26, 2025 am 12:20 AM

Maintenance mode plays a key role in Linux system management, helping to repair, upgrade and configuration changes. 1. Enter maintenance mode. You can select it through the GRUB menu or use the command "sudosystemctlisolaterscue.target". 2. In maintenance mode, you can perform file system repair and system update operations. 3. Advanced usage includes tasks such as resetting the root password. 4. Common errors such as not being able to enter maintenance mode or mount the file system, can be fixed by checking the GRUB configuration and using the fsck command.

Maintenance Mode in Linux: When and Why to Use ItMaintenance Mode in Linux: When and Why to Use ItApr 25, 2025 am 12:15 AM

The timing and reasons for using Linux maintenance mode: 1) When the system starts up, 2) When performing major system updates or upgrades, 3) When performing file system maintenance. Maintenance mode provides a safe and controlled environment, ensuring operational safety and efficiency, reducing impact on users, and enhancing system security.

Linux: Essential Commands and OperationsLinux: Essential Commands and OperationsApr 24, 2025 am 12:20 AM

Indispensable commands in Linux include: 1.ls: list directory contents; 2.cd: change working directory; 3.mkdir: create a new directory; 4.rm: delete file or directory; 5.cp: copy file or directory; 6.mv: move or rename file or directory. These commands help users manage files and systems efficiently by interacting with the kernel.

Linux Operations: Managing Files, Directories, and PermissionsLinux Operations: Managing Files, Directories, and PermissionsApr 23, 2025 am 12:19 AM

In Linux, file and directory management uses ls, cd, mkdir, rm, cp, mv commands, and permission management uses chmod, chown, and chgrp commands. 1. File and directory management commands such as ls-l list detailed information, mkdir-p recursively create directories. 2. Permission management commands such as chmod755file set file permissions, chownuserfile changes file owner, and chgrpgroupfile changes file group. These commands are based on file system structure and user and group systems, and operate and control through system calls and metadata.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool