Chinaunix
标题:
python新手求指点,如何才能让代码更加专业.
[打印本页]
作者:
jackson_cu
时间:
2015-03-23 16:02
标题:
python新手求指点,如何才能让代码更加专业.
本代码的主要功能是分析局域网扫描的日志文件, 然后根据电脑的名称或序更号查找资产管理系统中的对应的使用用户, 再发送邮件给这些用户提醒他们晚上没有关机,违反了公司的节能制度!
如果该电脑在白名单中,则忽略!
虽然代码己经工作起来了, 但我总是觉得代码有些地方不如意, 但又不知道怎么改进, 特别是try .... except 这块, 代码不知道怎么放更好.
以下是未关机电脑扫描的日志文件
======================Nmap Log=======================
Starting Nmap 5.51 at 2015-03-22 23:30 CST
Nmap scan report for 10.188.2.1
Host is up (0.0063s latency).
Nmap scan report for 10.188.2.11
Host is up (0.0022s latency).
Nmap scan report for 10.188.2.20
Host is up (0.00070s latency).
Nmap scan report for 10.188.2.21
Host is up (0.016s latency).
Nmap scan report for shz-pc-0000569.shz.local (10.188.2.63)
Host is up (0.00071s latency).
Nmap scan report for vnn-p0108.shz.local (10.188.2.81)
Host is up (0.00014s latency).
Nmap scan report for d7kqs42x.shz.local (10.188.2.91)
Host is up (0.00040s latency).
Nmap scan report for 10.188.2.106
Host is up (0.00033s latency).
Nmap scan report for vnn90539.shz.local (10.188.2.110)
Host is up (0.00033s latency).
Nmap scan report for d2jcv52x.shz.local (10.188.2.119)
Host is up (0.038s latency).
Nmap scan report for shz-pc-0000176.shz.local (10.188.2.176)
Host is up (0.00042s latency).
...
...
=======================END===============================
复制代码
以下是代码
==================Python Script=============================
#!/usr/bin/env python
import os
import datetime
import sys
import time
import MySQLdb
import smtplib, mimetypes
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
#To get the hostname by computer name or serialnumber
def getHostName(hostname):
if hostname.startswith('d'):
new_hostname = hostname.lstrip('d')
return new_hostname
else:
new_hostname = hostname
return new_hostname
#To get the PC owner's mail address from database
def getMailFromDB(hostname):
if hostname.startswith('shz'):
sql = '''SELECT u.email as mail
from glpi_computers as c left join glpi_users as u on c.FK_users=u.id
where c.name='%s';''' % hostname
cursor.execute(sql)
mail = cursor.fetchone()
if mail:
return mail[0]
else:
return 0
else:
sql = '''SELECT u.email as mail
from glpi_computers as c left join glpi_users as u on c.FK_users=u.id
where c.serial='%s';''' % hostname
cursor.execute(sql)
mail = cursor.fetchone()
if mail:
return mail[0]
else:
return 0
#To notify the PC owner in order to ask them shutdown their computer
def notifyUser(tomail,hostname):
msg = MIMEMultipart()
msg['From'] = "jackson.lee@mymaildomain.com"
msg['To'] = tomail
msg['Subject'] = ' !!!Please do not forget to shutdown your computer !!!'
txt = MIMEText('''Hi, you forgot shutdown your computer [%s] last night, that's why you get this email.\n
To reduce the electric usage risk and save the energy, please shutdown your computer before you leave office.\n
If you think that you need to keep your PC running during the night for working purpose, please send email to\n
your department manager and copy to me to apply the privilege, then IT will remove your PC from our monitoring list.\n
\n
Thanks for your understanding and cooperation!\n
IT Department''' % hostname)
msg.attach(txt)
smtp.sendmail('jackson.lee@mymaildomain.com', tomail, msg.as_string())
def alertUser(receipt,hostname):
print hostname,receipt
# To get the PC list in the white list
white_list = './approve_list.txt'
if os.path.exists(white_list):
try:
objfile = open(white_list)
except IOError:
print "the file %s can not be opened" % white_list
exit()
list = objfile.readlines()
approved_pc = []
for tmp_pc in list:
tmp_pc = tmp_pc.strip('\n')
approved_pc.append(tmp_pc)
print approved_pc
objfile.close()
#connect to mysql server
db = MySQLdb.connect('dbserver.shz.local','jackson','mypassword','helpdesk')
cursor = db.cursor()
#connect to mail server
smtp = smtplib.SMTP()
smtp.connect('smtpserver.shz.local')
#write the history to the log file
logfile = open('./log.txt','w+')
today = datetime.date.today()
yesterday = today - datetime.timedelta(days=1)
string_yesterday = yesterday.strftime('%Y-%m-%d')
if os.path.exists('../pc_scan/%s' % yesterday):
try:
pc_list = os.popen("cat ../pc_scan/%s|grep shz.local|awk '{ print $5 }'|awk -F . '{ print $1 }'" % yesterday)
all_pc = pc_list.read().splitlines()
print all_pc
for pc in all_pc:
hostname = getHostName(pc)
if hostname in approved_pc :
pass
else:
mail = getMailFromDB(hostname)
if mail:
notifyUser(mail,hostname)
alertUser(mail,hostname)
logMessage = string_yesterday+" "+hostname+" "+mail+'\n'
logfile.write(logMessage)
else:
print hostname, "no mail address for this computer"
except IOError:
print("sorry, the script can not read the file %s" % yesterday)
# disconnect from mail server
smtp.quit()
#to close the log file
objfile.close()
复制代码
作者:
substr函数
时间:
2015-08-04 22:10
如果你想速成的话,建议还是去找个培训班吧
作者:
donalds2008
时间:
2015-08-05 13:52
很好啊,能工作就OK
作者:
jackson_cu
时间:
2015-10-09 16:01
回复
3#
donalds2008
非常感谢, 总觉得自己的代码好像挺啰嗦的, 没有别人的干练.
作者:
dhhb
时间:
2015-10-16 15:42
pc_list = os.popen("cat ../pc_scan/%s|grep shz.local|awk '{ print $5 }'|awk -F . '{ print $1 }'" % yesterday)
你这里只grep shz.local,是看不到是否up/down了吧
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2