Skip to content

Instantly share code, notes, and snippets.

Created October 13, 2011 13:42
Star You must be signed in to star a gist
What would you like to do?
The only simple way to do SSH in Python today is to use subprocess + OpenSSH...
# All SSH libraries for Python are junk (2011-10-13).
# Too low-level (libssh2), too buggy (paramiko), too complicated
# (both), too poor in features (no use of the agent, for instance)
# Here is the right solution today:
import subprocess
import sys
# Ports are handled in ~/.ssh/config since we use OpenSSH
COMMAND="uname -a"
ssh = subprocess.Popen(["ssh", "%s" % HOST, COMMAND],
result = ssh.stdout.readlines()
if result == []:
error = ssh.stderr.readlines()
print >>sys.stderr, "ERROR: %s" % error
print result
Copy link

ssh = subprocess.Popen(["ssh", "%s" % HOST, "%s" %COMMAND],

You should read the documentation. Executive summary: shell=True is both dangerous and a bad idea in most cases. From a Python program, shell=False is the right solution most of the time. (See in the doc, around "If shell is True, it is recommended to pass args as a string rather than as a sequence.")

Copy link

datlife commented Nov 4, 2019

SSH without third-party library

Here is my take on SSH without using third-party library. I leveraged a concept of fork system call in UNIX [1].

# Create an ssh session with python
import os
import shlex

def create_ssh(host, user):
  """Create a ssh session"""
  ssh = "/usr/bin/ssh -t {user}@{host} ".format(user=user, host=host)
  # Now, fork a child from current process 
  # This is a basic concept from Operating System class.
  pid = os.fork()
  if pid == 0:  # a child process
     print("Executing: %s" %(ssh))
     cmd = shlex.split(ssh)
     os.execv(cmd[0], cmd)
  os.wait(pid, 0)
  print("ssh session is finished. :)")
if __name__ == "__main__":


Copy link

Insektosaurus commented Jan 11, 2020


Still populating top three google results when searching for 'python3 connect ssh and run script' :)

Copy link

faddison commented May 6, 2020

Still true today. Amazing how badly libraries like paramiko and fabric fail at such a simple task.

Copy link

Still a valid chain but still finding it hard to reliably send password from Osx or linux

Copy link

hoon0912 commented Jan 7, 2021

thank you

Copy link

Can tell how amazing it is when this solution still works today.
Thanks a lot.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment