This commit is contained in:
qiangyanwen 2022-12-26 18:21:03 +08:00
parent 1225366bed
commit c3534dff3c
1 changed files with 5 additions and 2 deletions

View File

@ -17,6 +17,7 @@ class SSHConnection(object):
self._client = None self._client = None
def __enter__(self): def __enter__(self):
print("客户端开始创建连接.....")
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
@ -32,7 +33,7 @@ class SSHConnection(object):
self._sftp = paramiko.SFTPClient.from_transport(self._transport) self._sftp = paramiko.SFTPClient.from_transport(self._transport)
self._sftp.put(local_path, remote_path) self._sftp.put(local_path, remote_path)
def exec_command(self, command): def command(self, command):
if self._client is None: if self._client is None:
self._client = paramiko.SSHClient() self._client = paramiko.SSHClient()
self._client._transport = self._transport self._client._transport = self._transport
@ -51,7 +52,9 @@ class SSHConnection(object):
self._transport.close() self._transport.close()
if self._client: if self._client:
self._client.close() self._client.close()
print("客户端关闭已成功.....")
with SSHConnection("47.96.135.132", 22, "root", "Qyw1994@520") as ssh: with SSHConnection("47.96.135.132", 22, "root", "Qyw1994@520") as ssh:
ls = ssh.exec_command("ls -l") ls = ssh.command("ls -l")
print(ls)