#!/usr/bin/expect
#Create Date: 2014-9-28
set f [open file r]
# 以只读方式打开普通文件file,并将其赋值给变量f;本例中file文件中记录了"ip 普通用户 密码 root用户 密码 端口"
# 如"192.168.0.13 mosys 123456 root w123456 62300"
# "192.168.0.15 mosys 123456 root w123456 62300"
while { [gets $f line] >= 0 } {
set timeout 30
# 设置超时时间,单位秒,-1为永不超时
set host [lindex $line 0]
# 提取file文件中的第一个参数赋值给变量host;
set user1 [lindex $line 1]
set passwd1 [lindex $line 2]
set user2 [lindex $line 3]
set passwd2 [lindex $line 4]
set port [lindex $line 5]
set scripts1 /expect/scripts/sys.sh
set scripts2 /expect/scripts/sys.exp
spawn scp -P $port -rqp $scripts1 $scripts2 $user1@$host:/home/$user1
expect {
"yes/no" {send "yes\r";exp_continue}
"*assword" {send "$passwd1\r"}
}
expect "100%"
spawn ssh -p $port $user1@$host
expect {
"yes/no" {send "yes\r";exp_continue}
"*assword" {send "$passwd1\r"}
}
expect "from"
send "su -\r"
expect "*assword"
send "$passwd2\r"
send "cd /home/$user1\r"
send "sh sys.sh\r"
send "rm -fr sys\*\r"
send "exit\r"
expect "logout"
send "exit\r"
expect eof
#interact #(保持交互状态,此脚本中不需要)
}
close $f
sys.sh和sys.exp 是推送到目标服务器执行的脚本,用于测试,作用是收集指定的信息并将结果发送回来
内容如下
sys.sh
#!/bin/bash
#Create Date: 2014-9-28
netstat -ntpl > 1.txt
ps aux > 2.txt
df -Hh > 3.txt
free -m > 4.txt
date=`date +%Y-%m-%d`
ip=$(ifconfig eth0|grep -oP '(?<=addr:)[\d.]+(?=\s*Bcast)')
bakdir=sys_$ip\_$date.tar.gz
tar -zcvf $bakdir 1.txt 2.txt 3.txt 4.txt >& /dev/null
rm -fr *.txt
if [ -e $bakdir ]
then
./sys.exp $bakdir
fi
sys.exp
#!/usr/bin/expect
set user root
set passwd w123456
set host 192.168.0.14
set dir [lindex $argv 0]
set timeout 30
spawn scp -rqp $dir $user@$host:/expect/log
expect {
"yes/no" { send "yes\r";exp_continue }
"*assword" { send "$passwd\r" }
}
expect eof
阅读(1527) | 评论(0) | 转发(0) |