Loading

Linux expect 远程自动登录机器并执行命令

0 运行环境

  • 两台虚拟机:Ubuntu 18 x64

  • Xshell 6

1 expect 介绍

expect 是一个自动化交互套件,主要应用于执行命令和程序时,系统以交互形式要求输入指定字符串,实现交互通信。

注意 expect 脚本能够执行的前提是本地机器安装了 expect

1.1 expect 安装

安装命令为:

sudo apt install expect

1.2 expect 自动交互流程

  1. spawn 启动指定进程

  2. expect 获取指定关键字

  3. send 向指定程序发送指定字符

  4. 执行完成退出

1.3 expect 常用命令

spawn               交互程序开始后面跟命令或者指定程序
expect              获取匹配信息匹配成功则执行expect后面的程序动作
send exp_send       用于发送指定的字符串信息
exp_continue        在expect中多次匹配就需要用到
send_user           用来打印输出 相当于shell中的echo
exit                退出expect脚本
eof                 expect执行结束 退出
set                 定义变量
puts                输出变量
set timeout         设置超时时间

2 expect 使用普通用户登录远程主机,并通过 sudo 到 root 权限,执行多条命令

2.1 代码

doExpect.sh

#! /usr/bin/expect

#	功能:
#		远程主机,备份旧文件,并用新文件替换旧文件
#
#	前置条件:
#		通过命令行参数,传入 远程主机 IP,用户名,密码,旧文件,旧文件备份的名字,新文件
#
#	输出:
#		无

if {$argc < 6} {
	send_user "usage: <ip> <username> <password> <old_file> <old_bf_file> <new_file>\n"
	
	exit
}

set ip [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]

# 旧文件
set old_file [lindex $argv 3]
# 旧文件备份
set old_bf_file [lindex $argv 4]
# 新文件
set new_file [lindex $argv 5]

spawn ssh $username@$ip "sudo su -"

expect {
"Are you sure you want to continue connecting (yes/no)?" {send "yes\r"}
"password:" { send "$password\r"}
}

expect "*]#"

# 备份旧文件
send "cp $old_file $old_bf_file\r"
# 用新文件替换旧文件
send "cp $new_file $old_file\r"

expect eof

2.2 运行与结果截图

2.2.1 执行前

本地电脑 上放着 expect 脚本,如下所示:

远程电脑 上放着旧文件 old.txt 和新文件 new.txt ,如下所示:

old.txt 中内容,如下所示:

new.txt 中内容,如下所示:

2.2.2 执行程序与结果

本地电脑 上不带任何参数运行 expect 脚本,会出现提示,如下所示:

本地电脑 上正常运行 expect 脚本,如下所示:

此时运行成功,查看远程电脑的文件

此时 old.txt 里的内容已经被 new.txt 替换,如下所示:

而查看 old.bk 里的内容正是原来的 old.txt 里的内容,如下所示:

成功达成预期!

3 参考文献

1、Linux expect 介绍和用法 - saneri(梦徒)- https://www.cnblogs.com/saneri/p/10819348.html

posted @ 2021-01-29 10:38  她爱喝水  阅读(735)  评论(0编辑  收藏  举报