python + expect + list = goto myip

简介

对于工程师来讲,服务器是必不可少的工具,我们上班大部分时间是在使用ssh这样的软件去登录,但是林子大了,啥鸟都有,群体需要保护,在你和服务器之间,有了堡垒机,每次登录都需要先登录堡垒机,然后登录服务器,So,

难道我们想浪费我们价值1000$/hour的time在登录服务器的过程中吗?
当然Say: NO!

思路很简单,
1. 我们需要借助expect来模拟我们登录服务器的过程。文件名denglu
2. 我们需要借助一个账号密码本,来记录我们的ip地址和对应的password。文件名list
3. 我们需要一个脚本来连接denglu和list。文件名goto

总结:
goto myip

读取list找到对应的ip地址和对应的密码
调用denglu来模拟登录

/bin/goto

#!/usr/bin/env python
#coding: utf8
# fileName: goto

import os,sys,re

host = sys.argv[1]

matchedline = []
for line in open("/bin/list"):
    result = re.findall(host,line)
    if len(result) == 1:
        matchedline.append(line)

if len(matchedline) == 1:
    secretline=matchedline[0]
    print "Found the machted line."
    value = re.findall("\S+",secretline)
    if len(value) == 2:
        print "Get the password from file."
        print value
    else:
        print "Please check your config file list."
        exit(1)
    print value
    host = value[0]
    passwd = value[1]
    os.system("/bin/denglu %s \"%s\""%(host, passwd))
else:
    print "No Not Find Matched. Exit............."

/bin/denglu

#!/usr/bin/expect -f 
# fileName: denglu

#log_file /tmp/1.txt

set username "yourName"
set password "yourPasswd"

# This is very important.
set HOST [lindex $argv 0]
set serverpassword [lindex $argv 1]
set timeout 30

#发给自己看的 
#send_user "$serverpassword"
#exit

# connect via ssh
spawn ssh -o StrictHostKeyChecking=no xxx@xxx.xxx.xxx -p xxxx

#######################
expect {
    -re "yes/no.*" {
        exp_send "yes\r"
        exp_continue
    }
    -re "password:.*" {
        exp_send "$password\r"
    }
}

expect {
    -re ">.*" {
        exp_send "ssh root@$HOST\r"
    }
}

expect {
    -re "yes/no.*" {
       exp_send "yes\r"
       exp_continue
    }
    -re "assword:.*" {
        exp_send "$serverpassword\r"
        #puts $serverpassword
        puts "**********"
    }
    -re "yes/no.*" {
       exp_send "yes\r"
       exp_continue
    }
}

expect {
    -re "yes/no.*" {
       exp_send "yes\r"
       exp_continue
    }
    -re "#.*" {
        interact
    }

}

/bin/list

ip1 password1
ip2 password2

goto denglu list三个文件我都放在了/bin下面,当然chmod a+x一下,然后使用命令goto ip1来登录。

Enjoy~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值