编写脚本实现登陆远程主机。(使用expect和shell脚本两种形式)。

发布时间 2023-10-07 14:22:57作者: 小糊涂90

expect脚本:

[10:40:45 root@centos8 ~]#cat expect{1..3}
#!/usr/bin/expect
spawn ssh 10.0.0.151
expect {
       "yes/no" { send "yes\n";exp_continue }
       "password" { send "123456\n" }
}
interact

##################################################

#!/usr/bin/expect
set ip 10.0.0.151
set user root
set password 123456
set timeout 10
spawn ssh $user@$ip
expect {
       "yes/no" { send "yes\n";exp_continue }
       "password" { send "$password\n" }

}
interact

##################################################

#!/usr/bin/expect
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
set timeout 10
spawn ssh $user@$ip
expect {
       "yes/no" { send "yes\n" ;exp_continue }
       "password" { send "$password\n" }

}
expect "#" { send "useradd hha\n" }
send "exit\n"
expect eof
#使用expect -f expect1执行脚本,或者给执行权限后./expect1执行。

shell脚本:


[10:43:08 root@centos8 ~]#cat expect4
#!/bin/bash
network=10.0.0
user=root
password=123456
iplist="
151
"


for ID in $iplist;do
ip=$network.$ID

expect <<fff
spawn ssh $user@$ip
set timeout 3
expect {
       "yes/no" { send "yes\n";exp_continue }
       "password" { send "$password\n" }
}
expect "#" { send "useradd hhh\n" }
expect eof
fff
done
#使用bash expect4,或给执行权限后./expect4运行脚本