巡检CENTOS服务器CPU,内存和磁盘多个分区的PYTHON脚本

这个脚本和前面写的过巡检脚本相似,https://shaka.blog.csdn.net/article/details/86533037

一、在这个基础上支持对多个磁盘分区的检查,python代码如下

# -*- coding: utf-8 -*-
import os,sys
#sys.setdefaultencoding('utf8')
import paramiko
import xlsxwriter
import time
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from multiprocessing import Process,Manager
import multiprocessing
import os

def trywexrestrdiskp(ips,idrsa):
    nowtime=time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time()))+""
    filenames=nowtime+'systeminfo.xlsx'
    workbook1 = xlsxwriter.Workbook(filenames)
    worksheet = workbook1.add_worksheet()
    t1='自定义CENTOS服务器运行情况'
    format=workbook1.add_format()
    #worksheet.set_column(0,15,20)
    format.set_bold()
    yellow=workbook1.add_format({'align':'center','valign':'vcenter','font_size':22,'fg_color':'FFC1C1'})
    yellow.set_bold()
    # worksheet.merge_range(0,0,0,4,t1,yellow)
    worksheet.merge_range('A1:I1',t1,yellow)
    worksheet.set_row(0, 38)
    worksheet.set_column("A:A",20)
    worksheet.set_column("B:B",11)
    worksheet.set_column("C:C",12)
    worksheet.set_column("D:D",12)
    worksheet.set_column("E:E",20)
    #worksheet.set_column("F:F",13)
    #worksheet.set_column("G:G",10)
    # worksheet.set_column("H:H",13)
    # worksheet.set_column("I:I",38)

    title=[u'IP地址',u'CPU使用率%',u'内存总量',u'内存使用率%',u'巡检结果']
    format=workbook1.add_format()
    #worksheet.set_column(0,15,20)
    format=workbook1.add_format({'align':'center','valign':'vcenter'})
    format.set_bold()
    worksheet.write_row('A2',title,format)
    worksheet.set_row(1, 25)
    row=2
    #col=1
    try:
        myfile=open(ips,'r')
        for line in myfile:
            ip=line.strip()
            try:
                ssh = paramiko.SSHClient()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                pkey = paramiko.RSAKey.from_private_key_file(idrsa)
                ssh.connect(hostname=ip,port=22,username='root',pkey=pkey,timeout=5)
                t = ssh.get_transport()
                sftp=paramiko.SFTPClient.from_transport(t)
                sftp.put("pm.sh","/tmp/pm.sh")
                stdindcpu, stdoutcpu, stderrcpu = ssh.exec_command("top -bn1 | awk '/Cpu/{print $2,$3,$4}' | sed 's/[a-z]//g' | sed 's/ //g' | awk -F',' '{print $1+$2+$3}'")
                stdinmomeryall, stdoutmomeryall, stderrmomeryall = ssh.exec_command("free -m | awk '{print $2}' | awk 'NR==2{print}'")
                stdinmomery, stdoutmomery, stderrmomery = ssh.exec_command("sh /tmp/pm.sh")  #上传并执行这个SHELL脚本来获取内存使用百分比
                musep=(stdoutmomery.read()).replace("\n", "")
                worksheet.write(row,0,ip)
                worksheet.write(row,1,(stdoutcpu.read()).replace("\n", ""))
                worksheet.write(row,2,(stdoutmomeryall.read()).replace("\n", ""))
                #worksheet.write(row,3,(stdoutmomery.read()).replace("\n", ""))
                worksheet.write(row,3,musep)
                remark="正常"
                try:
                    b=round(float(musep))
                    if int(b)>80:
                        remark="评估是否扩内存"  #内存使用率达到80%进行提示
                except Exception:
                    remark="NONE"
                worksheet.write(row,4,remark)  

                ymdhms=time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))



                t = ssh.get_transport()
                sftp=paramiko.SFTPClient.from_transport(t)

                sftp.put("diskpnum.sh","/tmp/diskpnum.sh")
                stdindps, stdoutdps, stderrdps = ssh.exec_command("sh /tmp/diskpnum.sh "+ymdhms)  #上传并执行这个SHELL脚本来获取磁盘信息
                dpnums=(stdoutdps).read().replace("\n", "")  #未使用,保留
                sftp.get("/tmp/diskusetmp"+ymdhms+".txt",ip+"diskusetmp"+ymdhms+".txt")
#把获取的磁盘信息放到本地来读取
                diskinfos=open(ip+"diskusetmp"+ymdhms+".txt",'r')
                n=5
                for lines in diskinfos:
                    cons=lines.split()
                    worksheet.set_column(n,n,20)
                    worksheet.write(row,n,"分区 "+cons[0].strip())
                    worksheet.set_column(n+1,n+1,20)
                    worksheet.write(row,n+1,"分区大小 "+cons[1].strip())
                    worksheet.set_column(n+2,n+2,20)
                    try:
                        dps=round(float(cons[2].strip()))
                        if int(dps)>80:
                            formatmred = workbook1.add_format({'bold': True, 'font_color': 'red'})
                            worksheet.write(row,n+2,"分区使用率 "+cons[2].strip(),formatmred)  #磁盘使用率达到80%用红色字体显示
                        else:
                            worksheet.write(row,n+2,"分区使用率 "+cons[2].strip())
                    except Exception:

                        worksheet.write(row,n+2,"分区使用率 "+cons[2].strip())
                    n=n+3
                #print tmplist
                diskinfos.close()
                os.remove(ip+"diskusetmp"+ymdhms+".txt")  #读取磁盘信息后删掉文件



            except Exception:
                print ip +" error"
                worksheet.write(row,0,ip)
                worksheet.write(row,1,"none")
                worksheet.write(row,2,"none")
                worksheet.write(row,3,"none")


            row=row+1



    except Exception:
        print "cannot open files"

    workbook1.close()



trywexrestrdiskp("ipss.txt","id_rsa")

 

 

二、程序会调用到的两个SHELL脚本

这个是获取内存百分比的

[root@k8s2 tmp]# cat pm.sh 
#!/bin/bash
set -u

InfoFile="/proc/meminfo"
[[ -f $InfoFile ]] || { echo "$InfoFile not exist,please check"; exit 124; }

TotalMem="$(grep '^MemTotal:' /proc/meminfo|grep  -o '[0-9]\{1,\}')"
BuffersMem="$(grep '^Buffers:' /proc/meminfo|grep  -o '[0-9]\{1,\}')"
CachedMem="$(grep '^Cached:' /proc/meminfo|grep  -o '[0-9]\{1,\}')"
FreeMem="$(grep '^MemFree:'  /proc/meminfo|grep  -o '[0-9]\{1,\}')"
RealFreeMem=`expr $FreeMem + $CachedMem + $BuffersMem`
RealUsedMem=`expr $TotalMem - $RealFreeMem`
#echo  $RealFreeMem
echo -e "${RealUsedMem}\t${TotalMem}"|awk '{printf "%2.2f\n",$1/$2*100}'


 

这个是获取磁盘分区信息的

[root@k8s2 tmp]# cat diskpnum.sh 
#!/bin/bash
pnum=`df -hP | grep -v tmpfs | grep -v boot | awk {'print $6'} | sed '1d' | wc -l`
cat /dev/null > /tmp/diskusetmp$1.txt  #脚本接受一个参数,就是PYTHON执行SHELL命令的时候加上的时间戳
for((i=1;i<=$pnum;i++));

do
pname=`df -hP | grep -v tmpfs | grep -v boot | awk {'print $6'} | sed '1d'| sed -n ''$i'p'`
all=`df -hP $pname | awk '{print $2}' | awk 'NR==2{print}'`
usep=`df -hP $pname | awk '{print $5}' | sed s'/%//' | awk 'NR==2{print}'` 
#echo "分区 "$pname "                 大小 "$all "  使用百分比 "$usep
echo $pname" "$all" "$usep >> /tmp/diskusetmp$1.txt

done

echo $pnum
#返回统计的分区的数量,暂时没用到,保留,脚本主要作用就是产生这个文件,让PYTHON取回

 

把这两个脚本放到PYTHON程序的同一级目录,并将做好认证的id_rsa文件和ipss.txt也放在同一级目录,ipss.txt每一行一个IP

 

 

三、执行效果

执行脚本生成的EXCEL

 一台服务器的数据将会在EXCEL表格的同一行显示,不论存在多少个分区,都在同一行的后面显示,如下

 

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页