shell expect实现ssh免交互执行命令的三种用法

1.EOF 标准输出作为 expect 标准输入

#!/bin/bash
USER=root
PASS=123.com
IP=192.168.1.120
expect << EOF
set timeout 30
spawn ssh $USER@$IP
expect {
"(yes/no)" {send "yes\r"; exp_continue}
"password:" {send "$PASS\r"}
}
expect "$USER@*" {send "$1\r"}
expect "$USER@*" {send "exit\r"}
expect eof
EOF

方法 2:

#!/bin/bash
USER=root
PASS=123.com
IP=192.168.1.120
expect -c "
spawn ssh $USER@$IP
expect {
\"(yes/no)\" {send \"yes\r\"; exp_continue}
\"password:\" {send \"$PASS\r\"; exp_continue}
\"$USER@*\" {send \"df -h\r exit\r\"; exp_continue}
}"

方法 3:将 expect 脚本独立出来
login.exp 登录文件:

#!/usr/bin/expect
set ip [lindex $argv 0]
set user [lindex $argv 1]
set passwd [lindex $argv 2]
set cmd [lindex $argv 3]
if { $argc != 4 } {
puts "Usage: expect login.exp ip user passwd"
exit 1
}
set timeout 30
spawn ssh $user@$ip
expect {
"(yes/no)" {send "yes\r"; exp_continue}
"password:" {send "$passwd\r"}
}
expect "$user@*" {send "$cmd\r"}
expect "$user@*" {send "exit\r"}
expect eof

执行命令脚本:

#!/bin/bash
HOST_INFO=user_info
for ip in $(awk ‘{print $1}‘ $HOST_INFO)
do
user=$(awk -v I="$ip" ‘I==$1{print $2}‘ $HOST_INFO)
pass=$(awk -v I="$ip" ‘I==$1{print $3}‘ $HOST_INFO)
expect login.exp $ip $user $pass $1
done

SSH 连接信息文件:

cat user_info

192.168.1.120 root 123456

shell expect实现ssh免交互执行命令的三种用法

上一篇:MAC开发环境搭建之yarn


下一篇:rabbitmq进程崩溃导致服务器宕机