使用expect登录自动远程服务器和执行重复任务

1.使用expect登录跳板机

#!/usr/bin/expect -f

set TERMSERV ***
set USER ***
set PASSWORD ***

# Start the session
catch {spawn ssh -l $USER $TERMSERV}

# Login
expect "*assword:*" { send "$PASSWORD\r" }
expect "*server:*" { send "1\r" }
expect "*bash*3.2*" { send "cd /tmp\r"; interact }  #把控制权交给用户

#通过跳板机登录线上机器
expect "*bash*3.2*" { send "ssh -l nobody ***\r" }
expect "*assword:*" { send "***\r" }
expect "*bash*3.2*" { send "cd /home/admin\r"; interact }

2.登录远程服务器并执行特定的任务

#!/usr/bin/expect -f

set USER nobody
set PASSWD viewlog
set SERVER_HOST [lindex $argv 0]
set REGEXP [lindex $argv 1]
set LOG_FILE [lindex $argv 2]
set TMP_FILE_NAME [lindex $argv 3]

catch {spawn ssh -l $USER $SERVER_HOST}
expect {
"*yes/no*" { send "yes\r" }
"*assword:*" { send "$PASSWD\r" }
}
expect "*nobody*" { send "egrep '$REGEXP' $LOG_FILE > /tmp/$TMP_FILE_NAME\r" }
expect "*nobody*" { send "exit\r" }

catch {spawn scp $USER@$SERVER_HOST:/tmp/$TMP_FILE_NAME $TMP_FILE_NAME}
expect "*assword:*" { send "$PASSWD\r" }
expect "*wuzhong*" { send_user "ok!!!" }

3.在多台服务器上执行相同的任务

#!/bin/bash

#set -x

servers=(
10.232.11.93
10.232.10.79
)

tmp=tmp_wz
i=0
for server in ${servers[*]}
do
i=$(($i+1))
./grepandscp.tcl $server "^ERROR" "/home/admin/wtm/logs/wtm.log" "${tmp}$i"
done
echo "task is over!"
 

猜你喜欢

转载自jiawu.iteye.com/blog/888535