diff --git a/utils/ssh_client.py b/utils/ssh_client.py index a3156bc..e1144be 100644 --- a/utils/ssh_client.py +++ b/utils/ssh_client.py @@ -15,12 +15,12 @@ class SSHConnection(object): self._transport = None self._sftp = None self._client = None - self._connect() # 建立连接 - def _connect(self): + def __enter__(self): transport = paramiko.Transport((self._host, self._port)) transport.connect(username=self._username, password=self._password) self._transport = transport + return self def download(self, remote_path, local_path): if self._sftp is None: @@ -46,8 +46,12 @@ class SSHConnection(object): return err_data return code - def close(self): + def __exit__(self, exc_type, exc_val, exc_tb): if self._transport: self._transport.close() if self._client: self._client.close() + + +with SSHConnection("47.96.135.132", 22, "root", "Qyw1994@520") as ssh: + ssh.exec_command("ls -l")