原文地址:http://hi.baidu.com/quanzhou722/item/cf4471f8e23d3149932af2a7

实在是太好的资料了,不得不转

  1. python实例手册
  2.  
  3. #encoding:utf8
  4. # 设定编码-支持中文
  5.  
  6. 0说明
  7.  
  8. 手册制作: 雪松
  9. 更新日期: 2013-12-19
  10. 欢迎系统运维加入Q群: 198173206 # 加群请回答问题
  11.  
  12. 请使用"notepad++"打开此文档,"alt+0"将函数折叠后方便查阅
  13. 请勿删除信息,转载请说明出处,抵制不道德行为。
  14. 错误在所难免,还望指正!
  15.  
  16. # python实例手册下载地址:
  17. http://hi.baidu.com/quanzhou722/item/cf4471f8e23d3149932af2a7
  18.  
  19. # shell实例手册最新下载地址:
  20. http://hi.baidu.com/quanzhou722/item/f4a4f3c9eb37f02d46d5c0d9
  21.  
  22. # LazyManage运维批量管理软件下载(shell):
  23. http://hi.baidu.com/quanzhou722/item/4ccf7e88a877eaccef083d1a
  24.  
  25. 查看帮助
  26. import os
  27. for i in dir(os):
  28. print i # 模块的方法
  29. help(os.path) # 方法的帮助
  30.  
  31. 变量
  32.  
  33. r=r'\n' # 输出时原型打印
  34. u=u'中文' # 定义为unicode编码
  35. global x # 全局变量
  36. a = 0 or 2 or 1 # 布尔运算赋值,a值为True既不处理后面,a值为2. None、字符串''、空元组()、空列表[],空字典{}、0、空字符串都是false
  37. name = raw_input("input:").strip() # 输入字符串变量
  38. num = int(raw_input("input:").strip()) # 输入字符串str转为int型
  39. locals() # 所有局部变量组成的字典
  40. locals().values() # 所有局部变量值的列表
  41. os.popen("date -d @{0} +'%Y-%m-%d %H:%M:%S'".format(12)).read() # 特殊情况引用变量 {0} 代表第一个参数
  42.  
  43. 打印
  44.  
  45. # 字符串 %s 整数 %d 浮点 %f 原样打印 %r
  46. print '字符串: %s 整数: %d 浮点: %f 原样打印: %r' % ('aa',2,1.0,'r')
  47. print 'abc', # 有逗号,代表不换行打印,在次打印会接着本行打印
  48.  
  49. 列表
  50. # 列表元素的个数最多 536870912
  51. shoplist = ['apple', 'mango', 'carrot', 'banana']
  52. shoplist[2] = 'aa'
  53. del shoplist[0]
  54. shoplist.insert('','www')
  55. shoplist.append('aaa')
  56. shoplist[::-1] # 倒着打印 对字符翻转串有效
  57.  
  58. 元组
  59.  
  60. # 不可变
  61. zoo = ('wolf', 'elephant', 'penguin')
  62.  
  63. 字典
  64.  
  65. ab = { 'Swaroop' : 'swaroopch@byteofpython.info',
  66. 'Larry' : 'larry@wall.org',
  67. }
  68. ab['c'] = 80 # 添加字典元素
  69. del ab['Larry'] # 删除字典元素
  70. ab.keys() # 查看所有键值
  71. ab.values() # 打印所有值
  72. ab.has_key('a') # 查看键值是否存在
  73. ab.items() # 返回整个字典列表
  74.  
  75. 流程结构
  76.  
  77. if判断
  78.  
  79. # 布尔值操作符 and or not 实现多重判断
  80. if a == b:
  81. print '=='
  82. elif a < b:
  83. print b
  84. else:
  85. print a
  86. fi
  87.  
  88. while循环
  89.  
  90. while True:
  91. if a == b:
  92. print "=="
  93. break
  94. print "!="
  95. else:
  96. print 'over'
  97.  
  98. count=0
  99. while(count<9):
  100. print count
  101. count += 1
  102.  
  103. for循环
  104.  
  105. sorted() # 返回一个序列(列表)
  106. zip() # 返回一个序列(列表)
  107. enumerate() # 返回迭代器(类似序列)
  108. reversed() # 反序迭代器对象
  109. dict.iterkeys() # 通过键迭代
  110. dict.itervalues() # 通过值迭代
  111. dict.iteritems() # 通过键-值对迭代
  112. randline() # 文件迭代
  113. iter(obj) # 得到obj迭代器 检查obj是不是一个序列
  114. iter(a,b) # 重复调用a,直到迭代器的下一个值等于b
  115. for i in range(1, 5):
  116. print i
  117. else:
  118. print 'over'
  119.  
  120. list = ['a','b','c','b']
  121. for i in range(len(list)):
  122. print list[i]
  123. for x, Lee in enumerate(list):
  124. print "%d %s Lee" % (x+1,Lee)
  125.  
  126. 流程结构简写
  127.  
  128. [ i * 2 for i in [8,-2,5]]
  129. [16,-4,10]
  130. [ i for i in range(8) if i %2 == 0 ]
  131. [0,2,4,6]
  132.  
  133. tab补全
  134.  
  135. # vim /usr/lib/python2.7/dist-packages/tab.py
  136. # python startup file
  137. import sys
  138. import readline
  139. import rlcompleter
  140. import atexit
  141. import os
  142. # tab completion
  143. readline.parse_and_bind('tab: complete')
  144. # history file
  145. histfile = os.path.join(os.environ['HOME'], '.pythonhistory')
  146.  
  147. 函数
  148.  
  149. def printMax(a, b = 1):
  150. if a > b:
  151. print a
  152. return a
  153. else:
  154. print b
  155. return b
  156. x = 5
  157. y = 7
  158. printMax(x, y)
  159.  
  160. 模块
  161.  
  162. # Filename: mymodule.py
  163. def sayhi():
  164. print 'mymodule'
  165. version = '0.1'
  166.  
  167. # 导入模块
  168. import mymodule
  169. from mymodule import sayhi, version
  170. # 使用模块中函数
  171. mymodule.sayhi()
  172.  
  173. 取参数
  174.  
  175. import sys
  176. for i in sys.argv:
  177. print i
  178.  
  179. 对象的方法
  180.  
  181. class Person:
  182. # 实例化初始化的方法
  183. def __init__(self, name ,age):
  184. self.name = name
  185. self.age = age
  186. print self.name
  187. # 有self此函数为方法
  188. def sayHi(self):
  189. print 'Hello, my name is', self.name
  190. #对象消逝的时候被调用
  191. def __del__(self):
  192. print 'over'
  193. # 实例化对象
  194. p = Person('Swaroop')
  195. # 使用对象方法
  196. p.sayHi()
  197. # 继承
  198. class Teacher(Person):
  199. def __init__(self, name, age, salary):
  200. Person.__init__(self, name, age)
  201. self.salary = salary
  202. print '(Initialized Teacher: %s)' % self.name
  203. def tell(self):
  204. Person.tell(self)
  205. print 'Salary: "%d"' % self.salary
  206. t = Teacher('Mrs. Shrividya', 40, 30000)
  207.  
  208. 文件处理
  209.  
  210. # 模式: 读'r' 写'w' 追加'a' 读写'r+' 二进制文件'b' 'rb','wb','rb+'
  211.  
  212. 写文件
  213. f = file('poem.txt', 'w')
  214. f.write("string")
  215. f.write(str(i))
  216. f.flush()
  217. f.close()
  218.  
  219. 读文件
  220. f = file('/etc/passwd','r')
  221. while True:
  222. line = f.readline() # 返回一行
  223. if len(line) == 0:
  224. break
  225. x = line.split(":") # 冒号分割定义序列
  226. #x = [ x for x in line.split(":") ] # 冒号分割定义序列
  227. #x = [ x.split("/") for x in line.split(":") ] # 先冒号分割,在/分割 打印x[6][1]
  228. print x[6],"\n",
  229. f.close()
  230.  
  231. 读文件2
  232. f = file('/etc/passwd')
  233. c = f.readlines() # 读入所以文件内容,可反复读取,大文件时占用内存较大
  234. for line in c:
  235. print line.rstrip(),
  236. f.close()
  237.  
  238. 读文件3
  239. for i in open('b.txt'): # 直接读取也可迭代,并有利于大文件读取,但不可反复读取
  240. print i,
  241.  
  242. 追加日志
  243. log = open('/home/peterli/xuesong','a')
  244. print >> log,'faaa'
  245. log.close()
  246.  
  247. with读文件
  248. with open('a.txt') as f:
  249. # print f.read() # 打印所有内容为字符串
  250. print f.readlines() # 打印所有内容按行分割的列表
  251.  
  252. csv读配置文件
  253. 192.168.1.5,web # 配置文件按逗号分割
  254. list = csv.reader(file('a.txt'))
  255. for line in list:
  256. print line # ['192.168.1.5', 'web']
  257.  
  258. 触发异常
  259.  
  260. class ShortInputException(Exception):
  261. '''A user-defined exception class.'''
  262. def __init__(self, length, atleast):
  263. Exception.__init__(self)
  264. self.length = length
  265. self.atleast = atleast
  266. try:
  267. s = raw_input('Enter something --> ')
  268. if len(s) < 3:
  269. raise ShortInputException(len(s), 3)
  270. except EOFError:
  271. print '\nWhy did you do an EOF on me?'
  272. except ShortInputException, x:
  273. print 'ShortInputException: The input was of length %d, \
  274. was expecting at least %d' % (x.length, x.atleast)
  275. else:
  276. print 'No exception was raised.'
  277.  
  278. 内建函数
  279.  
  280. dir(sys) # 显示对象的属性
  281. help(sys) # 交互式帮助
  282. int(obj) # 转型为整形
  283. str(obj) # 转为字符串
  284. len(obj) # 返回对象或序列长度
  285. open(file,mode) # 打开文件 #mode (r 读,w 写, a追加)
  286. range(0,3) # 返回一个整形列表
  287. raw_input("str:") # 等待用户输入
  288. type(obj) # 返回对象类型
  289. abs(-22) # 绝对值
  290. random # 随机数
  291. random.randrange(9) # 9以内随机数
  292. choice() # 随机返回给定序列的一个元素
  293. divmod(x,y) # 函数完成除法运算,返回商和余数。
  294. isinstance(object,int) # 测试对象类型 int
  295. round(x[,n]) # 函数返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数
  296. xrange() # 函数与range()类似,但xrnage()并不创建列表,而是返回一个xrange对象
  297. xrange([lower,]stop[,step])
  298. strip() # 是去掉字符串两端多于空格,该句是去除序列中的所有字串两端多余的空格
  299. del # 删除列表里面的数据
  300. cmp(x,y) # 比较两个对象 #根据比较结果返回一个整数,如果x<y,则返回-1;如果x>y,则返回1,如果x==y则返回0
  301. max() # 字符串中最大的字符
  302. min() # 字符串中最小的字符
  303. sorted() # 对序列排序
  304. reversed() # 对序列倒序
  305. enumerate() # 返回索引位置和对应的值
  306. sum() # 总和
  307. list() # 变成列表可用于迭代
  308. tuple() # 变成元组可用于迭代 #一旦初始化便不能更改的数据结构,速度比list快
  309. zip() # 返回一个列表
  310. >>> s = ['','','']
  311. >>> t = ['aa','bb','cc']
  312. >>> zip(s,t)
  313. [('', 'aa'), ('', 'bb'), ('', 'cc')]
  314.  
  315. 字符串相关模块
  316.  
  317. string # 字符串操作相关函数和工具
  318. re # 正则表达式
  319. struct # 字符串和二进制之间的转换
  320. c/StringIO # 字符串缓冲对象,操作方法类似于file对象
  321. base64 # Base16\32\64数据编解码
  322. codecs # 解码器注册和基类
  323. crypt # 进行单方面加密
  324. difflib # 找出序列间的不同
  325. hashlib # 多种不同安全哈希算法和信息摘要算法的API
  326. hma # HMAC信息鉴权算法的python实现
  327. md5 # RSA的MD5信息摘要鉴权
  328. rotor # 提供多平台的加解密服务
  329. sha # NIAT的安全哈希算法SHA
  330. stringprep # 提供用于IP协议的Unicode字符串
  331. textwrap # 文本包装和填充
  332. unicodedate # unicode数据库
  333.  
  334. 列表类型内建函数
  335.  
  336. list.append(obj) # 向列表中添加一个对象obj
  337. list.count(obj) # 返回一个对象obj在列表中出现的次数
  338. list.extend(seq) # 把序列seq的内容添加到列表中
  339. list.index(obj,i=0,j=len(list)) # 返回list[k] == obj 的k值,并且k的范围在i<=k<j;否则异常
  340. list.insert(index.obj) # 在索引量为index的位置插入对象obj
  341. list.pop(index=-1) # 删除并返回指定位置的对象,默认是最后一个对象
  342. list.remove(obj) # 从列表中删除对象obj
  343. list.reverse() # 原地翻转列表
  344. list.sort(func=None,key=None,reverse=False) # 以指定的方式排序列表中成员,如果func和key参数指定,则按照指定的方式比较各个元素,如果reverse标志被置为True,则列表以反序排列
  345.  
  346. 序列类型操作符
  347.  
  348. seq[ind] # 获取下标为ind的元素
  349. seq[ind1:ind2] # 获得下标从ind1到ind2的元素集合
  350. seq * expr # 序列重复expr次
  351. seq1 + seq2 # 连接seq1和seq2
  352. obj in seq # 判断obj元素是否包含在seq中
  353. obj not in seq # 判断obj元素是否不包含在seq中
  354.  
  355. 字符串类型内建方法
  356.  
  357. string.expandtabs(tabsize=8) # tab符号转为空格 #默认8个空格
  358. string.endswith(obj,beg=0,end=len(staring)) # 检测字符串是否已obj结束,如果是返回True #如果beg或end指定检测范围是否已obj结束
  359. string.count(str,beg=0,end=len(string)) # 检测str在string里出现次数
  360. string.find(str,beg=0,end=len(string)) # 检测str是否包含在string中
  361. string.index(str,beg=0,end=len(string)) # 检测str不在string中,会报异常
  362. string.isalnum() # 如果string至少有一个字符并且所有字符都是字母或数字则返回True
  363. string.isalpha() # 如果string至少有一个字符并且所有字符都是字母则返回True
  364. string.isnumeric() # 如果string只包含数字字符,则返回True
  365. string.isspace() # 如果string包含空格则返回True
  366. string.isupper() # 字符串都是大写返回True
  367. string.islower() # 字符串都是小写返回True
  368. string.lower() # 转换字符串中所有大写为小写
  369. string.upper() # 转换字符串中所有小写为大写
  370. string.lstrip() # 去掉string左边的空格
  371. string.rstrip() # 去掉string字符末尾的空格
  372. string.replace(str1,str2,num=string.count(str1)) # 把string中的str1替换成str2,如果num指定,则替换不超过num次
  373. string.startswith(obj,beg=0,end=len(string)) # 检测字符串是否以obj开头
  374. string.zfill(width) # 返回字符长度为width的字符,原字符串右对齐,前面填充0
  375. string.isdigit() # 只包含数字返回True
  376. string.split("分隔符") # 把string切片成一个列表
  377. ":".join(string.split()) # 以:作为分隔符,将所有元素合并为一个新的字符串
  378.  
  379. 序列类型相关的模块
  380.  
  381. array # 一种受限制的可变序列类型,元素必须相同类型
  382. copy # 提供浅拷贝和深拷贝的能力
  383. operator # 包含函数调用形式的序列操作符 operator.concat(m,n)
  384. re # perl风格的正则表达式查找
  385. StringIO # 把长字符串作为文件来操作 如: read() \ seek()
  386. cStringIO # 把长字符串作为文件来操,作速度更快,但不能被继承
  387. textwrap # 用作包装/填充文本的函数,也有一个类
  388. types # 包含python支持的所有类型
  389. collections # 高性能容器数据类型
  390.  
  391. 字典相关函数
  392.  
  393. dict([container]) # 创建字典的工厂函数。提供容器类(container),就用其中的条目填充字典
  394. len(mapping) # 返回映射的长度(键-值对的个数)
  395. hash(obj) # 返回obj哈希值,判断某个对象是否可做一个字典的键值
  396.  
  397. 字典内建方法
  398.  
  399. dict.clear() # 删除字典中所有元素
  400. dict copy() # 返回字典(浅复制)的一个副本
  401. dict.fromkeys(seq,val=None) # 创建并返回一个新字典,以seq中的元素做该字典的键,val做该字典中所有键对的初始值
  402. dict.get(key,default=None) # 对字典dict中的键key,返回它对应的值value,如果字典中不存在此键,则返回default值
  403. dict.has_key(key) # 如果键在字典中存在,则返回True 用in和not in代替
  404. dicr.items() # 返回一个包含字典中键、值对元组的列表
  405. dict.keys() # 返回一个包含字典中键的列表
  406. dict.iter() # 方法iteritems()、iterkeys()、itervalues()与它们对应的非迭代方法一样,不同的是它们返回一个迭代子,而不是一个列表
  407. dict.pop(key[,default]) # 和方法get()相似.如果字典中key键存在,删除并返回dict[key]
  408. dict.setdefault(key,default=None) # 和set()相似,但如果字典中不存在key键,由dict[key]=default为它赋值
  409. dict.update(dict2) # 将字典dict2的键值对添加到字典dict
  410. dict.values() # 返回一个包含字典中所有值得列表
  411.  
  412. 集合方法
  413.  
  414. s.issubset(t) # 如果s是t的子集,则返回True s <= t
  415. s.issuperset(t) # 如果t是s的超集,则返回True s >= t
  416. s.union(t) # 合并操作;返回一个新集合,该集合是s和t的并集 s | t
  417. s.intersection(t) # 交集操作;返回一个新集合,该集合是s和t的交集 s & t
  418. s.difference(t) # 返回一个新集合,改集合是s的成员,但不是t的成员 s - t
  419. s.symmetric_difference(t) # 返回一个新集合,该集合是s或t的成员,但不是s和t共有的成员 s ^ t
  420. s.copy() # 返回一个新集合,它是集合s的浅复制
  421. obj in s # 成员测试;obj是s中的元素 返回True
  422. obj not in s # 非成员测试:obj不是s中元素 返回True
  423. s == t # 等价测试 是否具有相同元素
  424. s != t # 不等价测试
  425. s < t # 子集测试;s!=t且s中所有元素都是t的成员
  426. s > t # 超集测试;s!=t且t中所有元素都是s的成员
  427.  
  428. 可变集合方法
  429.  
  430. s.update(t) # 用t中的元素修改s,s现在包含s或t的成员 s |= t
  431. s.intersection_update(t) # s中的成员是共用属于s和t的元素 s &= t
  432. s.difference_update(t) # s中的成员是属于s但不包含在t中的元素 s -= t
  433. s.symmetric_difference_update(t) # s中的成员更新为那些包含在s或t中,但不是s和t共有的元素 s ^= t
  434. s.add(obj) # 在集合s中添加对象obj
  435. s.remove(obj) # 从集合s中删除对象obj;如果obj不是集合s中的元素(obj not in s),将引发KeyError错误
  436. s.discard(obj) # 如果obj是集合s中的元素,从集合s中删除对象obj
  437. s.pop() # 删除集合s中的任意一个对象,并返回它
  438. s.clear() # 删除集合s中的所有元素
  439.  
  440. 序列化
  441.  
  442. #!/usr/bin/python
  443. import cPickle
  444. obj = {'':['','',''],'':['','','']}
  445.  
  446. pkl_file = open('account.pkl','wb')
  447. cPickle.down(obj,pkl_file)
  448. pkl_file.close()
  449.  
  450. pkl_file = open('account.pkl','rb')
  451. account_list = cPickle.load(pkl_file)
  452. pkl_file.close()
  453.  
  454. 文件对象方法
  455.  
  456. file.close() # 关闭文件
  457. file.fileno() # 返回文件的描述符
  458. file.flush() # 刷新文件的内部缓冲区
  459. file.isatty() # 判断file是否是一个类tty设备
  460. file.next() # 返回文件的下一行,或在没有其他行时引发StopIteration异常
  461. file.read(size=-1) # 从文件读取size个字节,当未给定size或给定负值的时候,读取剩余的所有字节,然后作为字符串返回
  462. file.readline(size=-1) # 从文件中读取并返回一行(包括行结束符),或返回最大size个字符
  463. file.readlines(sizhint=0) # 读取文件的所有行作为一个列表返回
  464. file.xreadlines() # 用于迭代,可替换readlines()的一个更高效的方法
  465. file.seek(off, whence=0) # 在文件中移动文件指针,从whence(0代表文件起始,1代表当前位置,2代表文件末尾)偏移off字节
  466. file.tell() # 返回当前在文件中的位置
  467. file.truncate(size=file.tell()) # 截取文件到最大size字节,默认为当前文件位置
  468. file.write(str) # 向文件写入字符串
  469. file.writelines(seq) # 向文件写入字符串序列seq;seq应该是一个返回字符串的可迭代对象
  470.  
  471. 文件对象的属性
  472.  
  473. file.closed # 表示文件已被关闭,否则为False
  474. file.encoding # 文件所使用的编码 当unicode字符串被写入数据时,它将自动使用file.encoding转换为字节字符串;若file.encoding为None时使用系统默认编码
  475. file.mode # Access文件打开时使用的访问模式
  476. file.name # 文件名
  477. file.newlines # 未读取到行分隔符时为None,只有一种行分隔符时为一个字符串,当文件有多种类型的行结束符时,则为一个包含所有当前所遇到的行结束符的列表
  478. file.softspace # 为0表示在输出一数据后,要加上一个空格符,1表示不加
  479.  
  480. os模块
  481.  
  482. 文件处理
  483. mkfifo()/mknod() # 创建命名管道/创建文件系统节点
  484. remove()/unlink() # 删除文件
  485. rename()/renames() # 重命名文件
  486. *stat() # 返回文件信息
  487. symlink() # 创建符号链接
  488. utime() # 更新时间戳
  489. tmpfile() # 创建并打开('w+b')一个新的临时文件
  490. walk() # 遍历目录树下的所有文件名
  491.  
  492. 目录/文件夹
  493. chdir()/fchdir() # 改变当前工作目录/通过一个文件描述符改变当前工作目录
  494. chroot() # 改变当前进程的根目录
  495. listdir() # 列出指定目录的文件
  496. getcwd()/getcwdu() # 返回当前工作目录/功能相同,但返回一个unicode对象
  497. mkdir()/makedirs() # 创建目录/创建多层目录
  498. rmdir()/removedirs() # 删除目录/删除多层目录
  499.  
  500. 访问/权限
  501. saccess() # 检验权限模式
  502. chmod() # 改变权限模式
  503. chown()/lchown() # 改变owner和groupID功能相同,但不会跟踪链接
  504. umask() # 设置默认权限模式
  505.  
  506. 文件描述符操作
  507. open() # 底层的操作系统open(对于稳健,使用标准的内建open()函数)
  508. read()/write() # 根据文件描述符读取/写入数据 按大小读取文件部分内容
  509. dup()/dup2() # 复制文件描述符号/功能相同,但是复制到另一个文件描述符
  510.  
  511. 设备号
  512. makedev() # 从major和minor设备号创建一个原始设备号
  513. major()/minor() # 从原始设备号获得major/minor设备号
  514.  
  515. os.path模块
  516.  
  517. os.path.expanduser('~/.ssh/key') # 家目录下文件的全路径
  518.  
  519. 分隔
  520. basename() # 去掉目录路径,返回文件名
  521. dirname() # 去掉文件名,返回目录路径
  522. join() # 将分离的各部分组合成一个路径名
  523. spllt() # 返回(dirname(),basename())元组
  524. splitdrive() # 返回(drivename,pathname)元组
  525. splitext() # 返回(filename,extension)元组
  526.  
  527. 信息
  528. getatime() # 返回最近访问时间
  529. getctime() # 返回文件创建时间
  530. getmtime() # 返回最近文件修改时间
  531. getsize() # 返回文件大小(字节)
  532.  
  533. 查询
  534. exists() # 指定路径(文件或目录)是否存在
  535. isabs() # 指定路径是否为绝对路径
  536. isdir() # 指定路径是否存在且为一个目录
  537. isfile() # 指定路径是否存在且为一个文件
  538. islink() # 指定路径是否存在且为一个符号链接
  539. ismount() # 指定路径是否存在且为一个挂载点
  540. samefile() # 两个路径名是否指向同一个文件
  541.  
  542. 相关模块
  543. base64 # 提供二进制字符串和文本字符串间的编码/解码操作
  544. binascii # 提供二进制和ASCII编码的二进制字符串间的编码/解码操作
  545. bz2 # 访问BZ2格式的压缩文件
  546. csv # 访问csv文件(逗号分隔文件)
  547. csv.reader(open(file))
  548. filecmp # 用于比较目录和文件
  549. fileinput # 提供多个文本文件的行迭代器
  550. getopt/optparse # 提供了命令行参数的解析/处理
  551. glob/fnmatch # 提供unix样式的通配符匹配的功能
  552. gzip/zlib # 读写GNU zip(gzip)文件(压缩需要zlib模块)
  553. shutil # 提供高级文件访问功能
  554. c/StringIO # 对字符串对象提供类文件接口
  555. tarfile # 读写TAR归档文件,支持压缩文件
  556. tempfile # 创建一个临时文件
  557. uu # uu格式的编码和解码
  558. zipfile # 用于读取zip归档文件的工具
  559. environ['HOME'] # 查看系统环境变量
  560.  
  561. 子进程
  562. os.fork() # 创建子进程,并复制父进程所有操作 通过判断pid = os.fork() 的pid值,分别执行父进程与子进程操作,0为子进程
  563. os.wait() # 等待子进程结束
  564.  
  565. 跨平台os模块属性
  566.  
  567. linesep # 用于在文件中分隔行的字符串
  568. sep # 用来分隔文件路径名字的字符串
  569. pathsep # 用于分割文件路径的字符串
  570. curdir # 当前工作目录的字符串名称
  571. pardir # 父目录字符串名称
  572.  
  573. 异常
  574.  
  575. NameError: # 尝试访问一个未申明的变量
  576. ZeroDivisionError: # 除数为零
  577. SyntaxErrot: # 解释器语法错误
  578. IndexError: # 请求的索引元素超出序列范围
  579. KeyError: # 请求一个不存在的字典关键字
  580. IOError: # 输入/输出错误
  581. AttributeError: # 尝试访问未知的对象属性
  582. ImportError # 没有模块
  583. IndentationError # 语法缩进错误
  584. KeyboardInterrupt # ctrl+C
  585. SyntaxError # 代码语法错误
  586. ValueError # 值错误
  587. TypeError # 传入对象类型与要求不符合
  588.  
  589. 触发异常
  590.  
  591. raise exclass # 触发异常,从exclass生成一个实例(不含任何异常参数)
  592. raise exclass() # 触发异常,但现在不是类;通过函数调用操作符(function calloperator:"()")作用于类名生成一个新的exclass实例,同样也没有异常参数
  593. raise exclass, args # 触发异常,但同时提供的异常参数args,可以是一个参数也可以是元组
  594. raise exclass(args) # 触发异常,同上
  595. raise exclass, args, tb # 触发异常,但提供一个跟踪记录(traceback)对象tb供使用
  596. raise exclass,instance # 通过实例触发异常(通常是exclass的实例)
  597. raise instance # 通过实例触发异常;异常类型是实例的类型:等价于raise instance.__class__, instance
  598. raise string # 触发字符串异常
  599. raise string, srgs # 触发字符串异常,但触发伴随着args
  600. raise string,args,tb # 触发字符串异常,但提供一个跟踪记录(traceback)对象tb供使用
  601. raise # 重新触发前一个异常,如果之前没有异常,触发TypeError
  602.  
  603. 内建异常
  604.  
  605. BaseException # 所有异常的基类
  606. SystemExit # python解释器请求退出
  607. KeyboardInterrupt # 用户中断执行
  608. Exception # 常规错误的基类
  609. StopIteration # 迭代器没有更多的值
  610. GeneratorExit # 生成器发生异常来通知退出
  611. SystemExit # python解释器请求退出
  612. StandardError # 所有的内建标准异常的基类
  613. ArithmeticError # 所有数值计算错误的基类
  614. FloatingPointError # 浮点计算错误
  615. OverflowError # 数值运算超出最大限制
  616. AssertionError # 断言语句失败
  617. AttributeError # 对象没有这个属性
  618. EOFError # 没有内建输入,到达EOF标记
  619. EnvironmentError # 操作系统错误的基类
  620. IOError # 输入/输出操作失败
  621. OSError # 操作系统错误
  622. WindowsError # windows系统调用失败
  623. ImportError # 导入模块/对象失败
  624. KeyboardInterrupt # 用户中断执行(通常是ctrl+c)
  625. LookupError # 无效数据查询的基类
  626. IndexError # 序列中没有此索引(index)
  627. KeyError # 映射中没有这个键
  628. MemoryError # 内存溢出错误(对于python解释器不是致命的)
  629. NameError # 未声明/初始化对象(没有属性)
  630. UnboundLocalError # 访问未初始化的本地变量
  631. ReferenceError # 若引用试图访问已经垃圾回收了的对象
  632. RuntimeError # 一般的运行时错误
  633. NotImplementedError # 尚未实现的方法
  634. SyntaxError # python语法错误
  635. IndentationError # 缩进错误
  636. TabError # tab和空格混用
  637. SystemError # 一般的解释器系统错误
  638. TypeError # 对类型无效的操作
  639. ValueError # 传入无效的参数
  640. UnicodeError # Unicode相关的错误
  641. UnicodeDecodeError # Unicode解码时的错误
  642. UnicodeEncodeError # Unicode编码时的错误
  643. UnicodeTranslateError # Unicode转换时错误
  644. Warning # 警告的基类
  645. DeprecationWarning # 关于被弃用的特征的警告
  646. FutureWarning # 关于构造将来语义会有改变的警告
  647. OverflowWarning # 旧的关于自动提升为长整形的警告
  648. PendingDeprecationWarning # 关于特性将会被废弃的警告
  649. RuntimeWarning # 可疑的运行时行为的警告
  650. SyntaxWarning # 可疑的语法的警告
  651. UserWarning # 用户代码生成的警告
  652.  
  653. class MyException(Exception): # 继承Exception异常的类,定义自己的异常
  654. pass
  655. try: # 监控这里的异常
  656. option=int(raw_input('my age:'))
  657. if option != 28:
  658. raise MyException,'a1' #触发异常
  659. except MyException,a: # 异常处理代码
  660. print 'MyExceptionaa'
  661. print a # 打印异常处内容
  662. except: # 捕捉所有其它错误
  663. print 'except'
  664. finally: # 无论什么情况都会执行 关闭文件或断开连接等
  665. print 'finally'
  666. else: # 无任何异常 无法和finally同用
  667. print 'no Exception'
  668.  
  669. 函数式编程的内建函数
  670.  
  671. apply(func[,nkw][,kw]) # 用可选的参数来调用func,nkw为非关键字参数,kw为关键字参数;返回值是函数调用的返回值
  672. filter(func,seq) # 调用一个布尔函数func来迭代遍历每个seq中的元素;返回一个使func返回值为true的元素的序列
  673. map(func,seq1[,seq2]) # 将函数func作用于给定序列(s)的每个元素,并用一个列表来提供返回值;如果func为None,func表现为一个身份函数,返回一个含有每个序列中元素集合的n个元组的列表
  674. reduce(func,seq[,init]) # 将二元函数作用于seq序列的元素,每次携带一堆(先前的结果以及下一个序列元素),连续地将现有的结果和下一个值作用在获得的随后的结果上,最后减少我们的序列为一个单一的返回值;如果初始值init给定,第一个比较会是init和第一个序列元素而不是序列的头两个元素
  675.  
  676. re正则
  677.  
  678. compile(pattern,flags=0) # 对正则表达式模式pattern进行编译,flags是可选标识符,并返回一个regex对象
  679. match(pattern,string,flags=0) # 尝试用正则表达式模式pattern匹配字符串string,flags是可选标识符,如果匹配成功,则返回一个匹配对象;否则返回None
  680. search(pattern,string,flags=0) # 在字符串string中搜索正则表达式模式pattern的第一次出现,flags是可选标识符,如果匹配成功,则返回一个匹配对象;否则返回None
  681. findall(pattern,string[,flags]) # 在字符串string中搜索正则表达式模式pattern的所有(非重复)出现:返回一个匹配对象的列表 # pattern=u'\u4e2d\u6587' 代表UNICODE
  682. finditer(pattern,string[,flags]) # 和findall()相同,但返回的不是列表而是迭代器;对于每个匹配,该迭代器返回一个匹配对象
  683. split(pattern,string,max=0) # 根据正则表达式pattern中的分隔符把字符string分割为一个列表,返回成功匹配的列表,最多分割max次(默认所有)
  684. sub(pattern,repl,string,max=0) # 把字符串string中所有匹配正则表达式pattern的地方替换成字符串repl,如果max的值没有给出,则对所有匹配的地方进行替换(subn()会返回一个表示替换次数的数值)
  685. group(num=0) # 返回全部匹配对象(或指定编号是num的子组)
  686. groups() # 返回一个包含全部匹配的子组的元组(如果没匹配成功,返回一个空元组)
  687.  
  688. 例子
  689. re.findall(r'a[be]c','123abc456eaec789') # 返回匹配对象列表 ['abc', 'aec']
  690. re.match("^(1|2) *(.*) *abc$", str).group(2) # 取第二个标签
  691. re.match("^(1|2) *(.*) *abc$", str).groups() # 取所有标签
  692. re.sub('[abc]','A','alex') # 替换
  693. for i in re.finditer(r'\d+',s): # 迭代
  694. print i.group(),i.span() #
  695.  
  696. 搜索网页中UNICODE格式的中文
  697. QueryAdd='http://www.anti-spam.org.cn/Rbl/Query/Result'
  698. Ip='222.129.184.52'
  699. s = requests.post(url=QueryAdd, data={'IP':Ip})
  700. re.findall(u'\u4e2d\u56fd', s.text, re.S)
  701.  
  702. 多线程
  703.  
  704. thread
  705. start_new_thread(function,args kwargs=None) # 产生一个新的线程
  706. allocate_lock() # 分配一个LockType类型的锁对象
  707. exit() # 让线程退出
  708. acquire(wait=None) # 尝试获取锁对象
  709. locked() # 如果获取了锁对象返回True
  710. release() # 释放锁
  711.  
  712. thread例子
  713.  
  714. #!/usr/bin/env python
  715. #thread_test.py
  716. #不支持守护进程
  717. import thread
  718. from time import sleep,ctime
  719.  
  720. loops = [4,2]
  721.  
  722. def loop(nloop,nsec,lock):
  723. print 'start loop %s at:%s' % (nloop,ctime())
  724. sleep(nsec)
  725. print 'loop %s done at: %s' % (nloop, ctime())
  726. lock.release() # 分配已获得的锁,操作结束后释放相应的锁通知主线程
  727.  
  728. def main():
  729. print 'starting at:',ctime()
  730. locks = []
  731. nloops = range(len(loops))
  732.  
  733. for i in nloops:
  734. lock = thread.allocate_lock() # 创建一个锁
  735. lock.acquire() # 调用各个锁的acquire()函数获得锁
  736. locks.append(lock) # 把锁放到锁列表locks中
  737. for i in nloops:
  738. thread.start_new_thread(loop,(i,loops[i],locks[i])) # 创建线程
  739. for i in nloops:
  740. while locks[i].locked():pass # 等待全部解锁才继续运行
  741. print 'all DONE at:',ctime()
  742.  
  743. if __name__ == '__main__':
  744. main()
  745.  
  746. threading
  747. Thread # 表示一个线程的执行的对象
  748. start() # 开始线程的执行
  749. run() # 定义线程的功能的函数(一般会被子类重写)
  750. join(timeout=None) # 允许主线程等待线程结束,程序挂起,直到线程结束;如果给了timeout,则最多等待timeout秒.
  751. getName() # 返回线程的名字
  752. setName(name) # 设置线程的名字
  753. isAlive() # 布尔标志,表示这个线程是否还在运行中
  754. isDaemon() # 返回线程的daemon标志
  755. setDaemon(daemonic) # 后台线程,把线程的daemon标志设置为daemonic(一定要在调用start()函数前调用)
  756. # 默认主线程在退出时会等待所有子线程的结束。如果希望主线程不等待子线程,而是在退出时自动结束所有的子线程,就需要设置子线程为后台线程(daemon)
  757. Lock # 锁原语对象
  758. Rlock # 可重入锁对象.使单线程可以在此获得已获得了的锁(递归锁定)
  759. Condition # 条件变量对象能让一个线程停下来,等待其他线程满足了某个条件.如状态改变或值的改变
  760. Event # 通用的条件变量.多个线程可以等待某个事件的发生,在事件发生后,所有的线程都会被激活
  761. Semaphore # 为等待锁的线程提供一个类似等候室的结构
  762. BoundedSemaphore # 与Semaphore类似,只是不允许超过初始值
  763. Time # 与Thread相似,只是他要等待一段时间后才开始运行
  764. activeCount() # 当前活动的线程对象的数量
  765. currentThread() # 返回当前线程对象
  766. enumerate() # 返回当前活动线程的列表
  767. settrace(func) # 为所有线程设置一个跟踪函数
  768. setprofile(func) # 为所有线程设置一个profile函数
  769.  
  770. threading例子1
  771.  
  772. #!/usr/bin/env python
  773. #encoding:utf8
  774. import threading
  775. from Queue import Queue
  776. from time import sleep,ctime
  777.  
  778. class ThreadFunc(object):
  779. def __init__(self,func,args,name=''):
  780. self.name=name
  781. self.func=func # loop
  782. self.args=args # (i,iplist[i],queue)
  783. def __call__(self):
  784. apply(self.func,self.args) # 函数apply() 执行loop函数并传递元组参数
  785. def loop(nloop,ip,queue):
  786. print 'start',nloop,'at:',ctime()
  787. queue.put(ip)
  788. sleep(2)
  789. print 'loop',nloop,'done at:',ctime()
  790. if __name__ == '__main__':
  791. threads = []
  792. queue = Queue()
  793. 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']
  794. nloops = range(len(iplist))
  795.  
  796. for i in nloops:
  797. t = threading.Thread(target=ThreadFunc(loop,(i,iplist[i],queue),loop.__name__))
  798. threads.append(t)
  799. for i in nloops:
  800. threads[i].start()
  801. for i in nloops:
  802. threads[i].join()
  803. for i in nloops:
  804. print queue.get()
  805.  
  806. threading例子2
  807.  
  808. #!/usr/bin/env python
  809. #encoding:utf8
  810. from Queue import Queue
  811. import random,time,threading
  812.  
  813. class Producer(threading.Thread):
  814. def __init__(self, t_name, queue):
  815. threading.Thread.__init__(self, name=t_name)
  816. self.data=queue
  817. def run(self):
  818. for i in range(5):
  819. print "%s: %s is producing %d to the queue!\n" %(time.ctime(), self.getName(), i)
  820. self.data.put(i)
  821. self.data.put(i*i)
  822. time.sleep(2)
  823. print "%s: %s finished!" %(time.ctime(), self.getName())
  824.  
  825. class Consumer(threading.Thread):
  826. def __init__(self, t_name, queue):
  827. threading.Thread.__init__(self, name=t_name)
  828. self.data=queue
  829. def run(self):
  830. for i in range(10):
  831. val = self.data.get()
  832. print "%s: %s is consuming. %d in the queue is consumed!\n" %(time.ctime(), self.getName(), val)
  833. print "%s: %s finished!" %(time.ctime(), self.getName())
  834.  
  835. if __name__ == '__main__':
  836. queue = Queue()
  837. producer = Producer('Pro.', queue)
  838. consumer = Consumer('Con.', queue)
  839. producer.start()
  840. consumer.start()
  841. producer.join()
  842. consumer.join()
  843.  
  844. 后台线程
  845.  
  846. import threading
  847. import time,random
  848.  
  849. class MyThread(threading.Thread):
  850. def run(self):
  851. wait_time=random.randrange(1,10)
  852. print "%s will wait %d seconds" % (self.name, wait_time)
  853. time.sleep(wait_time)
  854. print "%s finished!" % self.name
  855.  
  856. if __name__=="__main__":
  857. for i in range(5):
  858. t = MyThread()
  859. t.setDaemon(True) # 设置为后台线程,主线程完成时不等待子线程完成就结束
  860. t.start()
  861.  
  862. threading控制最大并发_查询日志中IP信息
  863.  
  864. #!/usr/bin/env python
  865. #coding:utf-8
  866. import urllib2
  867. import json
  868. import threading
  869. import time
  870.  
  871. '''
  872. by:某大牛
  873. QQ:185635687
  874. 这个是多线程并发控制. 如果要改成多进程,只需把threading 换成 mulitprocessing.Process , 对, 就是换个名字而已.
  875. '''
  876.  
  877. #获取ip 及其出现次数
  878. def ip_dic(file_obj, dic):
  879. for i in file_obj:
  880. if i:
  881. ip=i.split('-')[0].strip()
  882. if ip in dic.keys():
  883. dic[ip]=dic[ip] + 1
  884. else:
  885. dic[ip]=1
  886. return dic.iteritems()
  887.  
  888. #目标函数
  889. def get_data(url, ipcounts):
  890. data=urllib2.urlopen(url).read()
  891. datadict=json.loads(data)
  892. 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"])
  893. print fdata
  894.  
  895. #多线程
  896. def threads(iters):
  897. thread_pool = []
  898. for k in iters:
  899. url = "http://ip.taobao.com/service/getIpInfo.php?ip="
  900. ipcounts = k[1]
  901. url = (url + k[0]).strip()
  902. t = threading.Thread(target=get_data, args=(url, ipcounts))
  903. thread_pool.append(t)
  904. return thread_pool
  905.  
  906. #控制多线程
  907. def startt(t_list, max,second):
  908. l = len(t_list)
  909. n = max
  910. while l > 0:
  911. if l > max:
  912. nl = t_list[:max]
  913. t_list = t_list[max:]
  914. for t in nl:
  915. t.start()
  916. time.sleep(second)
  917. for t in nl:
  918. t.join()
  919. print '*'*15, str(n)+ ' ip has been queried'+'*'*15
  920. n += max
  921. l = len(t_list)
  922. continue
  923. elif l <= max:
  924. nl = t_list
  925. for t in nl:
  926. t.start()
  927. for t in nl:
  928. t.join()
  929. print '>>> Totally ' + str(n+l ) + ' ip has been queried'
  930. l = 0
  931.  
  932. if __name__ =="__main__":
  933. dic={}
  934. with open('access.log') as file_obj:
  935. it = ip_dic(file_obj, dic)
  936. t_list= threads(it)
  937. startt(t_list, 15, 1)
  938.  
  939. Queue通用队列
  940.  
  941. q=Queue(size) # 创建大小size的Queue对象
  942. qsize() # 返回队列的大小(返回时候,可能被其他进程修改,近似值)
  943. empty() # 如果队列为空返回True,否则Fales
  944. full() # 如果队列已满返回True,否则Fales
  945. put(item,block0) # 把item放到队列中,如果给了block(不为0),函数会一直阻塞到队列中有空间为止
  946. get(block=0) # 从队列中取一个对象,如果给了block(不为0),函数会一直阻塞到队列中有对象为止
  947. get_nowait # 默认get阻塞,这个不阻塞
  948.  
  949. multiprocessing
  950.  
  951. 多进程并发
  952.  
  953. #!/usr/bin/env python
  954. #encoding:utf8
  955. from multiprocessing import Process
  956. import time,os
  957. def f(name):
  958. time.sleep(1)
  959. print 'hello ',name
  960. print os.getppid() # 取得父进程ID
  961. print os.getpid() # 取得进程ID
  962. process_list = []
  963.  
  964. for i in range(10):
  965. p = Process(target=f,args=(i,))
  966. p.start()
  967. process_list.append(p)
  968. for j in process_list:
  969. j.join()
  970.  
  971. Queue进程间通信
  972.  
  973. from multiprocessing import Process,Queue
  974. import time
  975. def f(name):
  976. time.sleep(1)
  977. q.put(['hello'+str(name)])
  978. process_list = []
  979. q = Queue()
  980. if __name__ == '__main__':
  981. for i in range(10):
  982. p = Process(target=f,args=(i,))
  983. p.start()
  984. process_list.append(p)
  985. for j in process_list:
  986. j.join()
  987. for i in range(10):
  988. print q.get()
  989.  
  990. Pipe管道
  991.  
  992. from multiprocessing import Process,Pipe
  993. import time
  994. import os
  995.  
  996. def f(conn,name):
  997. time.sleep(1)
  998. conn.send(['hello'+str(name)])
  999. print os.getppid(),'-----------',os.getpid()
  1000. process_list = []
  1001. parent_conn,child_conn = Pipe()
  1002. if __name__ == '__main__':
  1003. for i in range(10):
  1004. p = Process(target=f,args=(child_conn,i))
  1005. p.start()
  1006. process_list.append(p)
  1007. for j in process_list:
  1008. j.join()
  1009. for p in range(10):
  1010. print parent_conn.recv()
  1011.  
  1012. 进程间同步
  1013. #加锁,使某一时刻只有一个进程 print
  1014. from multiprocessing import Process,Lock
  1015. import time
  1016. import os
  1017.  
  1018. def f(name):
  1019. lock.acquire()
  1020. time.sleep(1)
  1021. print 'hello--'+str(name)
  1022. print os.getppid(),'-----------',os.getpid()
  1023. lock.release()
  1024. process_list = []
  1025. lock = Lock()
  1026. if __name__ == '__main__':
  1027. for i in range(10):
  1028. p = Process(target=f,args=(i,))
  1029. p.start()
  1030. process_list.append(p)
  1031. for j in process_list:
  1032. j.join()
  1033.  
  1034. 共享内存
  1035.  
  1036. # 通过使用Value或者Array把数据存储在一个共享的内存表中
  1037. # 'd'和'i'参数是num和arr用来设置类型,d表示一个双精浮点类型,i表示一个带符号的整型。
  1038. from multiprocessing import Process,Value,Array
  1039. import time
  1040. import os
  1041.  
  1042. def f(n,a,name):
  1043. time.sleep(1)
  1044. n.value = name * name
  1045. for i in range(len(a)):
  1046. a[i] = -i
  1047. process_list = []
  1048. if __name__ == '__main__':
  1049. num = Value('d',0.0)
  1050. arr = Array('i',range(10))
  1051. for i in range(10):
  1052. p = Process(target=f,args=(num,arr,i))
  1053. p.start()
  1054. process_list.append(p)
  1055. for j in process_list:
  1056. j.join()
  1057. print num.value
  1058. print arr[:]
  1059.  
  1060. manager
  1061.  
  1062. # 比共享内存灵活,但缓慢
  1063. # 支持list,dict,Namespace,Lock,Semaphore,BoundedSemaphore,Condition,Event,Queue,Value,Array
  1064. from multiprocessing import Process,Manager
  1065. import time
  1066. import os
  1067.  
  1068. def f(d,name):
  1069. time.sleep(1)
  1070. d[name] = name * name
  1071. print d
  1072. process_list = []
  1073. if __name__ == '__main__':
  1074. manager = Manager()
  1075. d = manager.dict()
  1076. for i in range(10):
  1077. p = Process(target=f,args=(d,i))
  1078. p.start()
  1079. process_list.append(p)
  1080. for j in process_list:
  1081. j.join()
  1082. print d
  1083.  
  1084. 最大并发数
  1085.  
  1086. import multiprocessing
  1087. import time,os
  1088.  
  1089. result = []
  1090. def run(h):
  1091. print 'threading:' ,h,os.getpid()
  1092. p = multiprocessing.Pool(processes=20)
  1093.  
  1094. for i in range(100):
  1095. result.append(p.apply_async(run,(i,)))
  1096. p.close()
  1097.  
  1098. for res in result:
  1099. res.get(timeout=5)
  1100.  
  1101. socket通讯
  1102.  
  1103. from socket import * # 避免 socket.socket()
  1104.  
  1105. s.bind() # 绑定地址到套接字
  1106. s.listen() # 开始TCP监听
  1107. s.accept() # 被动接受TCP客户端连接,等待连接的到来
  1108. s.connect() # 主动初始化TCP服务器连接
  1109. s.connect_ex() # connect()函数的扩展版本,出错时返回出错码,而不是跑出异常
  1110. s.recv() # 接收TCP数据
  1111. s.send() # 发送TCP数据
  1112. s.sendall() # 完整发送TCP数据
  1113. s.recvfrom() # 接收UDP数据
  1114. s.sendto() # 发送UDP数据
  1115. s.getpeername() # 连接到当前套接字的远端的地址(TCP连接)
  1116. s.getsockname() # 当前套接字的地址
  1117. s.getsockopt() # 返回指定套接字的参数
  1118. s.setsockopt() # 设置指定套接字的参数
  1119. s.close() # 关闭套接字
  1120. s.setblocking() # 设置套接字的阻塞与非阻塞模式
  1121. s.settimeout() # 设置阻塞套接字操作的超时时间
  1122. s.gettimeout() # 得到阻塞套接字操作的超时时间
  1123. s.filen0() # 套接字的文件描述符
  1124. s.makefile() # 创建一个与该套接字关联的文件对象
  1125.  
  1126. socket.AF_UNIX # 只能够用于单一的Unix系统进程间通信
  1127. socket.AF_INET # 服务器之间网络通信
  1128. socket.AF_INET6 # IPv6
  1129.  
  1130. socket.SOCK_STREAM # 流式socket , for TCP
  1131. socket.SOCK_DGRAM # 数据报式socket , for UDP
  1132. socket.SOCK_RAW # 原始套接字,普通的套接字无法处理ICMP、IGMP等网络报文,而SOCK_RAW可以;其次,SOCK_RAW也可以处理特殊的IPv4报文;此外,利用原始套接字,可以通过IP_HDRINCL套接字选项由用户构造IP头。
  1133.  
  1134. socket.SOCK_RDM # 是一种可靠的UDP形式,即保证交付数据报但不保证顺序。SOCK_RAM用来提供对原始协议的低级访问,在需要执行某些特殊操作时使用,如发送ICMP报文。SOCK_RAM通常仅限于高级用户或管理员运行的程序使用。
  1135.  
  1136. socket.SOCK_SEQPACKET # 可靠的连续数据包服务
  1137.  
  1138. SocketServer
  1139.  
  1140. #!/usr/bin/python
  1141. #server.py
  1142. import SocketServer
  1143. import os
  1144. class MyTCP(SocketServer.BaseRequestHandler):
  1145. def handle(self):
  1146. while True:
  1147. self.data=self.request.recv(1024).strip()
  1148. if self.data == 'quit' or not self.data:break
  1149.  
  1150. cmd=os.popen(self.data).read()
  1151. if cmd == '':cmd= self.data + ': Command not found'
  1152. self.request.sendall(cmd)
  1153. if __name__ == '__main__':
  1154. HOST,PORT = '10.0.0.119',50007
  1155. server = SocketServer.ThreadingTCPServer((HOST,PORT),MyTCP)
  1156. server.serve_forever()
  1157.  
  1158. SocketClient
  1159.  
  1160. #!/usr/bin/python
  1161. #client.py
  1162. import socket
  1163.  
  1164. HOST='10.0.0.119'
  1165. PORT=50007
  1166. s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  1167. s.connect((HOST,PORT))
  1168.  
  1169. while True:
  1170. while True:
  1171. cmd=raw_input('CMD:').strip()
  1172. if cmd != '':break
  1173. s.sendall(cmd)
  1174. data=s.recv(1024).split('\n')
  1175. print 'cmd:'
  1176. for line in data:print line
  1177. s.close()
  1178.  
  1179. ftp
  1180.  
  1181. ftpserver
  1182.  
  1183. #!/usr/bin/python
  1184. #ftpserver.py
  1185.  
  1186. import SocketServer
  1187. import os
  1188. import cPickle
  1189. import md5
  1190. from time import sleep
  1191.  
  1192. def filer(file1):
  1193. try:
  1194. f = file(file1,'rb')
  1195. return cPickle.load(f)
  1196. except IOError:
  1197. return {}
  1198. except EOFError:
  1199. return {}
  1200. f.close()
  1201.  
  1202. def filew(file1,content):
  1203. f = file(file1,'wb')
  1204. cPickle.dump(content,f)
  1205. f.close()
  1206.  
  1207. class MyTCP(SocketServer.BaseRequestHandler):
  1208. def handle(self):
  1209. i = 0
  1210. while i<3:
  1211. user=self.request.recv(1024).strip()
  1212. userinfo=filer('user.pkl')
  1213. if userinfo.has_key(user.split()[0]):
  1214. if md5.new(user.split()[1]).hexdigest() == userinfo[user.split()[0]]:
  1215. results='login successful'
  1216. self.request.sendall(results)
  1217. login='successful'
  1218. break
  1219. else:
  1220. i = i + 1
  1221. results='Error:password not correct'
  1222. self.request.sendall(results)
  1223. continue
  1224. else:
  1225. i = i + 1
  1226. results='Error:password not correct'
  1227. self.request.sendall(results)
  1228. continue
  1229. break
  1230. else:
  1231. results = 'Error:Wrong password too many times'
  1232. self.request.sendall(results)
  1233. login='failure'
  1234. home_path = os.popen('pwd').read().strip() + '/' + user.split()[0]
  1235. current_path = '/'
  1236. print home_path
  1237. while True:
  1238. if login == 'failure':
  1239. break
  1240. print 'home_path:%s=current_path:%s' %(home_path,current_path)
  1241. cmd=self.request.recv(1024).strip()
  1242. print cmd
  1243. if cmd == 'quit':
  1244. break
  1245. elif cmd == 'dir':
  1246. list=os.listdir('%s%s' %(home_path,current_path))
  1247. if list:
  1248. dirlist,filelist = '',''
  1249. for i in list:
  1250. if os.path.isdir('%s%s%s' %(home_path,current_path,i)):
  1251. dirlist = dirlist + '\033[32m' + i + '\033[m\t'
  1252. else:
  1253. filelist = filelist + i + '\t'
  1254. results = dirlist + filelist
  1255. else:
  1256. results = '\033[31mnot find\033[m'
  1257. self.request.sendall(results)
  1258. elif cmd == 'pdir':
  1259. self.request.sendall(current_path)
  1260. elif cmd.split()[0] == 'mdir':
  1261. if cmd.split()[1].isalnum():
  1262. tmppath='%s%s%s' %(home_path,current_path,cmd.split()[1])
  1263. os.makedirs(tmppath)
  1264. self.request.sendall('\033[32mcreating successful\033[m')
  1265. else:
  1266. self.request.sendall('\033[31mcreate failure\033[m')
  1267. elif cmd.split()[0] == 'cdir':
  1268. if cmd.split()[1] == '/':
  1269. tmppath='%s%s' %(home_path,cmd.split()[1])
  1270. if os.path.isdir(tmppath):
  1271. current_path = cmd.split()[1]
  1272. self.request.sendall(current_path)
  1273. else:
  1274. self.request.sendall('\033[31mnot_directory\033[m')
  1275. elif cmd.split()[1].startswith('/'):
  1276. tmppath='%s%s' %(home_path,cmd.split()[1])
  1277. if os.path.isdir(tmppath):
  1278. current_path = cmd.split()[1] + '/'
  1279. self.request.sendall(current_path)
  1280. else:
  1281. self.request.sendall('\033[31mnot_directory\033[m')
  1282. else:
  1283. tmppath='%s%s%s' %(home_path,current_path,cmd.split()[1])
  1284. if os.path.isdir(tmppath):
  1285. current_path = current_path + cmd.split()[1] + '/'
  1286. self.request.sendall(current_path)
  1287. else:
  1288. self.request.sendall('\033[31mnot_directory\033[m')
  1289. elif cmd.split()[0] == 'get':
  1290. if os.path.isfile('%s%s%s' %(home_path,current_path,cmd.split()[1])):
  1291. f = file('%s%s%s' %(home_path,current_path,cmd.split()[1]),'rb')
  1292. self.request.sendall('ready_file')
  1293. sleep(0.5)
  1294. self.request.send(f.read())
  1295. f.close()
  1296. sleep(0.5)
  1297. elif os.path.isdir('%s%s%s' %(home_path,current_path,cmd.split()[1])):
  1298. self.request.sendall('ready_dir')
  1299. sleep(0.5)
  1300. for dirpath in os.walk('%s%s%s' %(home_path,current_path,cmd.split()[1])):
  1301. dir=dirpath[0].replace('%s%s' %(home_path,current_path),'',1)
  1302. self.request.sendall(dir)
  1303. sleep(0.5)
  1304. for filename in dirpath[2]:
  1305. self.request.sendall(filename)
  1306. sleep(0.5)
  1307. f = file('%s/%s' %(dirpath[0],filename),'rb')
  1308. self.request.send(f.read())
  1309. f.close()
  1310. sleep(0.5)
  1311. self.request.sendall('file_get_done')
  1312. sleep(0.5)
  1313. else:
  1314. self.request.sendall('dir_get_done')
  1315. sleep(0.5)
  1316. else:
  1317. self.request.sendall('get_failure')
  1318. continue
  1319. self.request.sendall('get_done')
  1320.  
  1321. elif cmd.split()[0] == 'send':
  1322. if os.path.exists('%s%s%s' %(home_path,current_path,cmd.split()[1])):
  1323. self.request.sendall('existing')
  1324. action=self.request.recv(1024)
  1325. if action == 'cancel':
  1326. continue
  1327. self.request.sendall('ready')
  1328. msg=self.request.recv(1024)
  1329. if msg == 'ready_file':
  1330. f = file('%s%s%s' %(home_path,current_path,cmd.split()[1]),'wb')
  1331. while True:
  1332. data=self.request.recv(1024)
  1333. if data == 'file_send_done':break
  1334. f.write(data)
  1335. f.close()
  1336.  
  1337. elif msg == 'ready_dir':
  1338. os.system('mkdir -p %s%s%s' %(home_path,current_path,cmd.split()[1]))
  1339. while True:
  1340. dir=self.request.recv(1024)
  1341. if dir == 'get_done':break
  1342. os.system('mkdir -p %s%s%s' %(home_path,current_path,dir))
  1343. while True:
  1344. filename=self.request.recv(1024)
  1345. if filename == 'dir_send_done':break
  1346. f = file('%s%s%s/%s' %(home_path,current_path,dir,filename),'wb')
  1347. while True:
  1348. data=self.request.recv(1024)
  1349. if data == 'file_send_done':break
  1350. f.write(data)
  1351. f.close()
  1352. self.request.sendall('%s/%s\t\033[32mfile_done\033[m' %(dir,filename))
  1353. self.request.sendall('%s\t\033[32mdir_done\033[m' %(dir))
  1354. elif msg == 'unknown_file':
  1355. continue
  1356.  
  1357. else:
  1358. results = cmd.split()[0] + ': Command not found'
  1359. self.request.sendall(results)
  1360.  
  1361. if __name__ == '__main__':
  1362. HOST,PORT = '10.152.14.85',50007
  1363. server = SocketServer.ThreadingTCPServer((HOST,PORT),MyTCP)
  1364. server.serve_forever()
  1365.  
  1366. ftpmanage
  1367.  
  1368. #!/usr/bin/python
  1369. #manage_ftp.py
  1370. import cPickle
  1371. import sys
  1372. import md5
  1373. import os
  1374. import getpass
  1375.  
  1376. def filer(file1):
  1377. try:
  1378. f = file(file1,'rb')
  1379. return cPickle.load(f)
  1380. except IOError:
  1381. return {}
  1382. except EOFError:
  1383. return {}
  1384. f.close()
  1385.  
  1386. def filew(file1,content):
  1387. f = file(file1,'wb')
  1388. cPickle.dump(content,f)
  1389. f.close()
  1390.  
  1391. while True:
  1392. print '''
  1393. 1.add user
  1394. 2.del user
  1395. 3.change password
  1396. 4.query user
  1397. 0.exit
  1398. '''
  1399. i = raw_input(':').strip()
  1400. userinfo=filer('user.pkl')
  1401. if i == '':
  1402. continue
  1403. elif i == '':
  1404. while True:
  1405. user=raw_input('user name:').strip()
  1406. if user.isalnum():
  1407. i = 0
  1408. while i<3:
  1409. passwd=getpass.getpass('passwd:').strip()
  1410. if passwd == '':
  1411. continue
  1412. else:
  1413. passwd1=getpass.getpass('Confirm password:').strip()
  1414. if passwd == passwd1:
  1415. mpasswd = md5.new(passwd).hexdigest()
  1416. userinfo[user] = mpasswd
  1417. os.system('mkdir -p %s' %user)
  1418. print '%s creating successful ' %user
  1419. break
  1420. else:
  1421. print "Passwords don't match "
  1422. i = i + 1
  1423. continue
  1424. else:
  1425. print 'Too many wrong'
  1426. continue
  1427. break
  1428. else:
  1429. print 'user not legal'
  1430. continue
  1431. elif i == '':
  1432. user=raw_input('user name:').strip()
  1433. if userinfo.has_key(user):
  1434. del userinfo[user]
  1435. print 'Delete users successfully'
  1436. else:
  1437. print 'user not exist'
  1438. continue
  1439. elif i == '':
  1440. user=raw_input('user name:').strip()
  1441. if userinfo.has_key(user):
  1442. i = 0
  1443. while i<3:
  1444. passwd=getpass.getpass('passwd:').strip()
  1445. if passwd == '':
  1446. continue
  1447. else:
  1448. passwd1=getpass.getpass('Confirm password:').strip()
  1449. if passwd == passwd1:
  1450. mpasswd = md5.new(passwd).hexdigest()
  1451. userinfo[user] = mpasswd
  1452. print '%s password is changed' %user
  1453. break
  1454. else:
  1455. print "Passwords don't match "
  1456. i = i + 1
  1457. continue
  1458. else:
  1459. print 'Too many wrong'
  1460. continue
  1461. else:
  1462. print 'user not exist'
  1463. continue
  1464. elif i == '':
  1465. print userinfo.keys()
  1466. elif i == '':
  1467. sys.exit()
  1468. else:
  1469. print 'select error'
  1470. continue
  1471. filew('user.pkl',content=userinfo)
  1472.  
  1473. ftpclient
  1474.  
  1475. #!/usr/bin/python
  1476. #ftpclient.py
  1477.  
  1478. import socket
  1479. import os
  1480. import getpass
  1481. from time import sleep
  1482.  
  1483. HOST='10.152.14.85'
  1484. PORT=50007
  1485. s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  1486. s.connect((HOST,PORT))
  1487.  
  1488. while True:
  1489. user = raw_input('user:').strip()
  1490. if user.isalnum():
  1491. while True:
  1492. passwd = getpass.getpass('passwd:').strip()
  1493. s.sendall(user + ' ' + passwd)
  1494. servercmd=s.recv(1024)
  1495. if servercmd == 'login successful':
  1496. print '\033[32m%s\033[m' %servercmd
  1497. break
  1498. else:
  1499. print servercmd
  1500.  
  1501. while True:
  1502. cmd=raw_input('FTP>').strip()
  1503. if cmd == '':
  1504. continue
  1505. if cmd.split()[0] == 'get':
  1506. if cmd == 'get':continue
  1507. for i in cmd.split()[1:]:
  1508. if os.path.exists(i):
  1509. confirm = raw_input("\033[31mPlease confirm whether the cover %s(Y/N):\033[m" %(i)).upper().startswith('Y')
  1510. if not confirm:
  1511. print '%s cancel' %i
  1512. continue
  1513. s.sendall('get ' + i)
  1514. servercmd=s.recv(1024)
  1515. if servercmd == 'inexistence':
  1516. print '%s \t\033[32minexistence\033[m' %i
  1517. continue
  1518. elif servercmd == 'ready_file':
  1519. f = file(i,'wb')
  1520. while True:
  1521. data=s.recv(1024)
  1522. if data == 'get_done':break
  1523. f.write(data)
  1524. f.close()
  1525. print '%s \t\033[32mfile_done\033[m' %(i)
  1526. elif servercmd == 'ready_dir':
  1527. try:
  1528. os.makedirs(i)
  1529. except:
  1530. pass
  1531. while True:
  1532. serverdir=s.recv(1024)
  1533. if serverdir == 'get_done':break
  1534. os.system('mkdir -p %s' %serverdir)
  1535. print '%s \t\033[32mdir_done\033[m' %(serverdir)
  1536. while True:
  1537. serverfile=s.recv(1024)
  1538. if serverfile == 'dir_get_done':break
  1539. f = file('%s/%s' %(serverdir,serverfile),'wb')
  1540. while True:
  1541. data=s.recv(1024)
  1542. if data == 'file_get_done':break
  1543. f.write(data)
  1544. f.close()
  1545. print '%s/%s \t\033[32mfile_done\033[m' %(serverdir,serverfile)
  1546.  
  1547. elif cmd.split()[0] == 'send':
  1548.  
  1549. if cmd == 'send':continue
  1550. for i in cmd.split()[1:]:
  1551. if not os.path.exists(i):
  1552. print '%s\t\033[31minexistence\033[m' %i
  1553. continue
  1554.  
  1555. s.sendall('send ' + i)
  1556. servercmd=s.recv(1024)
  1557. if servercmd == 'existing':
  1558. confirm = raw_input("\033[31mPlease confirm whether the cover %s(Y/N):\033[m" %(i)).upper().startswith('Y')
  1559. if confirm:
  1560. s.sendall('cover')
  1561. servercmd=s.recv(1024)
  1562. else:
  1563. s.sendall('cancel')
  1564. print '%s\tcancel' %i
  1565. continue
  1566.  
  1567. if os.path.isfile(i):
  1568. s.sendall('ready_file')
  1569. sleep(0.5)
  1570. f = file(i,'rb')
  1571. s.send(f.read())
  1572. sleep(0.5)
  1573. s.sendall('file_send_done')
  1574. print '%s\t\033[32mfile done\033[m' %(cmd.split()[1])
  1575. f.close()
  1576. elif os.path.isdir(i):
  1577. s.sendall('ready_dir')
  1578. sleep(0.5)
  1579. for dirpath in os.walk(i):
  1580. dir=dirpath[0].replace('%s/' %os.popen('pwd').read().strip(),'',1)
  1581. s.sendall(dir)
  1582. sleep(0.5)
  1583. for filename in dirpath[2]:
  1584. s.sendall(filename)
  1585. sleep(0.5)
  1586. f = file('%s/%s' %(dirpath[0],filename),'rb')
  1587. s.send(f.read())
  1588. f.close()
  1589. sleep(0.5)
  1590. s.sendall('file_send_done')
  1591. msg=s.recv(1024)
  1592. print msg
  1593.  
  1594. else:
  1595. s.sendall('dir_send_done')
  1596. msg=s.recv(1024)
  1597. print msg
  1598.  
  1599. else:
  1600. s.sendall('unknown_file')
  1601. print '%s\t\033[31munknown type\033[m' %i
  1602. continue
  1603. sleep(0.5)
  1604. s.sendall('get_done')
  1605.  
  1606. elif cmd.split()[0] == 'cdir':
  1607. if cmd == 'cdir':continue
  1608. s.sendall(cmd)
  1609. data=s.recv(1024)
  1610. print data
  1611. continue
  1612. elif cmd == 'ls':
  1613. list=os.popen(cmd).read().strip().split('\n')
  1614. if list:
  1615. dirlist,filelist = '',''
  1616. for i in list:
  1617. if os.path.isdir(i):
  1618. dirlist = dirlist + '\033[32m' + i + '\033[m\t'
  1619. else:
  1620. filelist = filelist + i + '\t'
  1621. results = dirlist + filelist
  1622. else:
  1623. results = '\033[31mnot find\033[m'
  1624. print results
  1625. continue
  1626. elif cmd == 'pwd':
  1627. os.system(cmd)
  1628. elif cmd.split()[0] == 'cd':
  1629. try:
  1630. os.chdir(cmd.split()[1])
  1631. except:
  1632. print '\033[31mcd failure\033[m'
  1633. elif cmd == 'dir':
  1634. s.sendall(cmd)
  1635. data=s.recv(1024)
  1636. print data
  1637. continue
  1638. elif cmd == 'pdir':
  1639. s.sendall(cmd)
  1640. data=s.recv(1024)
  1641. print data
  1642. continue
  1643. elif cmd.split()[0] == 'mdir':
  1644. if cmd == 'mdir':continue
  1645. s.sendall(cmd)
  1646. data=s.recv(1024)
  1647. print data
  1648. continue
  1649. elif cmd.split()[0] == 'help':
  1650. print '''
  1651. get [file] [dir]
  1652. send [file] [dir]
  1653.  
  1654. dir
  1655. mdir
  1656. cdir
  1657. pdir
  1658.  
  1659. pwd
  1660. md
  1661. cd
  1662. ls
  1663.  
  1664. help
  1665. quit
  1666. '''
  1667. continue
  1668. elif cmd == 'quit':
  1669. break
  1670. else:
  1671. print '\033[31m%s: Command not found,Please see the "help"\033[m' %cmd
  1672. else:
  1673. continue
  1674. break
  1675. s.close()
  1676.  
  1677. 扫描主机开放端口
  1678. #!/usr/bin/env python
  1679.  
  1680. import socket
  1681.  
  1682. def check_server(address,port):
  1683. s=socket.socket()
  1684. try:
  1685. s.connect((address,port))
  1686. return True
  1687. except socket.error,e:
  1688. return False
  1689.  
  1690. if __name__=='__main__':
  1691. from optparse import OptionParser
  1692. parser=OptionParser()
  1693. parser.add_option("-a","--address",dest="address",default='localhost',help="Address for server",metavar="ADDRESS")
  1694. parser.add_option("-s","--start",dest="start_port",type="int",default=1,help="start port",metavar="SPORT")
  1695. parser.add_option("-e","--end",dest="end_port",type="int",default=1,help="end port",metavar="EPORT")
  1696. (options,args)=parser.parse_args()
  1697. print 'options: %s, args: %s' % (options, args)
  1698. port=options.start_port
  1699. while(port<=options.end_port):
  1700. check = check_server(options.address, port)
  1701. if (check):
  1702. print 'Port %s is on' % port
  1703. port=port+1
  1704.  
  1705. mysql
  1706.  
  1707. #apt-get install mysql-server
  1708. #apt-get install python-MySQLdb
  1709. help(MySQLdb.connections.Connection) # 查看链接参数
  1710.  
  1711. conn=MySQLdb.connect(host='localhost',user='root',passwd='',db='fortress',port=3306) # 定义连接
  1712. #conn=MySQLdb.connect(unix_socket='/var/run/mysqld/mysqld.sock',user='root',passwd='123456') # 使用socket文件链接
  1713. cur=conn.cursor() # 定义游标
  1714. conn.select_db('fortress') # 选择数据库
  1715. sqlcmd = 'insert into user(name,age) value(%s,%s)' # 定义sql命令
  1716. cur.executemany(sqlcmd,[('aa',1),('bb',2),('cc',3)]) # 插入多条值
  1717. cur.execute('delete from user where id=20') # 删除一条记录
  1718. cur.execute("update user set name='a' where id=20") # 更细数据
  1719. sqlresult = cur.fetchall() # 接收全部返回结果
  1720. conn.commit() # 提交
  1721. cur.close() # 关闭游标
  1722. conn.close() # 关闭连接
  1723.  
  1724. import MySQLdb
  1725. def mydb(dbcmdlist):
  1726. try:
  1727. conn=MySQLdb.connect(host='localhost',user='root',passwd='',db='fortress',port=3306)
  1728. cur=conn.cursor()
  1729.  
  1730. cur.execute('create database if not exists fortress;') # 创建数据库
  1731. conn.select_db('fortress') # 选择数据库
  1732. cur.execute('drop table if exists log;') # 删除表
  1733. 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) );') # 创建表
  1734.  
  1735. result=[]
  1736. for dbcmd in dbcmdlist:
  1737. cur.execute(dbcmd) # 执行sql
  1738. sqlresult = cur.fetchall() # 接收全部返回结果
  1739. result.append(sqlresult)
  1740. conn.commit() # 提交
  1741. cur.close()
  1742. conn.close()
  1743. return result
  1744. except MySQLdb.Error,e:
  1745. print 'mysql error msg: ',e
  1746. sqlcmd=[]
  1747. sqlcmd.append("insert into log (loginuser,remoteip)values('%s','%s');" %(loginuser,remoteip))
  1748. mydb(sqlcmd)
  1749.  
  1750. sqlcmd=[]
  1751. sqlcmd.append("select * from log;")
  1752. result = mydb(sqlcmd)
  1753. for i in result[0]:
  1754. print i
  1755.  
  1756. paramiko
  1757.  
  1758. 安装
  1759. sudo apt-get install python-setuptools
  1760. easy_install
  1761. sudo apt-get install python-all-dev
  1762. sudo apt-get install build-essential
  1763.  
  1764. paramiko实例(账号密码登录执行命令)
  1765.  
  1766. #!/usr/bin/python
  1767. #ssh
  1768. import paramiko
  1769. import sys,os
  1770.  
  1771. host = '10.152.15.200'
  1772. user = 'peterli'
  1773. password = ''
  1774.  
  1775. s = paramiko.SSHClient() # 绑定实例
  1776. s.load_system_host_keys() # 加载本地HOST主机文件
  1777. s.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 允许连接不在know_hosts文件中的主机
  1778. s.connect(host,22,user,password,timeout=5) # 连接远程主机
  1779. while True:
  1780. cmd=raw_input('cmd:')
  1781. stdin,stdout,stderr = s.exec_command(cmd) # 执行命令
  1782. cmd_result = stdout.read(),stderr.read() # 读取命令结果
  1783. for line in cmd_result:
  1784. print line,
  1785. s.close()
  1786.  
  1787. paramiko实例(传送文件)
  1788.  
  1789. #!/usr/bin/evn python
  1790. import os
  1791. import paramiko
  1792. host='127.0.0.1'
  1793. port=22
  1794. username = 'peterli'
  1795. password = ''
  1796. ssh=paramiko.Transport((host,port))
  1797. privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')
  1798. mykey = paramiko.RSAKey.from_private_key_file( os.path.expanduser('~/.ssh/id_rsa')) # 加载key 不使用key可不加
  1799. ssh.connect(username=username,password=password) # 连接远程主机
  1800. # 使用key把 password=password 换成 pkey=mykey
  1801. sftp=paramiko.SFTPClient.from_transport(ssh) # SFTP使用Transport通道
  1802. sftp.get('/etc/passwd','pwd1') # 下载 两端都要指定文件名
  1803. sftp.put('pwd','/tmp/pwd') # 上传
  1804. sftp.close()
  1805. ssh.close()
  1806.  
  1807. paramiko实例(密钥执行命令)
  1808.  
  1809. #!/usr/bin/python
  1810. #ssh
  1811. import paramiko
  1812. import sys,os
  1813. host = '10.152.15.123'
  1814. user = 'peterli'
  1815. s = paramiko.SSHClient()
  1816. s.load_system_host_keys()
  1817. s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  1818. privatekeyfile = os.path.expanduser('~/.ssh/id_rsa') # 定义key路径
  1819. mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
  1820. # mykey=paramiko.DSSKey.from_private_key_file(privatekeyfile,password='061128') # DSSKey方式 password是key的密码
  1821. s.connect(host,22,user,pkey=mykey,timeout=5)
  1822. cmd=raw_input('cmd:')
  1823. stdin,stdout,stderr = s.exec_command(cmd)
  1824. cmd_result = stdout.read(),stderr.read()
  1825. for line in cmd_result:
  1826. print line,
  1827. s.close()
  1828.  
  1829. ssh并发(Pool控制最大并发)
  1830.  
  1831. #!/usr/bin/env python
  1832. #encoding:utf8
  1833. #ssh_concurrent.py
  1834.  
  1835. import multiprocessing
  1836. import sys,os,time
  1837. import paramiko
  1838.  
  1839. def ssh_cmd(host,port,user,passwd,cmd):
  1840. msg = "-----------Result:%s----------" % host
  1841.  
  1842. s = paramiko.SSHClient()
  1843. s.load_system_host_keys()
  1844. s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  1845. try:
  1846. s.connect(host,22,user,passwd,timeout=5)
  1847. stdin,stdout,stderr = s.exec_command(cmd)
  1848.  
  1849. cmd_result = stdout.read(),stderr.read()
  1850. print msg
  1851. for line in cmd_result:
  1852. print line,
  1853.  
  1854. s.close()
  1855. except paramiko.AuthenticationException:
  1856. print msg
  1857. print 'AuthenticationException Failed'
  1858. except paramiko.BadHostKeyException:
  1859. print msg
  1860. print "Bad host key"
  1861.  
  1862. result = []
  1863. p = multiprocessing.Pool(processes=20)
  1864. cmd=raw_input('CMD:')
  1865. f=open('serverlist.conf')
  1866. list = f.readlines()
  1867. f.close()
  1868. for IP in list:
  1869. print IP
  1870. host=IP.split()[0]
  1871. port=int(IP.split()[1])
  1872. user=IP.split()[2]
  1873. passwd=IP.split()[3]
  1874. result.append(p.apply_async(ssh_cmd,(host,port,user,passwd,cmd)))
  1875.  
  1876. p.close()
  1877.  
  1878. for res in result:
  1879. res.get(timeout=35)
  1880.  
  1881. ssh并发(取文件状态并发送邮件)
  1882.  
  1883. #!/usr/bin/python
  1884. #encoding:utf8
  1885. #config file: ip.list
  1886.  
  1887. import paramiko
  1888. import multiprocessing
  1889. import smtplib
  1890. import sys,os,time,datetime,socket,re
  1891. from email.mime.text import MIMEText
  1892.  
  1893. # 配置文件(IP列表)
  1894. Conf = 'ip.list'
  1895. user_name = 'peterli'
  1896. user_pwd = 'passwd'
  1897. port = 22
  1898. PATH = '/home/peterli/'
  1899.  
  1900. # 设置服务器名称、用户名、密码以及邮件后缀
  1901. mail_host = "smtp.163.com"
  1902. mail_user = "xuesong"
  1903. mail_pass = "mailpasswd"
  1904. mail_postfix = "163.com"
  1905. mailto_list = ["272121935@qq.com","quanzhou722@163.com"]
  1906. title = 'file check'
  1907.  
  1908. DATE1=(datetime.datetime.now() + datetime.timedelta(days=-1) ).strftime('%Y%m%d')
  1909. file_path = '%s%s' %(PATH,DATE1)
  1910.  
  1911. def Ssh_Cmd(file_path,host_ip,user_name,user_pwd,port=22):
  1912.  
  1913. s = paramiko.SSHClient()
  1914. s.load_system_host_keys()
  1915. s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  1916.  
  1917. try:
  1918. s.connect(hostname=host_ip,port=port,username=user_name,password=user_pwd)
  1919. stdin,stdout,stderr = s.exec_command('stat %s' %file_path)
  1920. stat_result = '%s%s' %(stdout.read(),stderr.read())
  1921. if stat_result.find('No such file or directory') == -1:
  1922. file_status = 'OK\t'
  1923. stdin,stdout,stderr = s.exec_command('du -sh %s' %file_path)
  1924. cmd1_result = '%s_%s' %(stat_result.split()[32],stat_result.split()[33].split('.')[0])
  1925. cmd2_result = ('%s%s' %(stdout.read(),stderr.read())).split()[0]
  1926. else:
  1927. file_status = '未生成\t'
  1928. cmd1_result = 'null'
  1929. cmd2_result = 'null'
  1930. q.put(['Login successful'])
  1931. s.close()
  1932. except socket.error:
  1933. file_status = '主机或端口错误'
  1934. cmd1_result = '-'
  1935. cmd2_result = '-'
  1936. except paramiko.AuthenticationException:
  1937. file_status = '用户或密码错误'
  1938. cmd1_result = '-'
  1939. cmd2_result = '-'
  1940. except paramiko.BadHostKeyException:
  1941. file_status = 'Bad host key'
  1942. cmd1_result = '-'
  1943. cmd2_result = '-'
  1944. except:
  1945. file_status = 'ssh异常'
  1946. cmd1_result = '-'
  1947. cmd2_result = '-'
  1948. 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))
  1949.  
  1950. def Concurrent(Conf,file_path,user_name,user_pwd,port):
  1951. # 执行总计
  1952. total = 0
  1953. # 读取配置文件
  1954. f=open(Conf)
  1955. list = f.readlines()
  1956. f.close()
  1957. # 并发执行
  1958. process_list = []
  1959. log_file = file('file_check.log', 'w')
  1960. log_file.write('检查时间\t\t业务\tIP\t\t文件状态\t大小\t生成时间\n')
  1961. for host_info in list:
  1962. # 判断配置文件中注释行跳过
  1963. if host_info.startswith('#'):
  1964. continue
  1965. # 取变量,其中任意变量未取到就跳过执行
  1966. try:
  1967. host_ip=host_info.split()[0].strip()
  1968. #user_name=host_info.split()[1]
  1969. #user_pwd=host_info.split()[2]
  1970. except:
  1971. log_file.write('Profile error: %s\n' %(host_info))
  1972. continue
  1973. #try:
  1974. # port=int(host_info.split()[3])
  1975. #except:
  1976. # port=22
  1977. total +=1
  1978. p = multiprocessing.Process(target=Ssh_Cmd,args=(file_path,host_ip,user_name,user_pwd,port))
  1979. p.start()
  1980. process_list.append(p)
  1981. for j in process_list:
  1982. j.join()
  1983. for j in process_list:
  1984. log_file.write(r.get())
  1985.  
  1986. successful = q.qsize()
  1987. log_file.write('执行完毕。 总执行:%s 登录成功:%s 登录失败:%s\n' %(total,successful,total - successful))
  1988. log_file.flush()
  1989. log_file.close()
  1990.  
  1991. def send_mail(to_list, sub):
  1992. me = mail_user + "<"+mail_user+"@"+mail_postfix+">"
  1993. fp = open('file_check.log')
  1994. msg = MIMEText(fp.read(),_charset="utf-8")
  1995. fp.close()
  1996. msg['Subject'] = sub
  1997. msg['From'] = me
  1998. msg['To'] = ";".join(to_list)
  1999. try:
  2000. send_smtp = smtplib.SMTP()
  2001. send_smtp.connect(mail_host)
  2002. send_smtp.login(mail_user, mail_pass)
  2003. send_smtp.sendmail(me, to_list, msg.as_string())
  2004. send_smtp.close()
  2005. return True
  2006. except Exception, e:
  2007. print str(e)[1]
  2008. return False
  2009.  
  2010. if __name__ == '__main__':
  2011. q = multiprocessing.Queue()
  2012. r = multiprocessing.Queue()
  2013. Concurrent(Conf,file_path,user_name,user_pwd,port)
  2014. if send_mail(mailto_list,title):
  2015. print "发送成功"
  2016. else:
  2017. print "发送失败"
  2018.  
  2019. LazyManage并发批量操作(判断非root交互到root操作)
  2020.  
  2021. #!/usr/bin/python
  2022. #encoding:utf8
  2023. # LzayManage.py
  2024. # config file: serverlist.conf
  2025.  
  2026. import paramiko
  2027. import multiprocessing
  2028. import sys,os,time,socket,re
  2029.  
  2030. def Ssh_Cmd(host_ip,Cmd,user_name,user_pwd,port=22):
  2031. s = paramiko.SSHClient()
  2032. s.load_system_host_keys()
  2033. s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  2034. s.connect(hostname=host_ip,port=port,username=user_name,password=user_pwd)
  2035. stdin,stdout,stderr = s.exec_command(Cmd)
  2036. Result = '%s%s' %(stdout.read(),stderr.read())
  2037. q.put('successful')
  2038. s.close()
  2039. return Result.strip()
  2040.  
  2041. def Ssh_Su_Cmd(host_ip,Cmd,user_name,user_pwd,root_name,root_pwd,port=22):
  2042. s = paramiko.SSHClient()
  2043. s.load_system_host_keys()
  2044. s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  2045. s.connect(hostname=host_ip,port=port,username=user_name,password=user_pwd)
  2046. ssh = s.invoke_shell()
  2047. time.sleep(0.1)
  2048. ssh.send('su - %s\n' %(root_name))
  2049. buff = ''
  2050. while not buff.endswith('Password: '):
  2051. resp = ssh.recv(9999)
  2052. buff +=resp
  2053. ssh.send('%s\n' %(root_pwd))
  2054. buff = ''
  2055. while True:
  2056. resp = ssh.recv(9999)
  2057. buff +=resp
  2058. if ': incorrect password' in buff:
  2059. su_correct='passwd_error'
  2060. break
  2061. elif buff.endswith('# '):
  2062. su_correct='passwd_correct'
  2063. break
  2064. if su_correct == 'passwd_correct':
  2065. ssh.send('%s\n' %(Cmd))
  2066. buff = ''
  2067. while True:
  2068. resp = ssh.recv(9999)
  2069. if resp.endswith('# '):
  2070. buff +=re.sub('\[.*@.*\]# $','',resp)
  2071. break
  2072. buff +=resp
  2073. Result = buff.lstrip('%s' %(Cmd))
  2074. q.put('successful')
  2075. elif su_correct == 'passwd_error':
  2076. Result = "\033[31mroot密码错误\033[m"
  2077. s.close()
  2078. return Result.strip()
  2079.  
  2080. def Send_File(host_ip,PathList,user_name,user_pwd,Remote='/tmp',port=22):
  2081. s=paramiko.Transport((host_ip,port))
  2082. s.connect(username=user_name,password=user_pwd)
  2083. sftp=paramiko.SFTPClient.from_transport(s)
  2084. for InputPath in PathList:
  2085. LocalPath = re.sub('^\./','',InputPath.rstrip('/'))
  2086. RemotePath = '%s/%s' %( Remote , os.path.basename( LocalPath ))
  2087. try:
  2088. sftp.rmdir(RemotePath)
  2089. except:
  2090. pass
  2091. try:
  2092. sftp.remove(RemotePath)
  2093. except:
  2094. pass
  2095. if os.path.isdir(LocalPath):
  2096. sftp.mkdir(RemotePath)
  2097. for path,dirs,files in os.walk(LocalPath):
  2098. for dir in dirs:
  2099. dir_path = os.path.join(path,dir)
  2100. sftp.mkdir('%s/%s' %(RemotePath,re.sub('^%s/' %LocalPath,'',dir_path)))
  2101. for file in files:
  2102. file_path = os.path.join(path,file)
  2103. sftp.put( file_path,'%s/%s' %(RemotePath,re.sub('^%s/' %LocalPath,'',file_path)))
  2104. else:
  2105. sftp.put(LocalPath,RemotePath)
  2106. q.put('successful')
  2107. sftp.close()
  2108. s.close()
  2109. Result = '%s \033[32m传送完成\033[m' % PathList
  2110. return Result
  2111.  
  2112. def Ssh(host_ip,Operation,user_name,user_pwd,root_name,root_pwd,Cmd=None,PathList=None,port=22):
  2113. msg = "\033[32m-----------Result:%s----------\033[m" % host_ip
  2114. try:
  2115. if Operation == 'Ssh_Cmd':
  2116. Result = Ssh_Cmd(host_ip=host_ip,Cmd=Cmd,user_name=user_name,user_pwd=user_pwd,port=port)
  2117. elif Operation == 'Ssh_Su_Cmd':
  2118. 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)
  2119. elif Operation == 'Ssh_Script':
  2120. Send_File(host_ip=host_ip,PathList=PathList,user_name=user_name,user_pwd=user_pwd,port=port)
  2121. Script_Head = open(PathList[0]).readline().strip()
  2122. LocalPath = re.sub('^\./','',PathList[0].rstrip('/'))
  2123. Cmd = '%s /tmp/%s' %( re.sub('^#!','',Script_Head), os.path.basename( LocalPath ))
  2124. Result = Ssh_Cmd(host_ip=host_ip,Cmd=Cmd,user_name=user_name,user_pwd=user_pwd,port=port)
  2125. elif Operation == 'Ssh_Su_Script':
  2126. Send_File(host_ip=host_ip,PathList=PathList,user_name=user_name,user_pwd=user_pwd,port=port)
  2127. Script_Head = open(PathList[0]).readline().strip()
  2128. LocalPath = re.sub('^\./','',PathList[0].rstrip('/'))
  2129. Cmd = '%s /tmp/%s' %( re.sub('^#!','',Script_Head), os.path.basename( LocalPath ))
  2130. 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)
  2131. elif Operation == 'Send_File':
  2132. Result = Send_File(host_ip=host_ip,PathList=PathList,user_name=user_name,user_pwd=user_pwd,port=port)
  2133. else:
  2134. Result = '操作不存在'
  2135.  
  2136. except socket.error:
  2137. Result = '\033[31m主机或端口错误\033[m'
  2138. except paramiko.AuthenticationException:
  2139. Result = '\033[31m用户名或密码错误\033[m'
  2140. except paramiko.BadHostKeyException:
  2141. Result = '\033[31mBad host key\033[m['
  2142. except IOError:
  2143. Result = '\033[31m远程主机已存在非空目录或没有写权限\033[m'
  2144. except:
  2145. Result = '\033[31m未知错误\033[m'
  2146. r.put('%s\n%s\n' %(msg,Result))
  2147.  
  2148. def Concurrent(Conf,Operation,user_name,user_pwd,root_name,root_pwd,Cmd=None,PathList=None,port=22):
  2149. # 读取配置文件
  2150. f=open(Conf)
  2151. list = f.readlines()
  2152. f.close()
  2153. # 执行总计
  2154. total = 0
  2155. # 并发执行
  2156. for host_info in list:
  2157. # 判断配置文件中注释行跳过
  2158. if host_info.startswith('#'):
  2159. continue
  2160. # 取变量,其中任意变量未取到就跳过执行
  2161. try:
  2162. host_ip=host_info.split()[0]
  2163. #user_name=host_info.split()[1]
  2164. #user_pwd=host_info.split()[2]
  2165. except:
  2166. print('Profile error: %s' %(host_info) )
  2167. continue
  2168. try:
  2169. port=int(host_info.split()[3])
  2170. except:
  2171. port=22
  2172. total +=1
  2173. p = multiprocessing.Process(target=Ssh,args=(host_ip,Operation,user_name,user_pwd,root_name,root_pwd,Cmd,PathList,port))
  2174. p.start()
  2175. # 打印执行结果
  2176. for j in range(total):
  2177. print(r.get() )
  2178. if Operation == 'Ssh_Script' or Operation == 'Ssh_Su_Script':
  2179. successful = q.qsize() / 2
  2180. else:
  2181. successful = q.qsize()
  2182. print('\033[32m执行完毕[总执行:%s 成功:%s 失败:%s]\033[m' %(total,successful,total - successful) )
  2183. q.close()
  2184. r.close()
  2185.  
  2186. def Help():
  2187. print(''' 1.执行命令
  2188. 2.执行脚本 \033[32m[位置1脚本(必须带脚本头),后可带执行脚本所需要的包\文件\文件夹路径,空格分隔]\033[m
  2189. 3.发送文件 \033[32m[传送的包\文件\文件夹路径,空格分隔]\033[m
  2190. 退出: 0\exit\quit
  2191. 帮助: help\h\?
  2192. 注意: 发送文件默认为/tmp下,如已存在同名文件会被强制覆盖,非空目录则中断操作.执行脚本先将本地脚本及包发送远程主机上,发送规则同发送文件
  2193. ''')
  2194.  
  2195. if __name__=='__main__':
  2196. # 定义root账号信息
  2197. root_name = 'root'
  2198. root_pwd = 'peterli'
  2199. user_name='peterli'
  2200. user_pwd='<++(3Ie'
  2201. # 配置文件
  2202. Conf='serverlist.conf'
  2203. if not os.path.isfile(Conf):
  2204. print('\033[33m配置文件 %s 不存在\033[m' %(Conf) )
  2205. sys.exit()
  2206. Help()
  2207. while True:
  2208. i = raw_input("\033[35m[请选择操作]: \033[m").strip()
  2209. q = multiprocessing.Queue()
  2210. r = multiprocessing.Queue()
  2211. if i == '':
  2212. if user_name == root_name:
  2213. Operation = 'Ssh_Cmd'
  2214. else:
  2215. Operation = 'Ssh_Su_Cmd'
  2216. Cmd = raw_input('CMD: ').strip()
  2217. if len(Cmd) == 0:
  2218. print('\033[33m命令为空\033[m')
  2219. continue
  2220. Concurrent(Conf=Conf,Operation=Operation,user_name=user_name,user_pwd=user_pwd,root_name=root_name,root_pwd=root_pwd,Cmd=Cmd)
  2221. elif i == '':
  2222. if user_name == root_name:
  2223. Operation = 'Ssh_Script'
  2224. else:
  2225. Operation = 'Ssh_Su_Script'
  2226. PathList = raw_input('\033[36m本地脚本路径: \033[m').strip().split()
  2227. if len(PathList) == 0:
  2228. print('\033[33m路径为空\033[m')
  2229. continue
  2230. if not os.path.isfile(PathList[0]):
  2231. print('\033[33m本地路径 %s 不存在或不是文件\033[m' %(PathList[0]) )
  2232. continue
  2233. for LocalPath in PathList[1:]:
  2234. if not os.path.exists(LocalPath):
  2235. print('\033[33m本地路径 %s 不存在\033[m' %(LocalPath) )
  2236. break
  2237. else:
  2238. Concurrent(Conf=Conf,Operation=Operation,user_name=user_name,user_pwd=user_pwd,root_name=root_name,root_pwd=root_pwd,PathList=PathList)
  2239. elif i == '':
  2240. Operation = 'Send_File'
  2241. PathList = raw_input('\033[36m本地路径: \033[m').strip().split()
  2242. if len(PathList) == 0:
  2243. print('\033[33m路径为空\033[m')
  2244. continue
  2245. for LocalPath in PathList:
  2246. if not os.path.exists(LocalPath):
  2247. print('\033[33m本地路径 %s 不存在\033[m' %(LocalPath) )
  2248. break
  2249. else:
  2250. Concurrent(Conf=Conf,Operation=Operation,user_name=user_name,user_pwd=user_pwd,root_name=root_name,root_pwd=root_pwd,PathList=PathList)
  2251. elif i == '' or i == 'exit' or i == 'quit':
  2252. print("\033[34m退出LazyManage脚本\033[m")
  2253. sys.exit()
  2254. elif i == 'help' or i == 'h' or i == '?':
  2255. Help()
  2256.  
  2257. web页面操作
  2258.  
  2259. 下载文件
  2260.  
  2261. #!/usr/bin/env python
  2262. #encoding:utf8
  2263. import urllib2
  2264.  
  2265. url = 'http://www.01happy.com/wp-content/uploads/2012/09/bg.png'
  2266. file("./pic/%04d.png" % i, "wb").write(urllib2.urlopen(url).read())
  2267.  
  2268. 读取网页指定内容
  2269.  
  2270. #读取整个网页,正则截取匹配信息
  2271. #!/usr/bin/env python
  2272. #encoding=utf-8
  2273. import re, urllib,datetime
  2274. def getPageCode(url, fromCharset, toCharset):
  2275. fr = urllib.urlopen(url)
  2276. pageCode = fr.read()
  2277. fr.close()
  2278. return pageCode
  2279. def getImgUrl(pageCode):
  2280. pattern = re.compile(r'(\d*\-\d*\-\d* \d*:\d*:\d*)')
  2281. return re.findall(pattern, pageCode)
  2282.  
  2283. if __name__ == '__main__':
  2284. f = file('url.conf')
  2285. c = f.readlines()
  2286. f.close()
  2287. for url in c:
  2288. pageCode = getPageCode(url.rstrip(), 'gb2312', 'utf8')
  2289. imgUrl = getImgUrl(pageCode)
  2290. print imgUrl
  2291.  
  2292. 读取网页图片大小
  2293.  
  2294. # 根据http头,得到content-type的值
  2295. #!/usr/bin/env python
  2296. #encoding=utf-8
  2297. import urllib2
  2298. url = 'http://www.01happy.com/wp-content/uploads/2012/09/bg.png'
  2299. reqst = urllib2.Request(url)
  2300. opener = urllib2.build_opener()
  2301. con = opener.open(reqst)
  2302. Type = con.headers.dict['content-type'][:5]
  2303. Length = int(con.headers.dict['content-length'])
  2304. if Length > 0:
  2305. print(Length)
  2306. print(Type)
  2307.  
  2308. 查看网页图片尺寸类型
  2309.  
  2310. #将图片读入内存
  2311. #!/usr/bin/env python
  2312. #encoding=utf-8
  2313. import cStringIO, urllib2, Image
  2314. url = 'http://www.01happy.com/wp-content/uploads/2012/09/bg.png'
  2315. file = urllib2.urlopen(url)
  2316. tmpIm = cStringIO.StringIO(file.read())
  2317. im = Image.open(tmpIm)
  2318. print im.format, im.size, im.mode
  2319.  
  2320. requests读取网页信息
  2321.  
  2322. #Requests是一个Python的HTTP客户端库
  2323. #安装: sudo pip install requests
  2324. import requests
  2325. r = requests.get('http://baidu.com')
  2326. #r = requests.get('https://baidu.com', auth=('user', 'pass')) # https需登录加auth
  2327. r.status_code # 状态码
  2328. r.headers # 网页头信息
  2329. r.headers['content-type'] # 网页头信息
  2330. r.headers['content-length'] # 网页头信息
  2331. r.text # 网页源码
  2332. r.content # 网页源码
  2333.  
  2334. 爬虫
  2335.  
  2336. #!/usr/bin/env python
  2337. #encoding:utf-8
  2338. #sudo pip install BeautifulSoup
  2339.  
  2340. import requests
  2341. from BeautifulSoup import BeautifulSoup
  2342. import re
  2343.  
  2344. baseurl = 'http://blog.sina.com.cn/s/articlelist_1191258123_0_1.html'
  2345.  
  2346. r = requests.get(baseurl)
  2347.  
  2348. for url in re.findall('<a.*?</a>', r.content, re.S):
  2349. if url.startswith('<a title='):
  2350. with open(r'd:/final.txt', 'ab') as f:
  2351. f.write(url + '\n')
  2352.  
  2353. linkfile = open(r'd:/final.txt', 'rb')
  2354. soup = BeautifulSoup(linkfile)
  2355. for link in soup.findAll('a'):
  2356. #print link.get('title') + ': ' + link.get('href')
  2357. ss = requests.get(link.get('href'))
  2358. for content in re.findall('<div id="sina_keyword_ad_area2" class="articalContent ">.*?</div>', ss.content, re.S):
  2359. with open(r'd:/myftp/%s.txt'%link.get('title').strip('<>'), 'wb') as f:
  2360. f.write(content)
  2361. print '%s has been copied.' % link.get('title')
  2362.  
  2363. 反垃圾邮件提交申诉
  2364.  
  2365. #!/usr/bin/env python
  2366. #encoding:utf-8
  2367. import requests
  2368. import re
  2369.  
  2370. IpList=['113.212.91.25','113.212.91.23']
  2371. QueryAdd='http://www.anti-spam.org.cn/Rbl/Query/Result'
  2372. ComplaintAdd='http://www.anti-spam.org.cn/Rbl/Getout/Submit'
  2373. data = {
  2374. 'CONTENT':'''我们是一家正规的XXX。xxxxxxx。恳请将我们的发送服务器IP移出黑名单。谢谢!
  2375. 处理措施:
  2376. 1.XXXX。
  2377. 2.XXXX。''',
  2378. 'CORP':'abc.com',
  2379. 'WWW':'www.abc.cm',
  2380. 'NAME':'def',
  2381. 'MAIL':'def@163.com.cn',
  2382. 'TEL':'010-50000000',
  2383. 'LEVEL':'',
  2384. }
  2385.  
  2386. for Ip in IpList:
  2387. query = requests.post(url=QueryAdd, data={'IP':Ip}) # 黑名单查询
  2388. if query.ok:
  2389. if re.findall(u'\u7533\u8bc9\u8131\u79bb', query.text, re.S): # 查找关键字 申诉脱离 既表明在黑名单中
  2390. data['IP']=Ip
  2391. complaint = requests.post(url=ComplaintAdd, data=data) # 提交申诉
  2392. if complaint.ok:
  2393. if re.findall(u'\u60a8\u7684\u9ed1\u540d\u5355\u8131\u79bb\u7533\u8bf7\u5df2\u63d0\u4ea4', complaint.text, re.S):
  2394. status='申请提交'
  2395. elif re.findall(u'\u8131\u79bb\u7533\u8bf7\u5df2\u88ab\u4ed6\u4eba\u63d0\u4ea4', complaint.text, re.S):
  2396. status='重复提交'
  2397. elif re.findall(u'\u7533\u8bf7\u7531\u4e8e\u8fd1\u671f\u5185\u6709\u88ab\u62d2\u7edd\u7684\u8bb0\u5f55', complaint.text, re.S):
  2398. status='近期拒绝'
  2399. else:
  2400. status='异常'
  2401. else:
  2402. status='正常'
  2403. print '%s %s' %(Ip,status)
  2404.  
  2405. 发送邮件
  2406.  
  2407. 发送邮件内容
  2408.  
  2409. #!/usr/bin/python
  2410. #encoding:utf8
  2411. # 导入 smtplib 和 MIMEText
  2412. import smtplib
  2413. from email.mime.text import MIMEText
  2414.  
  2415. # 定义发送列表
  2416. mailto_list=["272121935@qq.com","272121935@163.com"]
  2417.  
  2418. # 设置服务器名称、用户名、密码以及邮件后缀
  2419. mail_host = "smtp.163.com"
  2420. mail_user = "mailuser"
  2421. mail_pass = "password"
  2422. mail_postfix="163.com"
  2423.  
  2424. # 发送邮件函数
  2425. def send_mail(to_list, sub):
  2426. me = mail_user + "<"+mail_user+"@"+mail_postfix+">"
  2427. fp = open('context.txt')
  2428. msg = MIMEText(fp.read(),_charset="utf-8")
  2429. fp.close()
  2430. msg['Subject'] = sub
  2431. msg['From'] = me
  2432. msg['To'] = ";".join(to_list)
  2433. try:
  2434. send_smtp = smtplib.SMTP()
  2435. send_smtp.connect(mail_host)
  2436. send_smtp.login(mail_user, mail_pass)
  2437. send_smtp.sendmail(me, to_list, msg.as_string())
  2438. send_smtp.close()
  2439. return True
  2440. except Exception, e:
  2441. print str(e)
  2442. return False
  2443.  
  2444. if send_mail(mailto_list,"标题"):
  2445. print "测试成功"
  2446. else:
  2447. print "测试失败"
  2448.  
  2449. 发送附件
  2450.  
  2451. #!/usr/bin/python
  2452. #encoding:utf8
  2453. import smtplib
  2454. from email.mime.multipart import MIMEMultipart
  2455. from email.mime.base import MIMEBase
  2456. from email import encoders
  2457.  
  2458. def send_mail(to_list, sub, filename):
  2459. me = mail_user + "<"+mail_user+"@"+mail_postfix+">"
  2460. msg = MIMEMultipart()
  2461. msg['Subject'] = sub
  2462. msg['From'] = me
  2463. msg['To'] = ";".join(to_list)
  2464. submsg = MIMEBase('application', 'x-xz')
  2465. submsg.set_payload(open(filename,'rb').read())
  2466. encoders.encode_base64(submsg)
  2467. submsg.add_header('Content-Disposition', 'attachment', filename=filename)
  2468. msg.attach(submsg)
  2469. try:
  2470. send_smtp = smtplib.SMTP()
  2471. send_smtp.connect(mail_host)
  2472. send_smtp.login(mail_user, mail_pass)
  2473. send_smtp.sendmail(me, to_list, msg.as_string())
  2474. send_smtp.close()
  2475. return True
  2476. except Exception, e:
  2477. print str(e)[1]
  2478. return False
  2479.  
  2480. # 设置服务器名称、用户名、密码以及邮件后缀
  2481. mail_host = "smtp.163.com"
  2482. mail_user = "xuesong"
  2483. mail_pass = "mailpasswd"
  2484. mail_postfix = "163.com"
  2485. mailto_list = ["272121935@qq.com","quanzhou722@163.com"]
  2486. title = 'check'
  2487. filename = 'file_check.html'
  2488. if send_mail(mailto_list,title,filename):
  2489. print "发送成功"
  2490. else:
  2491. print "发送失败"
  2492.  
  2493. 解压缩
  2494.  
  2495. gzip压缩
  2496.  
  2497. import gzip
  2498. f_in = open('file.log', 'rb')
  2499. f_out = gzip.open('file.log.gz', 'wb')
  2500. f_out.writelines(f_in)
  2501. f_out.close()
  2502. f_in.close()
  2503.  
  2504. gzip压缩1
  2505.  
  2506. File = 'xuesong_18.log'
  2507. g = gzip.GzipFile(filename="", mode='wb', compresslevel=9, fileobj=open((r'%s.gz' %File),'wb'))
  2508. g.write(open(r'%s' %File).read())
  2509. g.close()
  2510.  
  2511. gzip解压
  2512.  
  2513. g = gzip.GzipFile(mode='rb', fileobj=open((r'xuesong_18.log.gz'),'rb'))
  2514. open((r'xuesong_18.log'),'wb').write(g.read())
  2515.  
  2516. 压缩tar.gz
  2517.  
  2518. import os
  2519. import tarfile
  2520. tar = tarfile.open("/tmp/tartest.tar.gz","w:gz") # 创建压缩包名
  2521. for path,dir,files in os.walk("/tmp/tartest"): # 递归文件目录
  2522. for file in files:
  2523. fullpath = os.path.join(path,file)
  2524. tar.add(fullpath) # 创建压缩包
  2525. tar.close()
  2526.  
  2527. 解压tar.gz
  2528.  
  2529. import tarfile
  2530. tar = tarfile.open("/tmp/tartest.tar.gz")
  2531. #tar.extract("/tmp") # 全部解压到指定路径
  2532. names = tar.getnames() # 包内文件名
  2533. for name in names:
  2534. tar.extract(name,path="./") # 解压指定文件
  2535. tar.close()
  2536.  
  2537. zip压缩
  2538. import zipfile,os
  2539. f = zipfile.ZipFile('filename.zip', 'w' ,zipfile.ZIP_DEFLATED) # ZIP_STORE 为默认表不压缩. ZIP_DEFLATED 表压缩
  2540. #f.write('file1.txt') # 将文件写入压缩包
  2541. for path,dir,files in os.walk("tartest"): # 递归压缩目录
  2542. for file in files:
  2543. f.write(os.path.join(path,file)) # 将文件逐个写入压缩包
  2544. f.close()
  2545.  
  2546. zip解压
  2547. if zipfile.is_zipfile('filename.zip'): # 判断一个文件是不是zip文件
  2548. f = zipfile.ZipFile('filename.zip')
  2549. for file in f.namelist(): # 返回文件列表
  2550. f.extract(file, r'/tmp/') # 解压指定文件
  2551. #f.extractall() # 解压全部
  2552. f.close()
  2553.  
  2554. 时间
  2555.  
  2556. import time
  2557. time.strftime('%Y-%m-%d_%X',time.localtime( time.time() ) )
  2558.  
  2559. 格式化时间
  2560. tomorrow.strftime('%Y%m%d_%H%M')
  2561.  
  2562. 上一个月最后一天
  2563. import datetime
  2564. lastMonth=datetime.date(datetime.date.today().year,datetime.date.today().month,1)-datetime.timedelta(1)
  2565. lastMonth.strftime("%Y/%m")
  2566.  
  2567. 前一天
  2568. (datetime.datetime.now() + datetime.timedelta(days=-1) ).strftime('%Y%m%d')
  2569.  
  2570. 上个月
  2571. time.localtime()[1] - 1
  2572.  
  2573. 时间戳转换可读时间
  2574. a=time.time()
  2575. time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(a))
  2576.  
  2577. 编码转换
  2578.  
  2579. a='中文' # 编码未定义按输入终端utf8或gbk
  2580. u=u'中文' # 定义为unicode编码 u值为 u'\u4e2d\u6587'
  2581. u.encode('utf8') # 转为utf8格式 u值为 '\xe4\xb8\xad\xe6\x96\x87'
  2582. print u # 结果显示 中文
  2583. print u.encode('utf8') # 转为utf8格式,当显示终端编码为utf8 结果显示 中文 编码不一致则乱码
  2584. print u.encode('gbk') # 当前终端为utf8 故乱码
  2585.  
  2586. ord('') # 字符转ASCII码
  2587. chr(52) # ASCII码转字符
  2588.  
  2589. hash
  2590.  
  2591. import md5
  2592. m = md5.new('').hexdigest()
  2593.  
  2594. import hashlib
  2595. m = hashlib.md5()
  2596. m.update("Nobody inspects") # 使用update方法对字符串md5加密
  2597. m.digest() # 加密后二进制结果
  2598. m.hexdigest() # 加密后十进制结果
  2599. hashlib.new("md5", "string").hexdigest() # 对字符串加密
  2600. hashlib.new("md5", open("file").read()).hexdigest() # 查看文件MD5值
  2601.  
  2602. 隐藏输入密码
  2603.  
  2604. import getpass
  2605. passwd=getpass.getpass()
  2606.  
  2607. 遍历递归
  2608.  
  2609. [os.path.join(x[0],y) for x in os.walk('/root/python/5') for y in x[2]]
  2610.  
  2611. for i in os.walk('/root/python/5/work/server'):
  2612. print i
  2613.  
  2614. Python处理信号
  2615.  
  2616. 信号的概念
  2617.  
  2618. 信号(signal): 进程之间通讯的方式,是一种软件中断。一个进程一旦接收到信号就会打断原来的程序执行流程来处理信号。
  2619. 发送信号一般有两种原因:
  2620. 1(被动式) 内核检测到一个系统事件.例如子进程退出会像父进程发送SIGCHLD信号.键盘按下control+c会发送SIGINT信号
  2621. 2(主动式) 通过系统调用kill来向指定进程发送信号
  2622. 操作系统规定了进程收到信号以后的默认行为,可以通过绑定信号处理函数来修改进程收到信号以后的行为,有两个信号是不可更改的 SIGTOP SIGKILL
  2623. 如果一个进程收到一个SIGUSR1信号,然后执行信号绑定函数,第二个SIGUSR2信号又来了,第一个信号没有被处理完毕的话,第二个信号就会丢弃。
  2624. 进程结束信号 SIGTERM SIGKILL 的区别: SIGTERM 比较友好,进程能捕捉这个信号,根据您的需要来关闭程序。在关闭程序之前,您可以结束打开的记录文件和完成正在做的任务。在某些情况下,假如进程正在进行作业而且不能中断,那么进程可以忽略这个SIGTERM信号。
  2625.  
  2626. 常见信号
  2627. kill -l # 查看linux提供的信号
  2628.  
  2629. SIGHUP 1 A # 终端挂起或者控制进程终止
  2630. SIGINT 2 A # 键盘终端进程(如control+c)
  2631. SIGQUIT 3 C # 键盘的退出键被按下
  2632. SIGILL 4 C # 非法指令
  2633. SIGABRT 6 C # 由abort(3)发出的退出指令
  2634. SIGFPE 8 C # 浮点异常
  2635. SIGKILL 9 AEF # Kill信号 立刻停止
  2636. SIGSEGV 11 C # 无效的内存引用
  2637. SIGPIPE 13 A # 管道破裂: 写一个没有读端口的管道
  2638. SIGALRM 14 A # 闹钟信号 由alarm(2)发出的信号
  2639. SIGTERM 15 A # 终止信号,可让程序安全退出 kill -15
  2640. SIGUSR1 30,10,16 A # 用户自定义信号1
  2641. SIGUSR2 31,12,17 A # 用户自定义信号2
  2642. SIGCHLD 20,17,18 B # 子进程结束自动向父进程发送SIGCHLD信号
  2643. SIGCONT 19,18,25 # 进程继续(曾被停止的进程)
  2644. SIGSTOP 17,19,23 DEF # 终止进程
  2645. SIGTSTP 18,20,24 D # 控制终端(tty)上按下停止键
  2646. SIGTTIN 21,21,26 D # 后台进程企图从控制终端读
  2647. SIGTTOU 22,22,27 D # 后台进程企图从控制终端写
  2648.  
  2649. 缺省处理动作一项中的字母含义如下:
  2650. A 缺省的动作是终止进程
  2651. B 缺省的动作是忽略此信号,将该信号丢弃,不做处理
  2652. C 缺省的动作是终止进程并进行内核映像转储(dump core),内核映像转储是指将进程数据在内存的映像和进程在内核结构中的部分内容以一定格式转储到文件系统,并且进程退出执行,这样做的好处是为程序员提供了方便,使得他们可以得到进程当时执行时的数据值,允许他们确定转储的原因,并且可以调试他们的程序。
  2653. D 缺省的动作是停止进程,进入停止状况以后还能重新进行下去,一般是在调试的过程中(例如ptrace系统调用)
  2654. E 信号不能被捕获
  2655. F 信号不能被忽略
  2656.  
  2657. Python提供的信号
  2658. import signal
  2659. dir(signal)
  2660. ['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']
  2661.  
  2662. 绑定信号处理函数
  2663. #encoding:utf8
  2664. import os,signal
  2665. from time import sleep
  2666. def onsignal_term(a,b):
  2667. print 'SIGTERM' # kill -15
  2668. signal.signal(signal.SIGTERM,onsignal_term) # 接收信号,执行相应函数
  2669.  
  2670. def onsignal_usr1(a,b):
  2671. print 'SIGUSR1' # kill -10
  2672. signal.signal(signal.SIGUSR1,onsignal_usr1)
  2673.  
  2674. while 1:
  2675. print 'ID',os.getpid()
  2676. sleep(10)
  2677.  
  2678. 通过另外一个进程发送信号
  2679. import os,signal
  2680. os.kill(16175,signal.SIGTERM) # 发送信号,16175是绑定信号处理函数的进程pid,需要自行修改
  2681. os.kill(16175,signal.SIGUSR1)
  2682.  
  2683. 父进程接收子进程结束发送的SIGCHLD信号
  2684. #encoding:utf8
  2685. import os,signal
  2686. from time import sleep
  2687.  
  2688. def onsigchld(a,b):
  2689. print '收到子进程结束信号'
  2690. signal.signal(signal.SIGCHLD,onsigchld)
  2691.  
  2692. pid = os.fork() # 创建一个子进程,复制父进程所有资源操作
  2693. if pid == 0: # 通过判断子进程os.fork()是否等于0,分别同时执行父进程与子进程操作
  2694. print '我是子进程,pid是',os.getpid()
  2695. sleep(2)
  2696. else:
  2697. print '我是父进程,pid是',os.getpid()
  2698. os.wait() # 等待子进程结束
  2699.  
  2700. 接收信号的程序,另外一端使用多线程向这个进程发送信号,会遗漏一些信号
  2701. #encoding:utf8
  2702. import os
  2703. import signal
  2704. from time import sleep
  2705. import Queue
  2706. QCOUNT = Queue.Queue() # 初始化队列
  2707. def onsigchld(a,b):
  2708. '''收到信号后向队列中插入一个数字1'''
  2709. print '收到SIGUSR1信号'
  2710. sleep(1)
  2711. QCOUNT.put(1) # 向队列中写入
  2712. signal.signal(signal.SIGUSR1,onsigchld) # 绑定信号处理函数
  2713. while 1:
  2714. print '我的pid是',os.getpid()
  2715. print '现在队列中元素的个数是',QCOUNT.qsize()
  2716. sleep(2)
  2717.  
  2718. 多线程发信号端的程序
  2719.  
  2720. #encoding:utf8
  2721. import threading
  2722. import os
  2723. import signal
  2724. def sendusr1():
  2725. print '发送信号'
  2726. os.kill(17788, signal.SIGUSR1) # 这里的进程id需要写前一个程序实际运行的pid
  2727. WORKER = []
  2728. for i in range(1, 7): # 开启6个线程
  2729. threadinstance = threading.Thread(target = sendusr1)
  2730. WORKER.append(threadinstance)
  2731. for i in WORKER:
  2732. i.start()
  2733. for i in WORKER:
  2734. i.join()
  2735. print '主线程完成'
  2736.  
  2737. python使用memcache
  2738.  
  2739. easy_install python-memcached # 安装(python2.7+)
  2740. import memcache
  2741. mc = memcache.Client(['10.152.14.85:12000'],debug=True)
  2742. mc.set('name','luo',60)
  2743. mc.get('name')
  2744. mc.delete('name1')
  2745.  
  2746. 保存数据
  2747.  
  2748. set(key,value,timeout) # 把key映射到value,timeout指的是什么时候这个映射失效
  2749. add(key,value,timeout) # 仅当存储空间中不存在键相同的数据时才保存
  2750. replace(key,value,timeout) # 仅当存储空间中存在键相同的数据时才保存
  2751.  
  2752. 获取数据
  2753.  
  2754. get(key) # 返回key所指向的value
  2755. get_multi(key1,key2,key3) # 可以非同步地同时取得多个键值, 比循环调用get快数十倍
  2756.  
  2757. python使用mongodb
  2758.  
  2759. 原文: http://blog.nosqlfan.com/html/2989.html
  2760.  
  2761. easy_install pymongo # 安装(python2.7+)
  2762. import pymongo
  2763. connection=pymongo.Connection('localhost',27017) # 创建连接
  2764. db = connection.test_database # 切换数据库
  2765. collection = db.test_collection # 获取collection
  2766. # db和collection都是延时创建的,在添加Document时才真正创建
  2767.  
  2768. 文档添加, _id自动创建
  2769. import datetime
  2770. post = {"author": "Mike",
  2771. "text": "My first blog post!",
  2772. "tags": ["mongodb", "python", "pymongo"],
  2773. "date": datetime.datetime.utcnow()}
  2774. posts = db.posts
  2775. posts.insert(post)
  2776. ObjectId('...')
  2777.  
  2778. 批量插入
  2779. new_posts = [{"author": "Mike",
  2780. "text": "Another post!",
  2781. "tags": ["bulk", "insert"],
  2782. "date": datetime.datetime(2009, 11, 12, 11, 14)},
  2783. {"author": "Eliot",
  2784. "title": "MongoDB is fun",
  2785. "text": "and pretty easy too!",
  2786. "date": datetime.datetime(2009, 11, 10, 10, 45)}]
  2787. posts.insert(new_posts)
  2788. [ObjectId('...'), ObjectId('...')]
  2789.  
  2790. 获取所有collection
  2791. db.collection_names() # 相当于SQL的show tables
  2792.  
  2793. 获取单个文档
  2794. posts.find_one()
  2795.  
  2796. 查询多个文档
  2797. for post in posts.find():
  2798. post
  2799.  
  2800. 加条件的查询
  2801. posts.find_one({"author": "Mike"})
  2802.  
  2803. 高级查询
  2804. posts.find({"date": {"$lt": "d"}}).sort("author")
  2805.  
  2806. 统计数量
  2807. posts.count()
  2808.  
  2809. 加索引
  2810. from pymongo import ASCENDING, DESCENDING
  2811. posts.create_index([("date", DESCENDING), ("author", ASCENDING)])
  2812.  
  2813. 查看查询语句的性能
  2814. posts.find({"date": {"$lt": "d"}}).sort("author").explain()["cursor"]
  2815. posts.find({"date": {"$lt": "d"}}).sort("author").explain()["nscanned"]
  2816.  
  2817. 斐波那契
  2818. #将函数结果作为列表可用于循环
  2819. def fab(max):
  2820. n, a, b = 0, 0, 1
  2821. while n < max:
  2822. yield b
  2823. a, b = b, a + b
  2824. n = n + 1
  2825. for n in fab(5):
  2826. print n
  2827.  
  2828. 乘法口诀
  2829.  
  2830. #!/usr/bin/python
  2831. for i in range(1,10):
  2832. for j in range(1,i+1):
  2833. print j,'*',i,'=',j*i,
  2834. else:
  2835. print ''
  2836.  
  2837. 最小公倍数
  2838.  
  2839. # 1-70的最小公倍数
  2840. def c(m,n):
  2841. a1=m
  2842. b1=n
  2843. r=n%m
  2844. while r!=0:
  2845. n=m
  2846. m=r
  2847. r=n%m
  2848. return (a1*b1)/m
  2849. d=1
  2850. for i in range(3,71,2):
  2851. d = c(d,i)
  2852. print d
  2853.  
  2854. PIL图像处理
  2855.  
  2856. import Image
  2857. im = Image.open("j.jpg") # 打开图片
  2858. print im.format, im.size, im.mode # 打印图像格式、像素宽和高、模式
  2859. # JPEG (440, 330) RGB
  2860. im.show() # 显示最新加载图像
  2861. box = (100, 100, 200, 200)
  2862. region = im.crop(box) # 从图像中提取出某个矩形大小的图像
  2863.  
  2864. 图片等比缩小
  2865.  
  2866. # -*- coding: cp936 -*-
  2867. import Image
  2868. import glob, os
  2869.  
  2870. #图片批处理
  2871. def timage():
  2872. for files in glob.glob('D:\\1\\*.JPG'):
  2873. filepath,filename = os.path.split(files)
  2874. filterame,exts = os.path.splitext(filename)
  2875. #输出路径
  2876. opfile = r'D:\\22\\'
  2877. #判断opfile是否存在,不存在则创建
  2878. if (os.path.isdir(opfile)==False):
  2879. os.mkdir(opfile)
  2880. im = Image.open(files)
  2881. w,h = im.size
  2882. #im_ss = im.resize((400,400))
  2883. #im_ss = im.convert('P')
  2884. im_ss = im.resize((int(w*0.12), int(h*0.12)))
  2885. im_ss.save(opfile+filterame+'.jpg')
  2886.  
  2887. if __name__=='__main__':
  2888. timage()
  2889.  
  2890. 取系统返回值赋给序列
  2891.  
  2892. cmd = os.popen("df -Ph|awk 'NR!=1{print $5}'").readlines();
  2893. cmd = os.popen('df -h').read().split('\n')
  2894. cmd = os.popen('lo 2>&1').read()
  2895.  
  2896. #取磁盘使用空间
  2897. import commands
  2898. df = commands.getoutput("df -hP")
  2899. [ x.split()[4] for x in df.split("\n") ]
  2900. [ (x.split()[0],x.split()[4]) for x in df.split("\n") if x.split()[4].endswith("%") ]
  2901.  
  2902. 将列表去重复
  2903.  
  2904. list(set(['qwe', 'as', '', '']))
  2905.  
  2906. 将列表转换成字符串
  2907.  
  2908. '\t'.join(li)
  2909.  
  2910. curses
  2911.  
  2912. import curses
  2913. myscreen = curses.initscr() # 初始化一个图形框
  2914. myscreen.border(0) # 定义边框宽度
  2915. myscreen.addstr(12, 25, "Python curses in action!") # 打印的位置
  2916. myscreen.refresh() # 使框生效
  2917. myscreen.getch() # 等待键盘输入
  2918. curses.endwin() # 关闭
  2919.  
  2920. curses菜单
  2921.  
  2922. #!/usr/bin/env python
  2923. #menu.py
  2924.  
  2925. from os import system
  2926. import curses
  2927.  
  2928. def get_param(prompt_string):
  2929. screen.clear()
  2930. screen.border(0)
  2931. screen.addstr(2, 2, prompt_string)
  2932. screen.refresh()
  2933. input = screen.getstr(10, 10, 60) # 等待用户输入内容赋值变量
  2934. return input
  2935.  
  2936. def execute_cmd(cmd_string):
  2937. system("clear")
  2938. a = system(cmd_string)
  2939. print ""
  2940. if a == 0:
  2941. print "Command executed correctly"
  2942. else:
  2943. print "Command terminated with error"
  2944. raw_input("Press enter")
  2945. print ""
  2946.  
  2947. x = 0
  2948.  
  2949. while x != ord(''): # 字符转ASCII码 chr
  2950. screen = curses.initscr()
  2951.  
  2952. screen.clear()
  2953. screen.border(0)
  2954. screen.addstr(2, 2, "Please enter a number...")
  2955. screen.addstr(4, 4, "1 - Add a user")
  2956. screen.addstr(5, 4, "2 - Restart Apache")
  2957. screen.addstr(6, 4, "3 - Show disk space")
  2958. screen.addstr(7, 4, "4 - Exit")
  2959. screen.refresh()
  2960.  
  2961. x = screen.getch()
  2962.  
  2963. if x == ord(''):
  2964. username = get_param("Enter the username")
  2965. homedir = get_param("Enter the home directory, eg /home/nate")
  2966. groups = get_param("Enter comma-separated groups, eg adm,dialout,cdrom")
  2967. shell = get_param("Enter the shell, eg /bin/bash:")
  2968. curses.endwin()
  2969. execute_cmd("useradd -d " + homedir + " -g 1000 -G " + groups + " -m -s " + shell + " " + username)
  2970. if x == ord(''):
  2971. curses.endwin()
  2972. execute_cmd("apachectl restart")
  2973. if x == ord(''):
  2974. curses.endwin()
  2975. execute_cmd("df -h")
  2976.  
  2977. curses.endwin()
  2978.  
  2979. 打印表格
  2980.  
  2981. map = [["a","b","c"],
  2982. ["d","e","f"],
  2983. ["g","h","i"]]
  2984. def print_board():
  2985. for i in range(0,3):
  2986. for j in range(0,3):
  2987. print "|",map[i][j],
  2988. #if j != 2:
  2989. print '|'
  2990.  
  2991. 生成html文件表格
  2992.  
  2993. log_file = file('check.html', 'w')
  2994. log_file.write("""
  2995. <!DOCTYPE HTML>
  2996. <html lang="utr-8">
  2997. <head>
  2998. <meta charset="UTF-8">
  2999. <title></title>
  3000. </head>
  3001. <body>
  3002. <table align='center' border='0' cellPadding='0' style='font-size:24px;'><tr ><td>状态统计</td></tr></table>
  3003. <style>.font{font-size:13px}</style>
  3004. <table align='center' border='1' borderColor=gray cellPadding=3 width=1350 class='font'>
  3005. <tr style='background-color:#666666'>
  3006. <th width=65>IP</th>
  3007. <th width=65>状态</th>
  3008. </tr>
  3009. """)
  3010. for i in list:
  3011. log_file.write('<tr><td>%s</td><td>%s</td></tr>\n' %(i.split()[0],i.split()[1]) )
  3012. log_file.write("""
  3013. </table>
  3014. </body>
  3015. </html>
  3016. """)
  3017. log_file.flush()
  3018. log_file.close()
  3019.  
  3020. 井字游戏
  3021.  
  3022. #!/usr/bin/python
  3023. # http://www.admin10000.com/document/2506.html
  3024. def print_board():
  3025. for i in range(0,3):
  3026. for j in range(0,3):
  3027. print map[2-i][j],
  3028. if j != 2:
  3029. print "|",
  3030. print ""
  3031.  
  3032. def check_done():
  3033. for i in range(0,3):
  3034. if map[i][0] == map[i][1] == map[i][2] != " " \
  3035. or map[0][i] == map[1][i] == map[2][i] != " ":
  3036. print turn, "won!!!"
  3037. return True
  3038.  
  3039. if map[0][0] == map[1][1] == map[2][2] != " " \
  3040. or map[0][2] == map[1][1] == map[2][0] != " ":
  3041. print turn, "won!!!"
  3042. return True
  3043.  
  3044. if " " not in map[0] and " " not in map[1] and " " not in map[2]:
  3045. print "Draw"
  3046. return True
  3047.  
  3048. return False
  3049.  
  3050. turn = "X"
  3051. map = [[" "," "," "],
  3052. [" "," "," "],
  3053. [" "," "," "]]
  3054. done = False
  3055.  
  3056. while done != True:
  3057. print_board()
  3058.  
  3059. print turn, "'s turn"
  3060. print
  3061.  
  3062. moved = False
  3063. while moved != True:
  3064. print "Please select position by typing in a number between 1 and 9, see below for which number that is which position..."
  3065. print "7|8|9"
  3066. print "4|5|6"
  3067. print "1|2|3"
  3068. print
  3069.  
  3070. try:
  3071. pos = input("Select: ")
  3072. if pos <=9 and pos >=1:
  3073. Y = pos/3
  3074. X = pos%3
  3075. if X != 0:
  3076. X -=1
  3077. else:
  3078. X = 2
  3079. Y -=1
  3080.  
  3081. if map[Y][X] == " ":
  3082. map[Y][X] = turn
  3083. moved = True
  3084. done = check_done()
  3085.  
  3086. if done == False:
  3087. if turn == "X":
  3088. turn = "O"
  3089. else:
  3090. turn = "X"
  3091.  
  3092. except:
  3093. print "You need to add a numeric value"
  3094.  
  3095. 网段划分
  3096.  
  3097. 题目
  3098. 192.168.1
  3099. 192.168.3
  3100. 192.168.2
  3101. 172.16.3
  3102. 192.16.1
  3103. 192.16.2
  3104. 192.16.3
  3105. 10.0.4
  3106.  
  3107. 输出结果:
  3108. 192.16.1-192.16.3
  3109. 192.168.1-192.168.3
  3110. 172.16.3
  3111. 10.0.4
  3112.  
  3113. 答案
  3114. #!/usr/bin/python
  3115.  
  3116. f = file('a.txt')
  3117. c = f.readlines()
  3118. dic={}
  3119.  
  3120. for i in c:
  3121. a=i.strip().split('.')
  3122. if a[0]+'.'+a[1] in dic.keys():
  3123. key=dic["%s.%s" %(a[0],a[1])]
  3124. else:
  3125. key=[]
  3126. key.append(a[2])
  3127. dic[a[0]+'.'+a[1]]=sorted(key)
  3128.  
  3129. for x,y in dic.items():
  3130. if y[0] == y[-1]:
  3131. print '%s.%s' %(x,y[0])
  3132. else:
  3133. print '%s.%s-%s.%s' %(x,y[0],x,y[-1])
  3134.  
  3135. 统计日志IP
  3136. # 打印出独立IP,并统计独立IP数
  3137. 219.140.190.130 - - [23/May/2006:08:57:59 +0800] "GET /fg172.exe HTTP/1.1" 200 2350253
  3138. 221.228.143.52 - - [23/May/2006:08:58:08 +0800] "GET /fg172.exe HTTP/1.1" 206 719996
  3139. 221.228.143.52 - - [23/May/2006:08:58:08 +0800] "GET /fg172.exe HTTP/1.1" 206 713242
  3140.  
  3141. #!/usr/bin/python
  3142. dic={}
  3143. a=open("a").readlines()
  3144. for i in a:
  3145. ip=i.strip().split()[0]
  3146. if ip in dic.keys():
  3147. dic[ip] = dic[ip] + 1
  3148. else:
  3149. dic[ip] = 1
  3150. for x,y in dic.items():
  3151. print x," ",y
  3152.  
  3153. 打印a-z
  3154. import string
  3155. string.lowercase # a-z小写
  3156. string.uppercase # A-Z大小

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

  1. 转载 python实例手册

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

  2. 【转载】python实例手册

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

  3. Python实例手册

    在电脑中突然发现一个这么好的资料,雪松大神制作,不敢独享,特与大家共享.连他的广告也一并复制了吧! python实例手册 #encoding:utf8 # 设定编码-支持中文 0说明 手册制作: 雪松 ...

  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. Spring、SpringMVC、Mybaitis框架配置

    给大家推荐2个网址,介绍的非常详细 SSM环境搭建 http://blog.csdn.net/zhshulin/article/details/37956105 SSM代码生成工具介绍 http:// ...

  2. [QualityCenter]设置工作流脚本-新建缺陷时描述字段模板设置

    需求:实现新建缺陷时,描述模板自动生成填写模板. 在脚本编辑器找到Defects_Bug_New函数,然后填写以下代码: Sub Defects_Bug_New    On Error Resume ...

  3. Effective Java 17 Design and document for inheritance or else prohibit it

    Principles The class must document its self-use of overridable methods. A class may have to provide ...

  4. 我的Windows核心编程——完成端口+套接字 图解

    ========================声明============================ 本文原创,转载请注明作者和出处,并保证文章的完整性(包括本声明). 本文不定期修改完善,为 ...

  5. 使用cxf构建webservice

    一.简介 cxf是apache下的一个开源的,功能齐全的WebService框架.是由Celtix和XFire两个开源框架组合而成.cxf可以帮助我们使用前端编程模型构建和开发服务,如JAX- WS和 ...

  6. npm 配置全局文件

    nodejs.npm 按照默认安装完成即可. 1.设置一下全局目录:配置npm的全局模块的存放路径以及cache的路径,将以上两个文件夹放在NodeJS的主目录下,便在NodeJs下建立"n ...

  7. JFrame小练习1

    1.文本域组件 public class TestJTextArea { public static void main(String[] args) { JFrame jf=new JFrame(& ...

  8. 第六篇 :微信公众平台开发实战Java版之如何自定义微信公众号菜单

    我们来了解一下 自定义菜单创建接口: http请求方式:POST(请使用https协议) https://api.weixin.qq.com/cgi-bin/menu/create?access_to ...

  9. Linux gcc命令

    一.简介 GCC 的意思也只是 GNU C Compiler 而已.经过了这么多年的发展,GCC 已经不仅仅能支持 C 语言:它现在还支持 Ada 语言.C++ 语言.Java 语言.Objectiv ...

  10. 事件查看器常见ID代码解释

    ID 类型 来   源 代 表 的 意 义 举 例 解 释 信息 Serial 在验证 \Device\Serial1 是否确实是串行口时,系统检测到先进先出方式(fifo).将使用该方式. 错误 W ...