expect 交互
expect
expect 是一种自动交互语言,能实现在shell脚本中为scp和ssh等自动输入密码自动登录.
exp_continue # 多个spawn命令时并行 interact # 执行完成后保持交互状态,把控制权交给控制台 expect "password:" # 判断关键字符 send "passwd\r" # 执行交互动作,与手工输入密码的动作等效。字符串结尾加"\r"
ssh 后 sudo
#!/bin/bash #sudo注释下行允许后台运行 #Defaults requiretty #sudo去掉!允许远程 #Defaults !visiblepw /usr/bin/expect -c ' set timeout 5 spawn ssh -o StrictHostKeyChecking=no xuesong1@192.168.42.128 "sudo grep xuesong1 /etc/passwd" expect { "passphrase" { send_user "sshkey\n" send "xuesong\r"; expect { "sudo" { send_user "sudo\n" send "xuesong\r" interact } eof { send_user "sudo eof\n" } } } "password:" { send_user "ssh\n" send "xuesong\r"; expect { "sudo" { send_user "sudo\n" send "xuesong\r" interact } eof { send_user "sudo eof\n" } } } "sudo" { send_user "sudo\n" send "xuesong\r" interact } eof { end_user "ssh eof\n" } } '