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
(责任编辑:IT)#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!" |