在电脑中突然发现一个这么好的资料,雪松大神制作,不敢独享,特与大家共享。连他的广告也一并复制了吧!

  1. python实例手册
  2.  
  3. #encoding:utf8
  4. # 设定编码-支持中文
  5.  
  6. 0说明
  7.  
  8. 手册制作: 雪松 littlepy reboot
  9. 更新日期: 2014-10-29
  10. 欢迎系统运维加入Q群: 198173206 # 加群请回答问题
  11. 欢迎运维开发加入Q群: 365534424 # 不定期技术分享
  12.  
  13. 请使用"notepad++"打开此文档,"alt+0"将函数折叠后方便查阅
  14. 请勿删除信息,转载请说明出处,抵制不道德行为。
  15. 错误在所难免,还望指正!
  16.  
  17. # python实例手册下载地址:
  18. http://hi.baidu.com/quanzhou722/item/cf4471f8e23d3149932af2a7
  19.  
  20. # shell实例手册最新下载地址:
  21. http://hi.baidu.com/quanzhou722/item/f4a4f3c9eb37f02d46d5c0d9
  22.  
  23. # LazyManage运维批量管理软件下载[shell]:
  24. http://hi.baidu.com/quanzhou722/item/4ccf7e88a877eaccef083d1a
  25.  
  26. # LazyManage运维批量管理软件下载[python]:
  27. http://hi.baidu.com/quanzhou722/item/4213db3626a949fe96f88d3c
  28.  
  29. 1 基础
  30.  
  31. 查看帮助
  32. import os
  33. for i in dir(os):
  34. print i # 模块的方法
  35. help(os.path) # 方法的帮助
  36.  
  37. 调试
  38. python -m trace -t aaaaaa.py
  39.  
  40. pip模块安装
  41.  
  42. yum install python-pip # centos安装pip
  43. sudo apt-get install python-pip # ubuntu安装pip
  44. pip官方安装脚本
  45. wget https://raw.github.com/pypa/pip/master/contrib/get-pip.py
  46. python get-pip.py
  47. 加载环境变量
  48. vim /etc/profile
  49. export PATH=/usr/local/python27/bin:$PATH
  50. . /etc/profile
  51.  
  52. pip install Package # 安装包 pip install requests
  53. pip show --files Package # 查看安装包时安装了哪些文件
  54. pip show --files Package # 查看哪些包有更新
  55. pip install --upgrade Package # 更新一个软件包
  56. pip uninstall Package # 卸载软件包
  57.  
  58. 变量
  59.  
  60. r=r'\n' # 输出时原型打印
  61. u=u'中文' # 定义为unicode编码
  62. global x # 全局变量
  63. a = 0 or 2 or 1 # 布尔运算赋值,a值为True既不处理后面,a值为2. None、字符串''、空元组()、空列表[],空字典{}、0、空字符串都是false
  64. name = raw_input("input:").strip() # 输入字符串变量
  65. num = int(raw_input("input:").strip()) # 输入字符串str转为int型
  66. locals() # 所有局部变量组成的字典
  67. locals().values() # 所有局部变量值的列表
  68. os.popen("date -d @{0} +'%Y-%m-%d %H:%M:%S'".format(12)).read() # 特殊情况引用变量 {0} 代表第一个参数
  69.  
  70. 打印
  71.  
  72. # 字符串 %s 整数 %d 浮点 %f 原样打印 %r
  73. print '字符串: %s 整数: %d 浮点: %f 原样打印: %r' % ('aa',2,1.0,'r')
  74. print 'abc', # 有逗号,代表不换行打印,在次打印会接着本行打印
  75.  
  76. 列表
  77.  
  78. # 列表元素的个数最多 536870912
  79. shoplist = ['apple', 'mango', 'carrot', 'banana']
  80. shoplist[2] = 'aa'
  81. del shoplist[0]
  82. shoplist.insert('4','www')
  83. shoplist.append('aaa')
  84. shoplist[::-1] # 倒着打印 对字符翻转串有效
  85. shoplist[2::3] # 从第二个开始每隔三个打印
  86. shoplist[:-1] # 排除最后一个
  87. '\t'.join(li) # 将列表转换成字符串
  88. sys.path[1:1]=[5] # 在位置1前面插入列表中一个值
  89. list(set(['qwe', 'as', '123', '123'])) # 将列表通过集合去重复
  90. eval("['1','a']") # 将字符串当表达式求值,得到列表
  91.  
  92. 元组
  93.  
  94. # 不可变
  95. zoo = ('wolf', 'elephant', 'penguin')
  96.  
  97. 字典
  98.  
  99. ab = { 'Swaroop' : 'swaroopch@byteofpython.info',
  100. 'Larry' : 'larry@wall.org',
  101. }
  102. ab['c'] = 80 # 添加字典元素
  103. del ab['Larry'] # 删除字典元素
  104. ab.keys() # 查看所有键值
  105. ab.values() # 打印所有值
  106. ab.has_key('a') # 查看键值是否存在
  107. ab.items() # 返回整个字典列表
  108.  
  109. 复制字典
  110. a = {1: {1: 2, 3: 4}}
  111. b = a
  112. b[1][1] = 8888 # a和b都为 {1: {1: 8888, 3: 4}}
  113. import copy
  114. c = copy.deepcopy(a) # 再次赋值 b[1][1] = 9999 拷贝字典为新的字典,互不干扰
  115.  
  116. a[2] = copy.deepcopy(a[1]) # 复制出第二个key,互不影响 {1: {1: 2, 3: 4},2: {1: 2, 3: 4}}
  117.  
  118. 流程结构
  119.  
  120. if判断
  121.  
  122. # 布尔值操作符 and or not 实现多重判断
  123. if a == b:
  124. print '=='
  125. elif a < b:
  126. print b
  127. else:
  128. print a
  129. fi
  130.  
  131. while循环
  132.  
  133. while True:
  134. if a == b:
  135. print "=="
  136. break
  137. print "!="
  138. else:
  139. print 'over'
  140.  
  141. count=0
  142. while(count<9):
  143. print count
  144. count += 1
  145.  
  146. for循环
  147.  
  148. sorted() # 返回一个序列(列表)
  149. zip() # 返回一个序列(列表)
  150. enumerate() # 返回循环列表序列 for i,v in enumerate(['a','b']):
  151. reversed() # 反序迭代器对象
  152. dict.iterkeys() # 通过键迭代
  153. dict.itervalues() # 通过值迭代
  154. dict.iteritems() # 通过键-值对迭代
  155. randline() # 文件迭代
  156. iter(obj) # 得到obj迭代器 检查obj是不是一个序列
  157. iter(a,b) # 重复调用a,直到迭代器的下一个值等于b
  158. for i in range(1, 5):
  159. print i
  160. else:
  161. print 'over'
  162.  
  163. list = ['a','b','c','b']
  164. for i in range(len(list)):
  165. print list[i]
  166. for x, Lee in enumerate(list):
  167. print "%d %s Lee" % (x+1,Lee)
  168.  
  169. # enumerate 使用函数得到索引值和对应值
  170. for i, v in enumerate(['tic', 'tac', 'toe']):
  171. print(i, v)
  172.  
  173. 流程结构简写
  174.  
  175. [ i * 2 for i in [8,-2,5]]
  176. [16,-4,10]
  177. [ i for i in range(8) if i %2 == 0 ]
  178. [0,2,4,6]
  179.  
  180. tab补全
  181.  
  182. # vim /usr/lib/python2.7/dist-packages/tab.py
  183. # python startup file
  184. import sys
  185. import readline
  186. import rlcompleter
  187. import atexit
  188. import os
  189. # tab completion
  190. readline.parse_and_bind('tab: complete')
  191. # history file
  192. histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
  193.  
  194. 函数
  195.  
  196. def printMax(a, b = 1):
  197. if a > b:
  198. print a
  199. return a
  200. else:
  201. print b
  202. return b
  203. x = 5
  204. y = 7
  205. printMax(x, y)
  206.  
  207. def update(*args,**kwargs):
  208. p=''
  209. for i,t in kwargs.items():
  210. p = p+ '%s=%s,' %(i,str(t))
  211. sql = "update 'user' set (%s) where (%s)" %(args[0],p)
  212. print sql
  213.  
  214. update('aaa',uu='uu',id=3)
  215.  
  216. 模块
  217.  
  218. # Filename: mymodule.py
  219. def sayhi():
  220. print 'mymodule'
  221. version = '0.1'
  222.  
  223. # 使用模块中方法
  224. import mymodule
  225. from mymodule import sayhi, version
  226. mymodule.sayhi() # 使用模块中函数方法
  227.  
  228. 类对象的方法
  229.  
  230. class Person:
  231. # 实例化初始化的方法
  232. def __init__(self, name ,age):
  233. self.name = name
  234. self.age = age
  235. print self.name
  236. # 有self此函数为方法
  237. def sayHi(self):
  238. print 'Hello, my name is', self.name
  239. # 对象消逝的时候被调用
  240. def __del__(self):
  241. print 'over'
  242. # 实例化对象
  243. p = Person('Swaroop')
  244. # 使用对象方法
  245. p.sayHi()
  246. # 继承
  247. class Teacher(Person):
  248. def __init__(self, name, age, salary):
  249. Person.__init__(self, name, age)
  250. self.salary = salary
  251. print '(Initialized Teacher: %s)' % self.name
  252. def tell(self):
  253. Person.tell(self)
  254. print 'Salary: "%d"' % self.salary
  255. t = Teacher('Mrs. Shrividya', 40, 30000)
  256.  
  257. 执行模块类中的所有方法
  258.  
  259. # moniItems.py
  260. import sys, time
  261. import inspect
  262.  
  263. class mon:
  264. def __init__(self, n):
  265. self.name = n
  266. self.data = dict()
  267. def run(self):
  268. print 'hello', self.name
  269. return self.runAllGet()
  270. def getDisk(self):
  271. return 222
  272. def getCpu(self):
  273. return 111
  274. def runAllGet(self):
  275. for fun in inspect.getmembers(self, predicate=inspect.ismethod):
  276. print fun[0], fun[1]
  277. if fun[0][:3] == 'get':
  278. self.data[fun[0][3:]] = fun[1]()
  279. print self.data
  280. return self.data
  281.  
  282. # 模块导入使用
  283. from moniItems import mon
  284. m = mon()
  285. m.runAllGet()
  286.  
  287. 文件处理
  288.  
  289. # 模式: 读'r' 写[清空整个文件]'w' 追加[文件需要存在]'a' 读写'r+' 二进制文件'b' 'rb','wb','rb+'
  290.  
  291. 写文件
  292. i={'ddd':'ccc'}
  293. f = file('poem.txt', 'a')
  294. f.write("string")
  295. f.write(str(i))
  296. f.flush()
  297. f.close()
  298.  
  299. 读文件
  300. f = file('/etc/passwd','r')
  301. c = f.read().strip() # 读取为一个大字符串,并去掉最后一个换行符
  302. for i in c.spilt('\n'): # 用换行符切割字符串得到列表循环每行
  303. print i
  304. f.close()
  305.  
  306. 读文件1
  307. f = file('/etc/passwd','r')
  308. while True:
  309. line = f.readline() # 返回一行
  310. if len(line) == 0:
  311. break
  312. x = line.split(":") # 冒号分割定义序列
  313. #x = [ x for x in line.split(":") ] # 冒号分割定义序列
  314. #x = [ x.split("/") for x in line.split(":") ] # 先冒号分割,在/分割 打印x[6][1]
  315. print x[6],"\n",
  316. f.close()
  317.  
  318. 读文件2
  319. f = file('/etc/passwd')
  320. c = f.readlines() # 读入所有文件内容,可反复读取,大文件时占用内存较大
  321. for line in c:
  322. print line.rstrip(),
  323. f.close()
  324.  
  325. 读文件3
  326. for i in open('b.txt'): # 直接读取也可迭代,并有利于大文件读取,但不可反复读取
  327. print i,
  328.  
  329. 追加日志
  330. log = open('/home/peterli/xuesong','a')
  331. print >> log,'faaa'
  332. log.close()
  333.  
  334. with读文件
  335. with open('a.txt') as f:
  336. for i in f:
  337. print i
  338. print f.read() # 打印所有内容为字符串
  339. print f.readlines() # 打印所有内容按行分割的列表
  340.  
  341. csv读配置文件
  342. 192.168.1.5,web # 配置文件按逗号分割
  343. list = csv.reader(file('a.txt'))
  344. for line in list:
  345. print line # ['192.168.1.5', 'web']
  346.  
  347. 内建函数
  348.  
  349. dir(sys) # 显示对象的属性
  350. help(sys) # 交互式帮助
  351. int(obj) # 转型为整形
  352. str(obj) # 转为字符串
  353. len(obj) # 返回对象或序列长度
  354. open(file,mode) # 打开文件 #mode (r 读,w 写, a追加)
  355. range(0,3) # 返回一个整形列表
  356. raw_input("str:") # 等待用户输入
  357. type(obj) # 返回对象类型
  358. abs(-22) # 绝对值
  359. random # 随机数
  360. choice() # 随机返回给定序列的一个元素
  361. divmod(x,y) # 函数完成除法运算,返回商和余数。
  362. round(x[,n]) # 函数返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数
  363. strip() # 是去掉字符串两端多于空格,该句是去除序列中的所有字串两端多余的空格
  364. del # 删除列表里面的数据
  365. cmp(x,y) # 比较两个对象 #根据比较结果返回一个整数,如果x<y,则返回-1;如果x>y,则返回1,如果x==y则返回0
  366. max() # 字符串中最大的字符
  367. min() # 字符串中最小的字符
  368. sorted() # 对序列排序
  369. reversed() # 对序列倒序
  370. enumerate() # 返回索引位置和对应的值
  371. sum() # 总和
  372. list() # 变成列表可用于迭代
  373. eval('3+4') # 将字符串当表达式求值 得到7
  374. exec 'a=100' # 将字符串按python语句执行
  375. exec(a+'=new') # 将变量a的值作为新的变量
  376. tuple() # 变成元组可用于迭代 #一旦初始化便不能更改的数据结构,速度比list快
  377. zip(s,t) # 返回一个合并后的列表 s = ['11','22'] t = ['aa','bb'] [('11', 'aa'), ('22', 'bb')]
  378. isinstance(object,int) # 测试对象类型 int
  379. xrange([lower,]stop[,step]) # 函数与range()类似,但xrnage()并不创建列表,而是返回一个xrange对象
  380.  
  381. 字符串相关模块
  382.  
  383. string # 字符串操作相关函数和工具
  384. re # 正则表达式
  385. struct # 字符串和二进制之间的转换
  386. c/StringIO # 字符串缓冲对象,操作方法类似于file对象
  387. base64 # Base16\32\64数据编解码
  388. codecs # 解码器注册和基类
  389. crypt # 进行单方面加密
  390. difflib # 找出序列间的不同
  391. hashlib # 多种不同安全哈希算法和信息摘要算法的API
  392. hma # HMAC信息鉴权算法的python实现
  393. md5 # RSA的MD5信息摘要鉴权
  394. rotor # 提供多平台的加解密服务
  395. sha # NIAT的安全哈希算法SHA
  396. stringprep # 提供用于IP协议的Unicode字符串
  397. textwrap # 文本包装和填充
  398. unicodedate # unicode数据库
  399.  
  400. 列表类型内建函数
  401.  
  402. list.append(obj) # 向列表中添加一个对象obj
  403. list.count(obj) # 返回一个对象obj在列表中出现的次数
  404. list.extend(seq) # 把序列seq的内容添加到列表中
  405. list.index(obj,i=0,j=len(list)) # 返回list[k] == obj 的k值,并且k的范围在i<=k<j;否则异常
  406. list.insert(index.obj) # 在索引量为index的位置插入对象obj
  407. list.pop(index=-1) # 删除并返回指定位置的对象,默认是最后一个对象
  408. list.remove(obj) # 从列表中删除对象obj
  409. list.reverse() # 原地翻转列表
  410. list.sort(func=None,key=None,reverse=False) # 以指定的方式排序列表中成员,如果func和key参数指定,则按照指定的方式比较各个元素,如果reverse标志被置为True,则列表以反序排列
  411.  
  412. 序列类型操作符
  413.  
  414. seq[ind] # 获取下标为ind的元素
  415. seq[ind1:ind2] # 获得下标从ind1到ind2的元素集合
  416. seq * expr # 序列重复expr次
  417. seq1 + seq2 # 连接seq1和seq2
  418. obj in seq # 判断obj元素是否包含在seq中
  419. obj not in seq # 判断obj元素是否不包含在seq中
  420.  
  421. 字符串类型内建方法
  422.  
  423. string.expandtabs(tabsize=8) # tab符号转为空格 #默认8个空格
  424. string.endswith(obj,beg=0,end=len(staring)) # 检测字符串是否已obj结束,如果是返回True #如果beg或end指定检测范围是否已obj结束
  425. string.count(str,beg=0,end=len(string)) # 检测str在string里出现次数 f.count('\n',0,len(f)) 判断文件行数
  426. string.find(str,beg=0,end=len(string)) # 检测str是否包含在string中
  427. string.index(str,beg=0,end=len(string)) # 检测str不在string中,会报异常
  428. string.isalnum() # 如果string至少有一个字符并且所有字符都是字母或数字则返回True
  429. string.isalpha() # 如果string至少有一个字符并且所有字符都是字母则返回True
  430. string.isnumeric() # 如果string只包含数字字符,则返回True
  431. string.isspace() # 如果string包含空格则返回True
  432. string.isupper() # 字符串都是大写返回True
  433. string.islower() # 字符串都是小写返回True
  434. string.lower() # 转换字符串中所有大写为小写
  435. string.upper() # 转换字符串中所有小写为大写
  436. string.lstrip() # 去掉string左边的空格
  437. string.rstrip() # 去掉string字符末尾的空格
  438. string.replace(str1,str2,num=string.count(str1)) # 把string中的str1替换成str2,如果num指定,则替换不超过num次
  439. string.startswith(obj,beg=0,end=len(string)) # 检测字符串是否以obj开头
  440. string.zfill(width) # 返回字符长度为width的字符,原字符串右对齐,前面填充0
  441. string.isdigit() # 只包含数字返回True
  442. string.split("分隔符") # 把string切片成一个列表
  443. ":".join(string.split()) # 以:作为分隔符,将所有元素合并为一个新的字符串
  444.  
  445. 序列类型相关的模块
  446.  
  447. array # 一种受限制的可变序列类型,元素必须相同类型
  448. copy # 提供浅拷贝和深拷贝的能力
  449. operator # 包含函数调用形式的序列操作符 operator.concat(m,n)
  450. re # perl风格的正则表达式查找
  451. StringIO # 把长字符串作为文件来操作 如: read() \ seek()
  452. cStringIO # 把长字符串作为文件来操,作速度更快,但不能被继承
  453. textwrap # 用作包装/填充文本的函数,也有一个类
  454. types # 包含python支持的所有类型
  455. collections # 高性能容器数据类型
  456.  
  457. 字典内建方法
  458.  
  459. dict.clear() # 删除字典中所有元素
  460. dict copy() # 返回字典(浅复制)的一个副本
  461. dict.fromkeys(seq,val=None) # 创建并返回一个新字典,以seq中的元素做该字典的键,val做该字典中所有键对的初始值
  462. dict.get(key,default=None) # 对字典dict中的键key,返回它对应的值value,如果字典中不存在此键,则返回default值
  463. dict.has_key(key) # 如果键在字典中存在,则返回True 用in和not in代替
  464. dicr.items() # 返回一个包含字典中键、值对元组的列表
  465. dict.keys() # 返回一个包含字典中键的列表
  466. dict.iter() # 方法iteritems()、iterkeys()、itervalues()与它们对应的非迭代方法一样,不同的是它们返回一个迭代子,而不是一个列表
  467. dict.pop(key[,default]) # 和方法get()相似.如果字典中key键存在,删除并返回dict[key]
  468. dict.setdefault(key,default=None) # 和set()相似,但如果字典中不存在key键,由dict[key]=default为它赋值
  469. dict.update(dict2) # 将字典dict2的键值对添加到字典dict
  470. dict.values() # 返回一个包含字典中所有值得列表
  471.  
  472. dict([container]) # 创建字典的工厂函数。提供容器类(container),就用其中的条目填充字典
  473. len(mapping) # 返回映射的长度(键-值对的个数)
  474. hash(obj) # 返回obj哈希值,判断某个对象是否可做一个字典的键值
  475.  
  476. 集合方法
  477.  
  478. s.update(t) # 用t中的元素修改s,s现在包含s或t的成员 s |= t
  479. s.intersection_update(t) # s中的成员是共用属于s和t的元素 s &= t
  480. s.difference_update(t) # s中的成员是属于s但不包含在t中的元素 s -= t
  481. s.symmetric_difference_update(t) # s中的成员更新为那些包含在s或t中,但不是s和t共有的元素 s ^= t
  482. s.add(obj) # 在集合s中添加对象obj
  483. s.remove(obj) # 从集合s中删除对象obj;如果obj不是集合s中的元素(obj not in s),将引发KeyError错误
  484. s.discard(obj) # 如果obj是集合s中的元素,从集合s中删除对象obj
  485. s.pop() # 删除集合s中的任意一个对象,并返回它
  486. s.clear() # 删除集合s中的所有元素
  487. s.issubset(t) # 如果s是t的子集,则返回True s <= t
  488. s.issuperset(t) # 如果t是s的超集,则返回True s >= t
  489. s.union(t) # 合并操作;返回一个新集合,该集合是s和t的并集 s | t
  490. s.intersection(t) # 交集操作;返回一个新集合,该集合是s和t的交集 s & t
  491. s.difference(t) # 返回一个新集合,改集合是s的成员,但不是t的成员 s - t
  492. s.symmetric_difference(t) # 返回一个新集合,该集合是s或t的成员,但不是s和t共有的成员 s ^ t
  493. s.copy() # 返回一个新集合,它是集合s的浅复制
  494. obj in s # 成员测试;obj是s中的元素 返回True
  495. obj not in s # 非成员测试:obj不是s中元素 返回True
  496. s == t # 等价测试 是否具有相同元素
  497. s != t # 不等价测试
  498. s < t # 子集测试;s!=t且s中所有元素都是t的成员
  499. s > t # 超集测试;s!=t且t中所有元素都是s的成员
  500.  
  501. 序列化
  502.  
  503. #!/usr/bin/python
  504. import cPickle
  505. obj = {'1':['4124','1241','124'],'2':['12412','142','1241']}
  506.  
  507. pkl_file = open('account.pkl','wb')
  508. cPickle.down(obj,pkl_file)
  509. pkl_file.close()
  510.  
  511. pkl_file = open('account.pkl','rb')
  512. account_list = cPickle.load(pkl_file)
  513. pkl_file.close()
  514.  
  515. 文件对象方法
  516.  
  517. file.close() # 关闭文件
  518. file.fileno() # 返回文件的描述符
  519. file.flush() # 刷新文件的内部缓冲区
  520. file.isatty() # 判断file是否是一个类tty设备
  521. file.next() # 返回文件的下一行,或在没有其他行时引发StopIteration异常
  522. file.read(size=-1) # 从文件读取size个字节,当未给定size或给定负值的时候,读取剩余的所有字节,然后作为字符串返回
  523. file.readline(size=-1) # 从文件中读取并返回一行(包括行结束符),或返回最大size个字符
  524. file.readlines(sizhint=0) # 读取文件的所有行作为一个列表返回
  525. file.xreadlines() # 用于迭代,可替换readlines()的一个更高效的方法
  526. file.seek(off, whence=0) # 在文件中移动文件指针,从whence(0代表文件起始,1代表当前位置,2代表文件末尾)偏移off字节
  527. file.tell() # 返回当前在文件中的位置
  528. file.truncate(size=file.tell()) # 截取文件到最大size字节,默认为当前文件位置
  529. file.write(str) # 向文件写入字符串
  530. file.writelines(seq) # 向文件写入字符串序列seq;seq应该是一个返回字符串的可迭代对象
  531.  
  532. 文件对象的属性
  533.  
  534. file.closed # 表示文件已被关闭,否则为False
  535. file.encoding # 文件所使用的编码 当unicode字符串被写入数据时,它将自动使用file.encoding转换为字节字符串;若file.encoding为None时使用系统默认编码
  536. file.mode # Access文件打开时使用的访问模式
  537. file.name # 文件名
  538. file.newlines # 未读取到行分隔符时为None,只有一种行分隔符时为一个字符串,当文件有多种类型的行结束符时,则为一个包含所有当前所遇到的行结束符的列表
  539. file.softspace # 为0表示在输出一数据后,要加上一个空格符,1表示不加
  540.  
  541. 异常处理
  542.  
  543. # try 中使用 sys.exit(2) 会被捕获,无法退出脚本,可使用 os._exit(2) 退出脚本
  544.  
  545. class ShortInputException(Exception): # 继承Exception异常的类,定义自己的异常
  546. def __init__(self, length, atleast):
  547. Exception.__init__(self)
  548. self.length = length
  549. self.atleast = atleast
  550. try:
  551. s = raw_input('Enter something --> ')
  552. if len(s) < 3:
  553. raise ShortInputException(len(s), 3) # 触发异常
  554. except EOFError:
  555. print '\nWhy did you do an EOF on me?'
  556. except ShortInputException, x: # 捕捉指定错误信息
  557. print 'ShortInputException: %d | %d' % (x.length, x.atleast)
  558. except Exception as err: # 捕捉所有其它错误信息内容
  559. print str(err)
  560. #except urllib2.HTTPError as err: # 捕捉外部导入模块的错误
  561. #except: # 捕捉所有其它错误 不会看到错误内容
  562. # print 'except'
  563. finally: # 无论什么情况都会执行 关闭文件或断开连接等
  564. print 'finally'
  565. else: # 无任何异常 无法和finally同用
  566. print 'No exception was raised.'
  567.  
  568. 不可捕获的异常
  569.  
  570. NameError: # 尝试访问一个未申明的变量
  571. ZeroDivisionError: # 除数为零
  572. SyntaxErrot: # 解释器语法错误
  573. IndexError: # 请求的索引元素超出序列范围
  574. KeyError: # 请求一个不存在的字典关键字
  575. IOError: # 输入/输出错误
  576. AttributeError: # 尝试访问未知的对象属性
  577. ImportError # 没有模块
  578. IndentationError # 语法缩进错误
  579. KeyboardInterrupt # ctrl+C
  580. SyntaxError # 代码语法错误
  581. ValueError # 值错误
  582. TypeError # 传入对象类型与要求不符合
  583.  
  584. 内建异常
  585.  
  586. BaseException # 所有异常的基类
  587. SystemExit # python解释器请求退出
  588. KeyboardInterrupt # 用户中断执行
  589. Exception # 常规错误的基类
  590. StopIteration # 迭代器没有更多的值
  591. GeneratorExit # 生成器发生异常来通知退出
  592. StandardError # 所有的内建标准异常的基类
  593. ArithmeticError # 所有数值计算错误的基类
  594. FloatingPointError # 浮点计算错误
  595. OverflowError # 数值运算超出最大限制
  596. AssertionError # 断言语句失败
  597. AttributeError # 对象没有这个属性
  598. EOFError # 没有内建输入,到达EOF标记
  599. EnvironmentError # 操作系统错误的基类
  600. IOError # 输入/输出操作失败
  601. OSError # 操作系统错误
  602. WindowsError # windows系统调用失败
  603. ImportError # 导入模块/对象失败
  604. KeyboardInterrupt # 用户中断执行(通常是ctrl+c)
  605. LookupError # 无效数据查询的基类
  606. IndexError # 序列中没有此索引(index)
  607. KeyError # 映射中没有这个键
  608. MemoryError # 内存溢出错误(对于python解释器不是致命的)
  609. NameError # 未声明/初始化对象(没有属性)
  610. UnboundLocalError # 访问未初始化的本地变量
  611. ReferenceError # 若引用试图访问已经垃圾回收了的对象
  612. RuntimeError # 一般的运行时错误
  613. NotImplementedError # 尚未实现的方法
  614. SyntaxError # python语法错误
  615. IndentationError # 缩进错误
  616. TabError # tab和空格混用
  617. SystemError # 一般的解释器系统错误
  618. TypeError # 对类型无效的操作
  619. ValueError # 传入无效的参数
  620. UnicodeError # Unicode相关的错误
  621. UnicodeDecodeError # Unicode解码时的错误
  622. UnicodeEncodeError # Unicode编码时的错误
  623. UnicodeTranslateError # Unicode转换时错误
  624. Warning # 警告的基类
  625. DeprecationWarning # 关于被弃用的特征的警告
  626. FutureWarning # 关于构造将来语义会有改变的警告
  627. OverflowWarning # 旧的关于自动提升为长整形的警告
  628. PendingDeprecationWarning # 关于特性将会被废弃的警告
  629. RuntimeWarning # 可疑的运行时行为的警告
  630. SyntaxWarning # 可疑的语法的警告
  631. UserWarning # 用户代码生成的警告
  632.  
  633. 触发异常
  634.  
  635. raise exclass # 触发异常,从exclass生成一个实例(不含任何异常参数)
  636. raise exclass() # 触发异常,但现在不是类;通过函数调用操作符(function calloperator:"()")作用于类名生成一个新的exclass实例,同样也没有异常参数
  637. raise exclass, args # 触发异常,但同时提供的异常参数args,可以是一个参数也可以是元组
  638. raise exclass(args) # 触发异常,同上
  639. raise exclass, args, tb # 触发异常,但提供一个跟踪记录(traceback)对象tb供使用
  640. raise exclass,instance # 通过实例触发异常(通常是exclass的实例)
  641. raise instance # 通过实例触发异常;异常类型是实例的类型:等价于raise instance.__class__, instance
  642. raise string # 触发字符串异常
  643. raise string, srgs # 触发字符串异常,但触发伴随着args
  644. raise string,args,tb # 触发字符串异常,但提供一个跟踪记录(traceback)对象tb供使用
  645. raise # 重新触发前一个异常,如果之前没有异常,触发TypeError
  646.  
  647. 跟踪异常栈
  648.  
  649. # traceback 获取异常相关数据都是通过sys.exc_info()函数得到的
  650. import traceback
  651. import sys
  652. try:
  653. s = raw_input()
  654. print int(s)
  655. except ValueError:
  656. # sys.exc_info() 返回值是元组,第一个exc_type是异常的对象类型,exc_value是异常的值,exc_tb是一个traceback对象,对象中包含出错的行数、位置等数据
  657. exc_type, exc_value, exc_tb = sys.exc_info()
  658. print "\n%s \n %s \n %s\n" %(exc_type, exc_value, exc_tb )
  659. traceback.print_exc() # 打印栈跟踪信息
  660.  
  661. 抓取全部错误信息存如字典
  662.  
  663. import sys, traceback
  664.  
  665. try:
  666. s = raw_input()
  667. int(s)
  668. except:
  669. exc_type, exc_value, exc_traceback = sys.exc_info()
  670. traceback_details = {
  671. 'filename': exc_traceback.tb_frame.f_code.co_filename,
  672. 'lineno' : exc_traceback.tb_lineno,
  673. 'name' : exc_traceback.tb_frame.f_code.co_name,
  674. 'type' : exc_type.__name__,
  675. 'message' : exc_value.message,
  676. }
  677.  
  678. del(exc_type, exc_value, exc_traceback)
  679. print traceback_details
  680. f = file('test1.txt', 'a')
  681. f.write("%s %s %s %s %s\n" %(traceback_details['filename'],traceback_details['lineno'],traceback_details['name'],traceback_details['type'],traceback_details['message'], ))
  682. f.flush()
  683. f.close()
  684.  
  685. 调试log
  686.  
  687. # cgitb覆盖了默认sys.excepthook全局异常拦截器
  688. def func(a, b):
  689. return a / b
  690. if __name__ == '__main__':
  691. import cgitb
  692. cgitb.enable(format='text')
  693. func(1, 0)
  694.  
  695. 函数式编程的内建函数
  696.  
  697. apply(func[,nkw][,kw]) # 用可选的参数来调用func,nkw为非关键字参数,kw为关键字参数;返回值是函数调用的返回值
  698. filter(func,seq) # 调用一个布尔函数func来迭代遍历每个seq中的元素;返回一个使func返回值为true的元素的序列
  699. map(func,seq1[,seq2]) # 将函数func作用于给定序列(s)的每个元素,并用一个列表来提供返回值;如果func为None,func表现为一个身份函数,返回一个含有每个序列中元素集合的n个元组的列表
  700. reduce(func,seq[,init]) # 将二元函数作用于seq序列的元素,每次携带一堆(先前的结果以及下一个序列元素),连续地将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值;如果初始值init给定,第一个比较会是init和第一个序列元素而不是序列的头两个元素
  701.  
  702. # filter 即通过函数方法只保留结果为真的值组成列表
  703. def f(x): return x % 2 != 0 and x % 3 != 0
  704. f(3) # 函数结果是False 3被filter抛弃
  705. f(5) # 函数结果是True 5被加入filter最后的列表结果
  706. filter(f, range(2, 25))
  707. [5, 7, 11, 13, 17, 19, 23]
  708.  
  709. # map 通过函数对列表进行处理得到新的列表
  710. def cube(x): return x*x*x
  711. map(cube, range(1, 11))
  712. [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
  713.  
  714. # reduce 通过函数会先接收初始值和序列的第一个元素,然后是返回值和下一个元素,依此类推
  715. def add(x,y): return x+y
  716. reduce(add, range(1, 11)) # 结果55 是1到10的和 x的值是上一次函数返回的结果,y是列表中循环的值
  717.  
  718. re正则
  719.  
  720. compile(pattern,flags=0) # 对正则表达式模式pattern进行编译,flags是可选标识符,并返回一个regex对象
  721. match(pattern,string,flags=0) # 尝试用正则表达式模式pattern匹配字符串string,flags是可选标识符,如果匹配成功,则返回一个匹配对象;否则返回None
  722. search(pattern,string,flags=0) # 在字符串string中搜索正则表达式模式pattern的第一次出现,flags是可选标识符,如果匹配成功,则返回一个匹配对象;否则返回None
  723. findall(pattern,string[,flags]) # 在字符串string中搜索正则表达式模式pattern的所有(非重复)出现:返回一个匹配对象的列表 # pattern=u'\u4e2d\u6587' 代表UNICODE
  724. finditer(pattern,string[,flags]) # 和findall()相同,但返回的不是列表而是迭代器;对于每个匹配,该迭代器返回一个匹配对象
  725. split(pattern,string,max=0) # 根据正则表达式pattern中的分隔符把字符string分割为一个列表,返回成功匹配的列表,最多分割max次(默认所有)
  726. sub(pattern,repl,string,max=0) # 把字符串string中所有匹配正则表达式pattern的地方替换成字符串repl,如果max的值没有给出,则对所有匹配的地方进行替换(subn()会返回一个表示替换次数的数值)
  727. group(num=0) # 返回全部匹配对象(或指定编号是num的子组)
  728. groups() # 返回一个包含全部匹配的子组的元组(如果没匹配成功,返回一个空元组)
  729.  
  730. 例子
  731. re.findall(r'a[be]c','123abc456eaec789') # 返回匹配对象列表 ['abc', 'aec']
  732. re.findall("(.)12[34](..)",a) # 取出匹配括号中内容 a='qedqwe123dsf'
  733. re.search("(.)123",a ).group(1) # 搜索匹配的取第1个标签
  734. re.match("^(1|2) *(.*) *abc$", str).group(2) # 取第二个标签
  735. re.match("^(1|2) *(.*) *abc$", str).groups() # 取所有标签
  736. re.sub('[abc]','A','alex') # 替换
  737. for i in re.finditer(r'\d+',s): # 迭代
  738. print i.group(),i.span() #
  739.  
  740. 搜索网页中UNICODE格式的中文
  741. QueryAdd='http://www.anti-spam.org.cn/Rbl/Query/Result'
  742. Ip='222.129.184.52'
  743. s = requests.post(url=QueryAdd, data={'IP':Ip})
  744. re.findall(u'\u4e2d\u56fd', s.text, re.S)
  745.  
  746. 编码转换
  747.  
  748. a='中文' # 编码未定义按输入终端utf8或gbk
  749. u=u'中文' # 定义为unicode编码 u值为 u'\u4e2d\u6587'
  750. u.encode('utf8') # 转为utf8格式 u值为 '\xe4\xb8\xad\xe6\x96\x87'
  751. print u # 结果显示 中文
  752. print u.encode('utf8') # 转为utf8格式,当显示终端编码为utf8 结果显示 中文 编码不一致则乱码
  753. print u.encode('gbk') # 当前终端为utf8 故乱码
  754. ord('4') # 字符转ASCII码
  755. chr(52) # ASCII码转字符
  756.  
  757. 遍历递归
  758.  
  759. [os.path.join(x[0],y) for x in os.walk('/root/python/5') for y in x[2]]
  760.  
  761. for i in os.walk('/root/python/5/work/server'):
  762. print i
  763.  
  764. 2 常用模块
  765.  
  766. sys
  767.  
  768. sys.argv # 取参数列表
  769. sys.exit(2) # 退出脚本返回状态 会被try截取
  770. sys.exc_info() # 获取当前正在处理的异常类
  771. sys.version # 获取Python解释程序的版本信息
  772. sys.maxint # 最大的Int值 9223372036854775807
  773. sys.maxunicode # 最大的Unicode值
  774. sys.modules # 返回系统导入的模块字段,key是模块名,value是模块
  775. sys.path # 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
  776. sys.platform # 返回操作系统平台名称
  777. sys.stdout # 标准输出
  778. sys.stdin # 标准输入
  779. sys.stderr # 错误输出
  780. sys.exec_prefix # 返回平台独立的python文件安装的位置
  781. sys.stdin.readline() # 从标准输入读一行
  782. sys.stdout.write("a") # 屏幕输出a
  783.  
  784. os
  785.  
  786. # 相对sys模块 os模块更为底层 os._exit() try无法抓取
  787. os.popen('id').read() # 执行系统命令得到返回结果
  788. os.system() # 得到返回状态 返回无法截取
  789. os.name # 返回系统平台 Linux/Unix用户是'posix'
  790. os.getenv() # 读取环境变量
  791. os.putenv() # 设置环境变量
  792. os.getcwd() # 当前工作路径
  793. os.chdir() # 改变当前工作目录
  794. os.walk('/root/') # 递归路径
  795.  
  796. 文件处理
  797. mkfifo()/mknod() # 创建命名管道/创建文件系统节点
  798. remove()/unlink() # 删除文件
  799. rename()/renames() # 重命名文件
  800. *stat() # 返回文件信息
  801. symlink() # 创建符号链接
  802. utime() # 更新时间戳
  803. tmpfile() # 创建并打开('w+b')一个新的临时文件
  804. walk() # 遍历目录树下的所有文件名
  805.  
  806. 目录/文件夹
  807. chdir()/fchdir() # 改变当前工作目录/通过一个文件描述符改变当前工作目录
  808. chroot() # 改变当前进程的根目录
  809. listdir() # 列出指定目录的文件
  810. getcwd()/getcwdu() # 返回当前工作目录/功能相同,但返回一个unicode对象
  811. mkdir()/makedirs() # 创建目录/创建多层目录
  812. rmdir()/removedirs() # 删除目录/删除多层目录
  813.  
  814. 访问/权限
  815. saccess() # 检验权限模式
  816. chmod() # 改变权限模式
  817. chown()/lchown() # 改变owner和groupID功能相同,但不会跟踪链接
  818. umask() # 设置默认权限模式
  819.  
  820. 文件描述符操作
  821. open() # 底层的操作系统open(对于稳健,使用标准的内建open()函数)
  822. read()/write() # 根据文件描述符读取/写入数据 按大小读取文件部分内容
  823. dup()/dup2() # 复制文件描述符号/功能相同,但是复制到另一个文件描述符
  824.  
  825. 设备号
  826. makedev() # 从major和minor设备号创建一个原始设备号
  827. major()/minor() # 从原始设备号获得major/minor设备号
  828.  
  829. os.path模块
  830.  
  831. os.path.expanduser('~/.ssh/key') # 家目录下文件的全路径
  832.  
  833. 分隔
  834. os.path.basename() # 去掉目录路径,返回文件名
  835. os.path.dirname() # 去掉文件名,返回目录路径
  836. os.path.join() # 将分离的各部分组合成一个路径名
  837. os.path.spllt() # 返回(dirname(),basename())元组
  838. os.path.splitdrive() # 返回(drivename,pathname)元组
  839. os.path.splitext() # 返回(filename,extension)元组
  840.  
  841. 信息
  842. os.path.getatime() # 返回最近访问时间
  843. os.path.getctime() # 返回文件创建时间
  844. os.path.getmtime() # 返回最近文件修改时间
  845. os.path.getsize() # 返回文件大小(字节)
  846.  
  847. 查询
  848. os.path.exists() # 指定路径(文件或目录)是否存在
  849. os.path.isabs() # 指定路径是否为绝对路径
  850. os.path.isdir() # 指定路径是否存在且为一个目录
  851. os.path.isfile() # 指定路径是否存在且为一个文件
  852. os.path.islink() # 指定路径是否存在且为一个符号链接
  853. os.path.ismount() # 指定路径是否存在且为一个挂载点
  854. os.path.samefile() # 两个路径名是否指向同一个文件
  855.  
  856. 相关模块
  857. base64 # 提供二进制字符串和文本字符串间的编码/解码操作
  858. binascii # 提供二进制和ASCII编码的二进制字符串间的编码/解码操作
  859. bz2 # 访问BZ2格式的压缩文件
  860. csv # 访问csv文件(逗号分隔文件)
  861. csv.reader(open(file))
  862. filecmp # 用于比较目录和文件
  863. fileinput # 提供多个文本文件的行迭代器
  864. getopt/optparse # 提供了命令行参数的解析/处理
  865. glob/fnmatch # 提供unix样式的通配符匹配的功能
  866. gzip/zlib # 读写GNU zip(gzip)文件(压缩需要zlib模块)
  867. shutil # 提供高级文件访问功能
  868. c/StringIO # 对字符串对象提供类文件接口
  869. tarfile # 读写TAR归档文件,支持压缩文件
  870. tempfile # 创建一个临时文件
  871. uu # uu格式的编码和解码
  872. zipfile # 用于读取zip归档文件的工具
  873. environ['HOME'] # 查看系统环境变量
  874.  
  875. 子进程
  876. os.fork() # 创建子进程,并复制父进程所有操作 通过判断pid = os.fork() 的pid值,分别执行父进程与子进程操作,0为子进程
  877. os.wait() # 等待子进程结束
  878.  
  879. 跨平台os模块属性
  880.  
  881. linesep # 用于在文件中分隔行的字符串
  882. sep # 用来分隔文件路径名字的字符串
  883. pathsep # 用于分割文件路径的字符串
  884. curdir # 当前工作目录的字符串名称
  885. pardir # 父目录字符串名称
  886.  
  887. commands
  888.  
  889. commands.getstatusoutput('id') # 返回元组(状态,标准输出)
  890. commands.getoutput('id') # 只返回执行的结果, 忽略返回值
  891. commands.getstatus('file') # 返回ls -ld file执行的结果
  892.  
  893. 文件和目录管理
  894.  
  895. import shutil
  896. shutil.copyfile('data.db', 'archive.db') # 拷贝文件
  897. shutil.move('/build/executables', 'installdir') # 移动文件或目录
  898.  
  899. 文件通配符
  900.  
  901. import glob
  902. glob.glob('*.py') # 查找当前目录下py结尾的文件
  903.  
  904. 随机模块
  905.  
  906. import random
  907. random.choice(['apple', 'pear', 'banana']) # 随机取列表一个参数
  908. random.sample(xrange(100), 10) # 不重复抽取10个
  909. random.random() # 随机浮点数
  910. random.randrange(6) # 随机整数范围
  911.  
  912. 发送邮件
  913.  
  914. 发送邮件内容
  915.  
  916. #!/usr/bin/python
  917. #encoding:utf8
  918. # 导入 smtplib 和 MIMEText
  919. import smtplib
  920. from email.mime.text import MIMEText
  921.  
  922. # 定义发送列表
  923. mailto_list=["272121935@qq.com","272121935@163.com"]
  924.  
  925. # 设置服务器名称、用户名、密码以及邮件后缀
  926. mail_host = "smtp.163.com"
  927. mail_user = "mailuser"
  928. mail_pass = "password"
  929. mail_postfix="163.com"
  930.  
  931. # 发送邮件函数
  932. def send_mail(to_list, sub):
  933. me = mail_user + "<"+mail_user+"@"+mail_postfix+">"
  934. fp = open('context.txt')
  935. msg = MIMEText(fp.read(),_charset="utf-8")
  936. fp.close()
  937. msg['Subject'] = sub
  938. msg['From'] = me
  939. msg['To'] = ";".join(to_list)
  940. try:
  941. send_smtp = smtplib.SMTP()
  942. send_smtp.connect(mail_host)
  943. send_smtp.login(mail_user, mail_pass)
  944. send_smtp.sendmail(me, to_list, msg.as_string())
  945. send_smtp.close()
  946. return True
  947. except Exception, e:
  948. print str(e)
  949. return False
  950.  
  951. if send_mail(mailto_list,"标题"):
  952. print "测试成功"
  953. else:
  954. print "测试失败"
  955.  
  956. 发送附件
  957.  
  958. #!/usr/bin/python
  959. #encoding:utf8
  960. import smtplib
  961. from email.mime.multipart import MIMEMultipart
  962. from email.mime.base import MIMEBase
  963. from email import encoders
  964.  
  965. def send_mail(to_list, sub, filename):
  966. me = mail_user + "<"+mail_user+"@"+mail_postfix+">"
  967. msg = MIMEMultipart()
  968. msg['Subject'] = sub
  969. msg['From'] = me
  970. msg['To'] = ";".join(to_list)
  971. submsg = MIMEBase('application', 'x-xz')
  972. submsg.set_payload(open(filename,'rb').read())
  973. encoders.encode_base64(submsg)
  974. submsg.add_header('Content-Disposition', 'attachment', filename=filename)
  975. msg.attach(submsg)
  976. try:
  977. send_smtp = smtplib.SMTP()
  978. send_smtp.connect(mail_host)
  979. send_smtp.login(mail_user, mail_pass)
  980. send_smtp.sendmail(me, to_list, msg.as_string())
  981. send_smtp.close()
  982. return True
  983. except Exception, e:
  984. print str(e)[1]
  985. return False
  986.  
  987. # 设置服务器名称、用户名、密码以及邮件后缀
  988. mail_host = "smtp.163.com"
  989. mail_user = "xuesong"
  990. mail_pass = "mailpasswd"
  991. mail_postfix = "163.com"
  992. mailto_list = ["272121935@qq.com","quanzhou722@163.com"]
  993. title = 'check'
  994. filename = 'file_check.html'
  995. if send_mail(mailto_list,title,filename):
  996. print "发送成功"
  997. else:
  998. print "发送失败"
  999.  
  1000. 解压缩
  1001.  
  1002. gzip压缩
  1003.  
  1004. import gzip
  1005. f_in = open('file.log', 'rb')
  1006. f_out = gzip.open('file.log.gz', 'wb')
  1007. f_out.writelines(f_in)
  1008. f_out.close()
  1009. f_in.close()
  1010.  
  1011. gzip压缩1
  1012.  
  1013. File = 'xuesong_18.log'
  1014. g = gzip.GzipFile(filename="", mode='wb', compresslevel=9, fileobj=open((r'%s.gz' %File),'wb'))
  1015. g.write(open(r'%s' %File).read())
  1016. g.close()
  1017.  
  1018. gzip解压
  1019.  
  1020. g = gzip.GzipFile(mode='rb', fileobj=open((r'xuesong_18.log.gz'),'rb'))
  1021. open((r'xuesong_18.log'),'wb').write(g.read())
  1022.  
  1023. 压缩tar.gz
  1024.  
  1025. import os
  1026. import tarfile
  1027. tar = tarfile.open("/tmp/tartest.tar.gz","w:gz") # 创建压缩包名
  1028. for path,dir,files in os.walk("/tmp/tartest"): # 递归文件目录
  1029. for file in files:
  1030. fullpath = os.path.join(path,file)
  1031. tar.add(fullpath) # 创建压缩包
  1032. tar.close()
  1033.  
  1034. 解压tar.gz
  1035.  
  1036. import tarfile
  1037. tar = tarfile.open("/tmp/tartest.tar.gz")
  1038. #tar.extract("/tmp") # 全部解压到指定路径
  1039. names = tar.getnames() # 包内文件名
  1040. for name in names:
  1041. tar.extract(name,path="./") # 解压指定文件
  1042. tar.close()
  1043.  
  1044. zip压缩
  1045. import zipfile,os
  1046. f = zipfile.ZipFile('filename.zip', 'w' ,zipfile.ZIP_DEFLATED) # ZIP_STORE 为默认表不压缩. ZIP_DEFLATED 表压缩
  1047. #f.write('file1.txt') # 将文件写入压缩包
  1048. for path,dir,files in os.walk("tartest"): # 递归压缩目录
  1049. for file in files:
  1050. f.write(os.path.join(path,file)) # 将文件逐个写入压缩包
  1051. f.close()
  1052.  
  1053. zip解压
  1054. if zipfile.is_zipfile('filename.zip'): # 判断一个文件是不是zip文件
  1055. f = zipfile.ZipFile('filename.zip')
  1056. for file in f.namelist(): # 返回文件列表
  1057. f.extract(file, r'/tmp/') # 解压指定文件
  1058. #f.extractall() # 解压全部
  1059. f.close()
  1060.  
  1061. 时间
  1062.  
  1063. import time
  1064. time.time() # 时间戳[浮点]
  1065. time.localtime()[1] - 1 # 上个月
  1066. int(time.time()) # 时间戳[整s]
  1067. tomorrow.strftime('%Y%m%d_%H%M') # 格式化时间
  1068. time.strftime('%Y-%m-%d_%X',time.localtime( time.time() ) ) # 时间戳转日期
  1069. time.mktime(time.strptime('2012-03-28 06:53:40', '%Y-%m-%d %H:%M:%S')) # 日期转时间戳
  1070.  
  1071. 判断输入时间格式是否正确
  1072.  
  1073. #encoding:utf8
  1074. import time
  1075. while 1:
  1076. atime=raw_input('输入格式如[14.05.13 13:00]:')
  1077. try:
  1078. btime=time.mktime(time.strptime('%s:00' %atime, '%y.%m.%d %H:%M:%S'))
  1079. break
  1080. except:
  1081. print '时间输入错误,请重新输入,格式如[14.05.13 13:00]'
  1082.  
  1083. 上一个月最后一天
  1084. import datetime
  1085. lastMonth=datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)
  1086. lastMonth.strftime("%Y/%m")
  1087.  
  1088. 前一天
  1089. (datetime.datetime.now() + datetime.timedelta(days=-1) ).strftime('%Y%m%d')
  1090.  
  1091. 两日期相差天数
  1092.  
  1093. import datetime
  1094. d1 = datetime.datetime(2005, 2, 16)
  1095. d2 = datetime.datetime(2004, 12, 31)
  1096. (d1 - d2).days
  1097.  
  1098. 向后加10个小时
  1099.  
  1100. import datetime
  1101. d1 = datetime.datetime.now()
  1102. d3 = d1 + datetime.timedelta(hours=10)
  1103. d3.ctime()
  1104.  
  1105. 参数[optparse]
  1106. import os, sys
  1107. import time
  1108. import optparse
  1109. # python aaa.py -t file -p /etc/opt -o aaaaa
  1110.  
  1111. def do_fiotest( type, path, output,):
  1112. print type, path, output,
  1113.  
  1114. def main():
  1115. parser = optparse.OptionParser()
  1116. parser.add_option('-t', '--type', dest = 'type', default = None, help = 'test type[file, device]')
  1117. parser.add_option('-p', '--path', dest = 'path', default = None, help = 'test file path or device path')
  1118. parser.add_option('-o', '--output', dest = 'output', default = None, help = 'result dir path')
  1119.  
  1120. (o, a) = parser.parse_args()
  1121.  
  1122. if None == o.type or None == o.path or None == o.output:
  1123. print "No device or file or output dir"
  1124. return -1
  1125.  
  1126. if 'file' != o.type and 'device' != o.type:
  1127. print "You need specify test type ['file' or 'device']"
  1128. return -1
  1129.  
  1130. do_fiotest(o.type, o.path, o.output)
  1131. print "Test done!"
  1132.  
  1133. if __name__ == '__main__':
  1134. main()
  1135.  
  1136. hash
  1137.  
  1138. import md5
  1139. m = md5.new('123456').hexdigest()
  1140.  
  1141. import hashlib
  1142. m = hashlib.md5()
  1143. m.update("Nobody inspects") # 使用update方法对字符串md5加密
  1144. m.digest() # 加密后二进制结果
  1145. m.hexdigest() # 加密后十进制结果
  1146. hashlib.new("md5", "string").hexdigest() # 对字符串加密
  1147. hashlib.new("md5", open("file").read()).hexdigest() # 查看文件MD5值
  1148.  
  1149. 隐藏输入密码
  1150.  
  1151. import getpass
  1152. passwd=getpass.getpass()
  1153.  
  1154. string打印a-z
  1155. import string
  1156. string.lowercase # a-z小写
  1157. string.uppercase # A-Z大小
  1158.  
  1159. paramiko [ssh客户端]
  1160.  
  1161. 安装
  1162. sudo apt-get install python-setuptools
  1163. easy_install
  1164. sudo apt-get install python-all-dev
  1165. sudo apt-get install build-essential
  1166.  
  1167. paramiko实例(账号密码登录执行命令)
  1168.  
  1169. #!/usr/bin/python
  1170. #ssh
  1171. import paramiko
  1172. import sys,os
  1173.  
  1174. host = '10.152.15.200'
  1175. user = 'peterli'
  1176. password = '123456'
  1177.  
  1178. s = paramiko.SSHClient() # 绑定实例
  1179. s.load_system_host_keys() # 加载本地HOST主机文件
  1180. s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 允许连接不在know_hosts文件中的主机
  1181. s.connect(host,22,user,password,timeout=5) # 连接远程主机
  1182. while True:
  1183. cmd=raw_input('cmd:')
  1184. stdin,stdout,stderr = s.exec_command(cmd) # 执行命令
  1185. cmd_result = stdout.read(),stderr.read() # 读取命令结果
  1186. for line in cmd_result:
  1187. print line,
  1188. s.close()
  1189.  
  1190. paramiko实例(传送文件)
  1191.  
  1192. #!/usr/bin/evn python
  1193. import os
  1194. import paramiko
  1195. host='127.0.0.1'
  1196. port=22
  1197. username = 'peterli'
  1198. password = '123456'
  1199. ssh=paramiko.Transport((host,port))
  1200. privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')
  1201. mykey = paramiko.RSAKey.from_private_key_file( os.path.expanduser('~/.ssh/id_rsa')) # 加载key 不使用key可不加
  1202. ssh.connect(username=username,password=password) # 连接远程主机
  1203. # 使用key把 password=password 换成 pkey=mykey
  1204. sftp=paramiko.SFTPClient.from_transport(ssh) # SFTP使用Transport通道
  1205. sftp.get('/etc/passwd','pwd1') # 下载 两端都要指定文件名
  1206. sftp.put('pwd','/tmp/pwd') # 上传
  1207. sftp.close()
  1208. ssh.close()
  1209.  
  1210. paramiko实例(密钥执行命令)
  1211.  
  1212. #!/usr/bin/python
  1213. #ssh
  1214. import paramiko
  1215. import sys,os
  1216. host = '10.152.15.123'
  1217. user = 'peterli'
  1218. s = paramiko.SSHClient()
  1219. s.load_system_host_keys()
  1220. s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  1221. privatekeyfile = os.path.expanduser('~/.ssh/id_rsa') # 定义key路径
  1222. mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
  1223. # mykey=paramiko.DSSKey.from_private_key_file(privatekeyfile,password='061128') # DSSKey方式 password是key的密码
  1224. s.connect(host,22,user,pkey=mykey,timeout=5)
  1225. cmd=raw_input('cmd:')
  1226. stdin,stdout,stderr = s.exec_command(cmd)
  1227. cmd_result = stdout.read(),stderr.read()
  1228. for line in cmd_result:
  1229. print line,
  1230. s.close()
  1231.  
  1232. ssh并发(Pool控制最大并发)
  1233.  
  1234. #!/usr/bin/env python
  1235. #encoding:utf8
  1236. #ssh_concurrent.py
  1237.  
  1238. import multiprocessing
  1239. import sys,os,time
  1240. import paramiko
  1241.  
  1242. def ssh_cmd(host,port,user,passwd,cmd):
  1243. msg = "-----------Result:%s----------" % host
  1244.  
  1245. s = paramiko.SSHClient()
  1246. s.load_system_host_keys()
  1247. s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  1248. try:
  1249. s.connect(host,22,user,passwd,timeout=5)
  1250. stdin,stdout,stderr = s.exec_command(cmd)
  1251.  
  1252. cmd_result = stdout.read(),stderr.read()
  1253. print msg
  1254. for line in cmd_result:
  1255. print line,
  1256.  
  1257. s.close()
  1258. except paramiko.AuthenticationException:
  1259. print msg
  1260. print 'AuthenticationException Failed'
  1261. except paramiko.BadHostKeyException:
  1262. print msg
  1263. print "Bad host key"
  1264.  
  1265. result = []
  1266. p = multiprocessing.Pool(processes=20)
  1267. cmd=raw_input('CMD:')
  1268. f=open('serverlist.conf')
  1269. list = f.readlines()
  1270. f.close()
  1271. for IP in list:
  1272. print IP
  1273. host=IP.split()[0]
  1274. port=int(IP.split()[1])
  1275. user=IP.split()[2]
  1276. passwd=IP.split()[3]
  1277. result.append(p.apply_async(ssh_cmd,(host,port,user,passwd,cmd)))
  1278.  
  1279. p.close()
  1280.  
  1281. for res in result:
  1282. res.get(timeout=35)
  1283.  
  1284. ssh并发(取文件状态并发送邮件)
  1285.  
  1286. #!/usr/bin/python
  1287. #encoding:utf8
  1288. #config file: ip.list
  1289.  
  1290. import paramiko
  1291. import multiprocessing
  1292. import smtplib
  1293. import sys,os,time,datetime,socket,re
  1294. from email.mime.text import MIMEText
  1295.  
  1296. # 配置文件(IP列表)
  1297. Conf = 'ip.list'
  1298. user_name = 'peterli'
  1299. user_pwd = 'passwd'
  1300. port = 22
  1301. PATH = '/home/peterli/'
  1302.  
  1303. # 设置服务器名称、用户名、密码以及邮件后缀
  1304. mail_host = "smtp.163.com"
  1305. mail_user = "xuesong"
  1306. mail_pass = "mailpasswd"
  1307. mail_postfix = "163.com"
  1308. mailto_list = ["272121935@qq.com","quanzhou722@163.com"]
  1309. title = 'file check'
  1310.  
  1311. DATE1=(datetime.datetime.now() + datetime.timedelta(days=-1) ).strftime('%Y%m%d')
  1312. file_path = '%s%s' %(PATH,DATE1)
  1313.  
  1314. def Ssh_Cmd(file_path,host_ip,user_name,user_pwd,port=22):
  1315.  
  1316. s = paramiko.SSHClient()
  1317. s.load_system_host_keys()
  1318. s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  1319.  
  1320. try:
  1321. s.connect(hostname=host_ip,port=port,username=user_name,password=user_pwd)
  1322. stdin,stdout,stderr = s.exec_command('stat %s' %file_path)
  1323. stat_result = '%s%s' %(stdout.read(),stderr.read())
  1324. if stat_result.find('No such file or directory') == -1:
  1325. file_status = 'OK\t'
  1326. stdin,stdout,stderr = s.exec_command('du -sh %s' %file_path)
  1327. cmd1_result = '%s_%s' %(stat_result.split()[32],stat_result.split()[33].split('.')[0])
  1328. cmd2_result = ('%s%s' %(stdout.read(),stderr.read())).split()[0]
  1329. else:
  1330. file_status = '未生成\t'
  1331. cmd1_result = 'null'
  1332. cmd2_result = 'null'
  1333. q.put(['Login successful'])
  1334. s.close()
  1335. except socket.error:
  1336. file_status = '主机或端口错误'
  1337. cmd1_result = '-'
  1338. cmd2_result = '-'
  1339. except paramiko.AuthenticationException:
  1340. file_status = '用户或密码错误'
  1341. cmd1_result = '-'
  1342. cmd2_result = '-'
  1343. except paramiko.BadHostKeyException:
  1344. file_status = 'Bad host key'
  1345. cmd1_result = '-'
  1346. cmd2_result = '-'
  1347. except:
  1348. file_status = 'ssh异常'
  1349. cmd1_result = '-'
  1350. cmd2_result = '-'
  1351. r.put('%s\t-\t%s\t%s\t%s\t%s\n' %(time.strftime('%Y-%m-%d_%H:%M'),host_ip,file_status,cmd2_result,cmd1_result))
  1352.  
  1353. def Concurrent(Conf,file_path,user_name,user_pwd,port):
  1354. # 执行总计
  1355. total = 0
  1356. # 读取配置文件
  1357. f=open(Conf)
  1358. list = f.readlines()
  1359. f.close()
  1360. # 并发执行
  1361. process_list = []
  1362. log_file = file('file_check.log', 'w')
  1363. log_file.write('检查时间\t\t业务\tIP\t\t文件状态\t大小\t生成时间\n')
  1364. for host_info in list:
  1365. # 判断配置文件中注释行跳过
  1366. if host_info.startswith('#'):
  1367. continue
  1368. # 取变量,其中任意变量未取到就跳过执行
  1369. try:
  1370. host_ip=host_info.split()[0].strip()
  1371. #user_name=host_info.split()[1]
  1372. #user_pwd=host_info.split()[2]
  1373. except:
  1374. log_file.write('Profile error: %s\n' %(host_info))
  1375. continue
  1376. #try:
  1377. # port=int(host_info.split()[3])
  1378. #except:
  1379. # port=22
  1380. total +=1
  1381. p = multiprocessing.Process(target=Ssh_Cmd,args=(file_path,host_ip,user_name,user_pwd,port))
  1382. p.start()
  1383. process_list.append(p)
  1384. for j in process_list:
  1385. j.join()
  1386. for j in process_list:
  1387. log_file.write(r.get())
  1388.  
  1389. successful = q.qsize()
  1390. log_file.write('执行完毕。 总执行:%s 登录成功:%s 登录失败:%s\n' %(total,successful,total - successful))
  1391. log_file.flush()
  1392. log_file.close()
  1393.  
  1394. def send_mail(to_list, sub):
  1395. me = mail_user + "<"+mail_user+"@"+mail_postfix+">"
  1396. fp = open('file_check.log')
  1397. msg = MIMEText(fp.read(),_charset="utf-8")
  1398. fp.close()
  1399. msg['Subject'] = sub
  1400. msg['From'] = me
  1401. msg['To'] = ";".join(to_list)
  1402. try:
  1403. send_smtp = smtplib.SMTP()
  1404. send_smtp.connect(mail_host)
  1405. send_smtp.login(mail_user, mail_pass)
  1406. send_smtp.sendmail(me, to_list, msg.as_string())
  1407. send_smtp.close()
  1408. return True
  1409. except Exception, e:
  1410. print str(e)[1]
  1411. return False
  1412.  
  1413. if __name__ == '__main__':
  1414. q = multiprocessing.Queue()
  1415. r = multiprocessing.Queue()
  1416. Concurrent(Conf,file_path,user_name,user_pwd,port)
  1417. if send_mail(mailto_list,title):
  1418. print "发送成功"
  1419. else:
  1420. print "发送失败"
  1421.  
  1422. LazyManage并发批量操作(判断非root交互到root操作)
  1423.  
  1424. #!/usr/bin/python
  1425. #encoding:utf8
  1426. # LzayManage.py
  1427. # config file: serverlist.conf
  1428.  
  1429. import paramiko
  1430. import multiprocessing
  1431. import sys,os,time,socket,re
  1432.  
  1433. def Ssh_Cmd(host_ip,Cmd,user_name,user_pwd,port=22):
  1434. s = paramiko.SSHClient()
  1435. s.load_system_host_keys()
  1436. s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  1437. s.connect(hostname=host_ip,port=port,username=user_name,password=user_pwd)
  1438. stdin,stdout,stderr = s.exec_command(Cmd)
  1439. Result = '%s%s' %(stdout.read(),stderr.read())
  1440. q.put('successful')
  1441. s.close()
  1442. return Result.strip()
  1443.  
  1444. def Ssh_Su_Cmd(host_ip,Cmd,user_name,user_pwd,root_name,root_pwd,port=22):
  1445. s = paramiko.SSHClient()
  1446. s.load_system_host_keys()
  1447. s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  1448. s.connect(hostname=host_ip,port=port,username=user_name,password=user_pwd)
  1449. ssh = s.invoke_shell()
  1450. time.sleep(0.1)
  1451. ssh.send('su - %s\n' %(root_name))
  1452. buff = ''
  1453. while not buff.endswith('Password: '):
  1454. resp = ssh.recv(9999)
  1455. buff +=resp
  1456. ssh.send('%s\n' %(root_pwd))
  1457. buff = ''
  1458. while True:
  1459. resp = ssh.recv(9999)
  1460. buff +=resp
  1461. if ': incorrect password' in buff:
  1462. su_correct='passwd_error'
  1463. break
  1464. elif buff.endswith('# '):
  1465. su_correct='passwd_correct'
  1466. break
  1467. if su_correct == 'passwd_correct':
  1468. ssh.send('%s\n' %(Cmd))
  1469. buff = ''
  1470. while True:
  1471. resp = ssh.recv(9999)
  1472. if resp.endswith('# '):
  1473. buff +=re.sub('\[.*@.*\]# $','',resp)
  1474. break
  1475. buff +=resp
  1476. Result = buff.lstrip('%s' %(Cmd))
  1477. q.put('successful')
  1478. elif su_correct == 'passwd_error':
  1479. Result = "\033[31mroot密码错误\033[m"
  1480. s.close()
  1481. return Result.strip()
  1482.  
  1483. def Send_File(host_ip,PathList,user_name,user_pwd,Remote='/tmp',port=22):
  1484. s=paramiko.Transport((host_ip,port))
  1485. s.connect(username=user_name,password=user_pwd)
  1486. sftp=paramiko.SFTPClient.from_transport(s)
  1487. for InputPath in PathList:
  1488. LocalPath = re.sub('^\./','',InputPath.rstrip('/'))
  1489. RemotePath = '%s/%s' %( Remote , os.path.basename( LocalPath ))
  1490. try:
  1491. sftp.rmdir(RemotePath)
  1492. except:
  1493. pass
  1494. try:
  1495. sftp.remove(RemotePath)
  1496. except:
  1497. pass
  1498. if os.path.isdir(LocalPath):
  1499. sftp.mkdir(RemotePath)
  1500. for path,dirs,files in os.walk(LocalPath):
  1501. for dir in dirs:
  1502. dir_path = os.path.join(path,dir)
  1503. sftp.mkdir('%s/%s' %(RemotePath,re.sub('^%s/' %LocalPath,'',dir_path)))
  1504. for file in files:
  1505. file_path = os.path.join(path,file)
  1506. sftp.put( file_path,'%s/%s' %(RemotePath,re.sub('^%s/' %LocalPath,'',file_path)))
  1507. else:
  1508. sftp.put(LocalPath,RemotePath)
  1509. q.put('successful')
  1510. sftp.close()
  1511. s.close()
  1512. Result = '%s \033[32m传送完成\033[m' % PathList
  1513. return Result
  1514.  
  1515. def Ssh(host_ip,Operation,user_name,user_pwd,root_name,root_pwd,Cmd=None,PathList=None,port=22):
  1516. msg = "\033[32m-----------Result:%s----------\033[m" % host_ip
  1517. try:
  1518. if Operation == 'Ssh_Cmd':
  1519. Result = Ssh_Cmd(host_ip=host_ip,Cmd=Cmd,user_name=user_name,user_pwd=user_pwd,port=port)
  1520. elif Operation == 'Ssh_Su_Cmd':
  1521. Result = Ssh_Su_Cmd(host_ip=host_ip,Cmd=Cmd,user_name=user_name,user_pwd=user_pwd,root_name=root_name,root_pwd=root_pwd,port=port)
  1522. elif Operation == 'Ssh_Script':
  1523. Send_File(host_ip=host_ip,PathList=PathList,user_name=user_name,user_pwd=user_pwd,port=port)
  1524. Script_Head = open(PathList[0]).readline().strip()
  1525. LocalPath = re.sub('^\./','',PathList[0].rstrip('/'))
  1526. Cmd = '%s /tmp/%s' %( re.sub('^#!','',Script_Head), os.path.basename( LocalPath ))
  1527. Result = Ssh_Cmd(host_ip=host_ip,Cmd=Cmd,user_name=user_name,user_pwd=user_pwd,port=port)
  1528. elif Operation == 'Ssh_Su_Script':
  1529. Send_File(host_ip=host_ip,PathList=PathList,user_name=user_name,user_pwd=user_pwd,port=port)
  1530. Script_Head = open(PathList[0]).readline().strip()
  1531. LocalPath = re.sub('^\./','',PathList[0].rstrip('/'))
  1532. Cmd = '%s /tmp/%s' %( re.sub('^#!','',Script_Head), os.path.basename( LocalPath ))
  1533. Result = Ssh_Su_Cmd(host_ip=host_ip,Cmd=Cmd,user_name=user_name,user_pwd=user_pwd,root_name=root_name,root_pwd=root_pwd,port=port)
  1534. elif Operation == 'Send_File':
  1535. Result = Send_File(host_ip=host_ip,PathList=PathList,user_name=user_name,user_pwd=user_pwd,port=port)
  1536. else:
  1537. Result = '操作不存在'
  1538.  
  1539. except socket.error:
  1540. Result = '\033[31m主机或端口错误\033[m'
  1541. except paramiko.AuthenticationException:
  1542. Result = '\033[31m用户名或密码错误\033[m'
  1543. except paramiko.BadHostKeyException:
  1544. Result = '\033[31mBad host key\033[m['
  1545. except IOError:
  1546. Result = '\033[31m远程主机已存在非空目录或没有写权限\033[m'
  1547. except:
  1548. Result = '\033[31m未知错误\033[m'
  1549. r.put('%s\n%s\n' %(msg,Result))
  1550.  
  1551. def Concurrent(Conf,Operation,user_name,user_pwd,root_name,root_pwd,Cmd=None,PathList=None,port=22):
  1552. # 读取配置文件
  1553. f=open(Conf)
  1554. list = f.readlines()
  1555. f.close()
  1556. # 执行总计
  1557. total = 0
  1558. # 并发执行
  1559. for host_info in list:
  1560. # 判断配置文件中注释行跳过
  1561. if host_info.startswith('#'):
  1562. continue
  1563. # 取变量,其中任意变量未取到就跳过执行
  1564. try:
  1565. host_ip=host_info.split()[0]
  1566. #user_name=host_info.split()[1]
  1567. #user_pwd=host_info.split()[2]
  1568. except:
  1569. print('Profile error: %s' %(host_info) )
  1570. continue
  1571. try:
  1572. port=int(host_info.split()[3])
  1573. except:
  1574. port=22
  1575. total +=1
  1576. p = multiprocessing.Process(target=Ssh,args=(host_ip,Operation,user_name,user_pwd,root_name,root_pwd,Cmd,PathList,port))
  1577. p.start()
  1578. # 打印执行结果
  1579. for j in range(total):
  1580. print(r.get() )
  1581. if Operation == 'Ssh_Script' or Operation == 'Ssh_Su_Script':
  1582. successful = q.qsize() / 2
  1583. else:
  1584. successful = q.qsize()
  1585. print('\033[32m执行完毕[总执行:%s 成功:%s 失败:%s]\033[m' %(total,successful,total - successful) )
  1586. q.close()
  1587. r.close()
  1588.  
  1589. def Help():
  1590. print(''' 1.执行命令
  1591. 2.执行脚本 \033[32m[位置1脚本(必须带脚本头),后可带执行脚本所需要的包\文件\文件夹路径,空格分隔]\033[m
  1592. 3.发送文件 \033[32m[传送的包\文件\文件夹路径,空格分隔]\033[m
  1593. 退出: 0\exit\quit
  1594. 帮助: help\h\?
  1595. 注意: 发送文件默认为/tmp下,如已存在同名文件会被强制覆盖,非空目录则中断操作.执行脚本先将本地脚本及包发送远程主机上,发送规则同发送文件
  1596. ''')
  1597.  
  1598. if __name__=='__main__':
  1599. # 定义root账号信息
  1600. root_name = 'root'
  1601. root_pwd = 'peterli'
  1602. user_name='peterli'
  1603. user_pwd='<++(3Ie'
  1604. # 配置文件
  1605. Conf='serverlist.conf'
  1606. if not os.path.isfile(Conf):
  1607. print('\033[33m配置文件 %s 不存在\033[m' %(Conf) )
  1608. sys.exit()
  1609. Help()
  1610. while True:
  1611. i = raw_input("\033[35m[请选择操作]: \033[m").strip()
  1612. q = multiprocessing.Queue()
  1613. r = multiprocessing.Queue()
  1614. if i == '1':
  1615. if user_name == root_name:
  1616. Operation = 'Ssh_Cmd'
  1617. else:
  1618. Operation = 'Ssh_Su_Cmd'
  1619. Cmd = raw_input('CMD: ').strip()
  1620. if len(Cmd) == 0:
  1621. print('\033[33m命令为空\033[m')
  1622. continue
  1623. Concurrent(Conf=Conf,Operation=Operation,user_name=user_name,user_pwd=user_pwd,root_name=root_name,root_pwd=root_pwd,Cmd=Cmd)
  1624. elif i == '2':
  1625. if user_name == root_name:
  1626. Operation = 'Ssh_Script'
  1627. else:
  1628. Operation = 'Ssh_Su_Script'
  1629. PathList = raw_input('\033[36m本地脚本路径: \033[m').strip().split()
  1630. if len(PathList) == 0:
  1631. print('\033[33m路径为空\033[m')
  1632. continue
  1633. if not os.path.isfile(PathList[0]):
  1634. print('\033[33m本地路径 %s 不存在或不是文件\033[m' %(PathList[0]) )
  1635. continue
  1636. for LocalPath in PathList[1:]:
  1637. if not os.path.exists(LocalPath):
  1638. print('\033[33m本地路径 %s 不存在\033[m' %(LocalPath) )
  1639. break
  1640. else:
  1641. Concurrent(Conf=Conf,Operation=Operation,user_name=user_name,user_pwd=user_pwd,root_name=root_name,root_pwd=root_pwd,PathList=PathList)
  1642. elif i == '3':
  1643. Operation = 'Send_File'
  1644. PathList = raw_input('\033[36m本地路径: \033[m').strip().split()
  1645. if len(PathList) == 0:
  1646. print('\033[33m路径为空\033[m')
  1647. continue
  1648. for LocalPath in PathList:
  1649. if not os.path.exists(LocalPath):
  1650. print('\033[33m本地路径 %s 不存在\033[m' %(LocalPath) )
  1651. break
  1652. else:
  1653. Concurrent(Conf=Conf,Operation=Operation,user_name=user_name,user_pwd=user_pwd,root_name=root_name,root_pwd=root_pwd,PathList=PathList)
  1654. elif i == '0' or i == 'exit' or i == 'quit':
  1655. print("\033[34m退出LazyManage脚本\033[m")
  1656. sys.exit()
  1657. elif i == 'help' or i == 'h' or i == '?':
  1658. Help()
  1659.  
  1660. pysnmp
  1661.  
  1662. #!/usr/bin/python
  1663. from pysnmp.entity.rfc3413.oneliner import cmdgen
  1664.  
  1665. cg = cmdgen.CommandGenerator()
  1666.  
  1667. # 注意IP 端口 组默认public oid值
  1668. varBinds = cg.getCmd( cmdgen.CommunityData('any-agent', 'public',0 ), cmdgen.UdpTransportTarget(('10.10.76.42', 161)), (1,3,6,1,4,1,2021,10,1,3,1), )
  1669.  
  1670. print varBinds[3][0][1]
  1671.  
  1672. 3 socket
  1673.  
  1674. socket.gethostname() # 获取主机名
  1675. from socket import * # 避免 socket.socket()
  1676. s=socket()
  1677. s.bind() # 绑定地址到套接字
  1678. s.listen() # 开始TCP监听
  1679. s.accept() # 被动接受TCP客户端连接,等待连接的到来
  1680. s.connect() # 主动初始化TCP服务器连接
  1681. s.connect_ex() # connect()函数的扩展版本,出错时返回出错码,而不是跑出异常
  1682. s.recv() # 接收TCP数据
  1683. s.send() # 发送TCP数据
  1684. s.sendall() # 完整发送TCP数据
  1685. s.recvfrom() # 接收UDP数据
  1686. s.sendto() # 发送UDP数据
  1687. s.getpeername() # 连接到当前套接字的远端的地址(TCP连接)
  1688. s.getsockname() # 当前套接字的地址
  1689. s.getsockopt() # 返回指定套接字的参数
  1690. s.setsockopt() # 设置指定套接字的参数
  1691. s.close() # 关闭套接字
  1692. s.setblocking() # 设置套接字的阻塞与非阻塞模式
  1693. s.settimeout() # 设置阻塞套接字操作的超时时间
  1694. s.gettimeout() # 得到阻塞套接字操作的超时时间
  1695. s.filen0() # 套接字的文件描述符
  1696. s.makefile() # 创建一个与该套接字关联的文件对象
  1697.  
  1698. socket.AF_UNIX # 只能够用于单一的Unix系统进程间通信
  1699. socket.AF_INET # 服务器之间网络通信
  1700. socket.AF_INET6 # IPv6
  1701.  
  1702. socket.SOCK_STREAM # 流式socket , for TCP
  1703. socket.SOCK_DGRAM # 数据报式socket , for UDP
  1704. socket.SOCK_RAW # 原始套接字,普通的套接字无法处理ICMP、IGMP等网络报文,而SOCK_RAW可以;其次,SOCK_RAW也可以处理特殊的IPv4报文;此外,利用原始套接字,可以通过IP_HDRINCL套接字选项由用户构造IP头。
  1705.  
  1706. socket.SOCK_RDM # 是一种可靠的UDP形式,即保证交付数据报但不保证顺序。SOCK_RAM用来提供对原始协议的低级访问,在需要执行某些特殊操作时使用,如发送ICMP报文。SOCK_RAM通常仅限于高级用户或管理员运行的程序使用。
  1707.  
  1708. socket.SOCK_SEQPACKET # 可靠的连续数据包服务
  1709.  
  1710. SocketServer
  1711.  
  1712. #!/usr/bin/python
  1713. #server.py
  1714. import SocketServer
  1715. import os
  1716. class MyTCP(SocketServer.BaseRequestHandler):
  1717. def handle(self):
  1718. while True:
  1719. self.data=self.request.recv(1024).strip()
  1720. if self.data == 'quit' or not self.data:break
  1721.  
  1722. cmd=os.popen(self.data).read()
  1723. if cmd == '':cmd= self.data + ': Command not found'
  1724. self.request.sendall(cmd)
  1725. if __name__ == '__main__':
  1726. HOST,PORT = '10.0.0.119',50007
  1727. server = SocketServer.ThreadingTCPServer((HOST,PORT),MyTCP)
  1728. server.serve_forever()
  1729.  
  1730. SocketClient
  1731.  
  1732. #!/usr/bin/python
  1733. #client.py
  1734. import socket
  1735.  
  1736. HOST='10.0.0.119'
  1737. PORT=50007
  1738. s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  1739. s.connect((HOST,PORT))
  1740.  
  1741. while True:
  1742. while True:
  1743. cmd=raw_input('CMD:').strip()
  1744. if cmd != '':break
  1745. s.sendall(cmd)
  1746. data=s.recv(1024).split('\n')
  1747. print 'cmd:'
  1748. for line in data:print line
  1749. s.close()
  1750.  
  1751. ftp
  1752.  
  1753. ftpserver
  1754.  
  1755. #!/usr/bin/python
  1756. #ftpserver.py
  1757.  
  1758. import SocketServer
  1759. import os
  1760. import cPickle
  1761. import md5
  1762. from time import sleep
  1763.  
  1764. def filer(file1):
  1765. try:
  1766. f = file(file1,'rb')
  1767. return cPickle.load(f)
  1768. except IOError:
  1769. return {}
  1770. except EOFError:
  1771. return {}
  1772. f.close()
  1773.  
  1774. def filew(file1,content):
  1775. f = file(file1,'wb')
  1776. cPickle.dump(content,f)
  1777. f.close()
  1778.  
  1779. class MyTCP(SocketServer.BaseRequestHandler):
  1780. def handle(self):
  1781. i = 0
  1782. while i<3:
  1783. user=self.request.recv(1024).strip()
  1784. userinfo=filer('user.pkl')
  1785. if userinfo.has_key(user.split()[0]):
  1786. if md5.new(user.split()[1]).hexdigest() == userinfo[user.split()[0]]:
  1787. results='login successful'
  1788. self.request.sendall(results)
  1789. login='successful'
  1790. break
  1791. else:
  1792. i = i + 1
  1793. results='Error:password not correct'
  1794. self.request.sendall(results)
  1795. continue
  1796. else:
  1797. i = i + 1
  1798. results='Error:password not correct'
  1799. self.request.sendall(results)
  1800. continue
  1801. break
  1802. else:
  1803. results = 'Error:Wrong password too many times'
  1804. self.request.sendall(results)
  1805. login='failure'
  1806. home_path = os.popen('pwd').read().strip() + '/' + user.split()[0]
  1807. current_path = '/'
  1808. print home_path
  1809. while True:
  1810. if login == 'failure':
  1811. break
  1812. print 'home_path:%s=current_path:%s' %(home_path,current_path)
  1813. cmd=self.request.recv(1024).strip()
  1814. print cmd
  1815. if cmd == 'quit':
  1816. break
  1817. elif cmd == 'dir':
  1818. list=os.listdir('%s%s' %(home_path,current_path))
  1819. if list:
  1820. dirlist,filelist = '',''
  1821. for i in list:
  1822. if os.path.isdir('%s%s%s' %(home_path,current_path,i)):
  1823. dirlist = dirlist + '\033[32m' + i + '\033[m\t'
  1824. else:
  1825. filelist = filelist + i + '\t'
  1826. results = dirlist + filelist
  1827. else:
  1828. results = '\033[31mnot find\033[m'
  1829. self.request.sendall(results)
  1830. elif cmd == 'pdir':
  1831. self.request.sendall(current_path)
  1832. elif cmd.split()[0] == 'mdir':
  1833. if cmd.split()[1].isalnum():
  1834. tmppath='%s%s%s' %(home_path,current_path,cmd.split()[1])
  1835. os.makedirs(tmppath)
  1836. self.request.sendall('\033[32mcreating successful\033[m')
  1837. else:
  1838. self.request.sendall('\033[31mcreate failure\033[m')
  1839. elif cmd.split()[0] == 'cdir':
  1840. if cmd.split()[1] == '/':
  1841. tmppath='%s%s' %(home_path,cmd.split()[1])
  1842. if os.path.isdir(tmppath):
  1843. current_path = cmd.split()[1]
  1844. self.request.sendall(current_path)
  1845. else:
  1846. self.request.sendall('\033[31mnot_directory\033[m')
  1847. elif cmd.split()[1].startswith('/'):
  1848. tmppath='%s%s' %(home_path,cmd.split()[1])
  1849. if os.path.isdir(tmppath):
  1850. current_path = cmd.split()[1] + '/'
  1851. self.request.sendall(current_path)
  1852. else:
  1853. self.request.sendall('\033[31mnot_directory\033[m')
  1854. else:
  1855. tmppath='%s%s%s' %(home_path,current_path,cmd.split()[1])
  1856. if os.path.isdir(tmppath):
  1857. current_path = current_path + cmd.split()[1] + '/'
  1858. self.request.sendall(current_path)
  1859. else:
  1860. self.request.sendall('\033[31mnot_directory\033[m')
  1861. elif cmd.split()[0] == 'get':
  1862. if os.path.isfile('%s%s%s' %(home_path,current_path,cmd.split()[1])):
  1863. f = file('%s%s%s' %(home_path,current_path,cmd.split()[1]),'rb')
  1864. self.request.sendall('ready_file')
  1865. sleep(0.5)
  1866. self.request.send(f.read())
  1867. f.close()
  1868. sleep(0.5)
  1869. elif os.path.isdir('%s%s%s' %(home_path,current_path,cmd.split()[1])):
  1870. self.request.sendall('ready_dir')
  1871. sleep(0.5)
  1872. for dirpath in os.walk('%s%s%s' %(home_path,current_path,cmd.split()[1])):
  1873. dir=dirpath[0].replace('%s%s' %(home_path,current_path),'',1)
  1874. self.request.sendall(dir)
  1875. sleep(0.5)
  1876. for filename in dirpath[2]:
  1877. self.request.sendall(filename)
  1878. sleep(0.5)
  1879. f = file('%s/%s' %(dirpath[0],filename),'rb')
  1880. self.request.send(f.read())
  1881. f.close()
  1882. sleep(0.5)
  1883. self.request.sendall('file_get_done')
  1884. sleep(0.5)
  1885. else:
  1886. self.request.sendall('dir_get_done')
  1887. sleep(0.5)
  1888. else:
  1889. self.request.sendall('get_failure')
  1890. continue
  1891. self.request.sendall('get_done')
  1892.  
  1893. elif cmd.split()[0] == 'send':
  1894. if os.path.exists('%s%s%s' %(home_path,current_path,cmd.split()[1])):
  1895. self.request.sendall('existing')
  1896. action=self.request.recv(1024)
  1897. if action == 'cancel':
  1898. continue
  1899. self.request.sendall('ready')
  1900. msg=self.request.recv(1024)
  1901. if msg == 'ready_file':
  1902. f = file('%s%s%s' %(home_path,current_path,cmd.split()[1]),'wb')
  1903. while True:
  1904. data=self.request.recv(1024)
  1905. if data == 'file_send_done':break
  1906. f.write(data)
  1907. f.close()
  1908.  
  1909. elif msg == 'ready_dir':
  1910. os.system('mkdir -p %s%s%s' %(home_path,current_path,cmd.split()[1]))
  1911. while True:
  1912. dir=self.request.recv(1024)
  1913. if dir == 'get_done':break
  1914. os.system('mkdir -p %s%s%s' %(home_path,current_path,dir))
  1915. while True:
  1916. filename=self.request.recv(1024)
  1917. if filename == 'dir_send_done':break
  1918. f = file('%s%s%s/%s' %(home_path,current_path,dir,filename),'wb')
  1919. while True:
  1920. data=self.request.recv(1024)
  1921. if data == 'file_send_done':break
  1922. f.write(data)
  1923. f.close()
  1924. self.request.sendall('%s/%s\t\033[32mfile_done\033[m' %(dir,filename))
  1925. self.request.sendall('%s\t\033[32mdir_done\033[m' %(dir))
  1926. elif msg == 'unknown_file':
  1927. continue
  1928.  
  1929. else:
  1930. results = cmd.split()[0] + ': Command not found'
  1931. self.request.sendall(results)
  1932.  
  1933. if __name__ == '__main__':
  1934. HOST,PORT = '10.152.14.85',50007
  1935. server = SocketServer.ThreadingTCPServer((HOST,PORT),MyTCP)
  1936. server.serve_forever()
  1937.  
  1938. ftpmanage
  1939.  
  1940. #!/usr/bin/python
  1941. #manage_ftp.py
  1942. import cPickle
  1943. import sys
  1944. import md5
  1945. import os
  1946. import getpass
  1947.  
  1948. def filer(file1):
  1949. try:
  1950. f = file(file1,'rb')
  1951. return cPickle.load(f)
  1952. except IOError:
  1953. return {}
  1954. except EOFError:
  1955. return {}
  1956. f.close()
  1957.  
  1958. def filew(file1,content):
  1959. f = file(file1,'wb')
  1960. cPickle.dump(content,f)
  1961. f.close()
  1962.  
  1963. while True:
  1964. print '''
  1965. 1.add user
  1966. 2.del user
  1967. 3.change password
  1968. 4.query user
  1969. 0.exit
  1970. '''
  1971. i = raw_input(':').strip()
  1972. userinfo=filer('user.pkl')
  1973. if i == '':
  1974. continue
  1975. elif i == '1':
  1976. while True:
  1977. user=raw_input('user name:').strip()
  1978. if user.isalnum():
  1979. i = 0
  1980. while i<3:
  1981. passwd=getpass.getpass('passwd:').strip()
  1982. if passwd == '':
  1983. continue
  1984. else:
  1985. passwd1=getpass.getpass('Confirm password:').strip()
  1986. if passwd == passwd1:
  1987. mpasswd = md5.new(passwd).hexdigest()
  1988. userinfo[user] = mpasswd
  1989. os.system('mkdir -p %s' %user)
  1990. print '%s creating successful ' %user
  1991. break
  1992. else:
  1993. print "Passwords don't match "
  1994. i = i + 1
  1995. continue
  1996. else:
  1997. print 'Too many wrong'
  1998. continue
  1999. break
  2000. else:
  2001. print 'user not legal'
  2002. continue
  2003. elif i == '2':
  2004. user=raw_input('user name:').strip()
  2005. if userinfo.has_key(user):
  2006. del userinfo[user]
  2007. print 'Delete users successfully'
  2008. else:
  2009. print 'user not exist'
  2010. continue
  2011. elif i == '3':
  2012. user=raw_input('user name:').strip()
  2013. if userinfo.has_key(user):
  2014. i = 0
  2015. while i<3:
  2016. passwd=getpass.getpass('passwd:').strip()
  2017. if passwd == '':
  2018. continue
  2019. else:
  2020. passwd1=getpass.getpass('Confirm password:').strip()
  2021. if passwd == passwd1:
  2022. mpasswd = md5.new(passwd).hexdigest()
  2023. userinfo[user] = mpasswd
  2024. print '%s password is changed' %user
  2025. break
  2026. else:
  2027. print "Passwords don't match "
  2028. i = i + 1
  2029. continue
  2030. else:
  2031. print 'Too many wrong'
  2032. continue
  2033. else:
  2034. print 'user not exist'
  2035. continue
  2036. elif i == '4':
  2037. print userinfo.keys()
  2038. elif i == '0':
  2039. sys.exit()
  2040. else:
  2041. print 'select error'
  2042. continue
  2043. filew('user.pkl',content=userinfo)
  2044.  
  2045. ftpclient
  2046.  
  2047. #!/usr/bin/python
  2048. #ftpclient.py
  2049.  
  2050. import socket
  2051. import os
  2052. import getpass
  2053. from time import sleep
  2054.  
  2055. HOST='10.152.14.85'
  2056. PORT=50007
  2057. s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  2058. s.connect((HOST,PORT))
  2059.  
  2060. while True:
  2061. user = raw_input('user:').strip()
  2062. if user.isalnum():
  2063. while True:
  2064. passwd = getpass.getpass('passwd:').strip()
  2065. s.sendall(user + ' ' + passwd)
  2066. servercmd=s.recv(1024)
  2067. if servercmd == 'login successful':
  2068. print '\033[32m%s\033[m' %servercmd
  2069. break
  2070. else:
  2071. print servercmd
  2072.  
  2073. while True:
  2074. cmd=raw_input('FTP>').strip()
  2075. if cmd == '':
  2076. continue
  2077. if cmd.split()[0] == 'get':
  2078. if cmd == 'get':continue
  2079. for i in cmd.split()[1:]:
  2080. if os.path.exists(i):
  2081. confirm = raw_input("\033[31mPlease confirm whether the cover %s(Y/N):\033[m" %(i)).upper().startswith('Y')
  2082. if not confirm:
  2083. print '%s cancel' %i
  2084. continue
  2085. s.sendall('get ' + i)
  2086. servercmd=s.recv(1024)
  2087. if servercmd == 'inexistence':
  2088. print '%s \t\033[32minexistence\033[m' %i
  2089. continue
  2090. elif servercmd == 'ready_file':
  2091. f = file(i,'wb')
  2092. while True:
  2093. data=s.recv(1024)
  2094. if data == 'get_done':break
  2095. f.write(data)
  2096. f.close()
  2097. print '%s \t\033[32mfile_done\033[m' %(i)
  2098. elif servercmd == 'ready_dir':
  2099. try:
  2100. os.makedirs(i)
  2101. except:
  2102. pass
  2103. while True:
  2104. serverdir=s.recv(1024)
  2105. if serverdir == 'get_done':break
  2106. os.system('mkdir -p %s' %serverdir)
  2107. print '%s \t\033[32mdir_done\033[m' %(serverdir)
  2108. while True:
  2109. serverfile=s.recv(1024)
  2110. if serverfile == 'dir_get_done':break
  2111. f = file('%s/%s' %(serverdir,serverfile),'wb')
  2112. while True:
  2113. data=s.recv(1024)
  2114. if data == 'file_get_done':break
  2115. f.write(data)
  2116. f.close()
  2117. print '%s/%s \t\033[32mfile_done\033[m' %(serverdir,serverfile)
  2118.  
  2119. elif cmd.split()[0] == 'send':
  2120.  
  2121. if cmd == 'send':continue
  2122. for i in cmd.split()[1:]:
  2123. if not os.path.exists(i):
  2124. print '%s\t\033[31minexistence\033[m' %i
  2125. continue
  2126.  
  2127. s.sendall('send ' + i)
  2128. servercmd=s.recv(1024)
  2129. if servercmd == 'existing':
  2130. confirm = raw_input("\033[31mPlease confirm whether the cover %s(Y/N):\033[m" %(i)).upper().startswith('Y')
  2131. if confirm:
  2132. s.sendall('cover')
  2133. servercmd=s.recv(1024)
  2134. else:
  2135. s.sendall('cancel')
  2136. print '%s\tcancel' %i
  2137. continue
  2138.  
  2139. if os.path.isfile(i):
  2140. s.sendall('ready_file')
  2141. sleep(0.5)
  2142. f = file(i,'rb')
  2143. s.send(f.read())
  2144. sleep(0.5)
  2145. s.sendall('file_send_done')
  2146. print '%s\t\033[32mfile done\033[m' %(cmd.split()[1])
  2147. f.close()
  2148. elif os.path.isdir(i):
  2149. s.sendall('ready_dir')
  2150. sleep(0.5)
  2151. for dirpath in os.walk(i):
  2152. dir=dirpath[0].replace('%s/' %os.popen('pwd').read().strip(),'',1)
  2153. s.sendall(dir)
  2154. sleep(0.5)
  2155. for filename in dirpath[2]:
  2156. s.sendall(filename)
  2157. sleep(0.5)
  2158. f = file('%s/%s' %(dirpath[0],filename),'rb')
  2159. s.send(f.read())
  2160. f.close()
  2161. sleep(0.5)
  2162. s.sendall('file_send_done')
  2163. msg=s.recv(1024)
  2164. print msg
  2165.  
  2166. else:
  2167. s.sendall('dir_send_done')
  2168. msg=s.recv(1024)
  2169. print msg
  2170.  
  2171. else:
  2172. s.sendall('unknown_file')
  2173. print '%s\t\033[31munknown type\033[m' %i
  2174. continue
  2175. sleep(0.5)
  2176. s.sendall('get_done')
  2177.  
  2178. elif cmd.split()[0] == 'cdir':
  2179. if cmd == 'cdir':continue
  2180. s.sendall(cmd)
  2181. data=s.recv(1024)
  2182. print data
  2183. continue
  2184. elif cmd == 'ls':
  2185. list=os.popen(cmd).read().strip().split('\n')
  2186. if list:
  2187. dirlist,filelist = '',''
  2188. for i in list:
  2189. if os.path.isdir(i):
  2190. dirlist = dirlist + '\033[32m' + i + '\033[m\t'
  2191. else:
  2192. filelist = filelist + i + '\t'
  2193. results = dirlist + filelist
  2194. else:
  2195. results = '\033[31mnot find\033[m'
  2196. print results
  2197. continue
  2198. elif cmd == 'pwd':
  2199. os.system(cmd)
  2200. elif cmd.split()[0] == 'cd':
  2201. try:
  2202. os.chdir(cmd.split()[1])
  2203. except:
  2204. print '\033[31mcd failure\033[m'
  2205. elif cmd == 'dir':
  2206. s.sendall(cmd)
  2207. data=s.recv(1024)
  2208. print data
  2209. continue
  2210. elif cmd == 'pdir':
  2211. s.sendall(cmd)
  2212. data=s.recv(1024)
  2213. print data
  2214. continue
  2215. elif cmd.split()[0] == 'mdir':
  2216. if cmd == 'mdir':continue
  2217. s.sendall(cmd)
  2218. data=s.recv(1024)
  2219. print data
  2220. continue
  2221. elif cmd.split()[0] == 'help':
  2222. print '''
  2223. get [file] [dir]
  2224. send [file] [dir]
  2225.  
  2226. dir
  2227. mdir
  2228. cdir
  2229. pdir
  2230.  
  2231. pwd
  2232. md
  2233. cd
  2234. ls
  2235.  
  2236. help
  2237. quit
  2238. '''
  2239. continue
  2240. elif cmd == 'quit':
  2241. break
  2242. else:
  2243. print '\033[31m%s: Command not found,Please see the "help"\033[m' %cmd
  2244. else:
  2245. continue
  2246. break
  2247. s.close()
  2248.  
  2249. 扫描主机开放端口
  2250. #!/usr/bin/env python
  2251.  
  2252. import socket
  2253.  
  2254. def check_server(address,port):
  2255. s=socket.socket()
  2256. try:
  2257. s.connect((address,port))
  2258. return True
  2259. except socket.error,e:
  2260. return False
  2261.  
  2262. if __name__=='__main__':
  2263. from optparse import OptionParser
  2264. parser=OptionParser()
  2265. parser.add_option("-a","--address",dest="address",default='localhost',help="Address for server",metavar="ADDRESS")
  2266. parser.add_option("-s","--start",dest="start_port",type="int",default=1,help="start port",metavar="SPORT")
  2267. parser.add_option("-e","--end",dest="end_port",type="int",default=1,help="end port",metavar="EPORT")
  2268. (options,args)=parser.parse_args()
  2269. print 'options: %s, args: %s' % (options, args)
  2270. port=options.start_port
  2271. while(port<=options.end_port):
  2272. check = check_server(options.address, port)
  2273. if (check):
  2274. print 'Port %s is on' % port
  2275. port=port+1
  2276.  
  2277. 4 mysql
  2278.  
  2279. #apt-get install mysql-server
  2280. #apt-get install python-MySQLdb
  2281. help(MySQLdb.connections.Connection) # 查看链接参数
  2282.  
  2283. conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',db='fortress',port=3306) # 定义连接
  2284. #conn=MySQLdb.connect(unix_socket='/var/run/mysqld/mysqld.sock',user='root',passwd='123456') # 使用socket文件链接
  2285. cur=conn.cursor() # 定义游标
  2286. conn.select_db('fortress') # 选择数据库
  2287. sqlcmd = 'insert into user(name,age) value(%s,%s)' # 定义sql命令
  2288. cur.executemany(sqlcmd,[('aa',1),('bb',2),('cc',3)]) # 插入多条值
  2289. cur.execute('delete from user where id=20') # 删除一条记录
  2290. cur.execute("update user set name='a' where id=20") # 更细数据
  2291. sqlresult = cur.fetchall() # 接收全部返回结果
  2292. conn.commit() # 提交
  2293. cur.close() # 关闭游标
  2294. conn.close() # 关闭连接
  2295.  
  2296. import MySQLdb
  2297. def mydb(dbcmdlist):
  2298. try:
  2299. conn=MySQLdb.connect(host='localhost',user='root',passwd='123456',db='fortress',port=3306)
  2300. cur=conn.cursor()
  2301.  
  2302. cur.execute('create database if not exists fortress;') # 创建数据库
  2303. conn.select_db('fortress') # 选择数据库
  2304. cur.execute('drop table if exists log;') # 删除表
  2305. cur.execute('CREATE TABLE log ( id BIGINT(20) NOT NULL AUTO_INCREMENT, loginuser VARCHAR(50) DEFAULT NULL, remoteip VARCHAR(50) DEFAULT NULL, PRIMARY KEY (id) );') # 创建表
  2306.  
  2307. result=[]
  2308. for dbcmd in dbcmdlist:
  2309. cur.execute(dbcmd) # 执行sql
  2310. sqlresult = cur.fetchall() # 接收全部返回结果
  2311. result.append(sqlresult)
  2312. conn.commit() # 提交
  2313. cur.close()
  2314. conn.close()
  2315. return result
  2316. except MySQLdb.Error,e:
  2317. print 'mysql error msg: ',e
  2318. sqlcmd=[]
  2319. sqlcmd.append("insert into log (loginuser,remoteip)values('%s','%s');" %(loginuser,remoteip))
  2320. mydb(sqlcmd)
  2321.  
  2322. sqlcmd=[]
  2323. sqlcmd.append("select * from log;")
  2324. result = mydb(sqlcmd)
  2325. for i in result[0]:
  2326. print i
  2327.  
  2328. 5 处理信号
  2329.  
  2330. 信号的概念
  2331.  
  2332. 信号(signal): 进程之间通讯的方式,是一种软件中断。一个进程一旦接收到信号就会打断原来的程序执行流程来处理信号。
  2333. 发送信号一般有两种原因:
  2334. 1(被动式) 内核检测到一个系统事件.例如子进程退出会像父进程发送SIGCHLD信号.键盘按下control+c会发送SIGINT信号
  2335. 2(主动式) 通过系统调用kill来向指定进程发送信号
  2336. 操作系统规定了进程收到信号以后的默认行为,可以通过绑定信号处理函数来修改进程收到信号以后的行为,有两个信号是不可更改的 SIGTOP SIGKILL
  2337. 如果一个进程收到一个SIGUSR1信号,然后执行信号绑定函数,第二个SIGUSR2信号又来了,第一个信号没有被处理完毕的话,第二个信号就会丢弃。
  2338. 进程结束信号 SIGTERM SIGKILL 的区别: SIGTERM 比较友好,进程能捕捉这个信号,根据您的需要来关闭程序。在关闭程序之前,您可以结束打开的记录文件和完成正在做的任务。在某些情况下,假如进程正在进行作业而且不能中断,那么进程可以忽略这个SIGTERM信号。
  2339.  
  2340. 常见信号
  2341. kill -l # 查看linux提供的信号
  2342.  
  2343. SIGHUP 1 A # 终端挂起或者控制进程终止
  2344. SIGINT 2 A # 键盘终端进程(如control+c)
  2345. SIGQUIT 3 C # 键盘的退出键被按下
  2346. SIGILL 4 C # 非法指令
  2347. SIGABRT 6 C # 由abort(3)发出的退出指令
  2348. SIGFPE 8 C # 浮点异常
  2349. SIGKILL 9 AEF # Kill信号 立刻停止
  2350. SIGSEGV 11 C # 无效的内存引用
  2351. SIGPIPE 13 A # 管道破裂: 写一个没有读端口的管道
  2352. SIGALRM 14 A # 闹钟信号 由alarm(2)发出的信号
  2353. SIGTERM 15 A # 终止信号,可让程序安全退出 kill -15
  2354. SIGUSR1 30,10,16 A # 用户自定义信号1
  2355. SIGUSR2 31,12,17 A # 用户自定义信号2
  2356. SIGCHLD 20,17,18 B # 子进程结束自动向父进程发送SIGCHLD信号
  2357. SIGCONT 19,18,25 # 进程继续(曾被停止的进程)
  2358. SIGSTOP 17,19,23 DEF # 终止进程
  2359. SIGTSTP 18,20,24 D # 控制终端(tty)上按下停止键
  2360. SIGTTIN 21,21,26 D # 后台进程企图从控制终端读
  2361. SIGTTOU 22,22,27 D # 后台进程企图从控制终端写
  2362.  
  2363. 缺省处理动作一项中的字母含义如下:
  2364. A 缺省的动作是终止进程
  2365. B 缺省的动作是忽略此信号,将该信号丢弃,不做处理
  2366. C 缺省的动作是终止进程并进行内核映像转储(dump core),内核映像转储是指将进程数据在内存的映像和进程在内核结构中的部分内容以一定格式转储到文件系统,并且进程退出执行,这样做的好处是为程序员提供了方便,使得他们可以得到进程当时执行时的数据值,允许他们确定转储的原因,并且可以调试他们的程序。
  2367. D 缺省的动作是停止进程,进入停止状况以后还能重新进行下去,一般是在调试的过程中(例如ptrace系统调用)
  2368. E 信号不能被捕获
  2369. F 信号不能被忽略
  2370.  
  2371. Python提供的信号
  2372. import signal
  2373. dir(signal)
  2374. ['NSIG', 'SIGABRT', 'SIGALRM', 'SIGBUS', 'SIGCHLD', 'SIGCLD', 'SIGCONT', 'SIGFPE', 'SIGHUP', 'SIGILL', 'SIGINT', 'SIGIO', 'SIGIOT', 'SIGKILL', 'SIGPIPE', 'SIGPOLL', 'SIGPROF', 'SIGPWR', 'SIGQUIT', 'SIGRTMAX', 'SIGRTMIN', 'SIGSEGV', 'SIGSTOP', 'SIGSYS', 'SIGTERM', 'SIGTRAP', 'SIGTSTP', 'SIGTTIN', 'SIGTTOU', 'SIGURG', 'SIGUSR1', 'SIGUSR2', 'SIGVTALRM', 'SIGWINCH', 'SIGXCPU', 'SIGXFSZ', 'SIG_DFL', 'SIG_IGN', '__doc__', '__name__', 'alarm', 'default_int_handler', 'getsignal', 'pause', 'signal']
  2375.  
  2376. 绑定信号处理函数
  2377. #encoding:utf8
  2378. import os,signal
  2379. from time import sleep
  2380. def onsignal_term(a,b):
  2381. print 'SIGTERM' # kill -15
  2382. signal.signal(signal.SIGTERM,onsignal_term) # 接收信号,执行相应函数
  2383.  
  2384. def onsignal_usr1(a,b):
  2385. print 'SIGUSR1' # kill -10
  2386. signal.signal(signal.SIGUSR1,onsignal_usr1)
  2387.  
  2388. while 1:
  2389. print 'ID',os.getpid()
  2390. sleep(10)
  2391.  
  2392. 通过另外一个进程发送信号
  2393. import os,signal
  2394. os.kill(16175,signal.SIGTERM) # 发送信号,16175是绑定信号处理函数的进程pid,需要自行修改
  2395. os.kill(16175,signal.SIGUSR1)
  2396.  
  2397. 父进程接收子进程结束发送的SIGCHLD信号
  2398. #encoding:utf8
  2399. import os,signal
  2400. from time import sleep
  2401.  
  2402. def onsigchld(a,b):
  2403. print '收到子进程结束信号'
  2404. signal.signal(signal.SIGCHLD,onsigchld)
  2405.  
  2406. pid = os.fork() # 创建一个子进程,复制父进程所有资源操作
  2407. if pid == 0: # 通过判断子进程os.fork()是否等于0,分别同时执行父进程与子进程操作
  2408. print '我是子进程,pid是',os.getpid()
  2409. sleep(2)
  2410. else:
  2411. print '我是父进程,pid是',os.getpid()
  2412. os.wait() # 等待子进程结束
  2413.  
  2414. 接收信号的程序,另外一端使用多线程向这个进程发送信号,会遗漏一些信号
  2415. #encoding:utf8
  2416. import os
  2417. import signal
  2418. from time import sleep
  2419. import Queue
  2420. QCOUNT = Queue.Queue() # 初始化队列
  2421. def onsigchld(a,b):
  2422. '''收到信号后向队列中插入一个数字1'''
  2423. print '收到SIGUSR1信号'
  2424. sleep(1)
  2425. QCOUNT.put(1) # 向队列中写入
  2426. signal.signal(signal.SIGUSR1,onsigchld) # 绑定信号处理函数
  2427. while 1:
  2428. print '我的pid是',os.getpid()
  2429. print '现在队列中元素的个数是',QCOUNT.qsize()
  2430. sleep(2)
  2431.  
  2432. 多线程发信号端的程序
  2433.  
  2434. #encoding:utf8
  2435. import threading
  2436. import os
  2437. import signal
  2438. def sendusr1():
  2439. print '发送信号'
  2440. os.kill(17788, signal.SIGUSR1) # 这里的进程id需要写前一个程序实际运行的pid
  2441. WORKER = []
  2442. for i in range(1, 7): # 开启6个线程
  2443. threadinstance = threading.Thread(target = sendusr1)
  2444. WORKER.append(threadinstance)
  2445. for i in WORKER:
  2446. i.start()
  2447. for i in WORKER:
  2448. i.join()
  2449. print '主线程完成'
  2450.  
  2451. 6 缓存数据库
  2452.  
  2453. python使用memcache
  2454.  
  2455. easy_install python-memcached # 安装(python2.7+)
  2456. import memcache
  2457. mc = memcache.Client(['10.152.14.85:12000'],debug=True)
  2458. mc.set('name','luo',60)
  2459. mc.get('name')
  2460. mc.delete('name1')
  2461.  
  2462. 保存数据
  2463.  
  2464. set(key,value,timeout) # 把key映射到value,timeout指的是什么时候这个映射失效
  2465. add(key,value,timeout) # 仅当存储空间中不存在键相同的数据时才保存
  2466. replace(key,value,timeout) # 仅当存储空间中存在键相同的数据时才保存
  2467.  
  2468. 获取数据
  2469.  
  2470. get(key) # 返回key所指向的value
  2471. get_multi(key1,key2,key3) # 可以非同步地同时取得多个键值, 比循环调用get快数十倍
  2472.  
  2473. python使用mongodb
  2474.  
  2475. 原文: http://blog.nosqlfan.com/html/2989.html
  2476.  
  2477. easy_install pymongo # 安装(python2.7+)
  2478. import pymongo
  2479. connection=pymongo.Connection('localhost',27017) # 创建连接
  2480. db = connection.test_database # 切换数据库
  2481. collection = db.test_collection # 获取collection
  2482. # db和collection都是延时创建的,在添加Document时才真正创建
  2483.  
  2484. 文档添加, _id自动创建
  2485. import datetime
  2486. post = {"author": "Mike",
  2487. "text": "My first blog post!",
  2488. "tags": ["mongodb", "python", "pymongo"],
  2489. "date": datetime.datetime.utcnow()}
  2490. posts = db.posts
  2491. posts.insert(post)
  2492. ObjectId('...')
  2493.  
  2494. 批量插入
  2495. new_posts = [{"author": "Mike",
  2496. "text": "Another post!",
  2497. "tags": ["bulk", "insert"],
  2498. "date": datetime.datetime(2009, 11, 12, 11, 14)},
  2499. {"author": "Eliot",
  2500. "title": "MongoDB is fun",
  2501. "text": "and pretty easy too!",
  2502. "date": datetime.datetime(2009, 11, 10, 10, 45)}]
  2503. posts.insert(new_posts)
  2504. [ObjectId('...'), ObjectId('...')]
  2505.  
  2506. 获取所有collection
  2507. db.collection_names() # 相当于SQL的show tables
  2508.  
  2509. 获取单个文档
  2510. posts.find_one()
  2511.  
  2512. 查询多个文档
  2513. for post in posts.find():
  2514. post
  2515.  
  2516. 加条件的查询
  2517. posts.find_one({"author": "Mike"})
  2518.  
  2519. 高级查询
  2520. posts.find({"date": {"$lt": "d"}}).sort("author")
  2521.  
  2522. 统计数量
  2523. posts.count()
  2524.  
  2525. 加索引
  2526. from pymongo import ASCENDING, DESCENDING
  2527. posts.create_index([("date", DESCENDING), ("author", ASCENDING)])
  2528.  
  2529. 查看查询语句的性能
  2530. posts.find({"date": {"$lt": "d"}}).sort("author").explain()["cursor"]
  2531. posts.find({"date": {"$lt": "d"}}).sort("author").explain()["nscanned"]
  2532.  
  2533. python使用redis
  2534.  
  2535. https://pypi.python.org/pypi/redis
  2536. pip install redis OR easy_install redis
  2537. import redis
  2538. r = redis.StrictRedis(host='localhost', port=6379, db=0)
  2539. r.set('foo', 'bar')
  2540. r.get('foo')
  2541. r.save()
  2542.  
  2543. 分片 # 没搞懂
  2544. redis.connection.Connection(host='localhost', port=6379, db=0, parser_class=<class 'redis.connection.PythonParser'>)
  2545. redis.ConnectionPool( connection_class=<class 'redis.connection.Connection'>, max_connections=None, **connection_kwargs)
  2546.  
  2547. python使用kestrel队列
  2548.  
  2549. # pykestrel
  2550. import kestrel
  2551.  
  2552. q = kestrel.Client(servers=['127.0.0.1:22133'],queue='test_queue')
  2553. q.add('some test job')
  2554. job = q.get() # 从队列读取工作
  2555. job = q.peek() # 读取下一份工作
  2556. # 读取一组工作
  2557. while True:
  2558. job = q.next(timeout=10) # 完成工作并获取下一个工作,如果没有工作,则等待10秒
  2559. if job is not None:
  2560. try:
  2561. # 流程工作
  2562. except:
  2563. q.abort() # 标记失败工作
  2564.  
  2565. q.finish() # 完成最后工作
  2566. q.close() # 关闭连接
  2567.  
  2568. kestrel状态检查
  2569. # kestrel支持memcache协议客户端
  2570. #!/usr/local/bin/python
  2571. # 10.13.81.125 22133 10000
  2572.  
  2573. import memcache
  2574. import sys
  2575. import traceback
  2576.  
  2577. ip="%s:%s" % (sys.argv[1],sys.argv[2])
  2578. try:
  2579. mc = memcache.Client([ip,])
  2580. st=mc.get_stats()
  2581. except:
  2582. print "kestrel connection exception"
  2583. sys.exit(2)
  2584.  
  2585. if st:
  2586. for s in st[0][1].keys():
  2587. if s.startswith('queue_') and s.endswith('_mem_items'):
  2588. num = int(st[0][1][s])
  2589. if num > int(sys.argv[3]):
  2590. print "%s block to %s" %(s[6:-6],num)
  2591. sys.exit(2)
  2592. print "kestrel ok!"
  2593. sys.exit(0)
  2594. else:
  2595. print "kestrel down"
  2596. sys.exit(2)
  2597.  
  2598. python使用tarantool
  2599.  
  2600. # pip install tarantool-queue
  2601.  
  2602. from tarantool_queue import Queue
  2603. queue = Queue("localhost", 33013, 0) # 连接读写端口 空间0
  2604. tube = queue.tube("name_of_tube") #
  2605. tube.put([1, 2, 3])
  2606.  
  2607. task = tube.take()
  2608. task.data # take task and read data from it
  2609. task.ack() # move this task into state DONE
  2610.  
  2611. 7 web页面操作
  2612.  
  2613. urllib2 [网络资源访问]
  2614.  
  2615. import urllib2
  2616. response = urllib2.urlopen('http://baidu.com')
  2617. print response.geturl() # url
  2618. headers = response.info()
  2619. print headers # web页面头部信息
  2620. print headers['date'] # 头部信息中的时间
  2621. date = response.read() # 返回页面所有信息[字符串]
  2622. # date = response.readlines() # 返回页面所有信息[列表]
  2623.  
  2624. for i in urllib2.urlopen('http://qq.com'): # 可直接迭代
  2625. print i,
  2626.  
  2627. 下载文件
  2628.  
  2629. #!/usr/bin/env python
  2630. #encoding:utf8
  2631. import urllib2
  2632.  
  2633. url = 'http://www.01happy.com/wp-content/uploads/2012/09/bg.png'
  2634. file("./pic/%04d.png" % i, "wb").write(urllib2.urlopen(url).read())
  2635.  
  2636. 抓取网页解析指定内容
  2637.  
  2638. #!/usr/bin/env python
  2639. #encoding:utf8
  2640.  
  2641. import urllib2
  2642. import urllib
  2643. import random
  2644. from bs4 import BeautifulSoup
  2645.  
  2646. url='http://www.aaammm.com/aaa/'
  2647.  
  2648. ua=["Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)",
  2649. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",
  2650. "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; .NET4.0C; .NET4.0E)",
  2651. "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36",
  2652. "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36",
  2653. "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36",
  2654. "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36",
  2655. "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36",
  2656. "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36",
  2657. "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36",
  2658. "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36",
  2659. "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0",
  2660. "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36"]
  2661.  
  2662. browser = random.choice(ua)
  2663.  
  2664. req_header = {'User-Agent':browser,
  2665. 'Accept':'text/html;q=0.9,*/*;q=0.8',
  2666. 'Cookie':'BAIDUID=4C8274B52CFB79DEB4FBA9A7EC76A1BC:FG=1; BDUSS=1dCdU1WNFdxUll0R09XcnBZTkRrVVVNbWVnSkRKSVRPeVljOUswclBoLUNzVEpVQVFBQUFBJCQAAAAAAAAAAAEAAADEuZ8BcXVhbnpob3U3MjIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIIIkC1SCJAtUY; BD_UPN=123143; BD_HOME=1', # 添真实登陆后的Cookie
  2667. 'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
  2668. 'Connection':'close',
  2669. }
  2670. #data = urllib.urlencode({'name':'xuesong','id':'30' }) # urllib 的处理参数的方法,可以再urllib2中使用
  2671. data = urllib2.quote("pgv_ref=im.perinfo.perinfo.icon&rrr=pppp")
  2672. req_timeout = 10
  2673. try:
  2674. req = urllib2.Request(url,data=data,headers=req_header) # data为None 则方法为get,有date为post方法
  2675. html = urllib2.urlopen(req,data=None,req_timeout).read()
  2676. except urllib2.HTTPError as err:
  2677. print str(err)
  2678. except:
  2679. print "timeout"
  2680. print(html)
  2681.  
  2682. # 百度带Cookie后查看自己的用户
  2683. #for i in html.split('\n'):
  2684. # if 'bds.comm.user=' in i:
  2685. # print i
  2686.  
  2687. soup = BeautifulSoup(html)
  2688. for i in soup.find_all(target="_blank",attrs={"class": "usr-pic"}): # 条件看情况选择
  2689. if i.img:
  2690. print(i.get('href'))
  2691.  
  2692. 模拟浏览器访问web页面 python3
  2693. #! /usr/bin/env python
  2694. # -*- coding=utf-8 -*-
  2695. import urllib.request
  2696.  
  2697. url = "http://www.baidu.com"
  2698. # AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11
  2699. headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1)',
  2700. 'Accept':'text/html;q=0.9,*/*;q=0.8',
  2701. 'Accept-Charset':'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
  2702. 'Connection':'close',
  2703. 'Referer':None #注意如果依然不能抓取的话,这里可以设置抓取网站的host
  2704. }
  2705.  
  2706. opener = urllib.request.build_opener()
  2707. opener.addheaders = [headers]
  2708. data = opener.open(url).read()
  2709.  
  2710. print(data)
  2711.  
  2712. requests [替代urllib2]
  2713.  
  2714. # Requests是一个Python的HTTP客户端库
  2715. # 官方中文文档 http://cn.python-requests.org/zh_CN/latest/user/quickstart.html#id2
  2716. # 安装: sudo pip install requests
  2717. import requests
  2718.  
  2719. # get方法提交表单
  2720. url = r'http://dict.youdao.com/search?le=eng&q={0}'.format(word.strip())
  2721. r = requests.get(url,timeout=2)
  2722.  
  2723. # get方法带参数 http://httpbin.org/get?key=val
  2724. payload = {'key1': 'value1', 'key2': 'value2'}
  2725. r = requests.get("http://httpbin.org/get", params=payload)
  2726.  
  2727. # post方法提交表单
  2728. QueryAdd='http://www.anti-spam.org.cn/Rbl/Query/Result'
  2729. r = requests.post(url=QueryAdd, data={'IP':'211.211.54.54'})
  2730.  
  2731. # 定制请求头post请求
  2732. payload = {'some': 'data'}
  2733. headers = {'content-type': 'application/json'}
  2734. r = requests.post(url, data=json.dumps(payload), headers=headers)
  2735.  
  2736. # https 需登录加auth
  2737. r = requests.get('https://baidu.com', auth=('user', 'pass'))
  2738.  
  2739. if r.ok: # 判断请求是否正常
  2740. print r.url # u'http://httpbin.org/get?key2=value2&key1=value1'
  2741. print r.status_code # 状态码
  2742. print r.content # 获取到的原始内容 可使用 BeautifulSoup4 解析处理判定结果
  2743. print r.text # 把原始内容转unicode编码
  2744. print r.headers # 响应头
  2745. print r.headers['content-type'] # 网页头信息 不存在为None
  2746. print r.cookies['example_cookie_name'] # 查看cookie
  2747. print r.history # 追踪重定向 [<Response [301]>] 开启重定向 allow_redirects=True
  2748.  
  2749. 获取JSON
  2750. r = requests.get('https://github.com/timeline.json')
  2751. r.json()
  2752.  
  2753. 获取图片
  2754. from PIL import Image
  2755. from StringIO import StringIO
  2756. i = Image.open(StringIO(r.content))
  2757.  
  2758. 发送cookies到服务器
  2759. url = 'http://httpbin.org/cookies'
  2760. cookies = dict(cookies_are='working')
  2761. r = requests.get(url, cookies=cookies)
  2762. r.text '{"cookies": {"cookies_are": "working"}}'
  2763.  
  2764. 在同一个Session实例发出的所有请求之间保持cookies
  2765. s = requests.Session()
  2766. s.get('http://httpbin.org/cookies/set/sessioncookie/123456789')
  2767. r = s.get("http://httpbin.org/cookies")
  2768. print r.text
  2769.  
  2770. 会话对象能够跨请求保持某些参数
  2771. s = requests.Session()
  2772. s.auth = ('user', 'pass')
  2773. s.headers.update({'x-test': 'true'})
  2774. s.get('http://httpbin.org/headers', headers={'x-test2': 'true'}) # both 'x-test' and 'x-test2' are sent
  2775.  
  2776. ssl证书验证
  2777. requests.get('https://github.com', verify=True)
  2778. requests.get('https://kennethreitz.com', verify=False) # 忽略证书验证
  2779. requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key')) # 本地指定一个证书 正确 <Response [200]> 错误 SSLError
  2780.  
  2781. 流式上传
  2782. with open('massive-body') as f:
  2783. requests.post('http://some.url/streamed', data=f)
  2784.  
  2785. 流式请求
  2786. import requests
  2787. import json
  2788.  
  2789. r = requests.post('https://stream.twitter.com/1/statuses/filter.json',
  2790. data={'track': 'requests'}, auth=('username', 'password'), stream=True)
  2791.  
  2792. for line in r.iter_lines():
  2793. if line: # filter out keep-alive new lines
  2794. print json.loads(line)
  2795.  
  2796. 自定义身份验证
  2797. from requests.auth import AuthBase
  2798. class PizzaAuth(AuthBase):
  2799. """Attaches HTTP Pizza Authentication to the given Request object."""
  2800. def __init__(self, username):
  2801. # setup any auth-related data here
  2802. self.username = username
  2803. def __call__(self, r):
  2804. # modify and return the request
  2805. r.headers['X-Pizza'] = self.username
  2806. return r
  2807. requests.get('http://pizzabin.org/admin', auth=PizzaAuth('kenneth'))
  2808.  
  2809. 基本身份认证
  2810. from requests.auth import HTTPBasicAuth
  2811. requests.get('https://api.github.com/user', auth=HTTPBasicAuth('user', 'pass'))
  2812.  
  2813. 摘要式身份认证
  2814. from requests.auth import HTTPDigestAuth
  2815. url = 'http://httpbin.org/digest-auth/auth/user/pass'
  2816. requests.get(url, auth=HTTPDigestAuth('user', 'pass'))
  2817.  
  2818. 代理
  2819. import requests
  2820. proxies = {
  2821. "http": "http://10.10.1.10:3128",
  2822. # "http": "http://user:pass@10.10.1.10:3128/", # 用户名密码
  2823. "https": "http://10.10.1.10:1080",
  2824. }
  2825. requests.get("http://example.org", proxies=proxies)
  2826. #也可以设置环境变量之间访问
  2827. export HTTP_PROXY="http://10.10.1.10:3128"
  2828. export HTTPS_PROXY="http://10.10.1.10:1080"
  2829.  
  2830. BeautifulSoup [html\xml解析器]
  2831.  
  2832. # BeautifulSoup中文官方文档
  2833. # http://www.crummy.com/software/BeautifulSoup/bs3/documentation.zh.html
  2834. # http://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html
  2835. # Beautiful Soup将复杂HTML文档转换成一个复杂的树形结构,每个节点都是Python对象,所有对象可以归纳为4种: Tag , NavigableString , BeautifulSoup , Comment
  2836.  
  2837. 导入模块
  2838. from BeautifulSoup import BeautifulSoup # For processing HTML 版本3.0 已停止更新
  2839. from BeautifulSoup import BeautifulStoneSoup # For processing XML
  2840. import BeautifulSoup # To get everything
  2841. from bs4 import BeautifulSoup # 版本4.0 bs4 安装: pip install BeautifulSoup4
  2842.  
  2843. from bs4 import BeautifulSoup
  2844. soup = BeautifulSoup(html_doc) # 解析html文本 可以是 requests 提交返回的页面 results.content
  2845. print(soup.prettify()) # 输出解析后的结构
  2846. print(soup.title) # 指定标签内容
  2847. print(soup.title.name) # 标签名
  2848. print(soup.title.string) # 标签内容
  2849. print(soup.title.parent.name) # 上层标签名
  2850. print(soup.p) # <p class="title"><b>The Dormouse's story</b></p>
  2851. print(soup.p['class']) # u'title' class属性值
  2852. print(soup.a) # 找到第一个a标签的标签行
  2853. print(soup.find_all('a',limit=2)) # 找到a标签的行,最多为limit个
  2854. print(soup.find(id="link3")) # 标签内id为link3的标签行
  2855. print(soup.get_text()) # 从文档中获取所有文字内容
  2856. soup.find_all("a", text="Elsie") # 从文档中搜索关键字
  2857. soup.find(text=re.compile("sisters")) # 从文档中正则搜索关键字
  2858. soup.find_all("a", class_="sister") # 按CSS搜索
  2859. soup.find_all(id='link2',"table",attrs={"class": "status"},href=re.compile("elsie")) # 搜索方法
  2860. for i in soup.find_all('a',attrs={"class": "usr-pic"}): # 循环所有a标签的标签行
  2861. if i.a.img:
  2862. print(i.a.img.get("src")) # 取出当前a标签中的连接
  2863. Tag
  2864. # find_all 后循环的值是 Tag 不是字符串 不能直接截取
  2865. tag.text # 文本
  2866. tag.name
  2867. tag.name = "blockquote" # 查找name为 blockquote 的
  2868. tag['class']
  2869. tag.attrs # 按熟悉查找
  2870. tag['class'] = 'verybold'
  2871.  
  2872. del tag['class'] # 删除
  2873. print(tag.get('class')) # 打印属性值
  2874. print(i.get('href')) # 打印连接
  2875.  
  2876. json
  2877.  
  2878. #!/usr/bin/python
  2879. import json
  2880.  
  2881. #json file temp.json
  2882. #{ "name":"00_sample_case1", "description":"an example."}
  2883.  
  2884. f = file("temp.json");
  2885. s = json.load(f) # 直接读取json文件
  2886. print s
  2887. f.close
  2888.  
  2889. d = {"a":1}
  2890. j=json.dumps(d) # 字典转json
  2891. json.loads(j) # json转字典
  2892.  
  2893. s = json.loads('{"name":"test", "type":{"name":"seq", "parameter":["1", "2"]}}')
  2894. print type(s) # dic
  2895. print s
  2896. print s.keys()
  2897. print s["type"]["parameter"][1]
  2898.  
  2899. cookielib [保留cookie登录页面]
  2900.  
  2901. ck = cookielib.CookieJar() # 通过 这个就可以实现请求带过去的COOKIE与发送回来的COOKIE值了。
  2902. opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(ck)) # 获取到COOKIE
  2903. urllib2.install_opener(opener) # 此句设置urllib2的全局opener
  2904. content = urllib2.urlopen(url).read()
  2905.  
  2906. 登录cacti取图片
  2907. #encoding:utf8
  2908. import urllib2
  2909. import urllib
  2910. import cookielib
  2911. def renrenBrower(url,user,password):
  2912. #查找form标签中的action提交地址
  2913. login_page = "http://10.10.76.79:81/cacti/index.php"
  2914. try:
  2915. #获得一个cookieJar实例
  2916. cj = cookielib.CookieJar()
  2917. #cookieJar作为参数,获得一个opener的实例
  2918. opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
  2919. #伪装成一个正常的浏览器,避免有些web服务器拒绝访问
  2920. opener.addheaders = [('User-agent','Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)')]
  2921. #生成Post数据,含有登陆用户名密码,所有表单内的input中name值
  2922. data = urllib.urlencode({"action":"login","login_username":user,"login_password":password})
  2923. #以post的方法访问登陆页面,访问之后cookieJar会自定保存cookie
  2924. opener.open(login_page,data)
  2925. #以带cookie的方式访问页面
  2926. op=opener.open(url)
  2927. #读取页面源码
  2928. data=op.read()
  2929. #将图片写到本地
  2930. #file("1d.png" , "wb").write(data)
  2931. return data
  2932. except Exception,e:
  2933. print str(e)
  2934. print renrenBrower("http://10.10.76.79:81/cacti/graph_image.php?local_graph_id=1630&rra_id=0&view_type=tree&graph_start=1397525517&graph_end=1397611917","admin","admin")
  2935.  
  2936. 例子2
  2937. import urllib, urllib2, cookielib
  2938. import os, time
  2939.  
  2940. headers = []
  2941.  
  2942. def login():
  2943. cj = cookielib.CookieJar()
  2944. opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
  2945. login_url = r'http://zhixing.bjtu.edu.cn/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1'
  2946. login_data = urllib.urlencode({'cookietime': '2592000', 'handlekey': 'ls', 'password': 'xxx',
  2947. 'quickforward': 'yes', 'username': 'GuoYuan'})
  2948. opener.addheaders = [('Host', 'zhixing.bjtu.edu.cn'),
  2949. ('User-Agent', 'Mozilla/5.0 (Ubuntu; X11; Linux i686; rv:8.0) Gecko/20100101 Firefox/8.0'),
  2950. ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
  2951. ('Accept-Language', 'en-us,en;q=0.5'),
  2952. ('Accept-Encoding', 'gzip, deflate'),
  2953. ('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7'),
  2954. ('Connection', 'keep-alive'),
  2955. ('Referer', 'http://zhixing.bjtu.edu.cn/forum.php'),]
  2956. opener.open(login_url, login_data)
  2957. return opener
  2958.  
  2959. if __name__ == '__main__':
  2960. opener = login()
  2961.  
  2962. url = r'http://zhixing.bjtu.edu.cn/forum.php?mod=topicadmin&action=moderate&optgroup=2&modsubmit=yes&infloat=yes&inajax=1'
  2963. data = {'fid': '601', 'formhash': '0cdd1596', 'frommodcp': '', 'handlekey': 'mods',
  2964. 'listextra': 'page%3D62', 'moderate[]': '496146', 'operations[]': 'type', 'reason': '...',
  2965. 'redirect': r'http://zhixing.bjtu.edu.cn/thread-496146-1-1.html', 'typeid': '779'}
  2966. data2 = [(k, v) for k,v in data.iteritems()]
  2967.  
  2968. cnt = 0
  2969. for tid in range(493022, 496146 + 1):
  2970. cnt += 1
  2971. if cnt % 20 == 0: print
  2972. print tid,
  2973.  
  2974. data2.append(('moderate[]', str(tid)))
  2975. if cnt % 40 == 0 or cnt == 496146:
  2976. request = urllib2.Request(url=url, data=urllib.urlencode(data2))
  2977. print opener.open(request).read()
  2978. data2 = [(k, v) for k,v in data.iteritems()]
  2979.  
  2980. httplib [http协议的客户端]
  2981.  
  2982. import httplib
  2983. conn3 = httplib.HTTPConnection('www.baidu.com',80,True,10)
  2984.  
  2985. 查看网页图片尺寸类型
  2986.  
  2987. #将图片读入内存
  2988. #!/usr/bin/env python
  2989. #encoding=utf-8
  2990. import cStringIO, urllib2, Image
  2991. url = 'http://www.01happy.com/wp-content/uploads/2012/09/bg.png'
  2992. file = urllib2.urlopen(url)
  2993. tmpIm = cStringIO.StringIO(file.read())
  2994. im = Image.open(tmpIm)
  2995. print im.format, im.size, im.mode
  2996.  
  2997. 爬虫
  2998.  
  2999. #!/usr/bin/env python
  3000. #encoding:utf-8
  3001. #sudo pip install BeautifulSoup
  3002.  
  3003. import requests
  3004. from BeautifulSoup import BeautifulSoup
  3005. import re
  3006.  
  3007. baseurl = 'http://blog.sina.com.cn/s/articlelist_1191258123_0_1.html'
  3008.  
  3009. r = requests.get(baseurl)
  3010.  
  3011. for url in re.findall('<a.*?</a>', r.content, re.S):
  3012. if url.startswith('<a title='):
  3013. with open(r'd:/final.txt', 'ab') as f:
  3014. f.write(url + '\n')
  3015.  
  3016. linkfile = open(r'd:/final.txt', 'rb')
  3017. soup = BeautifulSoup(linkfile)
  3018. for link in soup.findAll('a'):
  3019. #print link.get('title') + ': ' + link.get('href')
  3020. ss = requests.get(link.get('href'))
  3021. for content in re.findall('<div id="sina_keyword_ad_area2" class="articalContent ">.*?</div>', ss.content, re.S):
  3022. with open(r'd:/myftp/%s.txt'%link.get('title').strip('<>'), 'wb') as f:
  3023. f.write(content)
  3024. print '%s has been copied.' % link.get('title')
  3025.  
  3026. 反垃圾邮件提交申诉
  3027.  
  3028. #很遗憾,反垃圾邮件联盟改版后加了验证码
  3029.  
  3030. #!/usr/bin/env python
  3031. #encoding:utf-8
  3032. import requests
  3033. import re
  3034.  
  3035. IpList=['113.212.91.25','113.212.91.23']
  3036. QueryAdd='http://www.anti-spam.org.cn/Rbl/Query/Result'
  3037. ComplaintAdd='http://www.anti-spam.org.cn/Rbl/Getout/Submit'
  3038. data = {
  3039. 'CONTENT':'''我们是一家正规的XXX。xxxxxxx。恳请将我们的发送服务器IP移出黑名单。谢谢!
  3040. 处理措施:
  3041. 1.XXXX。
  3042. 2.XXXX。''',
  3043. 'CORP':'abc.com',
  3044. 'WWW':'www.abc.cm',
  3045. 'NAME':'def',
  3046. 'MAIL':'def@163.com.cn',
  3047. 'TEL':'010-50000000',
  3048. 'LEVEL':'0',
  3049. }
  3050.  
  3051. for Ip in IpList:
  3052. query = requests.post(url=QueryAdd, data={'IP':Ip}) # 黑名单查询
  3053. if query.ok:
  3054. if re.findall(u'\u7533\u8bc9\u8131\u79bb', query.text, re.S): # 查找关键字 申诉脱离 既表明在黑名单中
  3055. data['IP']=Ip
  3056. complaint = requests.post(url=ComplaintAdd, data=data) # 提交申诉
  3057. if complaint.ok:
  3058. if re.findall(u'\u60a8\u7684\u9ed1\u540d\u5355\u8131\u79bb\u7533\u8bf7\u5df2\u63d0\u4ea4', complaint.text, re.S):
  3059. status='申请提交'
  3060. elif re.findall(u'\u8131\u79bb\u7533\u8bf7\u5df2\u88ab\u4ed6\u4eba\u63d0\u4ea4', complaint.text, re.S):
  3061. status='重复提交'
  3062. elif re.findall(u'\u7533\u8bf7\u7531\u4e8e\u8fd1\u671f\u5185\u6709\u88ab\u62d2\u7edd\u7684\u8bb0\u5f55', complaint.text, re.S):
  3063. status='近期拒绝'
  3064. else:
  3065. status='异常'
  3066. else:
  3067. status='正常'
  3068. print '%s %s' %(Ip,status)
  3069.  
  3070. 有道词典
  3071.  
  3072. #!/usr/bin/env python
  3073. import requests
  3074. from bs4 import BeautifulSoup
  3075. # bs4安装: pip install BeautifulSoup4
  3076.  
  3077. def youdao(word):
  3078. url = r'http://dict.youdao.com/search?le=eng&q={0}'.format(word.strip())
  3079. r = requests.get(url)
  3080. if r.ok:
  3081. soup = BeautifulSoup(r.content)
  3082. div = soup.find_all('div', class_='trans-container')[:1] # find_all是bs4的方法
  3083. ul = BeautifulSoup(str(div[0]))
  3084. li = ul.find_all('li')
  3085. for mean in li:
  3086. print mean.text
  3087.  
  3088. def query():
  3089. print('Created by @littlepy, QQ:185635687')
  3090. while True:
  3091. word = raw_input('>>>')
  3092. youdao(word)
  3093.  
  3094. if __name__ == '__main__':
  3095. query()
  3096.  
  3097. python启动http服务提供访问或下载
  3098.  
  3099. python -m SimpleHTTPServer 9900
  3100.  
  3101. 8 并发
  3102.  
  3103. #线程安全/竞争条件,锁/死锁检测,同步/异步,阻塞/非阻塞,epoll非阻塞IO,信号量/事件,线程池,生产消费模型,伪并发,微线程,协程
  3104. #Stackless Python 是Python编程语言的一个增强版本,它使程序员从基于线程的编程方式中获得好处,并避免传统线程所带来的性能与复杂度问题。Stackless为 Python带来的微线程扩展,是一种低开销、轻量级的便利工具
  3105.  
  3106. threading多线程
  3107.  
  3108. thread
  3109. start_new_thread(function,args kwargs=None) # 产生一个新的线程
  3110. allocate_lock() # 分配一个LockType类型的锁对象
  3111. exit() # 让线程退出
  3112. acquire(wait=None) # 尝试获取锁对象
  3113. locked() # 如果获取了锁对象返回True
  3114. release() # 释放锁
  3115.  
  3116. thread例子
  3117.  
  3118. #!/usr/bin/env python
  3119. #thread_test.py
  3120. #不支持守护进程
  3121. import thread
  3122. from time import sleep,ctime
  3123.  
  3124. loops = [4,2]
  3125.  
  3126. def loop(nloop,nsec,lock):
  3127. print 'start loop %s at:%s' % (nloop,ctime())
  3128. sleep(nsec)
  3129. print 'loop %s done at: %s' % (nloop, ctime())
  3130. lock.release() # 分配已获得的锁,操作结束后释放相应的锁通知主线程
  3131.  
  3132. def main():
  3133. print 'starting at:',ctime()
  3134. locks = []
  3135. nloops = range(len(loops))
  3136.  
  3137. for i in nloops:
  3138. lock = thread.allocate_lock() # 创建一个锁
  3139. lock.acquire() # 调用各个锁的acquire()函数获得锁
  3140. locks.append(lock) # 把锁放到锁列表locks中
  3141. for i in nloops:
  3142. thread.start_new_thread(loop,(i,loops[i],locks[i])) # 创建线程
  3143. for i in nloops:
  3144. while locks[i].locked():pass # 等待全部解锁才继续运行
  3145. print 'all DONE at:',ctime()
  3146.  
  3147. if __name__ == '__main__':
  3148. main()
  3149.  
  3150. thread例子1
  3151.  
  3152. #coding=utf-8
  3153. import thread,time,os
  3154.  
  3155. def f(name):
  3156. i =3
  3157. while i:
  3158. time.sleep(1)
  3159. print name
  3160. i -= 1
  3161. # os._exit() 会把整个进程关闭
  3162. os._exit(22)
  3163.  
  3164. if __name__ == '__main__':
  3165. thread.start_new_thread(f,("th1",))
  3166. while 1:
  3167. pass
  3168. os._exit(0)
  3169.  
  3170. threading
  3171. Thread # 表示一个线程的执行的对象
  3172. start() # 开始线程的执行
  3173. run() # 定义线程的功能的函数(一般会被子类重写)
  3174. join(timeout=None) # 允许主线程等待线程结束,程序挂起,直到线程结束;如果给了timeout,则最多等待timeout秒.
  3175. getName() # 返回线程的名字
  3176. setName(name) # 设置线程的名字
  3177. isAlive() # 布尔标志,表示这个线程是否还在运行中
  3178. isDaemon() # 返回线程的daemon标志
  3179. setDaemon(daemonic) # 后台线程,把线程的daemon标志设置为daemonic(一定要在调用start()函数前调用)
  3180. # 默认主线程在退出时会等待所有子线程的结束。如果希望主线程不等待子线程,而是在退出时自动结束所有的子线程,就需要设置子线程为后台线程(daemon)
  3181. Lock # 锁原语对象
  3182. Rlock # 可重入锁对象.使单线程可以在此获得已获得了的锁(递归锁定)
  3183. Condition # 条件变量对象能让一个线程停下来,等待其他线程满足了某个条件.如状态改变或值的改变
  3184. Event # 通用的条件变量.多个线程可以等待某个事件的发生,在事件发生后,所有的线程都会被激活
  3185. Semaphore # 为等待锁的线程提供一个类似等候室的结构
  3186. BoundedSemaphore # 与Semaphore类似,只是不允许超过初始值
  3187. Time # 与Thread相似,只是他要等待一段时间后才开始运行
  3188. activeCount() # 当前活动的线程对象的数量
  3189. currentThread() # 返回当前线程对象
  3190. enumerate() # 返回当前活动线程的列表
  3191. settrace(func) # 为所有线程设置一个跟踪函数
  3192. setprofile(func) # 为所有线程设置一个profile函数
  3193.  
  3194. threading例子1
  3195.  
  3196. #!/usr/bin/env python
  3197. #encoding:utf8
  3198. import threading
  3199. from Queue import Queue
  3200. from time import sleep,ctime
  3201.  
  3202. class ThreadFunc(object):
  3203. def __init__(self,func,args,name=''):
  3204. self.name=name
  3205. self.func=func # loop
  3206. self.args=args # (i,iplist[i],queue)
  3207. def __call__(self):
  3208. apply(self.func,self.args) # 函数apply() 执行loop函数并传递元组参数
  3209. def loop(nloop,ip,queue):
  3210. print 'start',nloop,'at:',ctime()
  3211. queue.put(ip)
  3212. sleep(2)
  3213. print 'loop',nloop,'done at:',ctime()
  3214. if __name__ == '__main__':
  3215. threads = []
  3216. queue = Queue()
  3217. iplist = ['192.168.1.2','192.168.1.3','192.168.1.4','192.168.1.5','192.168.1.6','192.168.1.7','192.168.1.8']
  3218. nloops = range(len(iplist))
  3219.  
  3220. for i in nloops:
  3221. t = threading.Thread(target=ThreadFunc(loop,(i,iplist[i],queue),loop.__name__))
  3222. threads.append(t)
  3223. for i in nloops:
  3224. threads[i].start()
  3225. for i in nloops:
  3226. threads[i].join()
  3227. for i in nloops:
  3228. print queue.get()
  3229.  
  3230. threading例子2
  3231.  
  3232. #!/usr/bin/env python
  3233. #encoding:utf8
  3234. from Queue import Queue
  3235. import random,time,threading
  3236.  
  3237. class Producer(threading.Thread):
  3238. def __init__(self, t_name, queue):
  3239. threading.Thread.__init__(self, name=t_name)
  3240. self.data=queue
  3241. def run(self):
  3242. for i in range(5):
  3243. print "%s: %s is producing %d to the queue!\n" %(time.ctime(), self.getName(), i)
  3244. self.data.put(i)
  3245. self.data.put(i*i)
  3246. time.sleep(2)
  3247. print "%s: %s finished!" %(time.ctime(), self.getName())
  3248.  
  3249. class Consumer(threading.Thread):
  3250. def __init__(self, t_name, queue):
  3251. threading.Thread.__init__(self, name=t_name)
  3252. self.data=queue
  3253. def run(self):
  3254. for i in range(10):
  3255. val = self.data.get()
  3256. print "%s: %s is consuming. %d in the queue is consumed!\n" %(time.ctime(), self.getName(), val)
  3257. print "%s: %s finished!" %(time.ctime(), self.getName())
  3258.  
  3259. if __name__ == '__main__':
  3260. queue = Queue()
  3261. producer = Producer('Pro.', queue)
  3262. consumer = Consumer('Con.', queue)
  3263. producer.start()
  3264. consumer.start()
  3265. producer.join()
  3266. consumer.join()
  3267.  
  3268. threading例子3
  3269.  
  3270. # 启动线程后自动执行 run函数其他不可以
  3271. import threading
  3272. import time
  3273.  
  3274. class Th(threading.Thread):
  3275. def __init__(self,name):
  3276. threading.Thread.__init__(self)
  3277. self.t_name=name
  3278. self.daemon = True # 默认为false,让主线程等待处理完成
  3279. def run(self):
  3280. time.sleep(1)
  3281. print "this is " + self.t_name
  3282.  
  3283. if __name__ == '__main__':
  3284. thread1 = Th("Th_1")
  3285. thread1.start()
  3286.  
  3287. threading例子4
  3288.  
  3289. import threading
  3290. import time
  3291. class Th(threading.Thread):
  3292. def __init__(self,thread_name):
  3293. threading.Thread.__init__(self)
  3294. self.setName(thread_name)
  3295. def run(self):
  3296. threadLock.acquire()
  3297. print self.getName()
  3298. for i in range(3):
  3299. time.sleep(1)
  3300. print str(i)
  3301. print self.getName() + " is over"
  3302. threadLock.release()
  3303.  
  3304. if __name__ == '__main__':
  3305. threadLock = threading.Lock()
  3306. thread1 = Th("Th_1")
  3307. thread2 = Th("Th_2")
  3308. thread1.start()
  3309. thread2.start()
  3310.  
  3311. 后台线程
  3312.  
  3313. import threading
  3314. import time,random
  3315.  
  3316. class MyThread(threading.Thread):
  3317. def run(self):
  3318. wait_time=random.randrange(1,10)
  3319. print "%s will wait %d seconds" % (self.name, wait_time)
  3320. time.sleep(wait_time)
  3321. print "%s finished!" % self.name
  3322.  
  3323. if __name__=="__main__":
  3324. for i in range(5):
  3325. t = MyThread()
  3326. t.setDaemon(True) # 设置为后台线程,主线程完成时不等待子线程完成就结束
  3327. t.start()
  3328.  
  3329. threading控制最大并发_查询日志中IP信息
  3330.  
  3331. #!/usr/bin/env python
  3332. #coding:utf-8
  3333. import urllib2
  3334. import json
  3335. import threading
  3336. import time
  3337.  
  3338. '''
  3339. by:某大牛
  3340. QQ:185635687
  3341. 这个是多线程并发控制. 如果要改成多进程,只需把threading 换成 mulitprocessing.Process , 对, 就是换个名字而已.
  3342. '''
  3343.  
  3344. #获取ip 及其出现次数
  3345. def ip_dic(file_obj, dic):
  3346. for i in file_obj:
  3347. if i:
  3348. ip=i.split('-')[0].strip()
  3349. if ip in dic.keys():
  3350. dic[ip]=dic[ip] + 1
  3351. else:
  3352. dic[ip]=1
  3353. return dic.iteritems()
  3354.  
  3355. #目标函数
  3356. def get_data(url, ipcounts):
  3357. data=urllib2.urlopen(url).read()
  3358. datadict=json.loads(data)
  3359. fdata = u"ip:%s---%s,%s,%s,%s,%s" %(datadict["data"]["ip"],ipcounts,datadict["data"]["country"],datadict["data"]["region"],datadict["data"]["city"],datadict["data"]["isp"])
  3360. print fdata
  3361.  
  3362. #多线程
  3363. def threads(iters):
  3364. thread_pool = []
  3365. for k in iters:
  3366. url = "http://ip.taobao.com/service/getIpInfo.php?ip="
  3367. ipcounts = k[1]
  3368. url = (url + k[0]).strip()
  3369. t = threading.Thread(target=get_data, args=(url, ipcounts))
  3370. thread_pool.append(t)
  3371. return thread_pool
  3372.  
  3373. #控制多线程
  3374. def startt(t_list, max,second):
  3375. l = len(t_list)
  3376. n = max
  3377. while l > 0:
  3378. if l > max:
  3379. nl = t_list[:max]
  3380. t_list = t_list[max:]
  3381. for t in nl:
  3382. t.start()
  3383. time.sleep(second)
  3384. for t in nl:
  3385. t.join()
  3386. print '*'*15, str(n)+ ' ip has been queried'+'*'*15
  3387. n += max
  3388. l = len(t_list)
  3389. continue
  3390. elif l <= max:
  3391. nl = t_list
  3392. for t in nl:
  3393. t.start()
  3394. for t in nl:
  3395. t.join()
  3396. print '>>> Totally ' + str(n+l ) + ' ip has been queried'
  3397. l = 0
  3398.  
  3399. if __name__ =="__main__":
  3400. dic={}
  3401. with open('access.log') as file_obj:
  3402. it = ip_dic(file_obj, dic)
  3403. t_list= threads(it)
  3404. startt(t_list, 15, 1)
  3405.  
  3406. 多线程取队列
  3407.  
  3408. #!/usr/bin/python
  3409.  
  3410. import Queue
  3411. import threading
  3412. import time
  3413.  
  3414. exitFlag = 0
  3415.  
  3416. class myThread (threading.Thread):
  3417. def __init__(self, threadID, name, q):
  3418. threading.Thread.__init__(self)
  3419. self.threadID = threadID
  3420. self.name = name
  3421. self.q = q
  3422. def run(self):
  3423. print "Starting " + self.name
  3424. process_data(self.name, self.q)
  3425. print "Exiting " + self.name
  3426.  
  3427. def process_data(threadName, q):
  3428. while not exitFlag: # 死循环等待
  3429. queueLock.acquire()
  3430. if not q.empty(): # 判断队列是否为空
  3431. data = q.get()
  3432. print "%s processing %s" % (threadName, data)
  3433. queueLock.release()
  3434. time.sleep(1)
  3435.  
  3436. threadList = ["Thread-1", "Thread-2", "Thread-3"]
  3437. nameList = ["One", "Two", "Three", "Four", "Five"]
  3438. queueLock = threading.Lock() # 锁与队列并无任何关联,其他线程也进行取锁操作的时候就会检查是否有被占用,有就阻塞等待解锁为止
  3439. workQueue = Queue.Queue(10)
  3440. threads = []
  3441. threadID = 1
  3442.  
  3443. # Create new threads
  3444. for tName in threadList:
  3445. thread = myThread(threadID, tName, workQueue)
  3446. thread.start()
  3447. threads.append(thread)
  3448. threadID += 1
  3449.  
  3450. # Fill the queue
  3451. queueLock.acquire()
  3452. for word in nameList:
  3453. workQueue.put(word)
  3454. queueLock.release()
  3455.  
  3456. # Wait for queue to empty
  3457. while not workQueue.empty(): # 死循环判断队列被处理完毕
  3458. pass
  3459.  
  3460. # Notify threads it's time to exit
  3461. exitFlag = 1
  3462.  
  3463. # Wait for all threads to complete
  3464. for t in threads:
  3465. t.join()
  3466. print "Exiting Main Thread"
  3467.  
  3468. Queue通用队列
  3469.  
  3470. q=Queue(size) # 创建大小size的Queue对象
  3471. qsize() # 返回队列的大小(返回时候,可能被其他进程修改,近似值)
  3472. empty() # 如果队列为空返回True,否则Fales
  3473. full() # 如果队列已满返回True,否则Fales
  3474. put(item,block0) # 把item放到队列中,如果给了block(不为0),函数会一直阻塞到队列中有空间为止
  3475. get(block=0) # 从队列中取一个对象,如果给了block(不为0),函数会一直阻塞到队列中有对象为止
  3476. get_nowait # 默认get阻塞,这个不阻塞
  3477.  
  3478. multiprocessing [多进程并发]
  3479.  
  3480. 多线程
  3481.  
  3482. import urllib2
  3483. from multiprocessing.dummy import Pool as ThreadPool
  3484.  
  3485. urls=['http://www.baidu.com','http://www.sohu.com']
  3486.  
  3487. pool=ThreadPool(4) # 线程池
  3488. results=pool.map(urllib2.urlopen,urls)
  3489. pool.close()
  3490. pool.join()
  3491.  
  3492. 多进程并发
  3493.  
  3494. #!/usr/bin/env python
  3495. #encoding:utf8
  3496. from multiprocessing import Process
  3497. import time,os
  3498. def f(name):
  3499. time.sleep(1)
  3500. print 'hello ',name
  3501. print os.getppid() # 取得父进程ID
  3502. print os.getpid() # 取得进程ID
  3503. process_list = []
  3504.  
  3505. for i in range(10):
  3506. p = Process(target=f,args=(i,))
  3507. p.start()
  3508. process_list.append(p)
  3509. for j in process_list:
  3510. j.join()
  3511.  
  3512. Queue进程间通信
  3513.  
  3514. from multiprocessing import Process,Queue
  3515. import time
  3516. def f(name):
  3517. time.sleep(1)
  3518. q.put(['hello'+str(name)])
  3519. process_list = []
  3520. q = Queue()
  3521. if __name__ == '__main__':
  3522. for i in range(10):
  3523. p = Process(target=f,args=(i,))
  3524. p.start()
  3525. process_list.append(p)
  3526. for j in process_list:
  3527. j.join()
  3528. for i in range(10):
  3529. print q.get()
  3530.  
  3531. Pipe管道
  3532.  
  3533. from multiprocessing import Process,Pipe
  3534. import time
  3535. import os
  3536.  
  3537. def f(conn,name):
  3538. time.sleep(1)
  3539. conn.send(['hello'+str(name)])
  3540. print os.getppid(),'-----------',os.getpid()
  3541. process_list = []
  3542. parent_conn,child_conn = Pipe()
  3543. if __name__ == '__main__':
  3544. for i in range(10):
  3545. p = Process(target=f,args=(child_conn,i))
  3546. p.start()
  3547. process_list.append(p)
  3548. for j in process_list:
  3549. j.join()
  3550. for p in range(10):
  3551. print parent_conn.recv()
  3552.  
  3553. 进程间同步
  3554. #加锁,使某一时刻只有一个进程 print
  3555. from multiprocessing import Process,Lock
  3556. import time
  3557. import os
  3558.  
  3559. def f(name):
  3560. lock.acquire()
  3561. time.sleep(1)
  3562. print 'hello--'+str(name)
  3563. print os.getppid(),'-----------',os.getpid()
  3564. lock.release()
  3565. process_list = []
  3566. lock = Lock()
  3567. if __name__ == '__main__':
  3568. for i in range(10):
  3569. p = Process(target=f,args=(i,))
  3570. p.start()
  3571. process_list.append(p)
  3572. for j in process_list:
  3573. j.join()
  3574.  
  3575. 共享内存
  3576.  
  3577. # 通过使用Value或者Array把数据存储在一个共享的内存表中
  3578. # 'd'和'i'参数是num和arr用来设置类型,d表示一个双精浮点类型,i表示一个带符号的整型。
  3579. from multiprocessing import Process,Value,Array
  3580. import time
  3581. import os
  3582.  
  3583. def f(n,a,name):
  3584. time.sleep(1)
  3585. n.value = name * name
  3586. for i in range(len(a)):
  3587. a[i] = -i
  3588. process_list = []
  3589. if __name__ == '__main__':
  3590. num = Value('d',0.0)
  3591. arr = Array('i',range(10))
  3592. for i in range(10):
  3593. p = Process(target=f,args=(num,arr,i))
  3594. p.start()
  3595. process_list.append(p)
  3596. for j in process_list:
  3597. j.join()
  3598. print num.value
  3599. print arr[:]
  3600.  
  3601. manager
  3602.  
  3603. # 比共享内存灵活,但缓慢
  3604. # 支持list,dict,Namespace,Lock,Semaphore,BoundedSemaphore,Condition,Event,Queue,Value,Array
  3605. from multiprocessing import Process,Manager
  3606. import time
  3607. import os
  3608.  
  3609. def f(d,name):
  3610. time.sleep(1)
  3611. d[name] = name * name
  3612. print d
  3613. process_list = []
  3614. if __name__ == '__main__':
  3615. manager = Manager()
  3616. d = manager.dict()
  3617. for i in range(10):
  3618. p = Process(target=f,args=(d,i))
  3619. p.start()
  3620. process_list.append(p)
  3621. for j in process_list:
  3622. j.join()
  3623. print d
  3624.  
  3625. 最大并发数
  3626.  
  3627. import multiprocessing
  3628. import time,os
  3629.  
  3630. result = []
  3631. def run(h):
  3632. print 'threading:' ,h,os.getpid()
  3633. p = multiprocessing.Pool(processes=20)
  3634.  
  3635. for i in range(100):
  3636. result.append(p.apply_async(run,(i,)))
  3637. p.close()
  3638.  
  3639. for res in result:
  3640. res.get(timeout=5)
  3641.  
  3642. 9 框架
  3643.  
  3644. flask [微型网络开发框架]
  3645.  
  3646. # http://dormousehole.readthedocs.org/en/latest/
  3647. # html放在 ./templates/ js放在 ./static/
  3648.  
  3649. request.args.get('page', 1) # 获取参数 ?page=1
  3650. request.json # 获取传递的整个json数据
  3651. request.form.get("host",'127') # 获取表单值
  3652.  
  3653. 简单实例 # 接收数据和展示
  3654.  
  3655. import MySQLdb as mysql
  3656. from flask import Flask, request
  3657.  
  3658. app = Flask(__name__)
  3659. db.autocommit(True)
  3660. c = db.cursor()
  3661.  
  3662. """
  3663. CREATE TABLE `statusinfo` (
  3664. `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  3665. `hostname` varchar(32) NOT NULL,
  3666. `load` float(10) NOT NULL DEFAULT 0.00,
  3667. `time` int(15) NOT NULL,
  3668. `memtotal` int(15) NOT NULL,
  3669. `memusage` int(15) NOT NULL,
  3670. `memfree` int(15) NOT NULL,
  3671. PRIMARY KEY (`id`)
  3672. ) ENGINE=InnoDB AUTO_INCREMENT=161 DEFAULT CHARSET=utf8;
  3673. """
  3674.  
  3675. @app.route("/collect", methods=["GET", "POST"])
  3676. def collect():
  3677. sql = ""
  3678. if request.method == "POST":
  3679. data = request.json # 获取传递的json
  3680. hostname = data["Host"]
  3681. load = data["LoadAvg"]
  3682. time = data["Time"]
  3683. memtotal = data["MemTotal"]
  3684. memusage = data["MemUsage"]
  3685. memfree = data["MemFree"]
  3686.  
  3687. try:
  3688. sql = "INSERT INTO `statusinfo` (`hostname`,`load`,`time`,`memtotal`,`memusage`,`memfree`) VALUES('%s', %s, %s, %s, %s, %s);" % (hostname, load,time,memtotal,memusage,memfree)
  3689. ret = c.execute(sql)
  3690. return 'ok'
  3691. except mysql.IntegrityError:
  3692. return 'errer'
  3693.  
  3694. @app.route("/show", methods=["GET", "POST"])
  3695. def show():
  3696. try:
  3697. hostname = request.form.get("hostname") # 获取表单方式的变量值
  3698. sql = "SELECT `load` FROM `statusinfo` WHERE hostname = '%s';" % (hostname)
  3699. c.execute(sql)
  3700. ones = c.fetchall()
  3701. return render_template("sysstatus.html", data=ones, sql = sql)
  3702. except:
  3703. print 'hostname null'
  3704.  
  3705. from flask import render_template
  3706. @app.route("/xxx/<name>")
  3707. def hello_xx(name):
  3708. return render_template("sysstatus.html", name='teach')
  3709.  
  3710. if __name__ == "__main__":
  3711. app.run(host="0.0.0.0", port=50000, debug=True)
  3712.  
  3713. twisted [非阻塞异步服务器框架]
  3714.  
  3715. # 用来进行网络服务和应用程序的编程。虽然 Twisted Matrix 中有大量松散耦合的模块化组件,但该框架的中心概念还是非阻塞异步服务器这一思想。对于习惯于线程技术或分叉服务器的开发人员来说,这是一种新颖的编程风格,但它却能在繁重负载的情况下带来极高的效率。
  3716. pip install twisted
  3717.  
  3718. from twisted.internet import protocol, reactor, endpoints
  3719.  
  3720. class Echo(protocol.Protocol):
  3721. def dataReceived(self, data):
  3722. self.transport.write(data)
  3723. class EchoFactory(protocol.Factory):
  3724. def buildProtocol(self, addr):
  3725. return Echo()
  3726.  
  3727. endpoints.serverFromString(reactor, "tcp:1234").listen(EchoFactory())
  3728. reactor.run()
  3729.  
  3730. greenlet [微线程/协程框架]
  3731.  
  3732. # 更加原始的微线程的概念,没有调度,或者叫做协程。这在你需要控制你的代码时很有用。你可以自己构造微线程的 调度器;也可以使用"greenlet"实现高级的控制流。例如可以重新创建构造器;不同于Python的构造器,我们的构造器可以嵌套的调用函数,而被嵌套的函数也可以 yield 一个值。
  3733. pip install greenlet
  3734.  
  3735. tornado [极轻量级Web服务器框架]
  3736.  
  3737. # 高可伸缩性和epoll非阻塞IO,响应快速,可处理数千并发连接,特别适用用于实时的Web服务
  3738. # http://www.tornadoweb.cn/documentation
  3739. pip install tornado
  3740.  
  3741. import tornado.ioloop
  3742. import tornado.web
  3743.  
  3744. class MainHandler(tornado.web.RequestHandler):
  3745. def get(self):
  3746. self.write("Hello, world")
  3747.  
  3748. application = tornado.web.Application([
  3749. (r"/", MainHandler),
  3750. ])
  3751.  
  3752. if __name__ == "__main__":
  3753. application.listen(8888)
  3754. tornado.ioloop.IOLoop.instance().start()
  3755.  
  3756. Scrapy [web抓取框架]
  3757. # Python开发的一个快速,高层次的屏幕抓取和web抓取框架,用于抓取web站点并从页面中提取结构化的数据。Scrapy用途广泛,可以用于数据挖掘、监测和自动化测试。
  3758. pip install scrapy
  3759.  
  3760. from scrapy import Spider, Item, Field
  3761.  
  3762. class Post(Item):
  3763. title = Field()
  3764.  
  3765. class BlogSpider(Spider):
  3766. name, start_urls = 'blogspider', ['http://blog.scrapinghub.com']
  3767.  
  3768. def parse(self, response):
  3769. return [Post(title=e.extract()) for e in response.css("h2 a::text")]
  3770.  
  3771. scrapy runspider myspider.py
  3772.  
  3773. django [重量级web框架]
  3774.  
  3775. bottle [轻量级的Web框架]
  3776.  
  3777. 10 例子
  3778.  
  3779. 小算法
  3780.  
  3781. 斐波那契
  3782. #将函数结果作为列表可用于循环
  3783. def fab(max):
  3784. n, a, b = 0, 0, 1
  3785. while n < max:
  3786. yield b
  3787. a, b = b, a + b
  3788. n = n + 1
  3789. for n in fab(5):
  3790. print n
  3791.  
  3792. 乘法口诀
  3793.  
  3794. #!/usr/bin/python
  3795. for i in range(1,10):
  3796. for j in range(1,i+1):
  3797. print j,'*',i,'=',j*i,
  3798. else:
  3799. print ''
  3800.  
  3801. 最小公倍数
  3802.  
  3803. # 1-70的最小公倍数
  3804. def c(m,n):
  3805. a1=m
  3806. b1=n
  3807. r=n%m
  3808. while r!=0:
  3809. n=m
  3810. m=r
  3811. r=n%m
  3812. return (a1*b1)/m
  3813. d=1
  3814. for i in range(3,71,2):
  3815. d = c(d,i)
  3816. print d
  3817.  
  3818. 排序算法
  3819.  
  3820. 插入排序
  3821. def insertion_sort(sort_list):
  3822. iter_len = len(sort_list)
  3823. if iter_len < 2:
  3824. return sort_list
  3825. for i in range(1, iter_len):
  3826. key = sort_list[i]
  3827. j = i - 1
  3828. while j>=0 and sort_list[j]>key:
  3829. sort_list[j+1] = sort_list[j]
  3830. j -= 1
  3831. sort_list[j+1] = key
  3832. return sort_list
  3833.  
  3834. 选择排序
  3835. def selection_sort(sort_list):
  3836. iter_len = len(sort_list)
  3837. if iter_len < 2:
  3838. return sort_list
  3839. for i in range(iter_len-1):
  3840. smallest = sort_list[i]
  3841. location = i
  3842. for j in range(i, iter_len):
  3843. if sort_list[j] < smallest:
  3844. smallest = sort_list[j]
  3845. location = j
  3846. if i != location:
  3847. sort_list[i], sort_list[location] = sort_list[location], sort_list[i]
  3848. return sort_list
  3849.  
  3850. 冒泡排序算法
  3851. def bubblesort(numbers):
  3852. for j in range(len(numbers)-1,-1,-1):
  3853. for i in range(j):
  3854. if numbers[i]>numbers[i+1]:
  3855. numbers[i],numbers[i+1] = numbers[i+1],numbers[i]
  3856. print(i,j)
  3857. print(numbers)
  3858.  
  3859. 二分算法
  3860.  
  3861. #python 2f.py 123456789 4
  3862. # list('123456789') = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
  3863. #!/usr/bin/env python
  3864. import sys
  3865.  
  3866. def search2(a,m):
  3867. low = 0
  3868. high = len(a) - 1
  3869. while(low <= high):
  3870. mid = (low + high)/2
  3871. midval = a[mid]
  3872.  
  3873. if midval < m:
  3874. low = mid + 1
  3875. elif midval > m:
  3876. high = mid - 1
  3877. else:
  3878. print mid
  3879. return mid
  3880. print -1
  3881. return -1
  3882.  
  3883. if __name__ == "__main__":
  3884. a = [int(i) for i in list(sys.argv[1])]
  3885. m = int(sys.argv[2])
  3886. search2(a,m)
  3887.  
  3888. 将字典中所有time去掉
  3889.  
  3890. a={'version01': {'nba': {'timenba': 'valuesasdfasdf', 'nbanbac': 'vtimefasdf', 'userasdf': 'vtimasdf'}}}
  3891. eval(str(a).replace("time",""))
  3892.  
  3893. PIL图像处理
  3894.  
  3895. import Image
  3896. im = Image.open("j.jpg") # 打开图片
  3897. print im.format, im.size, im.mode # 打印图像格式、像素宽和高、模式
  3898. # JPEG (440, 330) RGB
  3899. im.show() # 显示最新加载图像
  3900. box = (100, 100, 200, 200)
  3901. region = im.crop(box) # 从图像中提取出某个矩形大小的图像
  3902.  
  3903. 图片等比缩小
  3904.  
  3905. # -*- coding: cp936 -*-
  3906. import Image
  3907. import glob, os
  3908.  
  3909. #图片批处理
  3910. def timage():
  3911. for files in glob.glob('D:\\1\\*.JPG'):
  3912. filepath,filename = os.path.split(files)
  3913. filterame,exts = os.path.splitext(filename)
  3914. #输出路径
  3915. opfile = r'D:\\22\\'
  3916. #判断opfile是否存在,不存在则创建
  3917. if (os.path.isdir(opfile)==False):
  3918. os.mkdir(opfile)
  3919. im = Image.open(files)
  3920. w,h = im.size
  3921. #im_ss = im.resize((400,400))
  3922. #im_ss = im.convert('P')
  3923. im_ss = im.resize((int(w*0.12), int(h*0.12)))
  3924. im_ss.save(opfile+filterame+'.jpg')
  3925.  
  3926. if __name__=='__main__':
  3927. timage()
  3928.  
  3929. 取系统返回值赋给序列
  3930.  
  3931. cmd = os.popen("df -Ph|awk 'NR!=1{print $5}'").readlines();
  3932. cmd = os.popen('df -h').read().split('\n')
  3933. cmd = os.popen('lo 2>&1').read()
  3934.  
  3935. #取磁盘使用空间
  3936. import commands
  3937. df = commands.getoutput("df -hP")
  3938. [ x.split()[4] for x in df.split("\n") ]
  3939. [ (x.split()[0],x.split()[4]) for x in df.split("\n") if x.split()[4].endswith("%") ]
  3940.  
  3941. 打印表格
  3942.  
  3943. map = [["a","b","c"],
  3944. ["d","e","f"],
  3945. ["g","h","i"]]
  3946. def print_board():
  3947. for i in range(0,3):
  3948. for j in range(0,3):
  3949. print "|",map[i][j],
  3950. #if j != 2:
  3951. print '|'
  3952.  
  3953. 生成html文件表格
  3954.  
  3955. log_file = file('check.html', 'w')
  3956. log_file.write("""
  3957. <!DOCTYPE HTML>
  3958. <html lang="utr-8">
  3959. <head>
  3960. <meta charset="UTF-8">
  3961. <title></title>
  3962. </head>
  3963. <body>
  3964. <table align='center' border='0' cellPadding='0' style='font-size:24px;'><tr ><td>状态统计</td></tr></table>
  3965. <style>.font{font-size:13px}</style>
  3966. <table align='center' border='1' borderColor=gray cellPadding=3 width=1350 class='font'>
  3967. <tr style='background-color:#666666'>
  3968. <th width=65>IP</th>
  3969. <th width=65>状态</th>
  3970. </tr>
  3971. """)
  3972. for i in list:
  3973. log_file.write('<tr><td>%s</td><td>%s</td></tr>\n' %(i.split()[0],i.split()[1]) )
  3974. log_file.write("""
  3975. </table>
  3976. </body>
  3977. </html>
  3978. """)
  3979. log_file.flush()
  3980. log_file.close()
  3981.  
  3982. 井字游戏
  3983.  
  3984. #!/usr/bin/python
  3985. # http://www.admin10000.com/document/2506.html
  3986. def print_board():
  3987. for i in range(0,3):
  3988. for j in range(0,3):
  3989. print map[2-i][j],
  3990. if j != 2:
  3991. print "|",
  3992. print ""
  3993.  
  3994. def check_done():
  3995. for i in range(0,3):
  3996. if map[i][0] == map[i][1] == map[i][2] != " " \
  3997. or map[0][i] == map[1][i] == map[2][i] != " ":
  3998. print turn, "won!!!"
  3999. return True
  4000.  
  4001. if map[0][0] == map[1][1] == map[2][2] != " " \
  4002. or map[0][2] == map[1][1] == map[2][0] != " ":
  4003. print turn, "won!!!"
  4004. return True
  4005.  
  4006. if " " not in map[0] and " " not in map[1] and " " not in map[2]:
  4007. print "Draw"
  4008. return True
  4009.  
  4010. return False
  4011.  
  4012. turn = "X"
  4013. map = [[" "," "," "],
  4014. [" "," "," "],
  4015. [" "," "," "]]
  4016. done = False
  4017.  
  4018. while done != True:
  4019. print_board()
  4020.  
  4021. print turn, "'s turn"
  4022. print
  4023.  
  4024. moved = False
  4025. while moved != True:
  4026. print "Please select position by typing in a number between 1 and 9, see below for which number that is which position..."
  4027. print "7|8|9"
  4028. print "4|5|6"
  4029. print "1|2|3"
  4030. print
  4031.  
  4032. try:
  4033. pos = input("Select: ")
  4034. if pos <=9 and pos >=1:
  4035. Y = pos/3
  4036. X = pos%3
  4037. if X != 0:
  4038. X -=1
  4039. else:
  4040. X = 2
  4041. Y -=1
  4042.  
  4043. if map[Y][X] == " ":
  4044. map[Y][X] = turn
  4045. moved = True
  4046. done = check_done()
  4047.  
  4048. if done == False:
  4049. if turn == "X":
  4050. turn = "O"
  4051. else:
  4052. turn = "X"
  4053.  
  4054. except:
  4055. print "You need to add a numeric value"
  4056.  
  4057. 网段划分
  4058.  
  4059. 题目
  4060. 192.168.1
  4061. 192.168.3
  4062. 192.168.2
  4063. 172.16.3
  4064. 192.16.1
  4065. 192.16.2
  4066. 192.16.3
  4067. 10.0.4
  4068.  
  4069. 输出结果:
  4070. 192.16.1-192.16.3
  4071. 192.168.1-192.168.3
  4072. 172.16.3
  4073. 10.0.4
  4074.  
  4075. 答案
  4076. #!/usr/bin/python
  4077.  
  4078. f = file('a.txt')
  4079. c = f.readlines()
  4080. dic={}
  4081.  
  4082. for i in c:
  4083. a=i.strip().split('.')
  4084. if a[0]+'.'+a[1] in dic.keys():
  4085. key=dic["%s.%s" %(a[0],a[1])]
  4086. else:
  4087. key=[]
  4088. key.append(a[2])
  4089. dic[a[0]+'.'+a[1]]=sorted(key)
  4090.  
  4091. for x,y in dic.items():
  4092. if y[0] == y[-1]:
  4093. print '%s.%s' %(x,y[0])
  4094. else:
  4095. print '%s.%s-%s.%s' %(x,y[0],x,y[-1])
  4096.  
  4097. 统计日志IP
  4098. # 打印出独立IP,并统计独立IP数
  4099. 219.140.190.130 - - [23/May/2006:08:57:59 +0800] "GET /fg172.exe HTTP/1.1" 200 2350253
  4100. 221.228.143.52 - - [23/May/2006:08:58:08 +0800] "GET /fg172.exe HTTP/1.1" 206 719996
  4101. 221.228.143.52 - - [23/May/2006:08:58:08 +0800] "GET /fg172.exe HTTP/1.1" 206 713242
  4102.  
  4103. #!/usr/bin/python
  4104. dic={}
  4105. a=open("a").readlines()
  4106. for i in a:
  4107. ip=i.strip().split()[0]
  4108. if ip in dic.keys():
  4109. dic[ip] = dic[ip] + 1
  4110. else:
  4111. dic[ip] = 1
  4112. for x,y in dic.items():
  4113. print x," ",y
  4114.  
  4115. 不定期更新,更新下载地址:
  4116. http://hi.baidu.com/quanzhou722/item/cf4471f8e23d3149932af2a7
  4117.  
  4118. 请勿删除信息,植入广告,抵制不道德行为。

  

Python实例手册的更多相关文章

  1. (转)Python实例手册

    原文地址:http://hi.baidu.com/quanzhou722/item/cf4471f8e23d3149932af2a7 实在是太好的资料了,不得不转 python实例手册 #encodi ...

  2. 转载 python实例手册

    python实例手册 #encoding:utf8# 设定编码-支持中文 0说明 手册制作: 雪松 更新日期: 2013-12-19 欢迎系统运维加入Q群: 198173206 # 加群请回答问题 请 ...

  3. 【转载】python实例手册

    今天写爬虫的时候遇到了问题,在网上不停地查找资料,居然碰到两篇好文章: 1.python实例手册   作者:没头脑的土豆 另一篇在这:shell实例手册 python实例手册 #encoding:ut ...

  4. (转)shell实例手册

    原文地址:http://hi.baidu.com/quanzhou722/item/f4a4f3c9eb37f02d46d5c0d9 实在是太好的资料了,不得不转 shell实例手册 0说明{ 手册制 ...

  5. 【转载】shell实例手册

    原文地址:shell实例手册  作者:没头脑的土豆 shell实例手册 0说明{ 手册制作: 雪松 更新日期: -- 欢迎系统运维加入Q群: 请使用"notepad++"打开此文档 ...

  6. 《Python学习手册》读书笔记

    之前为了编写一个svm分词的程序而简单学了下Python,觉得Python很好用,想深入并系统学习一下,了解一些机制,因此开始阅读<Python学习手册(第三版)>.如果只是想快速入门,我 ...

  7. 《Python学习手册》读书笔记【转载】

    转载:http://www.cnblogs.com/wuyuegb2312/archive/2013/02/26/2910908.html 之前为了编写一个svm分词的程序而简单学了下Python,觉 ...

  8. 《python参考手册(第四版)》【PDF】下载

    <python参考手册(第四版)>[PDF]下载链接: https://u253469.pipipan.com/fs/253469-230382222 内容介绍 本书是权威的Python语 ...

  9. (转) shell实例手册

    shell实例手册 1文件{ touch file              # 创建空白文件rm -rf 目录名           # 不提示删除非空目录(-r:递归删除 -f强制)dos2uni ...

随机推荐

  1. day2-心得

    模块sys和os #!/usr/bin/env python # -*- coding: utf-8 -*- import sys sys.path #打印环境变量 print(sys.argv) # ...

  2. Flask之测试与部署

    5.1 蓝图Blueprint 为什么学习蓝图? 我们学习Flask框架,是从写单个文件,执行hello world开始的.我们在这单个文件中可以定义路由.视图函数.定义模型等等.但这显然存在一个问题 ...

  3. jenkins 学习记录2

    主题 在之前的学习中(http://www.cnblogs.com/abcwt112/p/6274575.html)我已经学会怎么打包了..这篇文章记录分享我学习如何利用jenkins将打完的包发布到 ...

  4. java中的 equals 与 ==

    Java中的"=="永远比较的是两个对象是否是同一个对象(引用指向同一块内存就是同一个对象) Java中equals() 在使用必须与类挂上钩,不能单独使用.有的人这样理解&quo ...

  5. django 定时脚本

    python 第三方定时执行 from datetime import datetime import time import os from apscheduler.schedulers.backg ...

  6. Sprite Editor

    [Sprite Editor] 在Unity3D中,一个图片可以有多种类型(如下图).对于2D游戏开发,最常用的类型就是Sprite. 下图是Sprite Texture的属性,Packing Tag ...

  7. 在cmd中 操作 数据库 MySQL 的一些命令

    环境变量配置配置好以后, 打开cmd 连接:mysql -h主机地址 -u用户名 -p用户密码 (注:u与root可以不用加空格,其它也一样) 断开:exit (回车) 创建授权:grant sele ...

  8. 求正整数n的所有因子

    因子的概念:假如整数n除以m,结果是无余数的整数,那么我们称m就是n的因子. 需要注意的是,唯有被除数,除数,商皆为整数,余数为零时,此关系才成立.反过来说,我们称n为m的倍数. 求一个正整数n的所有 ...

  9. php常用 随机数

    <?php $number =range(1,50); //shuffle 将数组顺序随即打乱. shuffle($number); print_r($number); echo '<br ...

  10. 对C#泛型讲的很好的一篇文章

    请参考 https://www.cnblogs.com/kissdodog/archive/2013/01/27/2879185.html