概述
最近抽时间写了一个自动巡检脚本,只需配置服务器ip、用户名、密码即可实现服务器自动巡检,巡检日志以txt文件输出,免去了挨个敲命令巡检的麻烦,脚本比较简单可拉去代码进行二次开发。可以加上定时任务和巡检报告发送邮箱功能,实现完全托管。
源码
以下是完整代码:
#!/usr/bin/python3
from netmiko.huawei.huawei import huaweissh
import os
from datetime import datetime
import smtplib
from email.mime.text import mimetext
from email.header import header
from email.mime.multipart import mimemultipart
cmd_str = 'cmd_str'
cmd_name = 'name'
ip = 'ip'
user_name = 'username'
password = 'password'
# email config
smtp_host = '你的邮箱发送付服务地址'
smtp_port = 25
smtp_email = '你的发送邮箱号'
# 用户名,默认为发件人邮箱前缀
smtp_user ='你的发送邮箱号'
# 密码(注意,某些邮箱需要为smtp服务单独设置授权码,详情查看相关帮助)
smtp_password = '你的发送邮箱密码'
class servermaintenance:
net_connect = none
curr_dir = os.getcwd()
fo = none
file_name = none
email_files = []
# 建立服务器连接
def connect_huaweissh(self, _ip, _user_name, _pw):
try:
s5720 = {
'device_type': 'huawei',
'ip': _ip,
'username': _user_name,
'password': _pw,
}
# 实例化huaweissh
net_connect = huaweissh(**s5720)
self.net_connect = net_connect
except:
print("连接" + _ip + "错误")
# 运行指令
def execute(self, cmd_str, cmd_name):
result = self.net_connect.send_command(cmd_str)
print(result)
self.printfile('\n-------------------------任务【' + cmd_name + '】开始巡查 -------------------------\n')
self.printfile(result)
self.printfile('\n-------------------------任务【' + cmd_name + '】结束巡查 -------------------------\n')
return result
# 关闭连接
def disconnect(self):
self.net_connect.disconnect()
print("连接断开" + self.net_connect)
# 文件写入
def printfile(self, txt):
self.fo.write(txt)
# 发送邮箱
def sendemail(self):
msg = mimemultipart()
msg['from'] = header("master", 'utf-8')
msg['to'] = header('13693567027@163.com', 'utf-8')
subject = 'test email'
msg['subject'] = header(subject, 'utf-8')
# 邮件正文内容
content = ''
for filename in self.email_files:
content+=filename+'\n'
# 邮件附件
att = mimetext(open(filename+'.txt', 'rb').read(), 'base64', 'utf-8')
att['content-type'] = 'application/octet-stream' # 指定文件格式
att["content-disposition"] = 'attachment; filename="服务器巡检报告.txt"'
msg.attach(att)
msg.attach(mimetext(content, 'plain', 'utf-8'))
try:
# # 创建安全连接,使用smtp_ssl连接smtp服务器
smtp_client = smtplib.smtp(smtp_host) # 实例化对象
smtp_client.connect(smtp_host, smtp_port) # 连接163邮箱服务器,端口号为25
# # 向服务器标识用户身份
smtp_client.login(smtp_user, smtp_password)
# 发送邮件
smtp_client.sendmail(smtp_user, '13693567027@163.com', msg.as_string())
print("邮件发送成功")
except smtplib.smtpexception as e:
print("error: 无法发送邮件 ", e)
# 关闭smtp连接
smtp_client.quit()
def run(self,commands,hosts):
for host in hosts:
self.file_name = "服务器巡查_" + host[ip] + '_' + datetime.now().strftime(format="%y年%m月%d日%h时%m分%s秒")
self.email_files.append(self.file_name)
self.fo = open(self.file_name + ".txt", 'w+', encoding='utf-8')
self.connect_huaweissh(host[ip], host[user_name], host[password])
self.printfile(
'\n================================主机开始巡检: ' + host[ip] + '================================\n')
for command in commands:
self.execute(command[cmd_str], command[cmd_name])
self.printfile(
'\n================================主机巡检结束: ' + host[ip] + '================================\n')
commands = [
{cmd_str: "ps -ef |grep java", cmd_name: "运行中的应用"},
{cmd_str: "docker ps", cmd_name: "运行中的容器"},
{cmd_str: "df -th", cmd_name: "磁盘空间"},
{cmd_str: "free -h", cmd_name: "内存"},
{cmd_str: "ps -ef", cmd_name: "进程"},
{cmd_str: "crontab -l", cmd_name: "定时任务"},
{cmd_str: "cat /var/log/messages|grep error && dmesg |grep error", cmd_name: "操作系统日志"},
{cmd_str: "date", cmd_name: "操作系统时间"},
{cmd_str: "firewall-cmd --list-all", cmd_name: "防火墙"},
{cmd_str: "dmidecode -t system", cmd_name: "服务器型号"},
{cmd_str: "uname -a && uname -r", cmd_name: "操作系统与内核"},
{cmd_str: "last", cmd_name: "用户登录日志"},
]
hosts = [
{ip: '你的服务器ip', user_name: '你的服务器账号', password: '你的服务器密码'}
]
servermain = servermaintenance()
servermain.run(commands,hosts)
servermain.sendemail()linux系统巡检常用命令
1、查看服务器型号: dmidecode grep product name 或者 dmidecode -t system 或者 dmidecode -t1 或者dmidecodegrep“product"
2、查看主板的序列号: dmidecode grep serial number 或者 dmidecode -t system|grep serial number
3、统-查看服务器sn序列号和型号: dmidecode grep “system lnformation” -a9 egrepmanufacturer/product serial!
4、查看内核/操作系统: uname-a/r
5、查看操作系统版本: head -n ]/etc/issue #是数字1不是字母l查看centos操作系统版本: cat /etc/centos-release
查看版本: cat /proc/version #类似uname -r
6、查看cpu信息 (型号): cat/proc/cpuinfolgrep namelcut-f2 -d:|unig -c
7、查看物理cpu个数: cat /proc/cpuinfol grep“physicalid” sort uniql wc -l
8、查看每个物理cpu中core的个数(即核数): cat /proc/cpuinfo grep “cpu cores”|uniq
9、查看逻辑cpu的个数: cat /proc/cpuinfolgrep“processor”]wc-
10、查看内存信息: cat /proc/meminfo或者free 命令 或者cat /proc/meminfo grep memtota查看内存信息: dmidecode -t memory 或者dmidecode -t memory|grep
- 查看内存总量: grep memtotal /proc/meminfo
- 查看空闲内存量: grep memfree /proc/meminfo
11、查看所有swap分区的信息: cat /proc/swaps
查看内存使用量和交换区使用量: free-m
12、查看磁盘信息: fdisk - 或者fdisk -grep disk
查看各分区使用情况: df -h
13、列出所有启动的系统服务: chkconfig - list|grep on
14、查看磁盘io的性能:iostat -x 10
15、列出所有pci设备: ispci -tv
- 列出所有usb设备: lsusb -tv
- 列出加载的内核模块: lsmod
- 查看pci设备的信息: cat /proc/pci
16、列出所有usb设备的linux系统信息命令:isusb -tv
17、查看计算机名: hostname
18、查看指定目录的大小: du -sh< 目录名>
19、查看系统运行时间、用户数、负载: uptime
查看系统负载: cat /proc/loadavg
20、查看所有用户的定时任务: crontab -
21、查看挂接的分区状态: mount|column -t
22、查看所有网络接口的属性: ifconfig
23、查看防火墙设置:iptables -l
24、查看路由表: route -n
25、查看所有监听端口: netstat -intp
26、查看所有已经建立的连接: netstat -antp
查看网络统计信息: netstat -s
27、查看设备io端口: cat /proc/ioports
29、查看中断: cat /proc/interrupts
30、查看环境变量:env
31、查看所有进程:ps -ef
实时显示进程状态: top
32、查看活动用户: who
33、查看看磁盘参数(仅适用于ide设备): hdparm -i/dev/hda
查看启动时ide设备检测状况: dmesg|grepide
34、查看指定用户信息: id< 用户名>
35、查看用户登录日志: last
36、查看系统所有用户: cut -d:f1 /etc/passwd
37、查看系统所有组: cut -d: -f1 /etc/group
38、安全检查: cat /etc/passwd cat /etc/group
39、查看db2数据库的表空间详情: db2 list tablespaces show detail
40、日志查看:
- dmesg<目录/日志文件>
- cat /var <目录/日志文件>
- tail -f <目录/日志文件>/var/log/message 系统启动后的信息和错误日志,是red hat linux中最常用的日志之-/var/log/secure 与安全相关的日志信息
- /var/log/maillog 与邮件相关的日志信息
- /var/log/cron 与定时任务相关的日志信息
- /var/log/spooler 与uucp和news设备相关的日志信息
- /var/log/boot.log 守护进程启动和停止相关的日志消息
方法补充
linux-python运维自动巡检脚本
1.使用说明
createtime: 2022-12-21
createby: lln
createinfo:
检查服务器磁盘、内存、网络、docker容器等信息,以json格式输出至同目录下的report文件夹中,便于运维人员查看。
环境说明
centos版本 >=7
python2版本 >=2.6 (兼容python3)
使用步骤
1、将脚本文件linuxopsstartup.py放入任意目录下
2、执行 python linuxopsstartup.py 命令,进行服务器信息检查,检查结果输出至同目录下report文件夹中。
检查结果示例
[
{
"最后启动": [
"15:08 "
],
"发行版本": [
"centos linux release 7.9.2009 (core)"
],
"当前时间": [
"2022-12-20 17:50:13"
],
"系统": [
"gnu/linux"
],
"时区信息": [
"tue, 20 dec 2022 17:50:13 +0800"
],
"运行时间": [
"2022-12-20 17:50:13"
],
"内核": [
"3.10.0-1160.6.1.el7.x86_64"
],
"主机名": [
"localhost.localdomain"
]
},
{
"物理cpu个数": [
"1"
],
"cpu架构": [
"x86_64"
],
"每cpu核心数": [
"4"
],
"cpu型号": [
"intel(r) core(tm) i5-6400 cpu @ 2.70ghz"
],
"逻辑cpu个数": [
"4"
]
},
{
"内存总览": [
" total used free shared buff/cache available",
"mem: 15g 9.2g 307m 783m 5.9g 5.1g",
"swap: 7.8g 237m 7.6g"
]
},
{
"索引总量(mb)": 1125058,
"硬盘使用量(gb)": 1060,
"磁盘总览": [
"文件系统 容量 已用 可用 已用% 挂载点",
"devtmpfs 7.8g 0 7.8g 0% /dev",
"tmpfs 7.8g 0 7.8g 0% /dev/shm",
"tmpfs 7.8g 732m 7.1g 10% /run",
"tmpfs 7.8g 0 7.8g 0% /sys/fs/cgroup",
"/dev/mapper/centos-root 50g 31g 20g 62% /",
"/dev/sda2 1014m 188m 827m 19% /boot",
"/dev/sda1 200m 12m 189m 6% /boot/efi",
"/dev/mapper/centos-home 2.0t 38g 2.0t 2% /home",
"tmpfs 1.6g 0 1.6g 0% /run/user/0"
],
"硬盘总量(gb)": 3726,
"硬盘使用比例(%)": "28.46%",
"索引剩余量(mb)": 1095859,
"索引使用量(mb)": 29198,
"硬盘空余量(gb)": 2665,
"索引使用比例(%)": "2.60%"
},
{
"ip": [
"enp3s0 192.168.11.127/24,br-1849b047c9dd 172.19.0.1/16,docker0 172.17.0.1/16,br-7e3fcfcbbbdf 172.18.0.1/16,br-e9753d63540c 172.20.0.1/16"
],
"gateway": [
"192.168.11.1"
],
"dns": [
"223.5.5.5"
]
},
{
"空密码用户": [
"test"
],
"所有用户名": [
"root",
"bin",
"daemon",
"ntp"
]
},
{
"jdk信息": [
"openjdk version \"1.8.0_275\"",
"openjdk runtime environment (build 1.8.0_275-b01)",
"openjdk 64-bit server vm (build 25.275-b01, mixed mode)"
]
},
{
"防火墙状态": [
"not running"
]
},
{
"ssh开启状态": [
"active"
],
"ssh运行情况": [
"tcp 0 0 0.0.0.0:22 0.0.0.0:* listen 1062/sshd ",
"tcp 0 0 192.168.11.127:22 192.168.11.194:50779 established 10513/sshd: root@pt ",
"tcp 0 0 192.168.11.127:22 192.168.11.194:52458 established 17626/sshd: root@no ",
"tcp6 0 0 :::22 :::* listen 1062/sshd "
]
},
{
"ntp运行情况": [
"active"
]
},
{
"docker-compose version": [
"docker-compose version 1.29.2, build unknown"
],
"docker version": [
"docker version 20.10.0, build 7287ab3"
],
"docket stats": [
"container id name cpu % mem usage / limit mem % net i/o block i/o pids",
"d36c48b5c621 sinfcloud-rabbitmq 1.31% 122.7mib / 15.47gib 0.77% 3.78gb / 4.09gb 63.2mb / 2.58mb 29",
"40db1a93ec2d linux-command 0.00% 144kib / 15.47gib 0.00% 62.1kb / 1.3mb 1.44mb / 0b 1"
]
}
]
脚本完整代码
# -*- coding: utf-8 -*-
"""
linux 自动化脚本
# @time: 2022/11/4 10:20
# @author: lln
# @file: linuxopsstartup.py
"""
import json
import os
import platform
import time
def runcommand(command):
"""
执行命令,将所有读到的数据去除空行
:param command: 命令
:return: 去除空行后的命令
"""
lines = os.popen(command).readlines()
res = []
for line in lines:
res.append(line.replace('\n', ''))
return res
def getsysteminfo():
"""
使用内置库获取系统信息
"""
res = {
"操作系统名称及版本号": platform.platform(),
"操作系统版本号": platform.version(),
"操作系统的位数": platform.architecture(),
"计算机类型": platform.machine(),
"网络名称": platform.node(),
"处理器信息": platform.processor(),
}
return res
def getsystemstatus():
"""
系统信息,仅支持centos进行查询
"""
# 系统
os = runcommand("uname -o")
# 发行版本
release = runcommand("cat /etc/redhat-release 2>/dev/null")
# 内核
kernel = runcommand("uname -r")
# 主机名
hostname = runcommand("uname -n")
# 当前时间
localtime = runcommand("date +'%f %t'")
# 最后启动
lastreboot = runcommand("who -b | awk '{print $3,$4}'")
# 运行时间
uptime = runcommand("date +'%f %t'")
# 当前时区信息
time_zone = runcommand("date -r")
res = {
"系统": os,
"发行版本": release,
"内核": kernel,
"主机名": hostname,
"当前时间": localtime,
"最后启动": lastreboot,
"运行时间": uptime,
"时区信息": time_zone
}
return res
def getcpustatus():
"""
cpu信息
"""
# 物理cpu个数
physical_cpus = runcommand("grep 'physical id' /proc/cpuinfo| sort | uniq | wc -l")
# 逻辑cpu个数
virt_cpus = runcommand("grep 'processor' /proc/cpuinfo | wc -l")
# 每cpu核心数
cpu_kernels = runcommand("grep 'cores' /proc/cpuinfo|uniq| awk -f ': ' '{print $2}'")
# cpu型号
cpu_type = runcommand("grep 'model name' /proc/cpuinfo | awk -f ': ' '{print $2}' | sort | uniq")
# cpu架构
cpu_arch = runcommand("uname -m")
res = {
'物理cpu个数': physical_cpus,
'逻辑cpu个数': virt_cpus,
'每cpu核心数': cpu_kernels,
'cpu型号': cpu_type,
'cpu架构': cpu_arch
}
return res
def getmemstatus():
"""
内存信息
"""
# 总内存
memtotal = runcommand("grep memtotal /proc/meminfo| awk '{print $2}'")
memtotal_num = map(float, memtotal)[0]
# 可用内存
memfree = runcommand("grep memfree /proc/meminfo| awk '{print $2}'")
memfree_num = map(float, memfree)[0]
# 比例
proportion = '{:.4%}'.format(memfree_num / memtotal_num)
res = {
'总内存(gb)': '{:.5}'.format(float(memtotal_num / 1024 / 1024)),
'可用内存(gb)': '{:.5}'.format(float(memfree_num / 1024 / 1024)),
'已用比例(%)': proportion
}
return res
def getmemstatussimple():
memtotal = runcommand("free -h")
res = {
'内存总览': memtotal
}
return res
def getdiskstatus():
"""
磁盘检查
"""
# 生成临时数据记录文件
# os.popen("df -tp | sed '1d' | awk '$2!='tmpfs'{print}'")
# os.popen("df -htp | sed 's/mounted on/mounted/'> /tmp/disk")
# 硬盘总量
diskallinfo = runcommand("df -h | grep -v docker")
disktotal = runcommand("df -tp | sed '1d' | awk '$2!='tmpfs'{print}'| awk '{total+=$3}end{print total}'")
disktotalnum = int(disktotal[0])
# 硬盘使用量
diskused = runcommand("df -tp | sed '1d' | awk '$2!='tmpfs'{print}'| awk '{total+=$4}end{print total}'")
diskusednum = int(diskused[0])
# 硬盘空余量
diskfree = disktotalnum - diskusednum
# 硬盘使用比例
diskusedpercent = '{:.2%}'.format(diskusednum / disktotalnum)
# 索引总量
inodetotal = runcommand("df -itp | sed '1d' | awk '$2!='tmpfs'{print}' | awk '{total+=$3}end{print total}' ")
inodetotal_num = int(inodetotal[0])
# 索引使用量
inodeused = runcommand("df -itp | sed '1d' | awk '$2!='tmpfs'{print}' | awk '{total+=$4}end{print total}' ")
inodeused_num = int(inodeused[0])
# 索引剩余量
inodefree = inodetotal_num - inodeused_num
# 索引使用比例
inodepercent = '{:.2%}'.format(inodeused_num / inodetotal_num)
res = {
'磁盘总览': diskallinfo,
'硬盘总量(gb)': int(disktotalnum / 1024 / 1024),
'硬盘使用量(gb)': int(diskusednum / 1024 / 1024),
'硬盘空余量(gb)': int(diskfree / 1024 / 1024),
'硬盘使用比例(%)': diskusedpercent,
'索引总量(mb)': int(inodetotal_num / 1021),
'索引使用量(mb)': int(inodeused_num / 1021),
'索引剩余量(mb)': int(inodefree / 1021),
'索引使用比例(%)': inodepercent,
}
return res
def getnetworkstatus():
"""
网络检查
"""
gateway = runcommand("ip route | grep default | awk '{print $3}'")
dns = runcommand("grep nameserver /etc/resolv.conf| grep -v '#' | awk '{print $2}' | tr '\n' ',' | sed 's/,$//'")
ip = runcommand(
"ip -f inet addr | grep -v 127.0.0.1 | grep inet | awk '{print $nf,$2}' | tr '\n' ',' | sed 's/,$//'")
# todo 语句有问题会报错,sed的错误,需要检查下执行情况
# mac = runcommand("ip link | grep -v 'loopback\|loopback' | awk '{print $2}' | sed 'n;s/\n//' | tr '\n' ',' | sed 's/,$//'")
res = {
'gateway': gateway,
'dns': dns,
'ip': ip
# 'mac': mac
}
return res
def getuserstatus():
"""
所有用户和空密码用户
"""
all_user = runcommand("awk -f':' '{ print $1}' /etc/passwd")
empty_passwd_user = runcommand("getent shadow | grep -po '^[^:]*(?=::)'")
res = {
'所有用户名': all_user,
'空密码用户': empty_passwd_user
}
return res
def getjdkstatus():
"""
jdk信息
"""
jdkinfo = runcommand("java -version 2>&1")
res = {
'jdk信息': jdkinfo
}
return res
def getfirewallstatus():
"""
防火墙
"""
firewall = runcommand("firewall-cmd --state 2>&1")
# 兼容 ubuntu 防火墙命令报错 sh: not found 特殊处理
for info in firewall:
if "not found" in info:
firewall = runcommand("ufw status")
res = {
'防火墙状态': firewall
}
return res
def sshstatus():
"""
ssh 检查
"""
sshactive = runcommand("systemctl is-active sshd.service")
sshnetstat = runcommand("sudo netstat -atlunp | grep sshd")
res = {
'ssh开启状态': sshactive,
'ssh运行情况': sshnetstat
}
return res
def ntpstatus():
"""
ntp 检查
"""
ntpactive = runcommand("systemctl is-active ntpd")
res = {
'ntp运行情况': ntpactive
}
return res
def dockerstatus():
"""
docker 检查
"""
dk_version = runcommand("docker -v")
dk_stats = []
for info in dk_version:
if "version" not in info:
dk_version = "未安装docker"
else:
lines = os.popen(
"docker stats --all --no-stream").readlines()
for line in lines:
dk_stats.append(line.replace('\n', ''))
dp_version = runcommand("docker-compose --version")
for info in dp_version:
if "version" not in info:
dp_version = "未安装docker-compose"
res = {
'docker version': dk_version,
'docker-compose version': dp_version,
'docker stats': dk_stats
}
return res
def createreportfile(name, text):
"""
创建report的txt文件,并写入数据
"""
report_dir = os.getcwd() + os.sep + "report" + os.sep
# 判断当前路径是否存在,没有则创建new文件夹
if not os.path.exists(report_dir):
os.makedirs(report_dir)
# 在当前py文件所在路径下的new文件中创建txt
report_file = report_dir + name + '.txt'
# 打开文件,open()函数用于打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写。
file = open(report_file, 'w')
# 写入内容信息
file.write(text)
file.close()
print('report_file create success', report_file)
def printsinfcloud():
print("+------------------------------------------------+")
print("| 欢迎使用sinfcloud自动巡检工具 |")
print("| ____ _ __ ____ _ _ |")
print("|/ ___|(_)_ __ / _|/ ___| | ___ _ _ __| | |")
print("|\___ \| | _ \| |_| | | |/ _ \| | | |/ _ | |")
print("| ___) | | | | | _| |___| | (_) | |_| | (_| | |")
print("||____/|_|_| |_|_| \____|_|\___/ \__,_|\__,_| |")
print("| |")
print("+------------------------------------------------+")
if __name__ == '__main__':
printsinfcloud()
outputfilename = time.strftime('%y-%m-%d', time.localtime(time.time())) + "_report"
report = list()
report.append(getsysteminfo())
report.append(getsystemstatus())
report.append(getcpustatus())
report.append(getmemstatussimple())
report.append(getdiskstatus())
report.append(getnetworkstatus())
report.append(getuserstatus())
report.append(getjdkstatus())
report.append(getfirewallstatus())
report.append(sshstatus())
report.append(ntpstatus())
report.append(dockerstatus())
createreportfile(outputfilename,
json.dumps(report, sort_keys=true, indent=4, separators=(',', ':'), ensure_ascii=false))到此这篇关于python实现linux服务器自动巡检脚本的文章就介绍到这了,更多相关python linux自动巡检内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论