自动登录一台 服务器

  • 代码
[root@localhost D151SP160]# cat test1.exp
#!/bin/expect
set timeout 2

set user_name [lindex $argv 0]
set mypassword [lindex $argv 1]
set ip [lindex $argv 2]

#puts "user_name=$user_name"
#puts "user_password=$mypassword"
#puts "host_ip=$ip"
#
spawn ssh $user_name@$ip hostname
expect {
"continue" { send "yes\r"; exp_continue }
"*password:" { send "$mypassword\r" }
}
expect eof
  • 执行
[root@localhost D151SP160]# /bin/expect  ./test1.exp root admin_123 207.207.35.100
spawn ssh root@207.207.35.100 hostname
root@207.207.35.100's password:
node100

自动登录多台服务器

  • test.exp
[root@localhost D151SP160]# cat test.exp
#!/bin/expect
set timeout 2

set user_name [lindex $argv 0]
set mypassword [lindex $argv 1]
set ip [lindex $argv 2]

#puts "user_name=$user_name"
#puts "user_password=$mypassword"
#puts "host_ip=$ip"
#
spawn ssh $user_name@$ip hostname
expect {
"continue" { send "yes\r"; exp_continue }
"*password:" { send "$mypassword\r" }
}
#expect eof
  • auto_login.sh
[root@node101 D151SP160]# cat auto_login.sh
#! /bin/sh
declare -A host_info
host_info[207.207.35.100]=admin_123
host_info[207.101.67.209]=admin_123


for host in "${!host_info[@]}"
do
#echo "host=$host"
#echo "passwd=${host_info[$host]}"

echo "--------------- begin to login in $host -----------"
/bin/expect ./test.exp root ${host_info[$host]} $host
echo
done
  • 执行
[root@node101 D151SP160]# sh auto_login.sh
--------------- begin to login in 207.207.35.100 -----------
spawn ssh root@207.207.35.100 hostname
root@207.207.35.100's password:
node100

--------------- begin to login in 207.101.67.209 -----------
spawn ssh root@207.101.67.209 hostname
root@207.101.67.209's password:
node209