expect脚本远程登录、远程执行命令和脚本传参简单用法

时间:2023-03-08 18:38:03

expect介绍:

最近想写一个自动化安装脚本,涉及到远程登录、分发文件包、远程执行命令等,其中少不了来回输入登录密码,交互式输入命令等,这样就大大降低了效率,那么有什么方法能解决呢?不妨试试expect:

  • expect是一款自动化的脚本解释型的工具。
  • expect基于tcl脚本,expect脚本的运行需要tcl的支持。
  • expect对一些需要交互输入的命令很有帮助,比如ssh ftp scp telnet。
  • expect就可以根据设定的规则,自动帮我们输入密码,大大节省了时间。

远程登录linux服务器的时候,ssh命令需要手工输入密码,当登录多台机器的时候就会非常繁琐。

expect安装

一般机器不会自带expect和tcl需要手动安装。

[root@bqh-nfs- ~]# yum install expect tcl -y
[root@bqh-nfs- ~]# rpm -qa expect tcl
expect-5.44.1.15-.el6_4.x86_64
tcl-8.5.-.el6.x86_64

expect基础知识

expect脚本

脚本开头

expect脚本一般以#!/usr/bin/expect -f开头,类似bash脚本。

常用后缀

expect脚本常常以.exp或者.ex结束。

expect主要命令

  • spawn 新建一个进程,这个进程的交互由expect控制
  • expect 等待接受进程返回的字符串,直到超时时间,根据规则决定下一步操作
  • send 发送字符串给expect控制的进程
  • set 设定变量为某个值
  • exp_continue 重新执行expect命令分支
  • [lindex $argv 0] 获取expect脚本的第1个参数
  • [lindex $argv 1] 获取expect脚本的第2个参数
  • set timeout -1 设置超时方式为永远等待
  • set timeout 30 设置超时时间为30秒
  • interact 将脚本的控制权交给用户,用户可继续输入命令
  • expect eof 等待spawn进程结束后退出信号eof

expect命令分支

expect命令采用了tcl的模式-动作语法,此语法有以下几种模式:

单一分支语法

set password
expect "*assword:" { send "$password\r" }

当输出中匹配*assword:时,输出password变量的数值和回车。

多分支模式语法

set password
expect {
"(yes/no)?" { send "yes\r"; exp_continue }
"*assword:" { send "$password\r" }
}

当输出中包含(yes/no)?时,输出yes和回车,同时重新执行此多分支语句。

当输出中匹配*assword:时,输出password变量的数值和回车。

自动远程登录脚本:bqh-nfs-123机器免输密登录bqh-back-124机器上

[root@bqh-nfs- scripts]# vim test.exp 

#!/usr/bin/expect -f            #expect的路径,which expect查询获取
set timeout 20 #连接超时
set host "192.168.0.124"
set password ""
spawn ssh root@$host #登录服务器用户+地址
expect { #等待接受进程返回的字符串
"yes/no" {send "yes\n";exp_continue} #等待输入yes
"password:" {send "$password\n"} #等待输入密码
}
interact #将脚本的控制权交给用户,用户可继续输入命令

expect脚本远程登录、远程执行命令和脚本传参简单用法

执行结果如下:

expect脚本远程登录、远程执行命令和脚本传参简单用法

expect脚本远程执行命令:

[root@bqh-nfs- scripts]# vim test.exp 

#!/usr/bin/expect -f
set timeout
set host "192.168.0.124"
set password ""
spawn ssh root@$host
expect {
"yes/no" {send "yes\n";exp_continue}
"password:" {send "$password\n"}
}
expect "]*"
send "/application/nginx/sbin/nginx\n"
expect "]*"
send "lsof -i:80\n"
expect "]*"
send "echo 1147076062 >1.log\n"
expect "]*"
send "cat 1.log\n"
expect "]*"
send "exit\n"

expect脚本远程登录、远程执行命令和脚本传参简单用法

执行结果如下:

expect脚本远程登录、远程执行命令和脚本传参简单用法

expect脚本远程登录、远程执行命令和脚本传参简单用法

expet脚本传参执行命令:

[root@bqh-nfs- scripts]# cat test1.exp
#!/usr/bin/expect set user [lindex $argv ]
set host [lindex $argv ]
set passwd ""
set cmd [lindex $argv ]
spawn ssh $user@$host expect {
"yes/no" { send "yes\n"}
"password:" { send "$passwd\n" }
} expect "]*"
send "$cmd\n"
expect "]*"
send "exit\n"

expect脚本远程登录、远程执行命令和脚本传参简单用法

执行结果如下:

expect脚本远程登录、远程执行命令和脚本传参简单用法