|
| 1 | +from . import * |
| 2 | +import paramiko |
| 3 | +SShConfig = requirePackage("paramiko.config", "SSHConfig", real_name='paramiko') |
| 4 | +from paramiko import SSHClient |
| 5 | + |
| 6 | +class ParamikoSSH: |
| 7 | + def __init__(self): |
| 8 | + self.config = SShConfig() |
| 9 | + with open(os.path.expanduser("~/.ssh/config")) as f: |
| 10 | + self.config.parse(f) |
| 11 | + if os.path.exists(os.path.expanduser("~/.ssh/id_rsa")): |
| 12 | + self.identity = os.path.expanduser("~/.ssh/id_rsa") |
| 13 | + else: |
| 14 | + self.identity = None |
| 15 | + self.activate_connections = {} |
| 16 | + |
| 17 | + def _parse_host(self, host: str, user: str = None, port: int = 22, identity: str = None): |
| 18 | + host_config = self.config.lookup(host) |
| 19 | + if not host_config and not user: |
| 20 | + raise Exception("Host not found in config file.") |
| 21 | + if host_config: |
| 22 | + host = host_config.get("hostname", host) |
| 23 | + identity = host_config.get("identityfile") |
| 24 | + if not user: |
| 25 | + user = host_config.get("user", None) |
| 26 | + if not user: |
| 27 | + from QuickProject import QproErrorString |
| 28 | + QproDefaultConsole.print(QproErrorString, "User not found in config file.") |
| 29 | + if not identity: |
| 30 | + identity = self.identity |
| 31 | + port = host_config.get("port", port) |
| 32 | + return host, user, port, identity |
| 33 | + |
| 34 | + def connect(self, host: str, user: str = None, port: int = 22, identity: str = None) -> SSHClient: |
| 35 | + conn_id = self._parse_host(host, user, port, identity) |
| 36 | + |
| 37 | + if conn_id in self.activate_connections: |
| 38 | + return self.activate_connections[conn_id] |
| 39 | + |
| 40 | + ssh = SSHClient() |
| 41 | + ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) |
| 42 | + ssh.connect(*conn_id) |
| 43 | + self.activate_connections[conn_id] = ssh |
| 44 | + return ssh |
| 45 | + |
| 46 | + def close(self, host: str, user: str = None, port: int = 22, identity: str = None): |
| 47 | + conn_id = self._parse_host(host, user, port, identity) |
| 48 | + |
| 49 | + if conn_id in self.activate_connections: |
| 50 | + self.activate_connections[conn_id].close() |
| 51 | + del self.activate_connections[conn_id] |
| 52 | + |
| 53 | + def __del__(self): |
| 54 | + for k in self.activate_connections: |
| 55 | + self.activate_connections[k].close() |
| 56 | + self.activate_connections.clear() |
0 commit comments