expect是用来实现自动交互功能的工具之一,使用expect-send来实现交互过程。
注意:
1、脚本的执行方法与bash shell不一样,比如:expect example.sh
2、向一个脚本传递参数时,bash shell是使用$1,$2…来接收参数的;而expect则将脚本的执行参数保存在数组$argv中,在脚本中一般将其赋值给变量:set 变量名 [lindex $argv 参数]
1
2
3
4
5
6
7
8
9
10
11
12 | #!/usr/bin/expect set ip [lindex $argv 0] set password [lindex $argv 1] set timeout 2 spawn telnet $ip expect "*femto login:" send "root/r" expect "*Password:" send "$password/r" # 进入指定的机器后,就可执行相应的命令或者脚本 interact #expect eof |
注意:若登陆后便退出远程终端,则写expect eof
即可。
3、执行脚本
1 | expect autologin.sh 192.168.1.240 root |
很多时候,需要用expect命令实现登录远端服务器执行简单命令,诸如:重启服务器,ftp,ls, scp等命令。 里面涉及到输入密码的交互式场景,这个时候expect命令的巨大功效就出来了,下面是一个比较经典脚本实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 | #!/usr/bin/tclsh package require Expect set host_ip1 [lindex $argv 0] set host_usr [lindex $argv 1] set host_pwd [lindex $argv 2] spawn ssh $host_usr@$host_ip1 set timeout 60 expect { -re "password" {send "$host_pwd/n" } -re "yes/no" {send "yes/n" ;exp_continue} # 有的时候输入几次密码来确认,exp_continue } expect "#" send "ls /home/${host_user} | tee -a /tmp/ls.txt /r" expect "#" send "exit/r" expect eof |
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接
您可能感兴趣的文章:
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/1474.html