首页 > 其他分享 >paramiko 监控

paramiko 监控

时间:2022-12-27 17:46:28浏览次数:28  
标签:stdout mem replace 监控 print disk cpu paramiko

# -*- coding: utf-8 -*-

#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
#@auhor by ruiy
#
#
#
#pip install paramiko -i https://pypi.tuna.tsinghua.edu.cn/simple
#
#pip install psutil -i https://pypi.tuna.tsinghua.edu.cn/simple
#
#注意:添加openssh 账号sshadmin必须加入administrator组,否则获取相关监控指标数据为null
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

import paramiko
import datetime
import time
import os
import psutil

dt = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime())
#print(type(dt))
print("时间%s"%dt)

#psutil

def get_cpu_infos():
    cpu_count = psutil.cpu_count(logical=False)
    xc_count = psutil.cpu_count()
    cpu_percent = round((psutil.cpu_percent(1)),2)
    cpu_info = (cpu_count,xc_count,cpu_percent)
    return cpu_info


def get_mem_infos():
    memory = psutil.virtual_memory()
    total_mem = round((float(memory.total) / 1024 / 1024 / 1024),2)
    used_mem = round((float(memory.used) / 1024 / 1024 / 1024),2)
    free_mem = round((float(memory.free) / 1024 / 1024 / 1024),2)
    percent_mem = round((float(memory.used) / float(memory.total) * 100),2)
    mem_info = (total_mem,used_mem,free_mem,percent_mem)
    return mem_info

def get_disk_infos():
    list = psutil.disk_partitions()
    ilen = len(list)
    i = 0
    retlist1 = []
    retlist2 = []
    disk_info_list = []
    
    while i < ilen:
        diskinfo = psutil.disk_usage(list[i].device)
        total_disk = round((float(diskinfo.total) / 1024 / 1024 / 1024),2)
        used_disk = round((float(diskinfo.used) / 1024 / 1024 / 1024),2)
        free_disk = round((float(diskinfo.free) / 1024 / 1024 / 1024),2)
        #percent_disk = diskinfo.percent()
        retlist1 = [i,list[i].device,total_disk,used_disk,free_disk]
        disk_info_list.append(retlist1)
        i = i + 1
    return disk_info_list

#windows


#linux

if __name__ == '__main__':
    hosts = [
    #'hostname="127.0.0.1",port=3389,username="administrator",password=""',
    'hostname="1.2.3.172",port=22,username="administrator",password="qbkj"',
    'hostname="1.2.3.225",port=22,username="sshadmin",password="321"',
    'hostname="172.16.28.122",port=22,username="sshadmin",password="qb"',
    ]
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    for i in hosts:
        #print(i)
        splitx = i.split(',')
        ipx = splitx[0].split('=')[1].replace('"','')
        print(ipx)
        portx = int(splitx[1].split('=')[1])
        #print(portx)
        unamex = splitx[2].split('=')[1].replace('"','')
        #print(unamex)
        pwdx = splitx[3].split('=')[1].replace('"','')
        #print(pwdx)
        try:
            #建立连接
            ssh.connect(hostname=ipx,port=portx,username=unamex,password=pwdx)
            print("建立连接")
            #ssh.connect(hostname='1.2.3.172',port=22,username='sshadmin',password='321',timeout=3)
            #ssh.connect(hostname='1.2.3.172',port=22,username='sshadmin',password='321')
            stdin_init,stdout_init,stderr_init = ssh.exec_command("hostname")
            print((stdout_init.read()).decode('gbk'))

            time.sleep(1)
            #'''
            #windows
            #cpu利用率:wmic cpu get loadpercentage
            stdin,stdout,stderr = ssh.exec_command("wmic cpu get loadpercentage")
            #print(stdout.read())
            #time.sleep(100)
            #cpu_percent = stdout.read().decode('utf-8').replace('LoadPercentage','').replace('\n','')
            cpu_percent = stdout.read().decode('utf-8').replace('LoadPercentage','')
            #print("cpu利用率{x}".format(x = cpu_percent))
            xx = cpu_percent
            #print(type(xx))
            #print(xx)
            #print("rui%s"%(xx))
            #xr = xx
            #print("亲%s"%xr)
            print("cpu利用率%:{var}".format(var=xx))
            time.sleep(1)

            #占用cpu前5 进程
            stdin,stdout,stderr = ssh.exec_command('Powershell.exe -Command "  Get-Process | select *,@{N=\'CPUPC\';E={[float]$_.cpu}}|sort CPUPC -desc|select Id,name -first 5"')
            cpu5 = stdout.read().decode('utf-8')
            print(cpu5)

            #mem内存信息
            #systeminfo | findstr "物理内存总量:"
            stdin,stdout,stderr = ssh.exec_command('systeminfo | findstr "物理内存总量:"')
            mem_total = stdout.read().decode('gbk').replace('物理内存总量:','').replace('\t','').replace('MB','').replace(',','').replace('\n','').replace('     ','')
            print("总内存M:%s"%mem_total)
            time.sleep(1)

            #systeminfo | findstr "可用的物理内存:"
            stdin,stdout,stderr = ssh.exec_command('systeminfo | findstr "可用的物理内存:"')
            mem_free = stdout.read().decode('gbk').replace('可用的物理内存:','').replace('\t','').replace('MB','').replace(',','').replace('\n','').replace('     ','')
            print("可用内存M:%s"%mem_free)

            mem_use = int(mem_total) - int(mem_free)
            print("已使用内存M:%s"%mem_use)
            mem_use_percent = round(mem_use / int(mem_total),2)
            print("内存使用率%:{varx}".format(varx = float(mem_use_percent) * 100))
            #print()
            time.sleep(1)

            #占用mem前5
            stdin,stdout,stderr = ssh.exec_command('Powershell.exe -Command " Get-Process | select *,@{N=\'PrivateMemorySizePC\';E={[float]$_.PrivateMemorySize}}|sort PrivateMemorySize -desc|select Id,name -first 5"')
            mem5 = stdout.read().decode('utf-8')
            print(mem5)

            #disk
            #fsutil volume diskfree c:
            #wmic logicaldisk get caption

            stdin,stdout,stderr = ssh.exec_command('wmic logicaldisk get caption')
            #disk_partion_label = stdout.read().decode('gbk')
            #print(disk_partion_label)
            time.sleep(1)
            disk_partion_l = bytes.decode(stdout.read()).split('Caption')[1].replace('\r\r\n','').replace('      ','').split(":")
            #print(disk_partion_l)
            #print(len(disk_partion_l))
            #print(disk_partion_l[0])
            #x = "{}:".format(disk_partion_l[0])
            #print(x)
            #fsutil volume diskfree x
            #剔除list中空元素
            while ' ' in disk_partion_l:
                disk_partion_l.remove(' ')
            #print(disk_partion_l)
            for i in disk_partion_l:
                lab = "{}:".format(i)
                #print(lab)
                #stdin,stdout,stderr = ssh.exec_command("{}".format(lab))
                #print("fsutil volume diskfree %s"%(lab))
                stdin,stdout,stderr = ssh.exec_command("fsutil volume diskfree %s"%(lab))
                print(stdout.read().decode('gbk'))
                time.sleep(1)
            #disk_partion_label = stdout.read().decode('gbk').replace('Caption','').replace('\r\r','').split('\n')
            #disk_partion_label = stdout.read().decode('gbk').replace('Caption','').replace('\t','').replace("\r\r\n\r\r\n",'').replace('\r\r\n','').split(":")
            #print(disk_partion_label)
            #print(disk_partion_label[0])
            """
            print(len(disk_partion_label))
            for i in disk_partion_label:
                if i =='':
                    print("null")
                else:
                    print(i)
            """
            #mem_total = bytes.decode(stdout.read())
            #print(mem_total)
            #print(os.environ['SYSTEMDRIVE'])
            #stdin_init,stdout_init,stderr_init = ssh.exec_command("wmic os get TotalVisibleMemorySize")
            #mem_total = stdout_init.read().decode('utf-8').replace('TotalVisibleMemorySize','').replace('\t','').replace('\n','').replace('MB','')
            #mem_total = stdout_init.read()
            #print(float(float(int(mem_total)) / 1024 / 1024),2)
            #print(int(mem_total))
            #print((stdout_init.read()).decode('utf-8'))
            #print((stdout_init.read()))

            #infos = bytes.decode(stdout_init.read())
            #infos
            #print(infos)
            #infos = stdout_init.read()
            #print(infos)
            #'''
        except Exception as paramiko_err:
            print(paramiko_err)
            

        
        

    """
    cpuInfos = get_cpu_infos()
    print(cpuInfos)

    memInfos = get_mem_infos()
    print(memInfos)

    diskInfos = get_disk_infos()
    print(diskInfos)
    """

 

标签:stdout,mem,replace,监控,print,disk,cpu,paramiko
From: https://www.cnblogs.com/ruiy/p/17008605.html

相关文章

  • log4j 2_程序日志_监控程序运行状态
    2015年5月停止了对于log4j的更新。log4j2的配置文件不再支持properties文件格式,推荐使用xml文件配置。  一、日志级别fatal:致命错误,在catch块中使用。err......
  • 太阳能热水工程如何借助工业网关实现远程监控
    随着科学技术的发展,太阳能热水已经实现稳定的供给,十分方便好用。同时因其所具备的绿色低碳和成本节约优势,在农村地区、小区公寓等得到广泛使用。但由于太阳能热水器本身并不......
  • 轻便式Redis Monitor面向研发人员图形可视化监控工具
    redis_monitor​​https://github.com/hcymysql/redis_monitor​​轻便式RedisMonitor面向研发人员图形可视化监控工具,借鉴了LEPUS(天兔)监控平台以及redis-cliinfo命令输......
  • 【INDEX】使用“alter index ××× monitoring usage;”语句监控索引使用与否
    随着时间的累积,在没有很好的规划的情况下,​​数据库​​​中也许会存在大量长期不被使用的索引,如果快速的定位这些索引以便清理便摆在案头。我们可以使用“alter ​​index......
  • 供水水泵控制器PLC如何在线监控和远程维护
    泵站中的诸多水泵影响到供水的稳定,间接影响到居民的生活用水,需要进行监控维护,保证设备的稳定运行。我们可以借助物通博联工业智能网关来实现PLC的在线监控,并能在设备故障时......
  • iOS使用ffmpeg播放rstp实时监控视频数据流
    一、编译针对iOS平台的ffmpeg库(kxmovie)近期有一个项目,需要播放各种格式的音频、视频以及网络摄像头实时监控的视频流数据,经过多种折腾之后,最后选择了kxmovie,kxmovie项目已......
  • 统一观测|如何使用 Prometheus 监控 Windows
    作者:颍川引言微软Windows是当前主流操作系统之一,在桌面和服务端均有较大市场份额。对于Linux操作系统,Prometheus可以通过NodeExporter来进行基础资源(CPU、内存......
  • OpManager 实时网络监控
    网络是全球企业背后的基础。它在为您的员工提供行政服务以及为各大洲的客户提供服务方面发挥着关键作用。网络可帮助您将信息保存在一个集中位置-需要和限制所有其他入站......
  • Prometheus监控之pushgateway安装配置
    一、简介1、介绍1、pushgateway是什么pushgateway是另一种数据采集的方式,采用被动推送来获取监控数据的prometheus插件,它可以单独运行在任何节点上,并不一定要运行在被监控的......
  • 测试监控和测试控制
    在软件测试领域,QA管理者和高阶的测试人员必须实施不同的测试管理方法,例如测试监控和控制,以确保测试活动按照计划顺利执行。管理人员需要这些基本的管理策略来跟踪和调整测试......