paramiko使用上下文管理

# -*- coding: utf-8 -*-
import paramiko

SSH_HOST = '192.168.1.130'
SSH_PORT = 22
SSH_USERNAME = 'root'
SSH_PASSWORD = 'Aa753951123'


class SSHLinuxClient(object):
def __init__(self, hostname=SSH_HOST, port=SSH_PORT, username=SSH_USERNAME, password=SSH_PASSWORD):
self.hostname = hostname
self.port = port
self.username = username
self.password = password
self.connections = list()

def __enter__(self):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy)
client.connect(hostname=self.hostname, port=self.port, username=self.username, password=self.password)
self.connections.append(client)
return client

def __exit__(self, exc_ty, exc_val, tb):
self.connections.pop().close()


if __name__ == '__main__':
with SSHLinuxClient() as ssh:
_, stdout, _ = ssh.exec_command("df -h")
print(stdout.read().decode('utf-8'))
posted @ 2022-05-23 17:25  wyz_1  阅读(56)  评论(0编辑  收藏  举报