批量登陆linux服务器,linux 使用expect批量自动使用ssh登录多台服务器

#!/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

阅读(1088) | 评论(0) | 转发(0) |

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值