Chinaunix

标题: python新手求指点,如何才能让代码更加专业. [打印本页]

作者: jackson_cu    时间: 2015-03-23 16:02
标题: python新手求指点,如何才能让代码更加专业.
本代码的主要功能是分析局域网扫描的日志文件, 然后根据电脑的名称或序更号查找资产管理系统中的对应的使用用户, 再发送邮件给这些用户提醒他们晚上没有关机,违反了公司的节能制度!
如果该电脑在白名单中,则忽略!

虽然代码己经工作起来了, 但我总是觉得代码有些地方不如意, 但又不知道怎么改进, 特别是try .... except 这块, 代码不知道怎么放更好.

以下是未关机电脑扫描的日志文件
  1. ======================Nmap Log=======================

  2. Starting Nmap 5.51  at 2015-03-22 23:30 CST
  3. Nmap scan report for 10.188.2.1
  4. Host is up (0.0063s latency).
  5. Nmap scan report for 10.188.2.11
  6. Host is up (0.0022s latency).
  7. Nmap scan report for 10.188.2.20
  8. Host is up (0.00070s latency).
  9. Nmap scan report for 10.188.2.21
  10. Host is up (0.016s latency).
  11. Nmap scan report for shz-pc-0000569.shz.local (10.188.2.63)
  12. Host is up (0.00071s latency).
  13. Nmap scan report for vnn-p0108.shz.local (10.188.2.81)
  14. Host is up (0.00014s latency).
  15. Nmap scan report for d7kqs42x.shz.local (10.188.2.91)
  16. Host is up (0.00040s latency).
  17. Nmap scan report for 10.188.2.106
  18. Host is up (0.00033s latency).
  19. Nmap scan report for vnn90539.shz.local (10.188.2.110)
  20. Host is up (0.00033s latency).
  21. Nmap scan report for d2jcv52x.shz.local (10.188.2.119)
  22. Host is up (0.038s latency).
  23. Nmap scan report for shz-pc-0000176.shz.local (10.188.2.176)
  24. Host is up (0.00042s latency).
  25. ...
  26. ...

  27. =======================END===============================
复制代码
以下是代码
  1. ==================Python Script=============================

  2. #!/usr/bin/env python
  3. import os
  4. import datetime
  5. import sys
  6. import time
  7. import MySQLdb
  8. import smtplib, mimetypes
  9. from email.mime.text import MIMEText
  10. from email.mime.multipart import MIMEMultipart
  11. from email.mime.image import MIMEImage


  12. #To get the hostname by computer name or serialnumber
  13. def getHostName(hostname):
  14.     if hostname.startswith('d'):
  15.         new_hostname = hostname.lstrip('d')
  16.         return new_hostname
  17.     else:
  18.         new_hostname = hostname
  19.         return new_hostname


  20. #To get the PC owner's mail address from database
  21. def getMailFromDB(hostname):
  22.     if hostname.startswith('shz'):
  23.         sql = '''SELECT u.email as mail
  24.                  from glpi_computers as c left join glpi_users as u on c.FK_users=u.id
  25.                  where c.name='%s';''' % hostname
  26.         cursor.execute(sql)
  27.         mail = cursor.fetchone()
  28.         if mail:
  29.             return mail[0]
  30.         else:
  31.             return 0
  32.     else:
  33.         sql = '''SELECT u.email as mail
  34.                  from glpi_computers as c left join glpi_users as u on c.FK_users=u.id
  35.                  where c.serial='%s';''' % hostname
  36.         cursor.execute(sql)
  37.         mail = cursor.fetchone()
  38.         if mail:
  39.             return mail[0]
  40.         else:
  41.             return 0

  42. #To notify the PC owner in order to ask them shutdown their computer
  43. def notifyUser(tomail,hostname):
  44.     msg = MIMEMultipart()
  45.     msg['From'] = "jackson.lee@mymaildomain.com"
  46.     msg['To'] = tomail
  47.     msg['Subject'] = ' !!!Please do not forget to shutdown your computer !!!'

  48.     txt = MIMEText('''Hi, you forgot shutdown your computer [%s] last night, that's why you get this email.\n
  49. To reduce the electric usage risk and save the energy, please shutdown your computer before you leave office.\n
  50. If you think that you need to keep your PC running during the night for working purpose, please send email to\n
  51. your department manager and copy to me to apply the privilege, then IT will remove your PC from our monitoring list.\n
  52. \n
  53. Thanks for your understanding and cooperation!\n
  54. IT Department''' % hostname)
  55.     msg.attach(txt)
  56.     smtp.sendmail('jackson.lee@mymaildomain.com', tomail, msg.as_string())

  57. def alertUser(receipt,hostname):
  58.     print hostname,receipt

  59. # To get the PC list in the white list

  60. white_list = './approve_list.txt'

  61. if os.path.exists(white_list):
  62.     try:
  63.         objfile = open(white_list)
  64.     except IOError:
  65.         print "the file %s can not be opened" % white_list
  66.         exit()

  67. list = objfile.readlines()
  68. approved_pc = []
  69. for tmp_pc in list:
  70.     tmp_pc = tmp_pc.strip('\n')
  71.     approved_pc.append(tmp_pc)

  72. print approved_pc
  73. objfile.close()


  74. #connect to mysql server
  75. db = MySQLdb.connect('dbserver.shz.local','jackson','mypassword','helpdesk')
  76. cursor = db.cursor()

  77. #connect to mail server
  78. smtp = smtplib.SMTP()
  79. smtp.connect('smtpserver.shz.local')

  80. #write the history to the log file
  81. logfile = open('./log.txt','w+')
  82. today = datetime.date.today()
  83. yesterday = today - datetime.timedelta(days=1)
  84. string_yesterday = yesterday.strftime('%Y-%m-%d')
  85. if os.path.exists('../pc_scan/%s' % yesterday):
  86.     try:
  87.         pc_list = os.popen("cat ../pc_scan/%s|grep shz.local|awk '{ print $5 }'|awk -F . '{ print $1 }'" % yesterday)
  88.         all_pc = pc_list.read().splitlines()
  89.         print all_pc
  90.         for pc in all_pc:
  91.             hostname = getHostName(pc)
  92.             if hostname in approved_pc :
  93.                 pass
  94.             else:
  95.                 mail = getMailFromDB(hostname)
  96.                 if mail:
  97.                     notifyUser(mail,hostname)
  98.                     alertUser(mail,hostname)
  99.                     logMessage = string_yesterday+" "+hostname+" "+mail+'\n'
  100.                     logfile.write(logMessage)
  101.                 else:
  102.                     print hostname, "no mail address for this computer"
  103.     except IOError:
  104.         print("sorry, the script can not read the file %s" % yesterday)

  105. # disconnect from mail server
  106. smtp.quit()

  107. #to close the log file
  108. 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