Skip to main content

How to Connect Client Machine via SSH using Python


Python Secret #Author: ManishHacker1

Hello everyone, Today we will learn very interesting topic how to use SSH using python. In this article we will learn about SSH and how to connect your maching via ssh using python and how to run command on it.

Today we will make an automatic python script which is connect your one machine to another machine. Where do you play some interesting stuffs.

Most of time I think why we are using software. Why do we not make it?? If You are computer science student expand your mind and create your own software.

Python is an open source programming language and free also. Python has very huge library.
So now, we concentrate on our main topic. We will use pxssh class of the pexpect module in Python which is used to to take care of some of the automation needs, like ssh and ftp etc.

What is Pxssh?

pxssh class used to connect our client machine.This class extends pexpect.spawn to specialize setting up SSH connections. This adds methods for login, logout, and expecting the shell prompt. It does various tricky things to handle many situations in the SSH login process.For example, if the session is your first login, then pxssh automatically accepts the remote certificate; or if you have public key authentication setup then pxssh won’t wait for the password prompt.

Read Full Documentation

Before we start our script. We should know about some circumstances. Pexpect module fully not support on windows machine. If you use python 2.x version this module take some import errors. So now we will do demonstration for the Linux machine users.

If you have 2.7.3 in your Linux machine support only "import pxssh" and If you have latest version we will use pexpect in our script. For example:

from pexpect import pxssh

First open your linux machine for example Ubuntu or which you want. In my case i am using kali linux because python is pre install in Kali Linux. I am using Kali Linux 1 where python 2.7.3 is installed. This is not big deal. If you want to update your machine or if you use python 3.x version. Still our script will be same.

Note:Before this process please start your SSH server in your client machine.
If you don't have SSH server in your client machine first install it:
Type in your terminal:


apt-get install openssh-server
service -status -all
service ssh start

Lets Start:


from pexpect import pxssh
import getpass
try:
    s = pxssh.pxssh()
    hostname = raw_input('hostname: ')
    username = raw_input('username: ')
    password = getpass.getpass('password: ')
    s.login(hostname, username, password)
    s.sendline('uptime')   # run a command
    s.prompt()             # match the prompt
    print(s.before)        # print everything before the prompt.
    s.sendline('ls -l')
    s.prompt()
    print(s.before)
    s.sendline('df')
    s.prompt()
    print(s.before)
    s.logout()
except pxssh.ExceptionPxssh as e:
    print("pxssh failed on login.")
    print(e)

The above script save as "anyname.py" in any location. Where .py is extension. In my case I save my script on Desktop.

After that open your terminal and change your path where your python script is put.


After that type:

python connect.py   and press enter button.

Where connect.py is my python script name.

You can see a prompt. Put your hostname.
For example:you ip address

Open new terminal and find your computer ip or we will need client machine IP whose we want to connect.


hostname: 192.168.201.132

After that put your client machine's username.

username: root


Next, put your client machine's password.

password:toor    and press enter


you can see in above picture. we have successfully connect our client machine and run three commands.

  • uptime
  • ls -l
  • df

The above commands work using these below line in my program.


    s.sendline('uptime')   # run a command
    s.prompt()             # match the prompt
    print(s.before)        # print everything before the prompt.
    s.sendline('ls -l')
    s.prompt()
    print(s.before)
    s.sendline('df')
    s.prompt()
    print(s.before)
 

After that successfully logout using s.logout fuction.

Well, If you want to use many commands we will make a automatic script which will work like professional software which connect automatically to your client machine and when you put your command our script will show you the output.

And again you can put your next command.

Sorce Code:


import pxssh
def goto(linenum):
    global line
    line = linenum
s = pxssh.pxssh()
if not s.login ('192.168.201.132', 'root', 'toor'):
    print "SSH session failed on login."
    print str(s)
else:
    print "SSH session login successful"
    line = 1
    while True:
        mm = raw_input("Enter Your Command > ")
        s.sendline (mm)
        s.prompt()         # match the prompt
        print s.before     # print everything before the prompt.
        goto(1)

In the first step, we import everything we need and assign machine details to variables like.

import pxssh

If you use python 2.7.13 or 3.x you will use:

from pexpect import pxssh

After that we will define a funtion which is used for the loop.


def goto(linenum):
    global line
    line = linenum

Now our important step is that we will put client machine ip, username and password in our script which join us at the same time as our client machine.
For this we will use "s.login" fuction.

s.login ('192.168.201.132', 'root', 'toor'):

Where first, put host IP, after that put username and lastone is password.
Great... The above script save as "anyname.py" in any location. Where .py is extension. In my case I save my script on Desktop.
After that open your terminal and change your path where your python script is put.


After that type:

python connect1.py   and hit enter. 

Where connect1.py is my script name.


In the above pic, You can see a prompt where you can put your command. After that press enter button.


You can see in the above picture. We put "ls" command and press enter button. And we find output. And our script ready to next command.
Well, you can access all information of your client machine using commands.

If you want to terminate your session type:

exit


I hope you will have enjoyed read this article. In my next article we will learn how to crack SSH password using Python.

If you want to learn more interesting articles subscribe,share and like it.
Thank you very much for your support and love.

Best Python Training and Ethical Hacking Training in Meerut, Noida , Delhi.

Thank You for reading this article. And also like my FB page givin below link and share it.

Krypsec Digital Security Provided Python Training and Ethical Hacking Training
  • Best Python Training in Noida
  • Best Python Training in Delhi
  • Best Python Training in Meerut
  • Best Python Training in India
  • Best Ethical Hacking Training in Noida
  • Best Ethical Hacking Training in Delhi
  • Best Ethical Hacking Training in Meerut
  • Best Ethical Hacking Training in India

Follow ManishHacker1

Comments

Popular posts from this blog

How to create Folder Lock with Password Protected using Python

Amazon.in Widgets Python Blog #Author: ManishHacker1 Hello guys, Today we will be learn how to create folder lock with password protected using Python programming language. What is Folder Lock? Folder Lock is a data security software that is allows its users to encrypt thier files and folder. Lock, hide and password protects files and folder on your computer. You can use Folder Lock to secure your files and folder on windows. So, I am going to tell you how to make your own Folder Lock, without using any software. Pre-Reuisites: You will need only pyhton installed in your operating system. if you want to distribute your Folder Lock then you will be also need pyinstaller using to convert our python file to .exe file. Compatibility: Compatible with any Microsoft Windows Operating system. Instructions: First open your python IDE or Notepad, where you want to write code. If you use to notepad please remember indentation using to write code. Or copy th...

How to Connect Window Machine to Linux Machine Using Python via SSH

Python Secret #Author: ManishHacker1 Hello everyone, This is my another article about SSH connectivity to the client machine. In my previous article we have some trouble using pxssh module on windows machine. That's why I am writing another article for the SSH connection. In this article we will use paramiko module to connect another machine. This is fully supported windows, Mac and Linux machine users. In this article, I will show you how to use Paramiko SSH (a Python SSH library) to connect and gather information from another Machine. What is Paramiko? Paramiko is a Python (2.6+, 3.3+) implementation of the SSHv2 protocol [1], providing both client and server functionality. While it leverages a Python C extension for low level cryptography (Cryptography), Paramiko itself is a pure Python interface around SSH networking concepts. Read Full Documentation Let start our demonstration: Requirment: Paramiko( For SSH connection) How to Install paramilko modu...

How to Create MD5 Brute Force Script Using Python

Python Secret #Author: ManishHacker1 How to Create MD5 Brute Force Script Using Python Hello guys, Today we will be learn How to create MD5 brute force script using Python. What is brute-force Attack? Brute-force attack also known exhaustive key search Process of checking all possible keys Using a dictionary to attack with Dictionary is usually more effective than searching the whole key space. Exponentially grow with increasing key size. Brute force Attack Limit Because time/energy required to crack a key grows exponentially with key size, encryption in today's standards and computing power are safe brute-force attack. A 256 bit key would take on 50 of today's super computer 3x10^51 years What is Dictionary Attack Much faster than a whole key space search Not guaranteed Commonaly used on passwords Dictionaries can be found online A popular one is darkc0de.lst Good to run before a big dictionary like darkc0de. Can eliminate the most com...