- 论坛徽章:
- 27
|
本帖最后由 yifangyou 于 2011-06-30 11:29 编辑
下面是我的答案,执行之前先把文件头的中文注释去掉,python对于含有gbk的中文的.py文件有点问题,第8题需要在python2.6.5上运行- #1. 去除list中的重复数据 [11, 22, 33, 11, 22] => [11, 22, 33] 。
- #运行环境:CentOS5.4 python2.4.3 python 2.6.5
- # Python 2.4.3 (#1, May 24 2008, 13:47:28)
- # [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
- #执行:
- # [root@localhost ~]# python test1.py
- # please input number list split by ","> 11, 22, 33, 11, 22
- # [11, 22, 33]
- import re
- inputLine = raw_input('please input number list split by ","> ')
- numList=re.split('\W', inputLine)
- result=[]
- for n in numList:
- # 判断是否是数字串
- if n.isdigit():
- i=int(n)
- # 判断是否在结果集里
- if i not in result:
- result.append(i)
- print result
复制代码- #2. 格式化输出,三位一逗号 1234567 -> 1,234,567
- #运行环境:CentOS5.4 python2.4.3 python 2.6.5
- # Python 2.4.3 (#1, May 24 2008, 13:47:28)
- # [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
- #执行:
- # [root@localhost ~]# python test2.py
- # please input number> 1234567
- # 1,234,567
- import re
- num=''
- while not num.isdigit():
- num = raw_input('please input number> ')
- #反转字符串,低位在前
- rnum= num[::-1]
- #先按照3个整数匹配,其次按照2或1个整数匹配
- rarray =re.findall('(\d{3}|\d{1,2})',rnum)
- #逗号连接起来
- rnum=','.join(rarray)
- #反转回来
- print rnum[::-1]
复制代码- #3. 字符反转 abcde -> edcba
- #运行环境:CentOS5.4 python2.4.3 python 2.6.5
- # Python 2.4.3 (#1, May 24 2008, 13:47:28)
- # [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
- #执行:
- # [root@localhost ~]# python test3.py
- # please input string> abcdefg
- # gfedcba
- s = raw_input('please input string> ')
- print s[::-1]
复制代码- #4. 打印当前系统的挂载点和空间大小(Linux)
- #运行环境:CentOS5.4 python2.4.3 python 2.6.5
- # Python 2.4.3 (#1, May 24 2008, 13:47:28)
- # [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
- #执行:
- # [root@localhost ~]# python test4.py
- # 文件系统 容量 已用 可用 已用% 挂载点
- # /dev/sda2 194G 19G 166G 10% /
- # /dev/sda6 159G 190M 151G 1% /opt
- # /dev/sda3 97G 5.0G 87G 6% /data
- # /dev/sda1 190M 25M 156M 14% /boot
- # tmpfs 2.0G 0 2.0G 0% /dev/shm
- import os
- import re
- #用管道执行可取回返回结果
- p=os.popen('df -h')
- x=p.read()
- print x
- p.close()
复制代码- #5. 模拟登录401验证网站(Basic HTTP Authentication)
- #运行环境:CentOS5.4 python2.4.3 python 2.6.5
- # Python 2.4.3 (#1, May 24 2008, 13:47:28)
- # [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
- #执行:
- # [root@localhost ~]# python test5.py
- # 打开另一个SSH执行
- # [root@localhost ~]# curl -u abc:123 http://127.0.0.1:8081
- # login success!
- # [root@localhost ~]# curl -u abc:1234 http://127.0.0.1:8081
- # forbidden
- import BaseHTTPServer
- import re
- import cgi
- import base64
- class WebRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
- def get_Auth(self):
- username='abc'
- password='123'
- # 获取base64验证码
- b64=re.findall('\S+,self.headers['Authorization'])
- if len(b64)==0:
- return 0
- # 解码
- d64=base64.b64decode(b64[0])
- if d64==username+':'+password:
- return 1
- else:
- return 0
- def do_GET(self):
- if self.get_Auth() == 1: # 认证成功
- data='login success!\n'
- self.send_response(200)
- self.send_header('Content-Length',len(data))
- self.end_headers()
- self.wfile.write(data)
- else:
- data='forbidden\n' #对于认证失败的请求,返回 401 错误
- self.wfile.write('HTTP/1.1 401 Unauthorized\r\n')
- self.send_header('Content-Length',len(data))
- self.send_header('WWW-Authenticate','Basic realm="test5"')
- self.end_headers()
- self.wfile.write(data)
-
- server = BaseHTTPServer.HTTPServer(('127.0.0.1',8081), WebRequestHandler) #创建 HTTPSever 服务器,绑定地址:http://127.0.0.1:8081
- try:
- server.serve_forever() # 启动 HTTPServer 服务器
- except KeyboardInterrupt:
- pass
- server.server_close()
复制代码- #6. 获取远程某机器的系统当前日期时间(Linux)
- #运行环境:CentOS5.4 python2.4.3 python 2.6.5
- # Python 2.4.3 (#1, May 24 2008, 13:47:28)
- # [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
- #执行:
- # 执行服务端
- # [root@localhost ~]# python test6_timeServer.py
- # waiting for connection...
- # ...connected from: ('192.168.13.120', 48786)
- # ...connected from: ('192.168.13.120', 57623)
- # 打开另一个SSH执行客户端
- # [root@localhost ~]# python test6_timeClient.py
- # please input time server ip> 192.168.13.105
- # now is [Thu Jun 30 10:51:25 2011]
- # [root@localhost ~]# python test6_timeClient.py
- # please input time server ip>
- # connect : 1230 failed: (111, 'Connection refused')
- # [root@localhost ~]# python test6_timeClient.py
- # please input time server ip> 192.168.13.110
- # connect 192.168.13.110 : 1230 failed: timed out
- from SocketServer import (TCPServer as TCP,StreamRequestHandler as SRH)
- from time import ctime
- HOST = ''
- PORT = 1230
- ADDR = (HOST, PORT)
- class MyRequestHandler(SRH):
- def handle(self):
- print '...connected from:', self.client_address
- #返回时间给客户端
- self.wfile.write('now is %s' % (ctime()))
- #监听本机1230端口
- tcpServ = TCP(ADDR, MyRequestHandler)
- print 'waiting for connection...'
- try:
- tcpServ.serve_forever() # 启动 HTTPServer 服务器
- except KeyboardInterrupt:
- pass
- tcpServ.server_close()
复制代码- #test6_timeClient.py
- from socket import *
- import sys
- HOST = raw_input('please input time server ip> ')
- PORT = 1230
- BUFSIZ = 1024
- ADDR = (HOST, PORT)
- tcpCliSock = socket(AF_INET, SOCK_STREAM)
- tcpCliSock.settimeout(5)
- try:
- tcpCliSock.connect(ADDR)
- #向时间服务器查询
- tcpCliSock.send('what time is\r\n')
- #接收数据
- data = tcpCliSock.recv(BUFSIZ)
- print data.strip()
- tcpCliSock.close()
- except:
- (ErrorType, ErrorValue, ErrorTB) = sys.exc_info()
- print 'connect ',HOST,':',PORT,' failed:',ErrorValue
复制代码- #7. 打印Apache日志中访问次数最多的10条URL。
- #运行环境:CentOS5.4 python2.4.3 python 2.6.5
- # Python 2.4.3 (#1, May 24 2008, 13:47:28)
- # [GCC 4.1.2 20070626 (Red Hat 4.1.2-14)] on linux2
- #执行:
- # [root@localhost ~]# python test7.py
- # please input apache access_log file path > /root/access_log
- # " /favicon.ico " be accessed 4 times
- # " /icons/compressed.gif " be accessed 3 times
- # " /pic/ " be accessed 3 times
- # " /icons/back.gif " be accessed 3 times
- # " /icons/blank.gif " be accessed 3 times
- # " /pic " be accessed 3 times
- # " /pic/20110625-%d1%e3%c6%dc%ba%fe.zip " be accessed 3 times
- # " /index.php?=PHPE9568F35-D428-11d2-A769-00AA001ACF42 " be accessed 1 times
- # " /ganglia " be accessed 1 times
- # " / " be accessed 1 times
- import re
- f=None
- while not f:
- access_log = raw_input('please input apache access_log file path > ')
- f = open(access_log, 'r')
-
- results={}
- for eachLine in f.readlines():
- fields=re.match('.+"[A-Z]{3,6} (/.*) HTTP/1\.[10]".+', eachLine)
- if fields is not None:
- path=fields.group(1)
- if path in results:
- results[path]+=1
- else:
- results[path]=1
- f.close()
- rresults=sorted(results.items(), key=lambda results:results[1],reverse=True)
- for eachItem in rresults[:10]:
- print '"',eachItem[0],'" be accessed',eachItem[1],"times"
复制代码- #8. 并发抓取10个URL,打印出HTTP状态码
- #运行环境:CentOS5.4 python 2.6.5
- # Python 2.6.5 (r265:79063, Jun 29 2011, 12:30:49)
- # [GCC 4.1.2 20080704 (Red Hat 4.1.2-46)] on linux2
- # Type "help", "copyright", "credits" or "license" for more information.
- #执行:
- # [root@UNI-HEB-1-N015-bind-006 ~]# /usr/local/bin/python2.6 test8.py
- # starting at: Thu Jun 30 11:00:31 2011
- # all DONE at: Thu Jun 30 11:00:40 2011
- # http://www.youku.com response:200
- # http://www.sina.com.cn response:200
- # http://www.baidu.com response:200
- # http://www.sohu.com response:200
- # http://img.163.com/abd.jpg response:404
- # http://www.163.com response:200
- # http://www.qq.com response:200
- # https://img.alipay.com/images/cms2/201106/20110630574935.gif response:200
- # http://www.google.com response:200
- # http://192.168.13.110 response:0
- import threading
- import urllib
- from time import ctime
- #被测试的url
- urls = ['http://www.163.com',
- 'http://img.163.com/abd.jpg',
- 'http://www.google.com',
- 'http://www.sina.com.cn',
- 'http://192.168.13.110',
- 'http://www.sohu.com',
- 'http://www.baidu.com',
- 'http://www.qq.com',
- 'http://www.youku.com',
- 'https://img.alipay.com/images/cms2/201106/20110630574935.gif']
- #结果集
- results=[]
- #获取url线程
- def loop(i,aurl):
- try:
- f=urllib.urlopen(aurl)
- results.append(aurl+' response:'+str(f.code));
- f.close()
- except IOError, e:
- # 获取url出错,返回0
- results.append(aurl+' response:'+str(0));
-
- #开始时间
- print 'starting at:', ctime()
- threads = []
- nloops = range(len(urls))
- for i in nloops:
- t = threading.Thread(target=loop,args=(i,urls[i]))
- threads.append(t)
- for i in nloops: # start threads
- threads[i].start()
- for i in nloops: # wait for all
- threads[i].join() # threads to finish
- print 'all DONE at:', ctime()
- for result in results:
- print result
复制代码 |
|