Python自带模块及其作用

1 paramiko  (基于openssh,python封装的ssh)

模块python自带


用法:

1
2
3
4
5
6
7
8
9
10
11
12
13
import  paramiko                                          
ssh  =  paramiko.SSHClient()                               
ssh.load_system_host_keys()                              
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname = '192.168.100.20' ,port = 58422 ,username = 'oldboy' )
stdin, stdout,stderr = ssh.exec_command( 'uptime' )    
                 
type (stdout)
paramiko.ChannelFile
print  stderr.readlines()
[]
print  stdout.readlines()
[ ' 21:35:05 up 1 day, 55 min,  2 users,  load average: 0.00, 0.00, 0.00\n' ]


相当于shell当中的 

1
ssh  -p58422 oldboy@192.168.100.20 -o StrictHostKeyChecking=no  'uptime'


2 subprocess(尽量不要用这个模块,返回不美观,如果只是执行shell命令推荐commands模块) Python3

python自带模块 使用在python 3中取代python 2 中的commands模块

参考:http://www.jb51.net/article/48086.htm

常用fork子进程执行shell命令,可以返回结果和返回值

举例:
只需要返回值

1
2
3
4
5
6
7
In [ 6 ]: retcode  =  subprocess.call( 'ls -l' , shell = True )
total  12
- rw - rw - r - - 1  oldboy oldboy  239  Jan  19  21 : 13  access.log
- rw - rw - r - - 1  oldboy oldboy  458  Jan  19  20 : 50  arp.txt
- rw - r - - r - - 1  oldboy oldboy  184  Jan  16  12 : 04  hosts
In [ 7 ]:  print  retcode
0


注意: 

shell默认为False,等于 retcode = subprocess.call(["ls", "-l"])  列表的形式第一个为命令,后面的都作为参数传递


需要返回值

1
2
child1  =  subprocess.Popen([ "cat" , "/etc/passwd" ], stdout = subprocess.PIPE)
child1.stdout.readlines()

常用:

file="get_ldap_zhname.sh"

1
2
3
     child1  =  subprocess.Popen( 'sh '  +  file  +  ' ' +   um, shell = True , stdout = subprocess.PIPE)
     status  =  child1.wait()
     output  =  child1.stdout.read().strip()

3 comands模块(python 2中)

python自带模块

1
  status,output  =  commands.getstatusoutput( 'cat /etc/passwd' )

优点: 无论命令执行错误与正确,正确输出和错误输出都以字符串原样的字符串形式传递给output


4 multiprocessing模块

python自带模块

pool = multiprocessing.Pool(processes=4)

result_tmp.append(pool.apply_async(func, ( arg1,arg2,arg3)))



5 ping模块

pip install ping 

result = ping.quiet_ping(addr, timeout=2, count=5, psize=64)

loss_rate=result[0]

max_time=result[1]

average_time=result[2]


常用处理(取float的位数和把None值 变为0表示不通):

loss_rate = result[0]

max_time = float('%.3f'% result[1]) if isinstance(result[1], float) else 0

#if max_time and average_time is None use 0

average_time = float('%.3f'% result[2]) if isinstance(result[2], float) else 0



6 random模块

python自带

import random

常用函数

a. random函数 生成一个0-1的随机数

1
2
In [ 26 ]: random.random()
Out[ 26 ]:  0.6289910862564466



b.  sample 在一个列表(字符串)中随机抽样N个数,返回一个新的列表

1
2
3
4
In [ 27 ]: random.sample( xrange ( 1 , 100 ),  3 )
Out[ 27 ]: [ 94 91 53 ]
In [ 28 ]: random.sample( 'asdfasdf' 3 )
Out[ 28 ]: [ 'f' 'a' 'a' ]


c.  randint 函数,在指定的整数范围内(1<=x<=20),返回一个数

1
2
In [ 29 ]: random.randint( 1 , 20 )
Out[ 29 ]:  18



7 uuid模块

python自带

import uuid

常用: uuid1函数,通过mac和时间戳生成全球唯一的id

1
2
In [ 49 ]: uuid.uuid1()
Out[ 49 ]: UUID( 'cbb8c051-0929-11e6-9ba3-8c2937eebf3a' )


(注意是 UUID类型,经常转化为str类型)

1
2
In [ 50 ]:  str (uuid.uuid1())
Out[ 50 ]:  'cf296582-0929-11e6-8bbf-8c2937eebf3a'



8 hashlib 模块 

常用md5函数  (常结合uuid来生成一个32位的随机数)


1
2
In [ 48 ]: hashlib.md5( str (uuid.uuid1())).hexdigest()
Out[ 48 ]:  'd4aacc5bb29a24fd9db8e2ea1bf53cb7'



9 时间模块 time, datetime timedelta 

参考: http://cuidehua.blog.51cto.com/5449828/1767046

 


10 json模块

参考: http://cuidehua.blog.51cto.com/5449828/1767061



11 re 正则表达式模块

python自带

常用 判断一个字符串是否符合指定的表达式

1
2
3
4
5
6
7
8
In [ 9 ]:  import  re
In [ 10 ]: s  =  "10.1.1.223"
In [ 11 ]:  if  re.match(r "10.1" , s):
    ....:      print  "为10.1网段"
    ....:  else :
    ....:      print  "不在10.1网段"
    ....:     
10.1 网段


区别re.match()  和re.search()的区别

re.match(r“10.2,s”)   和  re.search(r”^10.2”,s)  是一样的

注:

1 匹配则返回对象本身,不匹配则放回None

2 match只匹配字符串的开始,如果开始不符合正则表达式,就返回None,而search匹配整个字符串,匹配到了则算匹配成功


12 collections 模块OrderedDict 函数

python自带内模块

作用: 定义有序字典,当有需要dict字典的key是有序的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
In [ 73 ]:  from  collections  import  OrderedDict
In [ 74 ]: od  =  OrderedDict()
In [ 75 ]: od[ 'key1' =  'value1'
In [ 76 ]: od[ 'key2' =  'value2' 
In [ 77 ]: od[ 'key3' =  'value3' 
In [ 78 ]: od
Out[ 78 ]: OrderedDict([( 'key1' 'value1' ), ( 'key2' 'value2' ), ( 'key3' 'value3' )])
In [ 79 ]: od.keys()
Out[ 79 ]: [ 'key1' 'key2' 'key3' ]
In [ 80 ]:  for  k,v  in  od.ite
od.items       od.iteritems   od.iterkeys    od.itervalues  
In [ 80 ]:  for  k,v  in  od.items():
    ....:      print  k,v
    ....:     
key1 value1
key2 value2
key3 value3



12 collections 模块Counter 函数

python再带内建(python 2.7 以上版本才有Counter函数)

Counter函数是属于字典的子类,所有也拥有字典相关的特性


重要用途: 返回列表(字符串)中元素出现的次数


1
2
3
In [ 11 ]:  from  collections  import  Counter
In [ 12 ]: l  =  [ 'a' , 'b' , 'a' , 'c' , 'a' , 'd' ]
In [ 13 ]: number_rep =  Counter(l)

返回的是keys和次数组成的字典

1
2
3
4
In [ 14 ]: number_rep
Out[ 14 ]: Counter({ 'a' 3 'b' 1 'c' 1 'd' 1 })
In [ 15 ]:  type (number_rep)
Out[ 15 ]: collections.Counter


拥有字典的大部分属性函数

1
2
In [ 16 ]: number_rep[ "a" ]
Out[ 16 ]:  3

1
2
In [ 18 ]: number_rep.keys()
Out[ 18 ]: [ 'a' 'c' 'b' 'd' ]

返回出现最多的key和次数组成的二元元组列表

1
2
In [ 19 ]: number_rep.most_common( 1 )
Out[ 19 ]: [( 'a' 3 )]


也有相加功能

1
2
3
4
5
In [ 21 ]: s  =  "efghfgfefda"
In [ 22 ]: Counter(s)
Out[ 22 ]: Counter({ 'a' 1 'd' 1 'e' 2 'f' 4 'g' 2 'h' 1 })
In [ 23 ]: number_rep  +  Counter(s)
Out[ 23 ]: Counter({ 'a' 4 'b' 1 'c' 1 'd' 2 'e' 2 'f' 4 'g' 2 'h' 1 })



注意:python 2.6环境中

pip install counter

from counter import Counter

13 linecache模块

python自带

import linecache


作用,读取文本行,大的文本,可以缓存到内存,下次再次读取直接从内存中拿取


用法:

返回所有行,以列表的形式

1
l_lines  =  linecache.getlines( 'filename' )

返回指定的一行,返回字符串形式

1
s_line  =  linecache.getline( 'filename' , linenumber).rstrip()

更新缓存,是直接从磁盘中读取文件,并更新内存中的缓存,返回列表形式的所有行

1
l_lines  =  linecache.updatecache( 'filename' )


更新缓存  所有拥有缓存的

1
linecache.checkcache()


或者 指定更新的文件

1
linecache.checkcache( 'filename' )