Sunday, October 24, 2021

[SOLVED] Cannot authenticate to SSH server with correct credentials (username and password) read from a local file

Issue

I'm making a small program that connects into an SSH server, testing multiple usernames and passwords that are inside a .txt file. The problem I'm having is when it get to the correct username and password it doesn't connect, or at least my if statement doesn't properly say it.

If I do pass it as regular variable or just set the username = 'correct user' ,password = 'correct password', it works. Here's part of the code, I'm testing in a local environment with a Linux VM:

# read files
fs = open('users.txt','r')
users = fs.readlines()
fs.close()
fs = open('passwords.txt','r')
psswds = fs.readlines()
fs.close()

# connect and test the password
for user in users:
    for psswd in psswds:
        try:        
            print(usuario)
            print(senha)
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            con = ssh.connect(ip,port,username = user,password = psswd)
            if con is None:
                print ('yes')
                break
            else:
                print ('nop')
            SSHClient.close()
        except paramiko.AuthenticationException:
            print('User and/or password incorrect')

Solution

When you use readlines, it keeps trailing new line characters in the lines.

So you are actually connecting with wrong credentials as both your username and password contain new line, which is not a part of the correct credentials.

See Getting rid of \n when using .readlines().



Answered By - Martin Prikryl