monitoring/utils/ssh_client.py

62 lines
2.0 KiB
Python

# _*_ coding: utf-8 _*_
# @Time :2022/12/26 16:33
# @Email :508737091@qq.com
# @Author :qiangyanwen
# @File :ssh_client.py
import paramiko
from config.log import logger
class SSHConnection(object):
def __init__(self, host, port, username, password):
self._host = host
self._port = port
self._username = username
self._password = password
self._transport = None
self._sftp = None
self._client = None
def __enter__(self):
logger.info("ssh开始创建链接")
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:
self._sftp = paramiko.SFTPClient.from_transport(self._transport)
self._sftp.get(remote_path, local_path)
def put(self, local_path, remote_path):
if self._sftp is None:
self._sftp = paramiko.SFTPClient.from_transport(self._transport)
self._sftp.put(local_path, remote_path)
def command(self, command):
if self._client is None:
self._client = paramiko.SSHClient()
self._client._transport = self._transport
stdin, stdout, stderr = self._client.exec_command(command)
out_data = stdout.read().decode('utf-8').strip()
code = stdout.channel.recv_exit_status()
if len(out_data) > 0:
return out_data
err_data = stderr.read().decode('utf-8').strip()
if len(err_data) > 0:
return err_data
return code
def __exit__(self, exc_type, exc_val, exc_tb):
if self._transport:
self._transport.close()
if self._client:
self._client.close()
logger.info("ssh 关闭连接")
with SSHConnection("47.96.135.132", 22, "root", "Qyw1994@520") as ssh:
ls = ssh.command("ls -l")
print(ls)