升級MAC系統后,發現用於MAC終端ssh服務器的登錄腳本無法正常執行了,表現為:需要手動輸入密鑰密碼,於是重新整理一下,恢復正常,在此記錄一下:
#!/usr/bin/expect -f
spawn ssh-add -D
expect "*removed."
spawn ssh-add -l
expect "*identities."
spawn ssh-add /Users/alsoalso/keys/RSA_Key01
expect "*RSA_Key01" {send "密鑰密碼\r";}
expect "Identity added:"
spawn ssh SSH用戶@IP地址 -pSSH端口 -i /Users/alsoalso/keys/RSA_Key01
expect "*yes/no*" { send "yes\n"; exp_continue }
interact
說明一下:
#!/usr/bin/expect -f 指定expect, 需要安裝
spawn ssh-add -D 刪除已add的密碼,mac終端對添加的條目有限制,所以每次都初始化一下
expect "*removed." 根據上一步的執行反饋,獲取關鍵字用於執行下一步的條件
spawn ssh-add -l 列出密鑰列表,非必須
expect "*identities." 根據上一步的執行反饋,獲取關鍵字用於執行下一步的條件,非必須
spawn ssh-add /Users/alsoalso/keys/RSA_Key01 添加密鑰文件
expect "*RSA_Key01" {send "密鑰密碼\r";} 輸入密鑰密碼
expect "Identity added:" 判斷密鑰是否登錄成功
spawn ssh SSH用戶@IP地址 -pSSH端口 -i /Users/alsoalso/keys/RSA_Key01 連接服務器
expect "*yes/no*" { send "yes\n"; exp_continue } 如果首次連接服務器,會有確認
interact 命令執行完成后保持登錄在遠程服務器上
20180322更新:直接切換為root用戶
#!/usr/bin/expect -f
spawn ssh-add -D
expect "*removed."
spawn ssh-add -l
expect "*identities."
spawn ssh-add /Users/alsoalso/keys/RSA_Key00
expect "*RSA_Key00" {send "mima\r";}
expect "Identity added:" { spawn ssh sshusername@ip -pssh端口 -i /Users/alsoalso/keys/RSA_Key00 }
expect "sshusername@hostname ~" { send "su\r" }
expect "密碼" { send "rootmima\r" }
expect "*yes/no*" { send "yes\r"; exp_continue }
interact