Making an SSH connection in Python using Paramiko: Hacking with Python Series

Paramiko is a python library providing SSHv2 protocol. It provides Client and Server feature. I have given the introduction in last article, in case you have missed it, here is the link: http://www.anonhack.in/2018/06/hacking-with-python-series-python-libraries-for-ssh/.

Let’s get on with the code because nothing is more interesting than the code itself.

Before, you run the code install the Paramiko library.

Command to install: pip install paramiko

Command to upgrade it: pip install –upgrade paramiko

Explanation for the code below:



param_ssh(addr,user,passwd): is the function I have created that takes hostname of the target machine with the username and password.


client = paramiko.SSHClient() : With this code we are creating an object for paramiko.SSHClient(). This object will handle all our requests and commands. You can name it anything.


client.set_missing_host_key_policy(paramiko.AutoAddPolicy()): This line handles the key policies, Add keys to the local hostkey lists. This line must be specified because key handling is important while making a connection.


sock=socket.socket()

ip=socket.gethostbyname(address) :
These two lines make a connection with the host to get the IP address. I added this line because I felt there is a need to add it if you enter a domain name and not a proper IP address. Must be enclosed in try and Except Block.


client.connect(ip, username=username, password=password, look_for_keys=False): This line will then make a SSH connection using ip, username, password and look_for_keys=False will set the search of private keys in the local machine to false. This ways it will make connection using password only.


print(“Connected Successfully with “+username+”:”+password)

stdin,stdout,stderr=client.exec_command(‘whoami’)

outlines=stdout.readlines()

resp=”.join(outlines) print(resp)

The above lines of code handles the std input and output when the connection has been successfully made. You can use interactive command so as to communicate with the server.



Code:

#!/usr/bin/python
import paramiko
import socket
import sys
#A variable 'e',this will act as a flag. You can also define it inside the function itself.
e=0

#A function I have defined that takes arguments addr as hostname,user as username,passwd as password
def param_ssh(addr,user,passwd):

        global e              #Making use of variable e in the function
       #Assigning the values
	username=user
	password=passwd
	address=addr
	#just a print line
  	print("Connecting to server...")

#defining an object for SSHClient(). client will act as a handler here. You can name it anything
       	client = paramiko.SSHClient()

#This handles the missing Keys while connecting to the server. It will add the host keys locally if not present.
       	client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
	try:
		sock=socket.socket()    #normal socket object 
		ip=socket.gethostbyname(address)  #getting IP address
		client.connect(ip, username=username, password=password, look_for_keys=False)   # Making connection 
		
	except Exception as r:
		e=1   #if exception is raised value of e will turn 1. Showing failue message
		print("[-]"+str(r)+" \nWrong credentials "+username+":"+password)
	
	#if the value of e stays 0 that means the connection has been made successfully then below lines will run	
	if(e==0):
		print("Connected Successfully with "+username+":"+password)
		stdin,stdout,stderr=client.exec_command('whoami')  #creating stdin,stdout,stderr command execution
		outlines=stdout.readlines()  #reading the terminal output
		resp=''.join(outlines)
		print(resp)
#checker for arguments
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]
	param_ssh(address,username,password)	


OUTPUT:

Paramiko ssh in python

Leave a Reply

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