# -*- coding: utf-8 -*-
# @Time : xxx
# @Author : xuping
# @Email : xxxx
# @File : monitor_server.py
# @Software: PyCharm
import paramiko
import re
import time
class MonitorServer:
'''
创建 ssh 连接函数
hostname, port, username, password,访问linux的ip,端口,用户名以及密码
'''
def sshConnect(self,hostname, port, username, password):
paramiko.util.log_to_file('paramiko_log')
try:
#创建一个SSH客户端client对象
sshClient = paramiko.SSHClient()
# 获取客户端host_keys,默认~/.ssh/known_hosts,非默认路径需指定
sshClient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#创建SSH连接
sshClient.connect(hostname, port, username, password)
except Exception as e:
print("SSH链接失败:[hostname:%s];[username:%s];[error:%s]" %(hostname,username,e))
exit()
return sshClient
'''
创建命令执行函数
command 传入linux运行指令
'''
def sshExecCmd(self,sshClient,command):
stdin, stdout, stderr = sshClient.exec_command(command)
filesystem_usage = stdout.readlines()
return filesystem_usage
'''
关闭ssh
'''
def sshClose(self,sshClient):
sshClient.close()
'''内存监控'''
def mem_info(self,linuxInfo):
command = 'cat /proc/meminfo'
for info in linuxInfo:#遍历所有服务器并去监控内存
hostname = info[0]
port = info[1]
username = info[2]
password = info[3]
sshClient = self.sshConnect(hostname, port, username, password)
sshRes = self.sshExecCmd(sshClient,command)
mem_values = re.findall("(\d+)\ kB", ",".join(sshRes))
MemTotal = mem_values[0]
MemFree = mem_values[1]
Buffers = mem_values[2]
Cached = mem_values[3]
SwapCached = mem_values[4]
SwapTotal = mem_values[13]
SwapFree = mem_values[14]
print('******************************内存监控,对应主机[name:%s]*********************************'% hostname)
print("*******************时间:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "******************")
print("总内存:", MemTotal)
print("空闲内存:", MemFree)
print("给文件的缓冲大小:", Buffers)
print("高速缓冲存储器使用的大小:", Cached)
print("被高速缓冲存储用的交换空间大小:", SwapCached)
print("给文件的缓冲大小:", Buffers)
if int(SwapTotal) == 0:
print(u"交换内存总共为:0")
else:
Rate_Swap = 100 - 100 * int(SwapFree) / float(SwapTotal)
print(u"交换内存利用率:", Rate_Swap)
Free_Mem = int(MemFree) + int(Buffers) + int(Cached)
Used_Mem = int(MemTotal) - Free_Mem
Rate_Mem = 100 * Used_Mem / float(MemTotal)
print(u"内存利用率:", str("%.2f" % Rate_Mem), "%")
self.sshClose(sshClient)
"""
磁盘空间监控
"""
def disk_stat(self,linuxInfo):
command = 'df -h'
for info in linuxInfo:
hostname = info[0]
port = info[1]
username = info[2]
password = info[3]
sshClient = self.sshConnect(hostname, port, username, password)
sshRes = self.sshExecCmd(sshClient, command)
sshResStr = ''.join(sshRes)
sshResList = sshResStr.strip().split('\n')
sshResLists=[]
disk_values = re.findall("(\d+)", str(sshResList[1:1]))
if disk_values == []:
fisrtStr = ' '.join(sshResList[1:3])
sshResLists.append(fisrtStr.strip().split())
for disk in sshResList[3:]:
sshResLists.append(disk.strip().split())
print('************************磁盘空间监控,对应主机[name:%s]****************************'%hostname)
print("*******************时间:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "******************")
for disklist in sshResLists:
print("\t文件系统:", disklist[0])
print("\t容量:", disklist[1])
print("\t已用:", disklist[2])
print("\t可用:", disklist[3])
print("\t已用%挂载点:", disklist[4])
print("\t磁盘挂载的目录所在(挂载点)",disklist[5])
self.sshClose(sshClient)
"""
端口监控
"""
def get_Com_Str(self,linuxInfo):
command = 'netstat -tpln'
for info in linuxInfo:
hostname = info[0]
port = info[1]
username = info[2]
password = info[3]
sshClient = self.sshConnect(hostname, port, username, password)
sshRes = self.sshExecCmd(sshClient, command)
sshResStr = ''.join(sshRes)
sshResList = sshResStr.strip().split('\n')
sshResLists = []
for sshCom in sshResList[2:]:
sshResLists.append(sshCom.strip().split())
print('******************************端口监控,对应主机[name:%s]*********************************'%hostname)
print("*******************时间:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), "******************")
for temp in sshResLists:
print("\t Proto:",temp[0])
print("\t Recv-Q:", temp[1])
print("\t Send-Q:", temp[2])
print("\t Local Address:", temp[3])
print("\t Foreign Address:", temp[4])
print("\t State:", temp[5])
print("\t PID/Program name:", temp[6])
print("****************************************")
**各位小伙伴们可以再这里继续添加想要监控的资源,上面是简单的列了几个简单封装几个方法,资源监控可以根据需求不断完善即可**