最近想写一个自动化安装脚本,涉及到远程登陆、分发文件包、远程执行命令等,其中少不了来回输入登陆密码,交互式输入命令等,这样就大大下降了效率,那么有什么方法能解决呢?不妨试试expect:linux
远程登陆linux服务器的时候,ssh命令须要手工输入密码,当登陆多台机器的时候就会很是繁琐。nginx
通常机器不会自带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脚本通常以#!/usr/bin/expect -f开头,相似bash脚本。bash
expect脚本经常以.exp或者.ex结束。服务器
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
[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
[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"
执行结果以下:
[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"
执行结果以下: