shell脚本控制远端服务器,使用ssh登陆服务器,使用expect命令进行交互
expect命令说明:
1.expect是Linux中的一种交互的命令,借助expect实现脚本的自动化。
2.except中的spawn命令,用来创建新的进程
spawn ssh $user@ip 创建ssh 链接。
3.send和expect和spawn创建的进程进行交互,expect等待接受数据,send向spawn创建的进程发送数据。
4.设置超时时间 set timeout -1或者使用exp_contiue,防止expect等待时间过长。
代码示例:
#!bash/sh
ip=111.111.111.11. #填写需要远程的ip地址
user=name
expect << -EOF
#创建ssh链接进程
spawn ssh $user@$ip
#使用expect和ssh进程通讯
expect {
#ssh第一次登陆时需要输入确认信息
#*(yes/no)?* 正则表达式匹配是否需要输入确认信息
#send 向ssh发送yes字符串
#exp_continue 防止第二次输入时不需要输入yes信息,等待时间过长
“*(yes/no)?*” { send “yes\r”;exp_continue }
#配置链接的服务器用户密码
“*assword” { send “111111\r” }
}
#*user@aaaa* 登陆后终端的命令行匹配,按实际登陆后命令行填写进行匹配
#登陆后执行脚本 aa.sh
expect “*user@aaaa*” { send “sh aa.sh \r” }
# ssh 退出登陆
expect “user@aaaa*” { send “exit\r” }
# 终止expect
expect eof
EOF