This commit is contained in:
qiangyanwen 2022-12-26 16:47:34 +08:00
parent 378bf3632b
commit 6cd92aebe4
1 changed files with 7 additions and 3 deletions

View File

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