1. 程式人生 > >shell指令碼使用ssh命令連線主機,自動建立目錄,分發程式,執行命令

shell指令碼使用ssh命令連線主機,自動建立目錄,分發程式,執行命令

=========shell呼叫ssh和ftp實現多主機自動管理功能===========

  • 自動登入多臺主機建立目錄
  • 自動向指定目錄下上傳指定檔案
  • 自動修改指定檔案內容

===================================================================================

#!/usr/bin/sh

set +x

echo "指令碼分發程式開始..."
newtaskmonpath=new_taskmon
oldport=44401
oldnodeid=CRM1

for hostnode in `cat hostnode_distri.txt|grep -v "^#"`
do
        hostip=`echo $hostnode|awk -F: '{print $1}'`
        username=`echo $hostnode|awk -F: '{print $2}'`
        passwd=`echo $hostnode|awk -F: '{print $3}'`
        homedir=`echo $hostnode|awk -F: '{print $4}'`
        node=`echo $hostnode|awk -F: '{print $5}'`
        tartype=`echo $hostnode|awk -F: '{print $6}'`
        newnodeid="$node"0
        tarname="iAgent_$tartype".tar
        echo "tarname is : $tarname"

        #建立new_taskmon目錄
        cmd_create_newtaskmon="mkdir new_taskmon"
        /usr/bin/expect <<EOF
        spawn ssh -o StrictHostKeyChecking=no -l $username $hostip
        expect "password:"
        send "$passwd\r"
        expect "login:"
        send "$cmd_create_newtaskmon\r"
        send "exit\r"
        expect eof
EOF
        #(sleep 1;echo $username;sleep 1;echo $passwd;sleep 1;echo "mkdir $newtaskmonpath";sleep 1)|telnet $hostip >> distribute.log
        sleep 1

        echo "建立$newtaskmonpath完成"
        ftp -n $hostip <<! > ftp.log
        user $username $passwd
        bin
        cd $newtaskmonpath
        put $tarname
        bye
!
        echo "ftp上傳檔案完成"

        #替換制定檔案的埠
        cdnew_taskmon="cd $homedir/$newtaskmonpath"
cdnew_taskmon="cd $homedir/$newtaskmonpath"
        untariAgent="tar -xvf $tarname iAgent"
        cdiAgent="cd $homedir/$newtaskmonpath/iAgent"
        mvfile="mv iAgent1.ini bak_iAgent1.ini"
        sedini="sed 's/$oldport/45$node/g' bak_iAgent1.ini > iAgent1.ini"
        rmbakini="rm bak_iAgent1.ini"
        cdplugin="cd $homedir/$newtaskmonpath/iAgent/plugin_iagent"
        mvxml="mv libAgent.xml bak_libAgent.xml"
        sedxml="sed 's/$oldnodeid/$newnodeid/g' bak_libAgent.xml > libAgent.xml"
        rmbakxml="rm bak_libAgent.xml"

        sleep 1

        /usr/bin/expect <<EOF
        spawn ssh -o StrictHostKeyChecking=no -l $username $hostip
        expect "password:"
        send "$passwd\r"
        expect "login:"
        send "$cdnew_taskmon\r"
        send "$untariAgent\r"
        send "$cdiAgent\r"
        send "$mvfile\r"
        send "$sedini\r"
        send "$rmbakini\r"
        send "$cdplugin\r"
        send "$mvxml\r"
        send "$sedxml\r"
        send "$rmbakxml\r"
        send "exit\r"
        expect eof
EOF
sleep 1

done

############################################################################################33

hostnode_distri.txtl格式如下

#主機ip:主機使用者名稱:主機密碼:主機home目錄:hostnode_def表nodeid前三位:主機作業系統型別:shell型別
127.0.0.1:username:password:/homebds/bdsa1:251:AIX:#!/usr/bin/ksh