[root@node2 ssh]# cat auto_ssh.sh #!/usr/bin/expect -f ########################################## #經過SSH服務將id.pas.pub公鑰推送到目標服務器實現免密登錄 #參數:1.system_username # 2.system_password # 3.system_hostname # 4.CommandList [多個命令間;間隔] #返回值: # 0 成功 # 1 參數個數不正確 # 2 SSH 服務器服務沒有打開 # 3 SSH 用戶名密碼不正確 # 4 鏈接SSH服務器超時 ########################################## proc usage {} { regsub ".*/" $::argv0 "" name send_user "Usage:\n" send_user "$name system_username system_password system_hostname CommandList\n" exit 1 } if {[llength $argv] !=3} { usage } #設置變量值 set timeout 10 set system_username [lindex $argv 0] set system_password [lindex $argv 1] set system_hostname [lindex $argv 2] #檢查主機是否可達 spawn ping ${system_hostname} -w 2 expect { -nocase -re "100% packet loss" { send_error "Ping ${system_hostname} is unreachable, Please check the IP address.\n" exit 1 } } #超時時間 set timeout 60 set resssh 0 spawn ssh-keygen -t rsa expect { "*file in which to save the key*" { send "\n\r" send_user "/root/.ssh\r" exp_continue "*Overwrite (y/n)*"{ send "n\n\r" } } "*Enter passphrase*" { send "\n\r" exp_continue } "*Enter same passphrase again*" { send "\n\r" exp_continue } } spawn ssh-copy-id -i /root/.ssh/id_rsa.pub $system_username@$system_hostname expect { #first connect, no public key in ~/.ssh/known_hosts "Are you sure you want to continue connecting (yes/no)?" { send "yes\r" expect "password:" send "$system_password\r" } #already has public key in ~/.ssh/known_hosts "password:" { send "$system_password\r" } "Now try logging into the machine" { #it has authorized, do nothing! } } expect eof