# coding: utf-8
"""
作者:xiaofeng
功能:自动获取阿里云服务器的cpu、内存、磁盘、网络流量等信息,定时生产一个excel文件
版本:v1.1.5
日期:21/11/2019
版本迭代:各模块封装成方法,其中优化cpu计算方法
"""
import os,time
import paramiko
import datetime
import re
import xlwt
def main():
print("欢迎使用Linux服务器自动化获取服务器信息工具")
print("此程序每12小时自动获取阿里云服务器状态生成excel文件到本地")
name = "\r正在远程连接生产服务器获取相关信息,请稍等"
for i in range(6):
time.sleep(0.5)
i = i * "."
comand = name + i
print(comand, end="")
print("")
make_excel()
linux_close()
return run_server()
# 服务器相关信息,下面输入你个人的用户名、密码、ip等信息,封装连接函数
def linux_conn(ML):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("192.168.1.100", 22, "root", "123456", timeout=10)
stdin, stdout, stderr = ssh.exec_command(ML)
comand = stdout.read()
if comand != b'':
return comand
else:
ssh.close()
print("-----------------------------------------------------------")
except Exception as re:
print("远程连接失败,请检查网络是否通畅....")
time.sleep(9999999999999)
# 服务器相关信息,下面输入你个人的用户名、密码、ip等信息,封装连接函数
def linux_conn1(ml):
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("192.168.1.101", 22, "root", "123456", timeout=10)
stdin, stdout, stderr = ssh.exec_command(ml)
comand = stdout.read()
if comand != b'':
return comand
else:
ssh.close()
print("信息获取成功,服务器远程连接已断开,进入计时再次连接.....")
print("-----------------------------------------------------------")
except Exception as re:
print("远程连接失败,请检查网络是否通畅....")
time.sleep(9999999999999)
def get_men_info():
# 查询生产服务器查询总内存大小
MemTotal_100 = int(linux_conn("free |grep 'Mem'| awk '{print $2}'"))
# 输入linux命令,查询内存free
MemUsed_100 = int(linux_conn("free |grep 'Mem'| awk '{print $3}'"))
mem_rate_100 = str(100 * round(MemUsed_100/ MemTotal_100, 2)) + "%"
# 查询服务器查询总内存大小
MemTotal_101 = int(linux_conn1("free |grep 'Mem'| awk '{print $2}'"))
# 输入linux命令,查询内存free
MemUsed_101 = int(linux_conn1("free |grep 'Mem'| awk '{print $3}'"))
mem_rate_101 = str(100 * round(MemUsed_101 / MemTotal_101, 2)) + "%"
print("生产服务器内存使用率为:" ,mem_rate_100)
print("测试服务器内存使用率为:", mem_rate_101)
return mem_rate_100,mem_rate_101
def get_cpu_info():
cpu_rate_100 = re.findall(r"\d+\.?\d*",linux_conn("sar -u 1 5 |grep 'Average'| awk '{print $3}'").decode("utf-8"))[0] + "%"
print("生产服务器CPU使用率为:",cpu_rate_100)
cpu_rate_101 = re.findall(r"\d+\.?\d*", linux_conn1("sar -u 1 5 |grep 'Average'| awk '{print $3}'").decode("utf-8"))[0] + "%"
print("测试服务器CPU使用率为:", cpu_rate_101)
return cpu_rate_100,cpu_rate_101
def get_disk_info():
#生产服务器
disk_total_100 = re.findall(r"\d+\.?\d*", linux_conn("df -hl | grep 'overlay2' | awk '{print$2}'").decode("utf-8"))[0]
disk_use_100 = re.findall(r"\d+\.?\d*", linux_conn("df -hl | grep 'overlay2' | awk '{print$3}'").decode("utf-8"))[0]
disk_rate_100 = re.findall(r"\d+\.?\d*", linux_conn("df -hl | grep 'overlay2' | awk '{print$5}'").decode("utf-8"))[0]+"%"
disk_info_100 = disk_use_100 + "G" + "/" + disk_total_100 + "G"
print("生产服务器磁盘的占比为:",disk_info_100)
print("生产服务器磁盘使用率为:",disk_rate_100)
#测试服务器
disk_total_101 = re.findall(r"\d+\.?\d*", linux_conn1("df -hl | grep 'overlay2' | awk '{print$2}'").decode("utf-8"))[0]
disk_use_101 = re.findall(r"\d+\.?\d*", linux_conn1("df -hl | grep 'overlay2' | awk '{print$3}'").decode("utf-8"))[0]
disk_rate_101 = re.findall(r"\d+\.?\d*", linux_conn1("df -hl | grep 'overlay2' | awk '{print$5}'").decode("utf-8"))[
0] + "%"
disk_info_101 = disk_use_101 + "G" + "/" + disk_total_101 + "T"
print("测试服务器磁盘的占比为:", disk_info_101)
print("测试服务器磁盘使用率为:", disk_rate_101)
return disk_info_100,disk_rate_100, disk_info_101, disk_rate_101
def get_net_info():
#查询下行流量
net_recv_100 = linux_conn("sar -n DEV 1 1 |grep 'veth2377eab' |grep 'Average' |awk '{print $5}'").decode("utf-8")
# 查询上行流量
net_send_100 = linux_conn("sar -n DEV 1 1 |grep 'veth2377eab' |grep 'Average' |awk '{print $6}'").decode("utf-8")
print("生产服务器上行网络流量:",net_send_100,end="")
print("生产服务器下行网络流量:",net_recv_100,end="")
# 查询下行流量
net_recv_101 = linux_conn1("sar -n DEV 1 1 |grep 'Average' |grep 'veth8186858' |awk '{print $5}'").decode("utf-8")
# 查询上行流量
net_send_101 = linux_conn1("sar -n DEV 1 1 |grep 'Average' |grep 'veth8186858' |awk '{print $6}'").decode("utf-8")
print("测试服务器上行网络流量:", net_send_101, end="")
print("测试服务器下行网络流量:", net_recv_101, end="")
return net_recv_100, net_send_100,net_recv_101,net_send_101
def get_time_info():
# 获取时间
date_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print("信息获取时间:", date_time)
return date_time
def linux_close():
#调用exit关闭连接终端,ssh对象会获取一个<b''>值,判断返回值是否为它即可完成远程套接字的断开连接
close = linux_conn("exit")
close1 = linux_conn1("exit")
def make_excel():
#获取各模块中的返回值
cpu_rate_100,cpu_rate_101 = get_cpu_info()
mem_rate_100,mem_rate_101 = get_men_info()
disk_info_100, disk_rate_100, disk_info_101, disk_rate_101 = get_disk_info()
net_recv_100, net_send_100,net_recv_101, net_send_101 = get_net_info()
date_time = get_time_info()
now_time = time.strftime('%Y{y}%m{m}%d{d}%H{h}%M{f}').format(y='年', m='月', d='日', h='时', f='分')
workbook_new = now_time + "服务器扫描日报.xlsx"
excelTabel= xlwt.Workbook()#创建excel对象
sheet1=excelTabel.add_sheet("服务器信息",cell_overwrite_ok=True)
borders = xlwt.Borders()
borders.left = 1 # 添加边框-虚线边框
borders.right = 1 # 添加边框-虚线边框
borders.top = 1 # 添加边框-虚线边框
borders.bottom = 1 # 添加边框-虚线边框
style = xlwt.XFStyle()
style.borders = borders
for i in range(10):
sheet1.col(i).width = 4500 #设置单元格宽高
list = ["服务器IP","服务器类型", "mac信息", "cpu信息", "内存信息", "磁盘信息(使用/总共)",
"磁盘使用率", "上行网络(kb)", "下行网络(kb)", "获取时间"]
info_100 = ["192.168.1.100","生产服务器","D6:5D:A5:9E:8B:2C",cpu_rate_100,mem_rate_100,disk_info_100,
disk_rate_100,net_send_100,net_recv_100,date_time]
info_101 = ["192.168.1.101","测试服务器","FE:54:00:FB:84:B7",cpu_rate_101,mem_rate_101,disk_info_101,
disk_rate_101,net_send_101,net_recv_101,date_time]
for i in range(10): #循环插入表头信息
a = list[i]
sheet1.write(0, i, a, style)
for i in range(10): #循环插入获取信息
b = info_100[i]
c = info_101[i]
sheet1.write(1, i, b, style)
sheet1.write(2, i, c, style)
excelTabel.save("服务器信息.xlsx")
os.renames("服务器信息.xlsx",workbook_new)
def run_server():
for i in range(43201):
seconds = 43101 - i
time.sleep(1)
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
print("\r距离系统再次扫描时间为%02d:%02d:%02d" % (h, m, s), end="")
print("")
print("-----------------------------------------------------------")
return main()
if __name__ == '__main__':
main()