设为首页 收藏本站
查看: 1197|回复: 0

[经验分享] python中常用到的模块和包名称

[复制链接]

尚未签到

发表于 2018-8-8 13:57:08 | 显示全部楼层 |阅读模式
  1 paramiko  (基于openssh,python封装的ssh)
  模块python自带
  用法:
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当中的
ssh -p58422 oldboy@192.168.100.20 -o StrictHostKeyChecking=no 'uptime'  2 subprocess(尽量不要用这个模块,返回不美观,如果只是执行shell命令推荐commands模块) Python3
  python自带模块 使用在python 3中取代python 2 中的commands模块
  参考:http://www.iyunv.net/article/48086.htm
  常用fork子进程执行shell命令,可以返回结果和返回值
  举例:
  只需要返回值
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"])  列表的形式第一个为命令,后面的都作为参数传递
  需要返回值
child1 = subprocess.Popen(["cat","/etc/passwd"], stdout=subprocess.PIPE)  
child1.stdout.readlines()
  常用:
  file="get_ldap_zhname.sh"
    child1 = subprocess.Popen('sh ' + file + ' '+  um, shell=True, stdout=subprocess.PIPE)  
    status = child1.wait()
  
    output = child1.stdout.read().strip()
  3 comands模块(python 2中)
  python自带模块
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的随机数
In [26]: random.random()  
Out[26]: 0.6289910862564466
  b.  sample 在一个列表(字符串)中随机抽样N个数,返回一个新的列表
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),返回一个数
In [29]: random.randint(1,20)  
Out[29]: 18
  7 uuid模块
  python自带
  import uuid
  常用: uuid1函数,通过mac和时间戳生成全球唯一的id
In [49]: uuid.uuid1()  
Out[49]: UUID('cbb8c051-0929-11e6-9ba3-8c2937eebf3a')
  (注意是 UUID类型,经常转化为str类型)
In [50]: str(uuid.uuid1())  
Out[50]: 'cf296582-0929-11e6-8bbf-8c2937eebf3a'
  8 hashlib 模块
  常用md5函数  (常结合uuid来生成一个32位的随机数)
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自带
  常用 判断一个字符串是否符合指定的表达式
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是有序的
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函数是属于字典的子类,所有也拥有字典相关的特性
  重要用途: 返回列表(字符串)中元素出现的次数
In [11]: from collections import Counter  
In [12]: l = ['a','b','a','c','a','d']
  
In [13]: number_rep= Counter(l)
  返回的是keys和次数组成的字典
In [14]: number_rep  
Out[14]: Counter({'a': 3, 'b': 1, 'c': 1, 'd': 1})
  
In [15]: type(number_rep)
  
Out[15]: collections.Counter
  拥有字典的大部分属性函数
In [16]: number_rep["a"]  
Out[16]: 3
In [18]: number_rep.keys()  
Out[18]: ['a', 'c', 'b', 'd']
  返回出现最多的key和次数组成的二元元组列表
In [19]: number_rep.most_common(1)  
Out[19]: [('a', 3)]
  也有相加功能
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
  作用,读取文本行,大的文本,可以缓存到内存,下次再次读取直接从内存中拿取
  用法:
  返回所有行,以列表的形式
l_lines = linecache.getlines('filename')  返回指定的一行,返回字符串形式
s_line = linecache.getline('filename', linenumber).rstrip()  更新缓存,是直接从磁盘中读取文件,并更新内存中的缓存,返回列表形式的所有行
l_lines = linecache.updatecache('filename')  更新缓存  所有拥有缓存的
linecache.checkcache()  或者 指定更新的文件
linecache.checkcache('filename')

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-548758-1-1.html 上篇帖子: python_备份mysql数据库 下篇帖子: python2初识
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表