Browse Source

Added utils from a previous project

master
Raphael Roberts 5 years ago
parent
commit
31a799d45a
  1. 37
      openwrt_backup/utils.py

37
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
Loading…
Cancel
Save