【shell】【demo】expect连接主机,并在主机上执行shell脚本

柔情痞子 提交于 2021-02-01 11:14:33

【shell】【demo】expect连接主机,并在主机上执行shell脚本

 【node_ips.txt】

10.10.0.17,root,AaBbCc

10.10.0.18,root,AaBbCc

 

 

【get_tree.sh】

#!/bin/bash

typeset server_host=$1

typeset server_username=$2

typeset server_password=$3

typeset server_treefile_path=$4

 

typeset node_ip=`hostname -i"

typeset NE_arr=("NODE1" "NODE2" "NODE _C" "NODE_D" "NODE_E")

 

for NE in ${NE_arr[@]}

do 

 

case ${NE} in

"NODE_C")

  NE="NODE3"

  ;;

"NODE_D")

  NE="NODE4"

  ;;

"NODE_E")

  NE="NODE5"

  ;;

*)

  echo "pls check the array NE_arr between node1 and node5"

  exit;

esac

 

typeset node_treefile_file="/tmp/treefile_${NE}.txt"

typeset tree_param=phifsDug

tree_user=${echo ${NE}|tr '[A-Z]'  '[a-z]'}

tree_dir="/home/${tree_user}"

 

if id -u ${tree_user} >/dev/null 2>&1; then

    tree -${tree_param} ${tree_dir} > ${node_treefile_file}

    expect -c "

spawn scp -r ${node_treefile_file} ${server_username}@${server_host}:${server_treefile_path}

expect {

\"*continue*\" {send \"yes\r\";exp_continue}

\"*Password:*\" {send \"${server_password}\r\";} }

set timeout -1

expect off;"

else

    echo "[INFO] user ${tree_user} does not exsit on host IP ${node_ip}ip"

fi

 

done

 

 

 

【main.sh】

#!/bin/bash

node_path="/tmp"

node_execute_path="${nodeq_path}/treeTools"

node_tree_log="${node_execute_path}/tree_log.log"  #日志

 

curPath=`pwd`

 

typeset server_host=`hostname -i` #所有节点tree结果上传到 当前执行脚本的机器上

typeset server_username="root"

typeset server_password= "AaBbCc"

typeset server_treefile_path="${curPath}/treefiles"

mkdir -p ${server_treefile_path}

 

while read line

do

 

if [ -z ${line} ];then

  break;

fi

 

typeset node_ip=`echo ${line}|awk -F ',' '{print $1}'`

typeset node_username=`echo ${line}|awk -F ',' '{print $2}'`

typeset node_passW=`echo ${line}|awk -F ',' '{print $3}'`

 

#上传脚本到节点

expect -c "

spawn scp -r ${curPath}/get_tree.sh ${node_username}@${node_ip}:${node_path}

expect {

\"*continue*\" {send \"yes\r\";exp_continue}

\"*Password:*\" {send \"${node_passW}\r\";}

}

set timeout -1

expect off;"

 

#ssh到节点,并在节点上执行脚本

/usr/bin/expect <<-EOF

spawn ssh ${node_username}@${node_ip}

set timeout -1

expect {

\"yes/no\" {send \"yes\r\";exp_continue}

\"assword:*\" {send \"${node_passW}\r\";}

 

#识别命令行的  "~]$" ,并键入相关命令(PS1变量)

expect "~ # "

send "mkdir -p ${node_exec_path}\r"

send "mv ${node_path}/get_tree.sh ${node_exec_path}\r"

send "cd ${node_exec_path}\r"

send "sh get_tree.sh ${server_host} ${server_username} ${server_password} ${server_treefile_path} > ${node_tree_log}\r"

send "exit\r"

expect eof

EOF

 

done < ${curPath}/ips.txt

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!