expect 交互

expect 

expect 是一种自动交互语言,能实现在shell脚本中为scp和ssh等自动输入密码自动登录.

exp_continue         # 多个spawn命令时并行
interact             # 执行完成后保持交互状态,把控制权交给控制台
expect "password:"   # 判断关键字符
send "passwd
"      # 执行交互动作,与手工输入密码的动作等效。字符串结尾加"
"

  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
"
         send "xuesong
";
         expect {
              "sudo" {
                    send_user "sudo
"
                    send "xuesong
"
                    interact
                    }
                    eof {
                    send_user "sudo eof
"
                    }
               }
         }
         "password:" {
                send_user "ssh
"
                send "xuesong
";
                expect {
                     "sudo" {
                      send_user "sudo
"
                      send "xuesong
"
                      interact
                      }
                      eof {
                      send_user "sudo eof
"
                      }
                 }
          }
          "sudo" {
                 send_user "sudo
"
                 send "xuesong
"
                 interact
                 }
           eof {
                 end_user "ssh eof
"
                 }
           }
           '
原文地址:https://www.cnblogs.com/sharesdk/p/8710019.html