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

expect介绍:

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

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

远程登陆linux服务器的时候,ssh命令须要手工输入密码,当登陆多台机器的时候就会很是繁琐。nginx

expect安装

通常机器不会自带expect和tcl须要手动安装。vim

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

expect基础知识

expect脚本

脚本开头

expect脚本通常以#!/usr/bin/expect -f开头,相似bash脚本。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的模式-动做语法,此语法有如下几种模式:app

单一分支语法

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

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

多分支模式语法

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

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

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

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

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

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

执行结果以下:3d

expect脚本远程执行命令:

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

#!/usr/bin/expect -f
set timeout 20
set host "192.168.0.124"
set password "123456"
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"

执行结果以下:

expet脚本传参执行命令:

[root@bqh-nfs-123 scripts]# cat test1.exp
#!/usr/bin/expect

set user [lindex $argv 0]
set host [lindex $argv 1]
set passwd "123456"
set cmd [lindex $argv 2]
spawn ssh $user@$host

expect {
"yes/no" { send "yes\n"}
"password:" { send "$passwd\n" }
}

expect "]*"
send "$cmd\n"
expect "]*"
send "exit\n"

执行结果以下:

相关文章
相关标签/搜索