shell练习-expect批量同传文件或目录

可一次scp多个文件或目录

默认host.txt路径,与脚本同目录,也可指定host.txt

如果有ping超时服务器会显示在最后一行

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/bin/bash
#功能:可一次scp多个文件或目录,到服务器群组的/tmp目录下
#host.txt文件,默认位置在脚本同级目录
#注:scp多个文件或目录,使用空格分隔!

#远端存放目录
#注:远端目录必须存在(未做判断处理)
FEDIR=/tmp

#需要scp文件或目录
read -p "Please enter the path of SCP:" SCPPATH

for i in `echo $SCPPATH`
do
if [ -d $i -o -f $i  ];then echo "path:$i" ;SCPFILE="$SCPFILE $i" ;else echo "Error,NO path:$i";exit;fi
done
echo "SCPLIE:$SCPFILE"
#脚本路径
SHPATH=`readlink -f $0`
SHDIR=`dirname $SHPATH`

#分隔
echo
#host.txt文件
echo "host.txt template: IPADD  USER  PWD"
echo "input Enter(default path:$SHDIR/host.txt)"
read -p "Please enter the path to host file:" HOSTPATH
if [ -z $HOSTPATH ];then HOSTPATH=$SHDIR/host.txt;fi
if [ ! -f $HOSTPATH ];then "Error,NO path:$HOSTPATH";exit;fi
if [ "$(cat $HOSTPATH|grep -Ev "^ |^#|^$"|awk '{print NF}'|sort -nr|head -n1)" -lt 3 ];then echo "Error,host template: IPADD  USER  PWD";exit;fi



#host.txt文件行数
HOSTNUM=`cat $HOSTPATH|wc -l`

#start
for i in `seq $HOSTNUM`
do
sed -n "$i"p $HOSTPATH|grep -Ev "^#|^ |^$" >/dev/null
    if [ $? -eq 0 ];then
    IPADD=`sed -n "$i"p $HOSTPATH|awk '{print $1}'`
    USER=`sed -n "$i"p $HOSTPATH |awk '{print $2}'`
    PWD=`sed -n "$i"p $HOSTPATH  |awk '{print $3}'`

            #ping-server
            ping -c 1 $IPADD >/dev/null
            if [ $? -eq 0 ];then

            echo "==========================scp $IPADD  start   =========================="
            expect <<EOF |tail -n +3

                    set timeout -1;
                    spawn scp -r $SCPFILE $USER@$IPADD:$FEDIR
                    expect {
                            "yes/no" { send "yes\n";exp_continue }
                            "s password" { send "$PWD\n" }
                    }
                    expect eof
EOF
            echo "==========================scp $IPADD  end =========================="
            echo
            else

            echo "--------------------------$IPADD      timeout --------------------------"
            TIMEOUT="$TIMEOUT,$IPADD"
            echo
            fi
    fi
done
if [ -n  "$(echo $TIMEOUT|tr -d ',')" ];then echo "TIMEOUT=$TIMEOUT";fi