码迷,mamicode.com
首页 > 其他好文 > 详细

分发系统介绍,expect脚本远程登录,expect脚本远程执行命令,expect脚本传递参数

时间:2018-06-06 00:56:40      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:expect

分发系统介绍
当我们要上线一个新代码的时候,如果机器少,我们的工作量不会很大,很容易完成,如果设备很多,有几十台,上百台的话,那我们的工作量会非常大,而且也不规范,这时,我们就可以用可以用开源的软件,expect脚本语言,进行实现分发系统的功能。

expect脚本远程登录
首先yum安装expect
yum install -y expect

然后写一个expect的远程登录脚本
#! /usr/bin/expect
set host "192.168.133.132" 这是expect的变量,它和shell不同的是变量前面要加set
set passwd "123456" 这是expect的变量,它和shell不同的是变量前面要加set
spawn ssh root@$host 登录机器的语句
expect {
"yes/no" { send "yes\r"; exp_continue} 第一次登录会提示yes或者是no,send是发送。\r是回车。exp_continue表示继续。
"assword:" { send "$passwd\r" }
}
interact 需要停留在远程的机器上,不需要退出。

然后给他增加权限
[root@linletao-001 ~]# chmod a+x 1.expect
执行脚本
[root@linletao-001 ~]# ./1.expect
spawn ssh root@192.168.218.129
The authenticity of host ‘192.168.218.129 (192.168.218.129)‘ can‘t be established.
ECDSA key fingerprint is SHA256:qNyAkC/T6wTJaqi1O2Ay20Y28uD8VsmNY3lgf4eTf60.
ECDSA key fingerprint is MD5:28:3a:76:a8:6e:db:04:ed:85:ff:fb:fe:25:33:b0:37.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added ‘192.168.218.129‘ (ECDSA) to the list of known hosts.
root@192.168.218.129‘s password:
Last login: Tue Jun 5 22:29:13 2018 from 192.168.218.1
[root@localhost ~]#
主机名已更改,登陆成功。

expect脚本远程执行命令

#!/usr/bin/expect
set user "root"
set passwd "19860127"
spawn ssh $user@192.168.218.129
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
expect "]" 当我们遇到】时,
send "touch /tmp/12.txt\r" 在tmp目录下创建文件12.txt,然后回车
expect "]
"
send "echo 1212 > /tmp/12.txt\r" 打印1212到我们刚创建的/tmp/12.txt
expect "]*"
send "exit\r" 退出
添加权限
[root@linletao-001 ~]# chmod a+x 2.expect
执行脚本
[root@linletao-001 ~]# ./2.expect
spawn ssh root@192.168.218.129
root@192.168.218.129‘s password:
Last login: Tue Jun 5 22:40:40 2018 from 192.168.218.130
[root@localhost ~]# touch /tmp/12.txt
[root@localhost ~]# echo 1212 > /tmp/12.txt
[root@localhost ~]# [root@linletao-001 ~]#

expect脚本传递参数

#!/usr/bin/expect
set user [lindex $argv 0] lindex $argv 第一个参数,这个命令是将值赋予user中
set host [lindex $argv 1]
set passwd "登录机器的密码"
set cm [lindex $argv 2]
spawn ssh $user@$host expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect "]"
send "$cm\r"
expect "]
"
send "exit\r"

分发系统介绍,expect脚本远程登录,expect脚本远程执行命令,expect脚本传递参数

标签:expect

原文地址:http://blog.51cto.com/13067688/2125314

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!