分发系统介绍,expect脚本远程登录, expect脚本远程执行命令, expect脚本传递参数...
发布日期:2021-08-26 18:18:50 浏览次数:53 分类:技术文章

本文共 2163 字,大约阅读时间需要 7 分钟。

分发系统介绍

当我们要上线一个新代码的时候,如果机器少,我们的工作量不会很大,很容易完成,如果设备很多,有几十台,上百台的话,那我们的工作量会非常大,而且也不规范,这时,我们就可以用可以用开源的软件,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"

转载于:https://blog.51cto.com/13067688/2125736

转载地址:https://blog.csdn.net/weixin_33894640/article/details/92718112 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:python-->上传与下载文件详解
下一篇:七周三课 Linux网络、firewalld和netfilter、netfilter5表5链等

发表评论

最新留言

逛到本站,mark一下
[***.202.152.39]2024年04月17日 14时06分38秒