• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Code Snippets / SSH Connection with Python

SSH Connection with Python

Author: PFB Staff Writer
Last Updated: August 28, 2020

Overview

Last week I wrote an article about the pexpect module in Python and how you can use it to take care of some of the automation needs, like ssh and ftp.

I would like to continue on that topic and write about it’s pxssh class. With the pxssh module, it’s easy to access other servers over SSH. This article is based on the official documentation found here: http://pexpect.sourceforge.net/pxssh.html

What is pxssh?

Pxssh is based on pexpect. It’s class extends pexpect.spawn to specialize setting up SSH connections. I use pxssh frequently for making ssh connections in python.

Module documentation

Open up a terminal and type in the following commands to get help about the module

import pxssh
help(pxssh)

Help on module pxssh:

NAME
   pxssh

FILE
   /usr/lib/python2.7/dist-packages/pxssh.py

DESCRIPTION
   This class extends pexpect.spawn to specialize setting up SSH connections.
   This adds methods for login, logout, and expecting the shell prompt.
    
   $Id: pxssh.py 513 2008-02-09 18:26:13Z noah $

CLASSES
   pexpect.ExceptionPexpect(exceptions.Exception)
       ExceptionPxssh
   pexpect.spawn(__builtin__.object)
       pxssh

You can also see the help here http://pexpect.sourceforge.net/pxssh.html

Methods and login process

Pxssh 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.

How does pxssh works?

pxssh uses the shell prompt to synchronize output from the remote host. In order to make this more robust it sets the shell prompt to something more unique than just $ or #.

This should work on most Borne/Bash or Csh style shells.

Example

This example runs a few commands on a remote server and prints the result.

First we import the modules that we need. (pxssh and getpass)

We import the getpass module, which will prompt the user for a password, without echoing what they type to the console.


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, e:
    print "pxssh failed on login."
    print str(e)

Run a command on a remote SSH server

Let’s show one more example. To run a command (‘uptime’) and to print the output, you need to do something like that :

import pxssh
s = pxssh.pxssh()
if not s.login ('localhost', 'myusername', 'mypassword'):
    print "SSH session failed on login."
    print str(s)
else:
    print "SSH session login successful"
    s.sendline ('uptime')
    s.prompt()         # match the prompt
    print s.before     # print everything before the prompt.
    s.logout()
    
#We can also execute multiple command like this:
s.sendline ('uptime;df -h')

For more information about pxssh, please see the official documentation

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Code Snippets, pxssh Author: PFB Staff Writer

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us