Linux expect

Linux expect 使用简介
一.登陆到远程主机

脚本代码如下:

##############################################
#!/usr/bin/expect
set timeout 30
spawn ssh -l username hostip
expect { 
"yes/no" { send "yes
";exp_continue } 
"password:" { send "hostpassword
" } 
} 
interact
##############################################
View Code

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 ";exp_continue }
      "password:" { send "hostpassword " }
      }

  判断连接 主机后输出的字符串进行捕获,发送相应的动作和密码确定连接(Linux 第一次连接主机会提示是否连接此主机) send "hostpassword "(发送密码,换行符号进行确认)

5. interact

  完成连接后保持连接在被控主机,如果不加此字段会登陆后就退出改 shell

二.执行远程命令行

  

##############################################
#!/usr/bin/expect
set timeout 30
spawn ssh -l username hostip
expect { 
"yes/no" { send "yes
";exp_continue } 
"password:" { send "hostpassword
" } 
} 
expect -re "]($|#) " 
send "bash /root/test.sh 
" 
expect -re "]($|#) " 
send "exit
" 
##############################################
View Code

1.expect -re "]($|#) "

  匹配终端输出字符

2.send "bash /root/test.sh  " 

  执行远程命令或者脚本

3.expect -re "]($|#) " 

  判断执行完毕与否

4.send "exit " 

  退出 shell

原文地址:https://www.cnblogs.com/edwardlogs/p/5018731.html