首页 > 编程语言 >python paramiko remote 采集监控信息

python paramiko remote 采集监控信息

时间:2024-07-13 17:11:11浏览次数:11  
标签:remote stdout python replace mem read print disk paramiko

#!/usr/bin/python
# -*- 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 / 10)
    free_mem = round((float(memory.free) / 1024 / 1024 / 1024),2)
    percent_mem = round((float(memory.used) 
    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="192.168.0.16",port=22,username="root",password=""',
    'hostname="192.168.0.204",port=22,username="root",password=""',
    'hostname="192.168.0.70",port=22,username="root",password=""',
    'hostname="192.168.0.84",port=22,username="root",password=""',
    'hostname="192.168.1.203",port=22,username="root",password=""',

    'hostname="192.168.0.2",port=22,username="root",password=""',
    'hostname="192.168.0.28",port=22,username="root",password=""',
    ]
    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].r
        print(ipx)
        portx = int(splitx[1].split('=')[1])
        #print(portx)
        unamex = splitx[2].split('=')[1].replace('"','')
        #print(unamex)
        pwdx = splitx[3].split('=')[1
        #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")
            stdin,stdout,stderr = ssh.exec_command("w | grep 'load average'")
            #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)

            #free -g
            stdin_mem,stdout_mem,stderr_mem = ssh.exec_command("free -g")
            mem_info = stdout_mem.read().decode('utf-8')
            print(mem_info)

            #netstat -naoltp | grep ESTABLISHED | wc -l
            stdin_conn,stdout_conn,stderr_conn = ssh.exec_command("netstat -naoltp | grep ESTABLISHED | wc -l")
            conn_info = stdout_conn.read().decode('utf-8')
            print("服务器已建立连接数:{v}".format(v=conn_info))

            #iostat sysstat
            stdin_disk_io_exec,stdout_disk_io_exec,stderr_disk_io_exec = ssh.exec_command('yum install sysstat -y')
            stdin_disk_io,stdout_disk_io,stderr_disk_io = ssh.exec_command('iostat -d -k 1 1 | grep "vda"')
            disk_io = stdout_disk_io.read().decode('utf-8')
            print(disk_io)

            #测试磁盘性能 dd if=/dev/zero of=testfile bs=1G count=1 oflag=direct
            #
            stdin_diskiotest,stdout_diskiotest,stderr_diskiotest = ssh.exec_command("dd if=/dev/zero of=testfile bs=1G count=1 oflag=direct")
            #stdin_diskiotest,stdout_diskiotest,stderr_diskiotest = ssh.exec_command("free -g")
            diskio = stderr_diskiotest.read().decode('utf-8')
            print("磁盘性能io测试:\n{disk_value}".format(disk_value=diskio))
            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)
    """

 

标签:remote,stdout,python,replace,mem,read,print,disk,paramiko
From: https://www.cnblogs.com/ruiy/p/18300340

相关文章

  • Python—学生信息管理系统(附源码)
    今天所要分享的文章是关于如何实现学生管理系统,有需要的朋友可以参考一下,希望可以帮到大家!文章目录一、开始界面实现1.定义主函数2.运用循环,获取用户需求二、函数实现各个模块功能1.添加学生信息2.展示学生信息3.查找学生信息4.删除学生信息5.退出程序三、把......
  • 基于Python酒店评论情感分析可视化系统
    专业技术开发,收藏关注不迷路文章目录一、项目介绍二、开发环境三、功能介绍四、效果图五、文章目录一、项目介绍随着电商网络经济的兴起,更多的人选择在线上预订酒店出行,电商旅游平台使得旅行者可以通过评论更加自由地选择价格和服务合意的酒店,同时也给人们提供了......
  • Python数据容器(1)--列表与元组
    数据容器在Python中,数据容器是指能够存储多个数据项(可以是不同类型的数据)的数据结构。Python提供了多种内置的数据容器类型,每种类型都有其特定的用途和特性。Python中最常用的数据容器有:List列表、Tuple元组、Dictionary字典、Set集合。本篇我们来介绍其中的List列表和Tuple......
  • 【Python】jupyter notebook平台的使用·
    目录一、安装Anaconda二、将BreadCancer.zip上传到jupyter notebook平台中三、了解BreadCancerClassifier.ipynb文件在jupyternotebook的单元格中的python代码,并运行。3.1 导入mainFun文件3.2 读入数据3.3开始训练3.4读入测试数据3.5 开始测试3.6 开始统计3......
  • 【Python】基础语法
    目录一、思考if__name__==”__main__”的意思和作用1.先执行comparenumber.py 2.再看test.py3._name_的意思4._name_的作用二、重要语法“tab”的作用1.test012.test02三、元组数据结构的创建和使用1.创建元组 2.访问元组的元素3.操作元组四、列表数......
  • python基础篇总结:数据类型
    在python中数据类型主要是以下9种分别是1.Int(整型);2.Float(浮点型);3.Bool(布尔型);4.Str(字符串);5.None(空值);6.List(列表);7.Tuple(元组);8.Dict(字典);9.Set(集合)等。一.Int(整数)整数是Python中最基本的数值类型,用于表示整数值。1.定义整数变量:2.使用内置函数处理整数:3.进行算......
  • Python 修改 pip 源为国内源
    1.临时换源:#清华源pipinstallmarkdown-ihttps://pypi.tuna.tsinghua.edu.cn/simple#阿里源pipinstallmarkdown-ihttps://mirrors.aliyun.com/pypi/simple/#腾讯源pipinstallmarkdown-ihttp://mirrors.cloud.tencent.com/pypi/simple#豆瓣源pipinstallm......
  • PyQt5学习之路一:python与QT搭配,实现UI设计与业务逻辑层分离
    一、Python安装1.下载Pythonpython官网链接如下:链接:https://www.python.org/根据图中提示选择需要的python版本,下载并安装二、QT安装1.下载QTQt官网链接如下:链接:https://www.qt.io/下载社区版QT就可以三、PyQt5的安装1.PyQt5简介python语言最为排行第一的......
  • 【Python实战项目】用Python制作游戏—pygame超级玛丽!游戏开发
    1、需求分析具备功能播放与停止背景音乐随机生成管道与导弹障碍显示积分跳跃躲避障碍碰撞障碍2、游戏功能结构玛丽冒险的功能结构主要分为三类,分别为音效、主窗体以及随机出现的障碍物。如下图3、游戏业务流程根据该游戏的需求分析以及功能结构##-、游戏预览......
  • 用Python生成一个漂亮的圣诞节词云
    展示效果代码#-*-coding:UTF-8-*-importjiebaimportrefromstylecloudimportgen_stylecloudfromPILimportImageimportnumpyasnpwithopen('./圣诞素材/Christmas.txt',encoding="utf-8")asf:data=f.read()#文本预处理去除一些无用的字符......