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.

52 lines
1.5 KiB

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