Last active
June 6, 2025 13:37
-
-
Save samukasmk/8d95ce662ce28958038a2ee17970bf31 to your computer and use it in GitHub Desktop.
Execute commands using SSH protocol by python script with Paramiko library
This file contains hidden or 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
#!/usr/bin/env python3 | |
# | |
# https://docs.paramiko.org/en/stable/ | |
# https://didatica.tech/paramiko-com-python-aprenda-a-utilizar-com-exemplos-praticos/ | |
import argparse | |
import sys | |
import time | |
import paramiko | |
def run_ssh_command(host: str, username: str, password: str, command: str) -> int: | |
""" | |
Connects to a remote host via SSH, executes a command, and returns its exit status. | |
Prints both stdout and stderr from the remote execution. | |
""" | |
ssh_client = paramiko.SSHClient() | |
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) | |
try: | |
ssh_client.connect(hostname=host, username=username, password=password) | |
except Exception as e: | |
print(f"Error: Failed to connect to {host} as {username}: {e}", file=sys.stderr) | |
return 1 | |
try: | |
stdin, stdout, stderr = ssh_client.exec_command(command) | |
# get command results | |
exit_status = stdout.channel.recv_exit_status() | |
stdout_text = stdout.read().decode("utf-8", errors="replace") | |
stderr_text = stderr.read().decode("utf-8", errors="replace") | |
except Exception as e: | |
print(f"Error: Failed to execute command '{command}': {e}", file=sys.stderr) | |
return 1 | |
finally: | |
ssh_client.close() | |
if stdout_text: | |
print("=== STDOUT ===") | |
print(stdout_text, end="") | |
if stderr_text: | |
print("=== STDERR ===", file=sys.stderr) | |
print(stderr_text, file=sys.stderr, end="") | |
print(f"\nExit status: {exit_status}") | |
return exit_status | |
def main(): | |
parser = argparse.ArgumentParser(prog="ssh_paramiko_command.py", | |
description="Execute a single SSH command on a remote host using Paramiko.") | |
parser.add_argument("-u", "--username", required=True, help="SSH username for authentication") | |
parser.add_argument("-p", "--password", required=True, help="SSH password for authentication") | |
parser.add_argument("-H", "--host", required=True, help="Remote host (IP or hostname) to connect to") | |
parser.add_argument("-c", "--command", required=True, help="Bash command to run on the remote host") | |
args = parser.parse_args() | |
start_time = time.perf_counter() | |
exit_code = run_ssh_command( | |
host=args.host, | |
username=args.username, | |
password=args.password, | |
command=args.command | |
) | |
elapsed_time = time.perf_counter() - start_time | |
print(f"\n=== ELAPSED TIME ===\n{elapsed_time:.4f} seconds") | |
sys.exit(exit_code) | |
if __name__ == "__main__": | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment