Last active
August 27, 2021 08:30
-
-
Save mightbxg/11fa2134e8e4193c038f5a0a5b008203 to your computer and use it in GitHub Desktop.
Execute remote command via SSH
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
#!/usr/bin/env python3 | |
import argparse | |
import paramiko | |
def try_connect(host, user, password) -> bool: | |
ssh = paramiko.SSHClient() | |
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) | |
try: | |
ssh.connect(host, username=user, password=password) | |
except: | |
return False | |
return True | |
def execute(host, user, password, cmd): | |
ssh = paramiko.SSHClient() | |
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) | |
ssh.connect(host, username=user, password=password) | |
stdin,stdout,stderr=ssh.exec_command(cmd) | |
opt = stdout.readlines() | |
opt = "".join(opt) | |
print(opt) | |
def execute2(user_host, password, cmd): | |
try: | |
user, host = user_host.split('@') | |
except ValueError: | |
print('Invalid user@host:', user_host) | |
return | |
execute(host, user, password, cmd) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description='Execute remote command via SSH.') | |
parser.add_argument('user_host', type=str, help='user@host') | |
parser.add_argument('password', type=str, help='password') | |
parser.add_argument('cmd', type=str, help='the command to be executed') | |
args = parser.parse_args() | |
user, host = args.user_host.split('@') | |
execute2(args.user_host, args.password, args.cmd) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment