python-ssh链接linux查询日志,并按日志等级在控制台分颜色输出日志
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 | import paramiko # unicode_utils.py def to_str(bytes_or_str): """ 把byte类型转换为str :param bytes_or_str: :return: """ if isinstance (bytes_or_str, bytes): value = bytes_or_str.decode( 'utf-8' ) else : value = bytes_or_str return value class SSHConnection( object ): def __init__( self , host_dict): self .host = host_dict[ 'host' ] self .port = host_dict[ 'port' ] self .username = host_dict[ 'username' ] self .pwd = host_dict[ 'pwd' ] self .__k = None def connect( self ): transport = paramiko.Transport(( self .host, self .port)) transport.connect(username = self .username, password = self .pwd) self .__transport = transport def close( self ): self .__transport.close() def run_cmd( self , command): """ 执行shell命令,返回字典 return {'color': 'red','res':error}或 return {'color': 'green', 'res':res} :param command: :return: """ ssh = paramiko.SSHClient() ssh._transport = self .__transport # 执行命令 stdin, stdout, stderr = ssh.exec_command(command) # 获取命令结果 res = to_str(stdout.read()) # 获取错误信息 error = to_str(stderr.read()) # 如果有错误信息,返回error # 否则返回res #这里代码写了根据状态控制台打印不同颜色,正常显示绿色,错误显示红色 if error.strip(): return f "\033[1;31;40m'res': {error}\033[0m" else : return f "\033[1;32;40m'res': {res}\033[0m" def upload( self , local_path, target_path): # 连接,上传 sftp = paramiko.SFTPClient.from_transport( self .__transport) # 将location.py 上传至服务器 /tmp/test.py sftp.put(local_path, target_path, confirm = True ) # print(os.stat(local_path).st_mode) # 增加权限 # sftp.chmod(target_path, os.stat(local_path).st_mode) sftp.chmod(target_path, 0o755 ) # 注意这里的权限是八进制的,八进制需要使用0o作为前缀 def download( self , target_path, local_path): # 连接,下载 sftp = paramiko.SFTPClient.from_transport( self .__transport) # 将location.py 下载至服务器 /tmp/test.py sftp.get(target_path, local_path) # 销毁 def __del__( self ): self .close() |
作者: yetangjian
出处: https://www.cnblogs.com/yetangjian/p/16060410.html
关于作者: yetangjian
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 原文链接 如有问题, 可邮件(yetangjian@outlook.com)咨询.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~