其他分享
首页 > 其他分享> > paramiko使用上下文管理

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'))

标签:__,username,password,管理,self,hostname,SSH,上下文,paramiko
来源: https://www.cnblogs.com/yz-w/p/16302053.html