标签:路径 远程登录 com code span bash 运行 输出 决定
最近想写一个自动化安装脚本,涉及到远程登录、分发文件包、远程执行命令等,其中少不了来回输入登录密码,交互式输入命令等,这样就大大降低了效率,那么有什么方法能解决呢?不妨试试expect:
远程登录linux服务器的时候,ssh命令需要手工输入密码,当登录多台机器的时候就会非常繁琐。
一般机器不会自带expect和tcl需要手动安装。
[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脚本。
expect脚本常常以.exp或者.ex结束。
expect命令采用了tcl的模式-动作语法,此语法有以下几种模式:
set password 123456 expect "*assword:" { send "$password\r" }
当输出中匹配*assword:时,输出password变量的数值和回车。
set password 123456 expect { "(yes/no)?" { send "yes\r"; exp_continue } "*assword:" { send "$password\r" } }
当输出中包含(yes/no)?时,输出yes和回车,同时重新执行此多分支语句。
当输出中匹配*assword:时,输出password变量的数值和回车。
[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 #将脚本的控制权交给用户,用户可继续输入命令
执行结果如下:
[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"
执行结果如下:
标签:路径 远程登录 com code span bash 运行 输出 决定
原文地址:https://www.cnblogs.com/su-root/p/11229316.html