From 31a799d45ae943ab27d590c97585ebba6bd26820 Mon Sep 17 00:00:00 2001 From: Raphael Roberts Date: Tue, 25 May 2021 14:54:36 -0500 Subject: [PATCH] Added utils from a previous project --- openwrt_backup/utils.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100755 openwrt_backup/utils.py diff --git a/openwrt_backup/utils.py b/openwrt_backup/utils.py new file mode 100755 index 0000000..b42378b --- /dev/null +++ b/openwrt_backup/utils.py @@ -0,0 +1,37 @@ +import paramiko +import os +from subprocess import list2cmdline + + +def connection_from_config(name): + """Create a connection from a Host entry in the .ssh/config file""" + config = paramiko.config.SSHConfig() + cp = os.path.expanduser("~/.ssh/config") + with open(cp) as file: + config.parse(file) + info = config.lookup(name) + info["username"] = info.pop("user") + info["key_filename"] = info.pop("identityfile") + info["port"] = int(info["port"]) + client = paramiko.client.SSHClient() + client.load_host_keys(os.path.expanduser("~/.ssh/known_hosts")) + client.connect(**info) + return client + + +def scp_put(connection: paramiko.sftp_client.SFTPClient, src, dst): + """Function to copy files from src to dst using connection (local to remote)""" + connection.put(src, dst) + + +def scp_get(connection: paramiko.sftp_client.SFTPClient, src, dst): + """Function to copy files from src to dst using connection (remote to local)""" + connection.get(src, dst) + + +def exec_remote(connection: paramiko.SSHClient, command): + """Function to execute specified command on conection""" + if not isinstance(command, str): + command = list2cmdline(command) + stdin, stdout, stderr = connection.exec_command(command) + return stdout, stderr