Skip to content

Instantly share code, notes, and snippets.

@gauravssnl
Forked from JonnyWong16/python_ssh.py
Created July 1, 2017 13:18
Show Gist options
  • Save gauravssnl/f8d54d1d510e19f7b139b4c3cb18abff to your computer and use it in GitHub Desktop.
Save gauravssnl/f8d54d1d510e19f7b139b4c3cb18abff to your computer and use it in GitHub Desktop.
Run a SSH command using Python
# 1. Install the paramikio module for python.
# pip install paramiko
# 2. Edit the SSH details below.
import paramiko
import sys
## EDIT SSH DETAILS ##
SSH_ADDRESS = "192.168.0.1"
SSH_USERNAME = "username"
SSH_PASSWORD = "password"
SSH_COMMAND = "echo 'Hello World!'"
## CODE BELOW ##
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_stdin = ssh_stdout = ssh_stderr = None
try:
ssh.connect(SSH_ADDRESS, username=SSH_USERNAME, password=SSH_PASSWORD)
ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(SSH_COMMAND)
except Exception as e:
sys.stderr.write("SSH connection error: {0}".format(e))
if ssh_stdout:
sys.stdout.write(ssh_stdout.read())
if ssh_stderr:
sys.stderr.write(ssh_stderr.read())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment