公司线上机器需要用堡垒机登录,堡垒机登录密码中有google动态密码(google authentication),每次登录都需要查看手机app里面的动态密码,十分不便,实在受不了了撸了个自动登录脚本#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import pexpect
import hmac, base64, struct, hashlib, time
hosts = [
{
"ip":"192.168.1.1",
"prot":"22",
"user":"****",
"password":"********",
"type":"堡垒机",
"options":{
"google_secret_key":"*******"
}
}
]
def get_google_code(secret_key):
key = base64.b32decode(secret_key)
msg = struct.pack(">Q", int(time.time())//30)
googleCode = hmac.new(key, msg, hashlib.sha1).digest()
o = ord(googleCode[19]) & 15
googleCode = str((struct.unpack(">I", googleCode[o:o+4])[0] & 0x7fffffff) % 1000000)
if len(googleCode) == 5:
googleCode = '0' + googleCode
print "google 动态密码:%s" % (googleCode)
return googleCode
def connection(cmd, pwd):
child = pexpect.spawn(cmd)
i = child.expect([".*assword.*", ".*ontinue.*?", pexpect.EOF, pexpect.TIMEOUT])
if( i == 0 ):
child.sendline("%s\n" % (pwd))
child.interact()
elif( i == 1):
child.sendline("yes")
child.expect(['password:'])
child.sendline("%s" % (pwd))
else:
print "连接失败"
print "序号 | ip | 端口 | 用户 |类型"
for i,host in enumerate(hosts):
print "%s |%s|%s|%s|%s" % (i+1,host['ip'],host['prot'],host['user'],host['type'])
no = input("输入序号:")
host = hosts[no-1]
if host["type"] == "堡垒机":
host["password"] = "%s%s" % (host["password"],get_google_code(host['options']['google_secret_key']))
cmd = "ssh -p %s %s@%s" % (host['prot'],host['user'],host['ip'])
connection(cmd,host["password"])