Skip to content

Instantly share code, notes, and snippets.

@Ivlyth
Created January 31, 2015 04:15
Show Gist options
  • Save Ivlyth/6a49d00088241795ea0f to your computer and use it in GitHub Desktop.
Save Ivlyth/6a49d00088241795ea0f to your computer and use it in GitHub Desktop.
利用 pexpect 模块来实现自动通过堡垒机登陆服务器
#!/usr/bin/env python
# -*- coding:utf8 -*-
'''
Author : myth
Date : 14-12-11
Email : belongmyth at 163.com
'''
import pexpect
import json
import urllib2
import sys
import struct, fcntl, termios, signal
REMOTE_IP = 'REAL IP HERE'
def get_ip(v):
if v=='60':
return 'REAL IP A'
if v=='5':
return 'REAL IP B'
if v=='8':
return 'REAL IP C'
if v=='61':
return 'REAL IP D'
return v
if len(sys.argv)>=2:
REMOTE_IP = get_ip(sys.argv[1])
# Tan14Key
Tan14Key = 'REAL KEY'
child = None
def get_password():
for i in range(5):
try:
req = urllib2.Request('API ADDR')
res = urllib2.urlopen(req).read()
data = json.loads(res)
return data['password']
except Exception as e:
pass
else:
return None
_msg_buff = []
class STDOUT:#standard output
@classmethod
def write(self,msg):
_msg_buff.append(msg)
@classmethod
def flush(cls):
pass
def sigwinch_passthrough(sig, data):
s = struct.pack("HHHH", 0, 0, 0, 0)
r = fcntl.ioctl(sys.stdout.fileno(), termios.TIOCGWINSZ , s)
a = struct.unpack('hhhh', r)
global child
child.setwinsize(a[0],a[1])
signal.signal(signal.SIGWINCH, sigwinch_passthrough)
def run_autossh():
global child
user = 'user name'
baolei_domain = 'a domain'
ssh_cmd = 'ssh %(user)s@%(baolei_domain)s -p 36899'%{'user':user,'baolei_domain':baolei_domain}
child = pexpect.spawn(ssh_cmd)
child.logfile = STDOUT
index = child.expect(["%(user)s@%(baolei_domain)s's password:"%{'user':user,'baolei_domain':baolei_domain},'Are you sure you want to continue connecting (yes/no)?',pexpect.EOF,pexpect.TIMEOUT])
if index > 1:
return False
if index == 1:
child.sendline('yes')
index = child.expect(["%(user)s@%(baolei_domain)s's password:"%{'user':user,'baolei_domain':baolei_domain},pexpect.EOF,pexpect.TIMEOUT])
if index != 0:
return False
password = get_password()
if password is None:
return False
child.sendline(password)
index = child.expect(['Please Enter Your Choose:',pexpect.EOF,pexpect.TIMEOUT])
if index != 0:
return False
child.sendline(REMOTE_IP)
index = child.expect(['#','Are you sure you want to continue connecting (yes/no)?',pexpect.EOF,pexpect.TIMEOUT])
if index > 1:
return False
if index == 1:
child.sendline('yes')
index = child.expect(['#',pexpect.EOF,pexpect.TIMEOUT])
if index != 0:
return False
child.sendline('')
child.expect(['#',pexpect.EOF,pexpect.TIMEOUT])
sigwinch_passthrough(None,None)
child.sendline('')
return True
if __name__ == '__main__':
r = run_autossh()
if r:
print 'Enjoy yourself...'
child.interact()
else:
print 'SSH Login Error ...'
print '\n'.join(_msg_buff)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment