python脚本自动登录_python ssh自动登录脚本

公司线上机器需要用堡垒机登录,堡垒机登录密码中有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"])

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值