shell中使用expect命令进行远程执行命令脚本

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44018338/article/details/102722263

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

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对脚本之家的支持。如果你想了解更多相关内容请查看下面相关链接

您可能感兴趣的文章:

猜你喜欢

转载自blog.csdn.net/weixin_44018338/article/details/102722263