Skip to content

Instantly share code, notes, and snippets.

@JonnyWong16
Last active February 12, 2024 21:09
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save JonnyWong16/e140f546b09950829685f000b7cf98bc to your computer and use it in GitHub Desktop.
Save JonnyWong16/e140f546b09950829685f000b7cf98bc 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 ##
def main():
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)
ssh_stdout.channel.recv_exit_status()
except Exception as e:
sys.stderr.write("SSH connection error: {0}".format(e))
if ssh_stdout:
sys.stdout.write(ssh_stdout.read().decode("UTF-8"))
if ssh_stderr:
sys.stderr.write(ssh_stderr.read().decode("UTF-8"))
if __name__ == "__main__":
main()
@lalaso
Copy link

lalaso commented Jan 3, 2018

I executed above program, but i am getting error as Channel closed. Please can someone guide me?

@girishlc
Copy link

I got this error, can you please comment on this,

SSH connection error: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

@cowlinator
Copy link

@lalaso, it could be because you ran it multiple times, and the client and connection were not closed properly the first time.

See https://gist.github.com/cowlinator/552ee27cd436e5f79c214107e4a779e6 for how to use SSHClient() with a context manager and how to use ssh.connect() and ssh.close() with a try, finally clause.

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