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.

54 lines
1.6 KiB

  1. from pathlib import Path
  2. from subprocess import list2cmdline
  3. from typing import Union
  4. import paramiko
  5. def connection_from_config(name: str, ssh_config_root: Path):
  6. """Create a connection from a Host entry in the .ssh/config file"""
  7. config = paramiko.config.SSHConfig()
  8. cp = ssh_config_root / "config"
  9. with open(cp) as file:
  10. config.parse(file)
  11. info = config.lookup(name)
  12. info["username"] = info.pop("user", None)
  13. info["key_filename"] = info.pop("identityfile", None)
  14. info["port"] = int(info.pop("port", 22))
  15. params = dict(
  16. hostname=None,
  17. port=22,
  18. username=None,
  19. password=None,
  20. pkey=None,
  21. key_filename=None,
  22. timeout=None,
  23. allow_agent=True,
  24. look_for_keys=True,
  25. compress=False,
  26. sock=None,
  27. gss_auth=False,
  28. gss_kex=False,
  29. gss_deleg_creds=True,
  30. gss_host=None,
  31. banner_timeout=None,
  32. auth_timeout=None,
  33. gss_trust_dns=True,
  34. passphrase=None,
  35. disabled_algorithms=None,
  36. )
  37. for key, value in info.items():
  38. if key in params.keys():
  39. params[key] = value
  40. client = paramiko.client.SSHClient()
  41. client.load_host_keys(ssh_config_root / "known_hosts")
  42. client.connect(**params)
  43. return client
  44. def exec_remote(connection: paramiko.SSHClient, command: Union[str, list]):
  45. """Function to execute specified command on conection"""
  46. if not isinstance(command, str):
  47. command = list2cmdline(command)
  48. stdin, stdout, stderr = connection.exec_command(command)
  49. return stdout, stderr