Linux Expect usage examples

Linux Expect usage examples

Expect introduction

We can implement simple control flow functions through Shell scripts, such as: looping, judgment, etc. For occasions that require interaction, manual intervention is necessary. Sometimes we may need to implement functions that interact with interactive programs such as telnet servers. Expect is a tool used to realize this function.

Expect is a free programming tool language for automating and communicating interactive tasks without human intervention. The author of Expect, Don Libes, defined Expect as follows when he started writing Expect in 1990: Expect is a software suite for automatic interactive tools (Expect [is a] software suite for automating interactive tools). Using it, the system administrator can create scripts to provide input to commands or programs, and these commands and programs expect input from the terminal (terminal). Generally speaking, these inputs require manual input. Expect can simulate the standard input according to the prompt of the program to provide the input required by the program to realize interactive program execution. Even a simple BBS chatbot can be implemented.

Expect is constantly evolving, becoming more and more powerful over time, and has become a powerful assistant for system administrators. Expect needs the support of the Tcl programming language. To run Expect on the system, Tcl must be installed first.

Expect automatic interaction process:
spawn starts the specified process—expect obtains the specified keyword—send sends the specified character to the specified program—executes and exits.

Expect sample

The following sample script can automatically log in to the specified host with ssh and execute commands

#!/usr/bin/expect
set timeout 20

if { [llength $argv] < 3} {
puts “Usage: $argv0 ip username pass”
exit 1
}

set ip [lindex $argv 0]
set username [lindex $argv 1]
set des_pass [lindex $argv 2]

–spawn starts the specified process
spawn ssh username @ username@username@ip

–expect Get the specified keyword
expect "Password: "

–send sends the specified character to the specified program
send “$des_pass\r”

–input your command line here, like the following examples
expect “%”
send “ls -l\r”
#expect “%”
#send “cd /app/aijh/audit_proc_monitor\r”
#expect “%”
#send “sh start_deamonnew.sh\r”

expect “%”
send “exit\r”

Guess you like

Origin blog.csdn.net/weixin_43182179/article/details/114602145