Shell 之批量執行傳輸文件


利用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編程實戰


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM