linux expect自动telnet对server做验证

有时候我们在产品发布之前可能面临需要对大量的服务器做环境验证,比方说在上百台server上验证文件是否存在,查看某个端口是否打开。 而我们又对服务器有很少的控制权限时,linux expect 是个不错的选择。

由于对expect不是很熟,写的比较乱

#########validateServer.sh

#!/bin/sh

if [ "$1" = "" ] || [ "$2" = "" ]; then
    echo "invalid parameters"
else
    for server in `cat $1`; do
        echo "---------->" $server
        ./validateServer.expect "ssh username\@$server" "$2" password
    done
fi

 

#########validateServer.expect

#!/usr/local/bin/expect -f

if {$argc!=3} {
    send_user "usage: validateServer.expect host command password\n"
    send_user "\teg. validateServer.expect \"ssh user@host\" \"ls -l\" password\n"
    send_user "\tCaution: command should be quoted.\n"
    exit
}

set host [lindex $argv 0]
set command [lindex $argv 1]
set password [lindex $argv 2]
eval spawn $host

expect {
    "Are you sure you want to continue connecting (yes/no)?" {
        # First connect, no public key in ~/.ssh/known_hosts
        send "yes\r"
        expect "assword:"
        send "$password\r"
    } 
    "Enter passphrase for key " {
        # Already has public key in ~/.ssh/known_hosts
        send "$password\r"
    }
    "assword:" {
        # Already has public key in ~/.ssh/known_hosts
        send "$password\r"
    }
    "Permission denied, please try again." {
        # Password not correct
        exit
    } 
    "Connection refused" {
        exit
    }
}

set timeout 2
expect "/ $"
send "$command\n"
expect {
   "Escape character is '^]'." {
        sleep 2
        send -- "\x1d"; # This is the hex value for ^]
        expect "telnet> "
        send -- "q\r"
   }
}
expect "/ $"
send "exit\n"

set timeout 30
expect {
    timeout {
        send_user "timeout...\n"
        exit
    }
    eof {
        send_user "exit....\n"
        exit
    }
}

exit 0

server列表

#### server_list.data
thejtechs-1.com
thejtechs-2.com
thejtechs-3.com
thejtechs-4.com

测试:

./validateServer.sh server_list.data "telnet www.thejtechs.com 80"
参考: http://www.thejtechs.com/blogDetail/74/linux-auto-telnet-for-server-validation

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值