python + expect + list = goto myip

  • Post author:
  • Post category:未分类
  • Post comments:0评论

简介

对于工程师来讲,服务器是必不可少的工具,我们上班大部分时间是在使用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~


版权声明:本文为vbaspdelphi原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。

发表评论