


Examples 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
#!/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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The sudo command allows users to run commands in elevated privilege mode without switching to superuser mode. This article will introduce how to simulate functions similar to sudo commands in Windows systems. What is the Shudao Command? Sudo (short for "superuser do") is a command-line tool that allows users of Unix-based operating systems such as Linux and MacOS to execute commands with elevated privileges typically held by administrators. Running SUDO commands in Windows 11/10 However, with the launch of the latest Windows 11 Insider preview version, Windows users can now experience this feature. This new feature enables users to

How to implement dual WeChat login on Huawei mobile phones? With the rise of social media, WeChat has become one of the indispensable communication tools in people's daily lives. However, many people may encounter a problem: logging into multiple WeChat accounts at the same time on the same mobile phone. For Huawei mobile phone users, it is not difficult to achieve dual WeChat login. This article will introduce how to achieve dual WeChat login on Huawei mobile phones. First of all, the EMUI system that comes with Huawei mobile phones provides a very convenient function - dual application opening. Through the application dual opening function, users can simultaneously

This article will introduce readers to how to use the command prompt (CommandPrompt) to find the physical address (MAC address) of the network adapter in Win11 system. A MAC address is a unique identifier for a network interface card (NIC), which plays an important role in network communications. Through the command prompt, users can easily obtain the MAC address information of all network adapters on the current computer, which is very helpful for network troubleshooting, configuring network settings and other tasks. Method 1: Use "Command Prompt" 1. Press the [Win+X] key combination, or [right-click] click the [Windows logo] on the taskbar, and in the menu item that opens, select [Run]; 2. Run the window , enter the [cmd] command, and then

In Win11 system, you can enable or disable Hyper-V enhanced session mode through commands. This article will introduce how to use commands to operate and help users better manage and control Hyper-V functions in the system. Hyper-V is a virtualization technology provided by Microsoft. It is built into Windows Server and Windows 10 and 11 (except Home Edition), allowing users to run virtual operating systems in Windows systems. Although virtual machines are isolated from the host operating system, they can still use the host's resources, such as sound cards and storage devices, through settings. One of the key settings is to enable Enhanced Session Mode. Enhanced session mode is Hyper

1. Overview The sar command displays system usage reports through data collected from system activities. These reports are made up of different sections, each containing the type of data and when the data was collected. The default mode of the sar command displays the CPU usage at different time increments for various resources accessing the CPU (such as users, systems, I/O schedulers, etc.). Additionally, it displays the percentage of idle CPU for a given time period. The average value for each data point is listed at the bottom of the report. sar reports collected data every 10 minutes by default, but you can use various options to filter and adjust these reports. Similar to the uptime command, the sar command can also help you monitor the CPU load. Through sar, you can understand the occurrence of excessive load

How to implement the WeChat clone function on Huawei mobile phones With the popularity of social software and people's increasing emphasis on privacy and security, the WeChat clone function has gradually become the focus of people's attention. The WeChat clone function can help users log in to multiple WeChat accounts on the same mobile phone at the same time, making it easier to manage and use. It is not difficult to implement the WeChat clone function on Huawei mobile phones. You only need to follow the following steps. Step 1: Make sure that the mobile phone system version and WeChat version meet the requirements. First, make sure that your Huawei mobile phone system version has been updated to the latest version, as well as the WeChat App.

The programming language PHP is a powerful tool for web development, capable of supporting a variety of different programming logics and algorithms. Among them, implementing the Fibonacci sequence is a common and classic programming problem. In this article, we will introduce how to use the PHP programming language to implement the Fibonacci sequence, and attach specific code examples. The Fibonacci sequence is a mathematical sequence defined as follows: the first and second elements of the sequence are 1, and starting from the third element, the value of each element is equal to the sum of the previous two elements. The first few elements of the sequence

What is the correct way to restart a service in Linux? When using a Linux system, we often encounter situations where we need to restart a certain service, but sometimes we may encounter some problems when restarting the service, such as the service not actually stopping or starting. Therefore, it is very important to master the correct way to restart services. In Linux, you can usually use the systemctl command to manage system services. The systemctl command is part of the systemd system manager
