免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
楼主: 无风之谷
打印 上一主题 下一主题

ChinaUnix技术实践之五——Python编程大赛 欢迎大家参与!!(获奖名单公布) [复制链接]

论坛徽章:
0
31 [报告]
发表于 2011-07-05 21:57 |只看该作者
  1. #1:
  2. print list(set([11, 22, 33, 11, 22]))
  3. #2:
  4. import locale
  5. locale.setlocale(locale.LC_ALL,'')
  6. print locale.format("%d", 1234567, grouping=True)
  7. print locale.format_string('%d',1234567,grouping=True)
  8. #3:
  9. 'abcde'[::-1]


  10. #8
  11. import urllib2,thread
  12. urls=['http://www.qq.com','http://www.lzu.edu.cn','http://www.baidu.cn']
  13. def ptstcd(url):
  14.     conn = urllib2.urlopen(url)
  15.     print url,' status code: ',conn.code
  16. for url in urls:
  17.     thread.start_new_thread(ptstcd,(url,))
复制代码
找了半天只做了这么几个。。。还有一个。。。明天再来。。。。

论坛徽章:
0
32 [报告]
发表于 2011-07-05 22:00 |只看该作者
我的是XP啊。。。。linux太多了吧。。。

论坛徽章:
0
33 [报告]
发表于 2011-07-05 22:48 |只看该作者
本帖最后由 lkk2003rty 于 2011-07-06 13:38 编辑

1 a = [11, 22, 33, 11, 22]
   a = list(set(a))

2
  1. def fun(num, pos=0):
  2.      import locale
  3.      locale.setlocale(locale.LC_ALL, "")
  4.      return locale.format("%.*f", (pos, num), True)
  5.    
复制代码
3
  1. b ='1234567890'
  2. b[::-1]
复制代码
4

  1. import os
  2. os.system('df -h')
复制代码
5
  1. #!/usr/bin/env python
  2. import urllib2,sys
  3. mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
  4. mgr.add_password(None, 'http://192.168.1.12/auth/index.html', "emacle", "galaxy")
  5. handler = urllib2.HTTPBasicAuthHandler(mgr)
  6. opener = urllib2.build_opener(handler)
  7. urllib2.install_opener(opener)
  8. try:
  9.     resp = urllib2.urlopen('http://192.168.1.12/auth/index.html')
  10. except (urllib2.URLError, urllib2.HTTPError)  as ex :
  11.     print "Fail to get page!"
  12.     if hasattr(ex, 'code'):
  13.         print "Error Code:",ex.code
  14.     if hasattr(ex, 'reason'):
  15.         print "Reason:",ex.reason
  16. except:
  17.     print "Unexpected error:", sys.exc_info()
  18. else:
  19.     print resp.msg, "\n", resp.read()
复制代码
6
  1. #!/usr/bin/env python
  2. import paramiko,sys
  3. cli = paramiko.SSHClient()
  4. cli.set_missing_host_key_policy( paramiko.AutoAddPolicy() )
  5. try:
  6.     cli.connect('192.168.1.22', username='super', password='super123')
  7.     stdin, stdout, stderr = cli.exec_command( 'date' );
  8. except (paramiko.SSHException, paramiko.AuthenticationException, paramiko.BadHostKeyException) as ex:
  9.     print "Fail to get time!"
  10.     if hasattr(ex, 'code'):
  11.         print "Error Code:",ex.code
  12.     if hasattr(ex, 'reason'):
  13.         print "Reason:",ex.reason
  14. except:
  15.     print "Unexpected error:", sys.exc_info()
  16. else:
  17.     print stdout.readlines()
复制代码
7apache 日志配置为
  1. LogFormat "%h %l %u %t \"%r\" %>s %b" common
  2. CustomLog "logs/access_log" common
复制代码
python脚本为
  1. #!/usr/bin/env python
  2. import os,sys,re
  3. if len(sys.argv) < 2:
  4.     print "Usage:./ana.py file"
  5.     sys.exit(1)
  6. if not os.path.isfile(sys.argv[1]):
  7.     print sys.argv[1], "is not file"
  8.     sys.exit(1)
  9. f = open(sys.argv[1], 'r')
  10. d = dict()
  11. for line in f:
  12.     m = re.search('([^ ]+)\sHTTP', line)
  13.     if m:
  14.         url = m.group(1)
  15.         if url in d:
  16.             d[url] += 1
  17.         else:
  18.             d[url] = 1
  19. f.close()
  20. cnt = 0
  21. for k,v in sorted(d.items(), key = lambda d:d[1],reverse = True):
  22.     if cnt < 10:
  23.         print k,v
  24.         cnt += 1
  25.     else:
  26.         break
复制代码
8
  1. #! /usr/bin/env python

  2. urls = ["http://www.google.com",
  3.         "http://www.baidu.com",
  4.         "http://www.sina.com.cn",
  5.         "http://www.qq.com",
  6.         "http://bbs.chinaunix.net",
  7.         "http://baike.baidu.com",
  8.         "http://zhidao.baidu.com",
  9.         "http://tieba.baidu.com",
  10.         "http://www.cnbeta.com",
  11.         "http://www.python.org"]

  12. import eventlet
  13. from eventlet.green import urllib2  

  14. def fetch(url):
  15.     resp = urllib2.urlopen(url)
  16.     return url,resp

  17. pool = eventlet.GreenPool(200)
  18. for u,i in pool.imap(fetch, urls):
  19.     print u,"\t",i.code
复制代码
搞定~~~~~

论坛徽章:
0
34 [报告]
发表于 2011-07-06 10:19 |只看该作者
本帖最后由 xinyv 于 2011-07-07 12:12 编辑

上面的很多题目的答案都是用 bash 命令实现,这是 python 比赛啊 ~~
发个纯 python 写的,不用 bash 命令的版本
  1. #!/usr/bin/python
  2. # -*- coding: gbk -*-
  3. import os,ctypes
  4. # 列表去重
  5. li=[11, 22, 33, 11, 22]
  6. li=list(set(li))
  7. li.sort()
  8. print li

  9. # 字符串表示
  10. Str="1234567"
  11. S=len(Str)%3
  12. New=Str[0:S]+","
  13. for i in range(S,len(Str),3):
  14.   New=New+Str[i:i+3]+","
  15. if New[-1]==",":
  16.   New=New[0:-1]
  17. print New

  18. # 反转字符串
  19. A="abcde"
  20. A=A[::-1]
  21. print A

  22. # 遍历文件系统空间
  23. F=open('/proc/mounts','r')
  24. for i in F.readlines():
  25.   Stat=os.statvfs(i.split(' ')[1])
  26.   print "%15s %8dM %8dM" % (i.split(' ')[1],((Stat.f_bavail+Stat.f_bfree)*Stat.f_bsize)/(1024*1024),Stat.f_bavail*Stat.f_bsize/(1024*1024))
  27. F.close()

  28. # 模拟登录401验证网站(Basic HTTP Authentication)
  29. import httplib,base64
  30. host="test.example.com"
  31. user="admin"
  32. passwd="123456"
  33. fd=httplib.HTTPConnection(host, 80, False)
  34. fd.request('get', '/', headers = {"Authorization": "Basic "+base64.b64encode(user+":"+passwd)})
  35. print fd.getresponse().read()
  36. fd.close()
  37. # 获取远程某机器的系统当前日期时间(Linux)
  38. # 题目没写服务器端的服务,看来我们可以使用任意服务了,前面 telnet ssh ntp 都有人写过了,这里我写 snmp 方法获得,要求服务器开 snmp 服务。
  39. import socket,binascii
  40. host=("172.16.2.2",161)
  41. community="public"
  42. securityModel="2"
  43. mib=".1.3.6.1.2.1.25.1.2.0"

  44. pdu="302a0201"
  45. s=hex(int(securityModel)-1).replace('0x','')
  46. if(len(s) == 1):
  47.   s='0'+s
  48. pdu=pdu+s+"04"
  49. s=len(community).__hex__().replace('0x','')
  50. if(len(s) == 1):
  51.   s='0'+s
  52. pdu=pdu+s+binascii.b2a_hex(community)+"a01d020420d9e402020100020100300f300d06"
  53. sl=mib.split('.')
  54. s=hex(len(sl)-2).replace('0x','')
  55. if(len(s) == 1):
  56.   s='0'+s
  57. pdu=pdu+s+"2b"
  58. for i in range(3,len(sl)):
  59.   s=int(sl[i]).__hex__().replace('0x','')
  60.   if(len(s) == 1):
  61.     s='0'+s
  62.   pdu=pdu+s
  63. pdu=pdu+"0500"

  64. udp_sc = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  65. udp_sc.sendto(binascii.a2b_hex(pdu),host)
  66. A=udp_sc.recvfrom(1024)
  67. udp_sc.close()
  68. DT=[int(binascii.b2a_hex(A[0][44:46]),16)]
  69. for i in range(46,51):
  70.   DT.append(int(binascii.b2a_hex(A[0][i:i+1]),16))
  71. print "%04d-%02d-%02d %02d:%02d:%02d" % (DT[0],DT[1],DT[2],DT[3],DT[4],DT[5])

  72. # 打印Apache日志中访问次数最多的10条URL。
  73. logfile="/var/log/access_log"
  74. A={};url=1

  75. fd = open(logfile,"r")
  76. while(url):
  77.   try:
  78.     url=fd.readline().split(' ')[6]
  79.     if url not in A:
  80.       A[url]=1
  81.     else:
  82.       A[url]=A[url]+1
  83.   except IndexError,e:
  84.     url=0

  85. fd.close()
  86. A=sorted(A.iteritems(), key=lambda d:d[1], reverse=True)
  87. for i in range(0,10,1):
  88.   print "%5d %-60s%5d" % (i+1,A[i][0],A[i][1])

  89. # 并发抓取10个URL,打印出HTTP状态码。线程的已经很多人写了,来个进程的玩玩
  90. import os,sys,httplib,time

  91. def work(url):
  92.   child_pid=os.fork()
  93.   if(child_pid == 0):
  94.     fd = httplib.HTTPConnection("search.buildhr.com", 80, False)
  95.     fd.request('GET', url, headers = {"User-Agent" : "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"})
  96.     r1 = fd.getresponse()
  97.     print r1.status, r1.reason
  98.     sys.stdout=open(str(os.getpid())+".html", 'w')
  99.     if (r1.status == 200):
  100.       print r1.read()
  101.     else:
  102.       for x in r1.msg.values():
  103.         print x
  104.     fd.close()
  105.     sys.exit(0)

  106. for x in range(120100,120111):
  107.   work("/job_search_result.php?hids_function="+str(x))

  108. for x in range(120100,120111):
  109.   os.wait()

  110. print ""
复制代码

论坛徽章:
0
35 [报告]
发表于 2011-07-06 23:34 |只看该作者
本帖最后由 car292516198 于 2011-07-07 18:48 编辑

来得较迟,有了前面高手猛人的代码,再突破,寻找新方法就很难了。幸好第一题,发现可用有序字典,否则没信心做下去。有序字典太旧的版本可能不支持,它与一般字典基本一样,差别是顺序存储。
1.
  1. import collections
  2. D=collections.OrderedDict()
  3. L=[11,22,33,11,22]
  4. for i in L:
  5.     D[i]=None
  6. print D.keys()
复制代码


2.
print '{:,}'.format(1234567)

3.
print 'abcde'[::-1]

4.
import os
print os.popen('df -h').read()

5.
这题用路由器测试最方便,本人就是用自己路由器测试通过,但注意域realm要一字不差。
  1. import urllib2
  2. ip='192.168.1.1'
  3. realm='Wireless Soho Router'
  4. auth_handler = urllib2.HTTPBasicAuthHandler()
  5. auth_handler.add_password(realm=realm,        
  6.                           uri=ip,
  7.                           user='admin',
  8.                           passwd='admin')
  9. opener = urllib2.build_opener(auth_handler)
  10. urllib2.install_opener(opener)
  11. try:
  12.     result=urllib2.urlopen('http://'+ip)
  13.     print result.code
  14. except Exception,e:
  15.     print e,'---Please check realm and ip.'
复制代码
6.
host是远程机地址。
import os
os.system("ssh host date")

7.
“d[line]=d.get(line,0)+1”字典中的get方法,如果line已在字典中,get返回相关数字,加1并设为新值;如不在字典中,get返回默认值0,并加1,相当于:
    if line not in d:
        d[line]=0
    d[line]+=1
我日志文件的URL的索引是6,不同的请修改。
  1. import re
  2. input=open('C:\\Program Files\\wamp\\logs\\access.log','r')
  3. d={}
  4. for line in input:
  5.     line=line.split()[6]     
  6.     d[line]=d.get(line,0)+1
  7. D=sorted(d.items(),key=lambda d:d[1],reverse=True)[:10]
  8. print D
复制代码
8.
  1. import thread,urllib2
  2. def do(url):
  3.     try:
  4.         u=urllib2.urlopen(url)
  5.         print url,u.code
  6.     except Exception,e:
  7.         print url,e
  8.         
  9. for i in [163,263,136,137,138,139,11,22,33,44]:
  10.     url = 'http://www.%s.com' % i
  11.     thread.start_new_thread(do,(url,))
复制代码

论坛徽章:
16
IT运维版块每日发帖之星
日期:2015-08-24 06:20:00综合交流区版块每日发帖之星
日期:2015-10-14 06:20:00IT运维版块每日发帖之星
日期:2015-10-25 06:20:00IT运维版块每日发帖之星
日期:2015-11-06 06:20:00IT运维版块每日发帖之星
日期:2015-12-10 06:20:00平安夜徽章
日期:2015-12-26 00:06:302016猴年福章徽章
日期:2016-02-18 15:30:34IT运维版块每日发帖之星
日期:2016-04-15 06:20:00IT运维版块每日发帖之星
日期:2016-05-21 06:20:00综合交流区版块每日发帖之星
日期:2016-08-16 06:20:002015七夕节徽章
日期:2015-08-21 11:06:17IT运维版块每日发帖之星
日期:2015-08-14 06:20:00
36 [报告]
发表于 2011-07-07 16:17 |只看该作者
回复 41# car292516198


    您好,请教下这个域realm表示什么意思,代表什么啊?我正在研究这个401认证

论坛徽章:
0
37 [报告]
发表于 2011-07-07 18:30 |只看该作者
回复 43# expert1


    域realm,类似cookie的网页地址,不同的网站有不同的cookie。认证在保留密码时,是域、密码相对应保存的。比如有两路由器,分别保留了密码,下次登录时,可以区分开。但如果两路由器域相同,密码不同,这样密码会覆盖掉,只能保存一密码。路由器型号相同,域则相同,也可以用PHP来进行认证测试。

论坛徽章:
1
2015年迎新春徽章
日期:2015-03-04 09:58:11
38 [报告]
发表于 2011-07-07 18:41 |只看该作者
回复  expert1


    域realm,类似cookie的网页地址,不同的网站有不同的cookie。认证在保留密码时,是 ...
car292516198 发表于 2011-07-07 18:30



   如果用PHP来进行认证测试(手册上有),域是自定义的。登录时你先保存密码,接着将php文件的域改掉,再登录时就不行了,将域改回来,登录就行了(行指不需输入密码)。有时浏览器会保存会话状态,不登录也能通过,这样需先关闭浏览器,再打开。

论坛徽章:
0
39 [报告]
发表于 2011-07-08 16:43 |只看该作者
奖品不够吸引人啊

论坛徽章:
0
40 [报告]
发表于 2011-07-11 14:32 |只看该作者
奖品不够吸引人啊
ZSMDEV 发表于 2011-07-08 16:43



    呵呵。。重在参与嘛
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

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

清除 Cookies - ChinaUnix - Archiver - WAP - TOP