Linux expect
一.登陆到远程主机
脚本代码如下:
##############################################
#!/usr/bin/expect
set timeout 30
spawn ssh -l username hostip
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "hostpassword\r" }
}
interact
##############################################
1. #!/usr/bin/expect
这一行告诉操作系统脚本里的代码使用那一个shell来执行。这里的expect其实和linux下的bash
2. set timeout 30
设置 脚本超时时间
3. spawn ssh -l username hostip
spawn是进入expect环境后才可以执行的expect内部命令,主要的功能是给ssh运行进程加个壳,用来传递交互指令。
4. expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "hostpassword\r" }
}
判断连接 主机后输出的字符串进行捕获,发送相应的动作和密码确定连接(Linux 第一次连接主机会提示是否连接此主机) send "hostpassword\r"(发送密码,换行符号进行确认)
5. interact
完成连接后保持连接在被控主机,如果不加此字段会登陆后就退出改 shell
二.执行远程命令行
##############################################
#!/usr/bin/expect
set timeout 30
spawn ssh -l username hostip
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "hostpassword\r" }
}
expect -re "\](\$|#) "
send "bash /root/test.sh \r"
expect -re "\](\$|#) "
send "exit\r"
##############################################
1.expect -re "\](\$|#) "
匹配终端输出字符
2.send "bash /root/test.sh \r"
执行远程命令或者脚本
3.expect -re "\](\$|#) "
判断执行完毕与否
4.send "exit\r"
退出 shell
我们只需要努力,然后剩下的交给时间。


浙公网安备 33010602011771号