前提条件,需要安装expect,安装方法请参考

​http://tongzidane.blog.163.com/blog/static/5816589220118161127811/​


#!/usr/bin/expect

 # 设置超时时间为 60 秒
 set timeout  60
 # 设置要登录的主机 IP 地址
 set host 192.168.0.4
 # 设置以什么名字的用户登录
 set name root
 # 设置用户名的登录密码
 set password 123456

 #spawn 一个 ssh 登录进程
 spawn  ssh $host -l $name
 # 等待响应,第一次登录往往会提示是否永久保存 RSA 到本机的 know hosts 列表中;等到回答后,在提示输出密码;之后就直接提示输入密码
 expect {
    "(yes/no)?" {
        send "yes\n"
        expect "password:"
        send "$pasword\n"
    }
 "assword:" {
        send "$password\n"
    }
 }
 expect "#"
 # 下面测试是否登录到 $host
 send "uname\n"
 expect "Linux"
 send_user  "Now you can do some operation on this terminal\n"
 # 这里使用了 interact 命令,使执行完程序后,用户可以在 $host 终端进行交互操作。
 Interact

 

如果不使用interact.也可以使用 expect eof