Making An SSH Connection In Python Using PXSSH: Hacking With Python Series

The pxssh library is a part of pexpect package in python. Pxssh library provides you the way to connect as SSH client to SSH enabled servers, it handles the keys itself, so you don’t need to specially specify any line of code for it. I find it quite easier for making bruteforcing script via this particular library. But if you are looking for something that will also help you upload anything on other server then you better use Paramiko, it provides uploading capabilities too.

Let’s get on with the code:

I have provided the explanation within the code itself in # as comments. If you do not understand something, feel free to ask via comments.

Code:

#!/usr/bin/python

# importing only pxssh from pexpect
from pexpect import pxssh
import sys

#connect is my own function which takes address,username and password as command line arguments
def connect(addr,username,password):
user=username
passwd=password
print("Trying to connect...")

try:
s= pxssh.pxssh() #s is an object for pxssh

#here in this conditional statement we will check if login is successfully dont or not, if not then print "SSH connection failed"
if not (s.login(addr,user,passwd)):
print("SSH Connection failed")
else:
print("SSH connection established with "+user+" : "+passwd)

#once the login has been successfully done, the lines below will help us send commands to the connected SSH server and print the output on our console
s.sendline('whoami')
s.prompt()
print(s.before)
s.logout()

except Exception as r:
print(r)

if len(sys.argv) < 4: print('Not enough arguments\n>>hostname,username,password required.')
else:
address=sys.argv[1]
username=sys.argv[2]
password=sys.argv[3]
connect(address,username,password) 

OUTPUT:

pxssh usage in python

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: