天天看點

實作自動SSH連接配接

#!/usr/bin/expect  
set timeout 10  
set username [lindex $argv 0]  
set password [lindex $argv 1]  
set hostname [lindex $argv 2]  
#set username ftpuser
#set password ftpuser
#spawn 模拟終端互動
#ssh-copy-id将本機目前使用者的ssh登入公鑰copy到目标機器上
# "*(yes/no)*" 傳回内容包含yes/no,表示添加host到已知host
#password 表示要輸入目标機器的密碼
#"*please*","*Permission denied*" 錯誤,沒法成功添加ssh公鑰到目标機器
#"*All keys were skipped*","*you wanted were added*" 已添加過,則直接跳過。

spawn ssh-copy-id $username@$hostname
expect {
            "*(yes/no)*" {
				send "yes\r"; 
				exp_continue;
			}
			
            "password:" {
                send "$password\r";
				exp_continue;
            }
			"*please*" { exit 5 }
			"*All keys were skipped*" { exit }
			"*you wanted were added*" {exit }
			"*Permission denied*" { exit 6 }
        }
expect eof
           
#1.儲存上面的代碼為sh檔案,并設定檔案具有執行權限
#2.如下使用
./auto_ssh.sh "username" "passpord" "ip"
           
ssh

繼續閱讀