烹茶细论

Python获取服务器硬件信息脚本

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
#-*- coding: UTF-8 -*-
import sys
import os
import paramiko
import MySQLdb
import commands
#导入发邮件的函数
import gmail
import time
import socket
import fcntl
import struct
file_name = "log/message.txt"
description = "lsb_release -a |grep Description | cut -f2 -d :"
cpu = "cat /proc/cpuinfo | grep name | cut -f2 -d: | uniq -c"
bit = "getconf LONG_BIT"
men = "cat /proc/meminfo |grep MemTotal |cut -f2 -d : |awk '{a=int($1/1024/1024+1);b=\"G\";c=(a\"\"b);print c}'"
mun_partitions = "cat /proc/partitions |egrep sd[a-z]{1}$ |wc -l"
parttions = "cat /proc/partitions |egrep sd[a-z]{1}$ |awk '{a=int($3/1024/1024);b=\"G\";c=(a\"\"b);print $4,c}'"
network = "lspci | grep Ethernet |cut -f3 -d :"
kernel_version = "cat /proc/version |awk '{print $3}'"
men_num = "dmidecode|grep -P -A5 'Memory\s+Device'|grep Size|grep -v Range |grep -v 'No Module Installed' |wc -l"
#获取IP地址
def get_ip_address(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(fcntl.ioctl(
s.fileno(),
0x8915, # SIOCGIFADDR
struct.pack('256s', ifname[:15])
)[20:24])
#执行系统命令并获得返回值
def command(comm):
(status, output) = commands.getstatusoutput(comm)
return output.lstrip()
def info():
name = [u'系统', u"系统位数",u"内核版本","cpu",u"内存条数量", u"内存大小", u"磁盘数量", u"磁盘", u"网卡"]
messages = [ description, bit, kernel_version , cpu, men_num, men, mun_partitions, parttions, network]
details = []
for i in range(len(name)):
detail = name[i] + " : "+ command(messages[i]).replace('\n',',')
details.append(detail)
return details
#逐行读取文本内容
def txt():
infos_txt = info()
w = open(file_name, 'w')
msg = ''
for i in infos_txt :
w.write(i)
w.write("\n")
msg = msg + i + "<br>"
w.close()
return msg
def read_txt():
f = open(file_name, 'rw')
text = f.read()
f.close()
return text
'''
首次执行将设备硬件信息写入到当前目录log/message.txt中,并且发送邮件
之后执行,如果信息和之前的一致,不做任何操作
如果信息不一致,则备份log/message.txt 并且发送邮件告知哪里有变化
'''
def files(ifcfg,email):
infos = info()
if os.path.isfile(file_name):
f = open(file_name, 'rw')
text = f.read()
if text == "":
f.close()
message = txt()
title = u"【设备信息】新设备"+get_ip_address(ifcfg)
gmail.send('mail@XX.com', email, title , message)
else :
f.close()
file_line = open(file_name, 'rw')
try:
i = 0
result = 0
mesg_alerts = ''
while 1:
line = file_line.readline()
if not line:
break
line = line.replace('\n','')
lines = line.split(':')
old_mesg = lines[1].lstrip()
new_info = infos[i].split(':')
new_mesg = new_info[1].lstrip()
if new_mesg != old_mesg :
mesg_alert = lines[0] + u" 由原来的 " + old_mesg + u" 变为 " + new_mesg
mesg_alerts += mesg_alert +"<br>"
result = 1
i += 1
if result == 1 :
print mesg_alerts
times = time.strftime('%Y-%m-%d',time.localtime(time.time()))
comm = "mv log/message.txt log/message%s.txt" % times
os.system(comm)
txt()
title = u"【设备信息】设备硬件变更"+get_ip_address(ifcfg)
gmail.send('mail@XX.com', email, title , mesg_alerts)
else :
print "设备正常"
finally:
file_line.close()
else:
if os.path.exists("log") == False:
os.mkdir("log")
f = open(file_name, 'w')
f.write("")
f.close()
message = txt()
title = u"【设备信息】新设备"+get_ip_address(ifcfg)
gmail.send('mail@XX.com', email, title , message)
if __name__=="__main__":
#ifcname 网卡名称
ifname ="eth0"
email ="who@mail.com"
files(ifname,email)
[/python]
gmail.py
[python]
'''
别人的的邮件发送脚本,引用。
'''
#-*- encoding: utf-8 -*-
import email
import string, sys, os, email
import time
import smtplib, datetime
from email import Message, Header, MIMEText, MIMEMultipart
reload(sys)
sys.setdefaultencoding('utf-8')
class MailCreator:
def __init__(self):
# 创建邮件的message对象
self.msg = email.Message.Message()
self.mail = ""
def create(self, mailheader, maildata, mailattachlist=[]):
# mailheader 是dict类型,maildata是list, 且里面第一项为纯文本类型,第二项为html.
# mailattachlist 是list, 里面为附件文件名
if not mailheader or not maildata:
return
for k in mailheader.keys():
# 对subject要作特殊处理,中文要转换一下。
# 比如 "我的一个测试邮件" 就要转换为 =?gb2312?b?ztK1xNK7uPay4srU08q8/g==?=
if k == 'subject':
self.msg[k] = email.Header.Header(mailheader[k], 'gb2312')
else:
self.msg[k] = mailheader[k]
# 创建纯文本部分
body_plain = email.MIMEText.MIMEText(maildata[0], _subtype='plain', _charset='gb2312')
body_html = None
# 创建html部分,这个是可选的
if maildata[1]:
body_html = email.MIMEText.MIMEText(maildata[1], _subtype='html', _charset='gb2312')
# 创建一个multipart, 然后把前面的文本部分和html部分都附加到上面,至于为什么,可以看看mime相关内容
attach=email.MIMEMultipart.MIMEMultipart()
attach.attach(body_plain)
if body_html:
attach.attach(body_html)
# 处理每一个附件
for fname in mailattachlist:
attachment=email.MIMEText.MIMEText(email.Encoders._bencode(open(fname,'rb').read()))
# 这里设置文件类型,全部都设置为Application.当然也可以是Image,Audio什么的,这里不管那么多
attachment.replace_header('Content-type','Application/octet-stream;name="'+os.path.basename(fname)+'"')
# 一定要把传输编码设置为base64,因为这里默认就是用的base64
attachment.replace_header('Content-Transfer-Encoding', 'base64')
attachment.add_header('Content-Disposition','attachment;filename="'+os.path.basename(fname)+'"')
attach.attach(attachment)
# 生成最终的邮件
self.mail = self.msg.as_string()[:-1] + attach.as_string()
return self.mail
def dosend(header, msg):
#发送邮件
s = smtplib.SMTP('smtp.gmail.com')
s.set_debuglevel(0)
s.ehlo()
s.starttls()
s.ehlo()
s.login('bot@zdworks.com', 'zwikUps6')
dest_str = header['to']
dests = dest_str.split(',')
s.sendmail(header['from'], dests, msg)
s.close()
def send(From, To, title, body, attachments=[]):
mc = MailCreator()
header = {'from': From, 'to': To, 'subject': title.encode("gb2312")}
data = ['', body.encode('gb2312')]
mail = mc.create(header, data, attachments)
dosend(header, mail)
def send_by_file(From, To, title, body, attachments=[]):
lines = []
if os.path.exists(path):
f = open(path)
lines = f.readlines()
f.close()
msg = ""
for line in lines:
msg = msg + line + u"<br>"
send(From, To, title, msg, attachments)
if __name__ == '__main__':
#send('a', 'b', 't', 'ok')
send('mail@gmial.com','收件人',u'标题',u'内容')

结果:

系统 : No LSB modules are available., Ubuntu 10.10

系统位数 : 64

内核版本 : 2.6.32-24-server

cpu : 8 Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz

内存条数量 : 4

硬件内存大小 : 8G

系统检测内存大小 : 8G

磁盘数量 : 2

磁盘 : sda 931G,sdb 1863G

网卡 : Realtek Semiconductor Co., Ltd. RTL8111/8168B PCI Express Gigabit Ethernet controller (rev 06)