Python系统巡检脚本

需求

领导要求春节期间对某台业务服务器进行重点巡检,但是回老家很不方便,所以制定一个脚本。
脚本思路大概如下:

1、获取服务器的性能信息,业务信息,数据库备份信息等
2、制定word模板
3、将服务器信息插入到word模板中生成新的word文档
4、将word文档通过邮件方式发送给领导

具体实现

word模板主要信息定制如下

Alt text

脚本内容如下

使用脚本之前需要解决缺少openssl-devel支持的问题,命令如下:

1
yum install gcc libffi-devel python-devel openssl-devel -y

在脚本内需要使用psutil包和docxtpl包,使用pip安装:

1
2
3
pip install psutil
pip install docxtpl
pip install paramiko

脚本内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
#!/usr/bin/python
# coding:utf-8
#Author:Francis

import os
import subprocess
import psutil
import time
import commands
import datetime
import smtplib

from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from psutil import *
from docxtpl import DocxTemplate

def date_1():
return time.strftime('%Y/%m/%d',time.localtime(time.time()))

def date_2():
return time.strftime('%Y%m%d',time.localtime(time.time()))

def hostname():
print socket.gethostname()

def cpu_usage_rate():
#cmd = """ top -bn1 | grep '%Cpu(s)'|awk '{for(i=1;i<9;i=i+1){printf $i" "};printf "\n"}' """
cmd = """ top -bn1 | grep '%Cpu(s)'|awk '{for(i=1;i<9;i=i+1){printf $i" "}}' """
cpu_usage = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
#print (cpu_usage.stdout.read())
#print ('获取内存占用率: '+(str)(psutil.virtual_memory().percent)+'%')
#print ('打印本机cpu占用率: '+(str)(psutil.cpu_percent(0))+'%')
return cpu_usage.stdout.read()

def os_load_average():
cmd = """ uptime | sed 's/,//g' | awk '{print $8,$9,$10}' """
load_average = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
#rint (load_average.stdout.read())
return load_average.stdout.read()

def memory_usage_rate():
vime = virtual_memory()
#print 'Memory: %5s%% %6s/%s' % (
#vime.percent, str(int(vime.used / 1024 / 1024)) + 'M', str(int(vime.total / 1024 / 1024)) + 'M')
return 'Memory: %5s%% %6s/%s' % (
vime.percent, str(int(vime.used / 1024 / 1024)) + 'M', str(int(vime.total / 1024 / 1024)) + 'M')

def disk_info():
cmd = """ df -h|grep '/dev/vd' """
disk_info = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
#print (disk_info.stdout.read())
return disk_info.stdout.read()

def process_info():
cmd = """ ps -ef|grep java|grep -Ev 'grep' """
process_info = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
#print (process_info.stdout.read())
return process_info.stdout.read()



def is_error(SubStrList,Str):
#判断字符串Str是否包含序列SubStrList中的每一个子字符串
flag=[]
for substr in SubStrList:
for i in Str:
if substr in i:
flag.append(i)

return flag

def new_error_file():
#要求文件名称中包含这些字符
keyword=['error']
file_dir = "/data/work/log/"
listtmp=os.listdir(file_dir)
#rint listtmp
#rint '—'*100
list=is_error(keyword,listtmp)
#rint list
list.sort(key=lambda fn: os.path.getmtime(file_dir+fn) if not os.path.isdir(file_dir+fn) else 0)
file=os.path.join(file_dir,list[-1])
d=datetime.datetime.fromtimestamp(os.path.getmtime(file_dir+list[-1]))
#rint '—'*100
#rint('最后改动的文件是'+list[-1]+",时间:"+d.strftime("%Y-%m-%d %H-%M-%S"))
#rint file
return file

def mysql_status():
cmd = """ ps -ef|grep mysql|grep -Ev 'grep' """
mysql_status = subprocess.Popen(cmd, shell=True, stdout = subprocess.PIPE, stderr = subprocess.STDOUT)
#print (mysql_status.stdout.read())
return mysql_status.stdout.read()

def mysql_backup_file():
testdir = "/data/mysql/backup/"
#列出目录下所有的文件
list = os.listdir(testdir)
#对文件修改时间进行升序排列
list.sort(key=lambda fn: os.path.getmtime(testdir+fn) if not os.path.isdir(testdir+fn) else 0)
#获取最新修改时间的文件
filetime = datetime.datetime.fromtimestamp(os.path.getmtime(testdir+list[-1]))
#获取文件所在目录
filepath = os.path.join(testdir,list[-1])
#rint("最新修改的文件(夹):"+list[-1])
#rint("时间:"+filetime.strftime('%Y-%m-%d %H-%M-%S'))
#print filepath
return filepath

def mysql_backup():
testdir = "/data/mysql/backup/"
#列出目录下所有的文件
list = os.listdir(testdir)
#对文件修改时间进行升序排列
list.sort(key=lambda fn:os.path.getmtime(testdir + fn))
#获取最新修改时间的文件
filetime = datetime.datetime.fromtimestamp(os.path.getmtime(testdir+list[-1]))
#获取文件所在目录
filepath = os.path.join(testdir,list[-1])
#rint("最新修改的文件(夹):"+list[-1])
#rint("时间:"+filetime.strftime('%Y-%m-%d %H-%M-%S'))
#print filepath
return filepath

def get_disk_info():
print '磁盘信息:'
for i in disk_io_counters(perdisk=True).items():
print i

def get_net_info():
print '网络情况:'
for i in net_io_counters(pernic=True).items():
print i

def create_email(email_from, email_to, email_Subject, email_text, annex_path, annex_name):
# 输入发件人昵称、收件人昵称、主题,正文,附件地址,附件名称生成一封邮件
#生成一个空的带附件的邮件实例
message = MIMEMultipart()
#将正文以text的形式插入邮件中
message.attach(MIMEText(email_text, 'plain', 'utf-8'))
#生成发件人名称(这个跟发送的邮件没有关系)
message['From'] = Header(email_from, 'utf-8')
#生成收件人名称(这个跟接收的邮件也没有关系)
message['To'] = Header(email_to, 'utf-8')
#生成邮件主题
message['Subject'] = Header(email_Subject, 'utf-8')
#读取附件的内容
att1 = MIMEText(open(annex_path, 'rb').read(), 'base64', 'utf-8')
att1["Content-Type"] = 'application/octet-stream'
#生成附件的名称
att1.add_header('Content-Disposition', u'attachment', filename = ("utf-8", "",annex_name))
#att1["Content-Disposition"] = add_header('attachment; filename=' + annex_name)
#att1["Content-Disposition"] = 'attachment; filename=' + annex_name
#将附件内容插入邮件中
message.attach(att1)
#返回邮件
return message

def send_email(sender, password, receiver, msg):
# 一个输入邮箱、密码、收件人、邮件内容发送邮件的函数
try:
#找到你的发送邮箱的服务器地址,已加密的形式发送
server = smtplib.SMTP_SSL("smtp.exmail.qq.com", 465) # 发件人邮箱中的SMTP服务器
server.ehlo()
#登录你的账号
server.login(sender, password) # 括号中对应的是发件人邮箱账号、邮箱密码
#发送邮件
server.sendmail(sender, receiver, msg.as_string()) # 括号中对应的是发件人邮箱账号、收件人邮箱账号(是一个列表)、邮件内容
print("邮件发送成功")
server.quit() # 关闭连接
except Exception:
print(traceback.print_exc())
print("邮件发送失败")

session000 = date_2()
session001 = cpu_usage_rate()
session002 = os_load_average()
session003 = memory_usage_rate()
session004 = disk_info()
session005 = process_info()
session006 = new_error_file()
session007 = mysql_status()
session008 = mysql_backup_file()
session009 = date_1()

def main():
docx_into = "/data/scripts/gbj_ls_checkos_template.docx"
docx_out = open("gbj_ls_checkos_" + session000 + ".docx",'w')
tpl=DocxTemplate(docx_into)
sd = tpl.new_subdoc()
context = {
'output001' : "%s" % session001,
'output002' : "%s" % session002,
'output003' : "%s" % session003,
'output004' : "%s" % session004,
'output005' : "%s" % session005,
'output006' : "%s" % session006,
'output007' : "%s" % session007,
'output008' : "%s" % session008,
'output009' : "%s" % session009,
}

tpl.render(context)
tpl.save(docx_out)


my_email_from = '我发'
my_email_to = '你收'
# 邮件标题
my_email_Subject = '巡检报告'
# 邮件正文
my_email_text = "Dear all,\n\t附件为你猜猜是什么,请查收!\n\n我发的"
#附件地址
my_annex_path = "gbj_ls_checkos_" + session000 + ".docx"
#附件名称
my_annex_name = "gbj_ls_checkos__" + session000 + ".docx"
# 生成邮件
my_msg = create_email(my_email_from, my_email_to, my_email_Subject,
my_email_text, my_annex_path, my_annex_name)
my_sender = 'yunwei@actionsky.com'
my_password = 'Action!23'
#接收人邮箱列表
my_receiver = ['fujinpeng@actionsky.com','dutingting@actionsky.com','meilei@actionsky.com']
#发送邮件
send_email(my_sender, my_password, my_receiver, my_msg)
print(datetime.datetime.now())

'''
print '—'*100
hostname()
print '\n'
cpu_usage_rate()
print '\n'
os_load_average()
print '\n'
memory_usage_rate()
print '\n'
disk_info()
print '\n'
process_info()
print '\n'
new_error_file()
print '\n'
mysql_status()
print '\n'
mysql_backup_file()
print '\n'
mysql_backup()
print '\n'
get_net_info()
print '\n'
get_disk_info()
print '\n'
print date_1()
print '\n'
print date_2()
'''

if __name__ == '__main__':
main()

本文标题:Python系统巡检脚本

文章作者:Francis

原始链接:http://www.cnops.com/posts/d00f65b4.html

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。