shell小工具 -- 批量scp或ssh

#!/bin/sh
#批量scp文件或ssh遠程執行指令腳本,在相對路徑下創建list文件配置IP和密碼,格式:
# 10.90.10.10 asd123
# 創建command_list或file_list ,配置遠程執行的指令 或 需要scp的文件列表
cp /dev/null failed.log
cp /dev/null success.log
EXEC_HOST()
{
total=$(cat list | wc -l)
curr=0

while read ip password
do
    curr=$(($curr + 1))
    echo -e `date`"=====================================[total $total,current $curr]Begin to process $ip ....\n"
    if [ "$path" ];then
        echo "scp begin"
        command="spawn scp $path $ip:$path"
    fi
    if [ "$shell" ];then
       echo "ssh begin"
       command="spawn ssh -o ConnectTimeout=3 root@$ip \"$shell\""
    fi

    if [ "$ip" != "" ]; then
        ping -c 1 $ip > /dev/null
        ret=$?
        if [ $ret -eq 1 ]; then
            printf "%03d: %s\r\n" $iCount "ping $ip Failed,please check the network!"
            echo `date`"ping $ip fail" >> failed.log
        else
            expect -c "set timeout 20
             set passwderror 0
             $command
             expect {
                 \"*assword:*\" {
                     if { \$passwderror == 1 } {
                     puts \"passwd is error\"
                     exit 2
                     }
                     set timeout 1000
                     set passwderror 1
                     send \"$password\r\"
                     exp_continue
                 }
                 \"*es/no)?*\" {
                     send \"yes\r\"
                     exp_continue
                 }
                 \"*(y,N)*\"{
                    send \"y\r\"
                    exp_continue
                 }
                 timeout {
                     puts \"connect is timeout\"
                     exit 3
                 }
             }"
            if [ $? -ne 0 ]; then
                echo `date` "exec $shell to $ip fail" >> failed.log
            else
                echo `date` "exec $shell to $ip success" >> success.log
            fi
        fi
    fi
done < list
}

main()
{
        
    if [ -f command_list ];then
        exec < command_list
        while read shell
        do
            EXEC_HOST
        done
    elif [ -f filelist ];then
        exec < filelist
        while read path
        do
            EXEC_HOST
        done
    fi
}

main "$@"
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章