Linux下用expect实现ssh自动登录并执行脚本

Linux下用expect实现ssh自动登录并执行脚本

expect不是系统自带的,需要安装:

        yum install expect

装完后才可执行以下脚本。

 ssh密码认证的登陆脚本:

#!/bin/bash

# 匹配提示符
CMD_PROMPT="\](\$|#)"

# 要执行的脚本
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 {
    	    *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"

ssh公钥认证的登陆脚本:

#!/bin/bash

# 匹配提示符
CMD_PROMPT="\](\$|#)"

# 要执行的脚本
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 是回显,相当于echo。

 2. spawn 是开启新的进程

 3. expect{  } 这是匹配上一条指令的输出,,比如上面spawn 那句执行完后,会提示你输入密码,提示语中会包含 password,因此就匹配*assword*,然后就send -- $password 把密码发过去。

 4. send 就是发指令到对端

 5. expect 内部有个exp_continue ,意思是重新匹配所在的expect,相当于while的continue

 6. expect 的 -re 表示匹配正则表达式

ps:expect 内部的指令的参数中特殊字符需在前面加\转义

类似的还可实现ftp登陆,自动上传下载文件等等。

猜你喜欢

转载自lixiaohui.iteye.com/blog/2322992