Linux system expect command operation example

  
                

Among many Linux commands, the expect command is less common. We can use the expect command to implement automatic login of the script, waiting for feedback from the process, and so on. So what are the uses of the expect command? Come with Xiaobian.

first look at a piece of code:

#! /usr/bin/expect

set timeout 30

spawn ssh -l root 192.168.1.188

expect “password:”

send &ldquo ;abc123456\ ”

interact

Explain these 6 lines:

Line 1 [#! /usr/bin/expect]

This line tells the code in the operating system script to use that shell to execute. The expectation here is actually a kind of thing like bash under linux and cmd under windows. This line needs to be in the first line of the script.

Line 2 [set timeout 30]

Basically knowing English knows that this is setting the timeout period. Now you just need to remember that his timing unit is: seconds

Line 3 [spawn ssh -l username 192.168.1.188]

spawn is the internal command that can be executed after entering the expect environment. If there is no expect or direct execution under the default SHELL, it is not found. To the spawn command. So don't use the commands like “which spawn“ to find the spawn command. For example, dir in windows is an internal command. This command is provided by the shell. You cannot find an executable file for dir.com or dir.exe. Its main function is to add a shell to the ssh running process to pass interactive commands.

Line 4 [expect “password:”]

The expect here is also an internal command of expect, a little dizzy, expect shell commands and internal commands are the same, but Not a function, just get used to it. The meaning of this command is to judge whether the string containing "ldwords" is included in the last output. If there is, it will return immediately. Otherwise, it will wait for a while and then return. The waiting time is 30 seconds previously set

Line 5 [send “abc123456\ ”]

Here is the execution of the interactive action, equivalent to the action of manually entering the password.

Tips: Don't forget to add “\ ” at the end of the command string. If there is an abnormal wait state, you can check it.

Line 6 [interact]

After the execution is complete, keep the interactive state and give control to the console. At this time, you can manually operate it. If you do not have this sentence, you will exit after logging in, instead of staying on the remote terminal.

Under Linux, you can use this command when you execute ssh login or scp to copy files, and you can enter the password automatically.

Case 1: Remote Execution Command

#! /usr/bin/expect -f

set timeout 30

spawn ssh -l root 192.168.1.188

expect {

“yes/no&rdquo { send “yes\ ”;exp_continue }

“password:” { send “abc123456\ ” }

}

expect -re &ldquo ;\\](\\$

Copyright © Windows knowledge All Rights Reserved