Last active
April 5, 2022 11:52
-
-
Save codesenju/cd8b4d5b7257a3d42c2483ae2bfe2732 to your computer and use it in GitHub Desktop.
Paramiko Skeleton
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
import paramiko, sys, os | |
hostname = '' | |
username = '' | |
password = '' | |
PORT = '22' | |
ssh = paramiko.SSHClient() | |
def run_local_cmd(your_command): | |
print(your_command) | |
try: | |
os.system(your_command) | |
except Exception as err: | |
print("Unable to execute local cmd: " + your_command + " {} " + format(err)) | |
sys.exit(1) | |
def execRemoteCommand(cmd_, client): | |
print(cmd_) | |
stdin, stdout, stderr = client.exec_command(cmd_) | |
output = stderr.readlines() | |
output_line = ''.join(output) | |
print(output_line) | |
output = stdout.readlines() | |
output_line = ''.join(output) | |
print(output_line) | |
def get_arguments(): | |
get_arguments() | |
try: | |
# get arguments hostname username password | |
cred = [sys.argv[1], sys.argv[2], sys.argv[3]] | |
global hostname | |
global username | |
global password | |
hostname = cred[0] | |
username = cred[1] | |
password = cred[2] | |
except Exception as err: | |
print("Unable to get arguments: {}".format(err)) | |
sys.exit(1) | |
if __name__ == "__main__": | |
try: | |
ssh_client = paramiko.SSHClient() | |
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) | |
ssh_client.connect(hostname=hostname, username=username, password=password, port=PORT) | |
sftp_client = ssh_client.open_sftp() | |
# 1. CHANGE PATH ON THE REMOTE SERVER | |
print("##########-1.-CHANGE-PATH-##########") | |
sftp_client.chdir("/tmp") | |
print(sftp_client.getcwd()) | |
# 2. RUN COMMAND ON REMOTE SERVER | |
print("##########-2.-REMOTE-COMMAND-##########") | |
execRemoteCommand("ls -l /tmp", ssh_client) | |
# 3. COPY FILE TO REMOTE SERVER | |
print("##########-3.-REMOTE-COMMAND-##########") | |
sftp_client.put("README.md", "README.md") | |
execRemoteCommand("stat /tmp/README.md", ssh_client) | |
# 4. DOWNLOAD FILE FROM REMOTE SERVER | |
print("##########-4.-DOWNLOAD-FILE-##########") | |
sftp_client.get("/tmp/remote_file.txt","remote_file.txt") | |
except Exception as err: | |
print("SSH CLIENT ERROR: {}".format(err)) | |
finally: | |
sftp_client.close() | |
ssh_client.close() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment