Last active
February 12, 2024 21:09
-
-
Save JonnyWong16/e140f546b09950829685f000b7cf98bc to your computer and use it in GitHub Desktop.
Run a SSH command using Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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() |
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
@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
I executed above program, but i am getting error as Channel closed. Please can someone guide me?