Use expect to realize ssh automatic login and script execution under Linux

Use expect to realize ssh automatic login and script execution under Linux

 

expect is not built into the system, it needs to be installed:

        yum install expect

After the installation is complete, the following script can be executed.

 

 Login script for ssh password authentication:

#!/bin/bash

# match prompt
CMD_PROMPT="\](\$|#)"

# Script to execute
script="/root/test.sh"

username="root"
password="123456"
host="192.168.1.109"
port=22

expect -c "
	send_user connecting\ to\ $host...\r # spaces to be escaped
	spawn ssh -p $port $username@$host
	expect {
    	    *yes/no* { send -- yes\r;exp_continue;}
   	    *assword* { send -- $password\r;}
	}
	expect -re $CMD_PROMPT
	send -- $script\r
	expect -re $CMD_PROMPT
	exit
"
echo "\r"

 

Login script for ssh public key authentication:

 

#!/bin/bash

# match prompt
CMD_PROMPT="\](\$|#)"

# Script to execute
script="/root/test.sh"

username="root"
password="123456"
host="192.168.1.109"
port=22

expect -c "
	send_user connecting\ to\ $host...\r
	spawn ssh -p $port $username@$host
	expect -re $CMD_PROMPT
	send -- $script\r
	expect -re $CMD_PROMPT
	exit
"
echo "\r"
 

 

 1. send_user is an echo, equivalent to echo.

 2. spawn is to start a new process

 3. expect{ } This is the output that matches the previous command. For example, after the spawn sentence above is executed, you will be prompted to enter a password. The prompt will contain password, so it matches *assword*, and then send -- $ password send the password.

 4. send is to send an instruction to the peer

 5. There is an exp_continue inside expect, which means to re-match the expect, which is equivalent to the continue of while

 6. The -re of expect means to match the regular expression

 

ps: Special characters in the parameters of the command inside expect need to be escaped with \ in front

 

Similar can also achieve ftp login, automatic upload and download files and so on.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326479479&siteId=291194637