免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3623 | 回复: 4
打印 上一主题 下一主题

python新手求指点,如何才能让代码更加专业. [复制链接]

论坛徽章:
1
2015年辞旧岁徽章
日期:2015-03-03 16:54:15
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-03-23 16:02 |只看该作者 |倒序浏览
本代码的主要功能是分析局域网扫描的日志文件, 然后根据电脑的名称或序更号查找资产管理系统中的对应的使用用户, 再发送邮件给这些用户提醒他们晚上没有关机,违反了公司的节能制度!
如果该电脑在白名单中,则忽略!

虽然代码己经工作起来了, 但我总是觉得代码有些地方不如意, 但又不知道怎么改进, 特别是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()
复制代码

论坛徽章:
26
2015亚冠之胡齐斯坦钢铁
日期:2015-06-25 21:40:202015亚冠之柏斯波利斯
日期:2015-08-31 17:03:192015亚冠之柏斯波利斯
日期:2015-11-07 13:10:00程序设计版块每日发帖之星
日期:2015-11-10 06:20:00每日论坛发贴之星
日期:2015-11-10 06:20:00程序设计版块每日发帖之星
日期:2015-11-26 06:20:00程序设计版块每日发帖之星
日期:2015-12-02 06:20:00黄金圣斗士
日期:2015-12-07 17:57:4615-16赛季CBA联赛之天津
日期:2015-12-23 18:34:14程序设计版块每日发帖之星
日期:2016-01-02 06:20:00程序设计版块每日发帖之星
日期:2016-01-06 06:20:00每日论坛发贴之星
日期:2016-01-06 06:20:00
2 [报告]
发表于 2015-08-04 22:10 |只看该作者
如果你想速成的话,建议还是去找个培训班吧

求职 : Linux运维
论坛徽章:
3
戌狗
日期:2015-01-11 13:27:532015年辞旧岁徽章
日期:2015-03-03 16:54:152015年亚洲杯纪念徽章
日期:2015-05-08 15:03:30
3 [报告]
发表于 2015-08-05 13:52 |只看该作者
很好啊,能工作就OK

论坛徽章:
1
2015年辞旧岁徽章
日期:2015-03-03 16:54:15
4 [报告]
发表于 2015-10-09 16:01 |只看该作者
回复 3# donalds2008

非常感谢, 总觉得自己的代码好像挺啰嗦的, 没有别人的干练.


   

论坛徽章:
0
5 [报告]
发表于 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了吧
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP