You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

37 lines
1.2 KiB

  1. import paramiko
  2. import os
  3. from subprocess import list2cmdline
  4. def connection_from_config(name):
  5. """Create a connection from a Host entry in the .ssh/config file"""
  6. config = paramiko.config.SSHConfig()
  7. cp = os.path.expanduser("~/.ssh/config")
  8. with open(cp) as file:
  9. config.parse(file)
  10. info = config.lookup(name)
  11. info["username"] = info.pop("user")
  12. info["key_filename"] = info.pop("identityfile")
  13. info["port"] = int(info["port"])
  14. client = paramiko.client.SSHClient()
  15. client.load_host_keys(os.path.expanduser("~/.ssh/known_hosts"))
  16. client.connect(**info)
  17. return client
  18. def scp_put(connection: paramiko.sftp_client.SFTPClient, src, dst):
  19. """Function to copy files from src to dst using connection (local to remote)"""
  20. connection.put(src, dst)
  21. def scp_get(connection: paramiko.sftp_client.SFTPClient, src, dst):
  22. """Function to copy files from src to dst using connection (remote to local)"""
  23. connection.get(src, dst)
  24. def exec_remote(connection: paramiko.SSHClient, command):
  25. """Function to execute specified command on conection"""
  26. if not isinstance(command, str):
  27. command = list2cmdline(command)
  28. stdin, stdout, stderr = connection.exec_command(command)
  29. return stdout, stderr