升级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 "密钥密码
";}
expect "Identity added:"
spawn ssh SSH用户@IP地址 -pSSH端口 -i /Users/alsoalso/keys/RSA_Key01
expect "*yes/no*" { send "yes
"; 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 "密钥密码 ";} 输入密钥密码
expect "Identity added:" 判断密钥是否登录成功
spawn ssh SSH用户@IP地址 -pSSH端口 -i /Users/alsoalso/keys/RSA_Key01 连接服务器
expect "*yes/no*" { send "yes "; 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 ";}
expect "Identity added:" { spawn ssh sshusername@ip -pssh端口 -i /Users/alsoalso/keys/RSA_Key00 }
expect "sshusername@hostname ~" { send "su " }
expect "密码" { send "rootmima " }
expect "*yes/no*" { send "yes "; exp_continue }
interact