expect

#!/bin/bash
passwd='nihao23d23d'
/usr/bin/expect << _EOF
spawn ssh -p22 flli@10.189.103.12
expect {
         "Are you sure you want to continue connecting (yes/no)?" {
              send "yes
"
       }
         "*password:" {
             send "${passwd}
"
       }
         "Permission denied, please try again." { 
             exit 
       }
         "Connection refused" {
             exit
       }
        timeout {
             exit
       }
        eof {
            exit
      }
}
expect "*$"
send "hostname
"
expect "*$"
send "exit
"
expect eof
_EOF
原文地址:https://www.cnblogs.com/ilifeilong/p/9460990.html