用python实现服务器监控,通过SSH可以实现服务器状态的获取,通过socket实现应用服务端口测试应用状态。
# -*- coding: utf-8 -*-
import os
import socket
import time
pemfile = "/home/zjk/.ssh/服务器登录证书.pem"
# 服务器列表
serverList = [
{
"name": "01服务器",
"server": "www.server01.com",
"user": "root",
},
{
"name": "02服务器",
"server": "www.server02.com",
"user": "root",
},
]
# 应用系统列表
serviceList = [
{
"name": "后端服务器",
"server": "b.server01.com",
"port": 8540,
},
{
"name": "UI",
"server": "03.server01.com",
"port": 8010,
},
]
def queryServerState():
states = {"server": [], "service": []}
print("==================================================\033[1;31m服务器状态", '\033[0m')
for s in serverList:
sinfo = {}
sinfo["name"] = s["name"]
sinfo["server"] = s["server"]
sinfo["type"] = "server"
# try:
print("-----------------------------------------------------------------------\033[1;34m" + s["server"], '\033[0m')
out=os.popen("timeout 5s ssh -o StrictHostKeyChecking=no " + s["user"] + "@" + s["server"] + " -i " + pemfile + " 'uptime'").read().strip()
print(out)
sinfo["uptime"] = out
time.sleep(0.1)
print("--------------------------------------")
try:
out=os.popen("timeout 5s ssh -o StrictHostKeyChecking=no " + s["user"] + "@" + s["server"] + " -i " + pemfile + " 'df -h | grep \"/$\"'").read().strip()
# print(out)
a = out.split(" ")
# print(a)
l = ""
for i in a:
if i != "":
l = l + i + ","
print(l)
sinfo["df"] = l
except Exception:
sinfo["df"] = "ERROR"
print("\033[1;31mERROR", '\033[0m', s["name"], s["server"], '\033[0m')
time.sleep(0.1)
print("--------------------------------------")
try:
out=os.popen("timeout 5s ssh -o StrictHostKeyChecking=no " + s["user"] + "@" + s["server"] + " -i " + pemfile + " 'free -h | sed -n \'2,2p\''").read().strip()
# print(out)
a = out.split(" ")
# print(a)
l = ""
for i in a:
if i != "":
l = l + i + ","
print(l)
sinfo["free"] = l
except Exception:
sinfo["free"] = "ERROR"
print("\033[1;31mERROR", '\033[0m', s["name"], s["server"], '\033[0m')
time.sleep(0.1)
sinfo["reftime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
states["server"].append(sinfo)
print("==================================================\033[1;31m应用系统状态", '\033[0m')
for s in serviceList:
sinfo = {}
sinfo["name"] = s["name"]
sinfo["server"] = s["server"]
sinfo["type"] = "service"
sinfo["port"] = s["port"]
rs = ""
try:
sk = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sk.settimeout(5)
sk.connect((s["server"],s["port"]))
rs = "OK"
print("\033[0;32mOK", '\033[0m', s["name"], s["server"], s["port"], '\033[0m')
except Exception:
rs = "NO"
print("\033[1;31mNO", '\033[0m', s["name"], s["server"], s["port"], '\033[0m')
sk.close()
sinfo["state"] = rs
sinfo["reftime"] = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
states["service"].append(sinfo)
time.sleep(0.1)
return states
if __name__ == "__main__":
print(queryServerState())
取得了数据就可以嵌入到应用中提取、处理、显示了。
Copyright © 2021 .长沙麦涛网络科技有限公司 All rights reserved.
湘ICP备20015126号-2
联系我们