利用Expect来实现自动交互传输文件
run_file.exp 脚本解决ssh交互问题
#!/usr/bin/expect
if { $argc != 3 } {
puts "Usage: expect $argv0 file host dir"
exit
}
set file [lindex $argv 0]
set host [lindex $argv 1]
set dir [lindex $argv 2]
set password "test"
spawn scp -P22 -rp $file root@$host:$dir
expect {
"yes/no" {send "yes\r";exp_continue}
"*password" {send "$password\r"}
}
expect eof
run_cmd.sh 利用 shell 循环执行 Expect 脚本命令,批量传输文件
#!/bin/bash
#Author:mcsiberiawolf
#Time:2019-02-13 10:57:07
#Name:cp_file.sh
#Version:V1.0
#Description: This is a test script.
if [ $# -ne 2 ]; then
echo $"Usage:$0 file dir"
exit 1
fi
file=$1
dir=$2
for n in 2 3
do
expect cp_file.exp $file 192.168.7.$n $dir
done
示例
[root@ansible expect]# ls
a.txt cp_file.exp cp_file.sh run_cmd.exp run_cmd.sh
[root@ansible expect]# sh cp_file.sh a.txt ~
spawn scp -P22 -rp a.txt root@192.168.7.2:/root
root@192.168.7.2's password:
a.txt 100% 0 0.0KB/s 00:00
spawn scp -P22 -rp a.txt root@192.168.7.3:/root
root@192.168.7.3's password:
a.txt
# 查看文件是否传输成功
# 可用前文中 https://www.cnblogs.com/mcsiberiawolf/articles/10368313.html 中的 run_cmd.sh 和 run_cmd.exp 脚本
[root@ansible expect]# sh run_cmd.sh "ls -l ~"
spawn ssh root@192.168.7.2 ls -l ~
root@192.168.7.2's password:
total 4
-rw-------. 1 root root 2052 Jan 30 16:47 anaconda-ks.cfg
-rw-r--r--. 1 root root 0 Feb 13 10:59 a.txt
spawn ssh root@192.168.7.3 ls -l ~
root@192.168.7.3's password:
total 4
-rw-------. 1 root root 2050 Jan 30 16:49 anaconda-ks.cfg
-rw-r--r--. 1 root root 0 Feb 13 10:59 a.txt
参考文章
跟老男孩学Linux运维 Shell编程实战