最近开始复习python的使用,把服务器运维常用的模块的用法进行了实例化概述。==========sort=========================
python 排序;
ls=[1,31,13,141,41]
ls.sort()
print ls
元组sort:
>>> lst=[(‘wyl‘,24),(‘hjj‘,25),(‘zs‘,22),(‘lisi‘,14)]
>>> sorted(lst,key=lambda lst:lst[1],reverse=True)
[(‘hjj‘, 25), (‘wyl‘, 24), (‘zs‘, 22), (‘lisi‘, 14)]
字典排序:
>>> print d
{‘a‘: 2, ‘e‘: 221, ‘d‘: 222, ‘f‘: 22, ‘age‘: 24, ‘name‘: ‘wyl‘}
>>> sorted(d.iteritems(),key= lambda d:d[1])
[(‘a‘, 2), (‘f‘, 22), (‘age‘, 24), (‘e‘, 221), (‘d‘, 222), (‘name‘, ‘wyl‘)]
==========paramiko=========================
python ssh模块:
import paramiko
def ssh(host,cmd):
#host = ‘192.168.0.213‘
user = ‘root‘
s = paramiko.SSHClient()
s.load_system_host_keys()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
privatekeyfile = os.path.expanduser(‘~/.ssh/id_rsa‘)
mykey = paramiko.RSAKey.from_private_key_file(privatekeyfile)
# mykey=paramiko.DSSKey.from_private_key_file(privatekeyfile,password=‘061128‘)
s.connect(host,22,user,pkey=mykey,timeout=5)
#cmd=raw_input(‘cwd:‘)
#cmd="ip a | grep inet | grep 192.168 | grep brd | awk -F/22 ‘{print $1}‘|awk ‘{print $2}‘"
stdin,stdout,stderr = s.exec_command(cmd)
cmd_result = stdout.read(),stderr.read()
for line in cmd_result:
return line.strip("\n")
s.close()
print ssh("192.168.0.2",‘ls /root‘)
==========multiprocessing=============
import multiprocessing
def bingfa(picmip):
Srealmount=set(ssh(picmip,"mount|awk ‘$1~/192.168.0.7/{print $1}‘").rstrip().split("\n"))
#print Srealmount
shortlist=list(Slocalmountls - Srealmount)
for sl in shortlist:
print "mount-error-"+sl + time.ctime()
f=open(‘/share/yunwei/shell/mountip.txt‘)
pool=multiprocessing.Pool(processes=4)
for ips in f:
pool.apply_async(bingfa,(ips,))
pool.close()
pool.join()
f.close()
========MySQLdb===============
python mysql模块:
import MySQLdb
def pyfmysql(*args):
conn=MySQLdb.connect(host=‘10.0.0.24‘,user=‘root‘,passwd=‘xxxxx‘,db=‘mon‘,port=3306)
cur=conn.cursor()
conn.select_db(‘monitor‘)
cur.execute("""insert into T_SYS_LOG (CONTENT,HOST_IP,MONITOR_TYPE,MONITOR_LEVEL,SMS_FLAG,GROUP_ID) values(%s,%s,%r,%r,%r,%r)""",args)
#sqlcmd=‘insert into T_SYS_LOG(CONTENT, HOST_IP, MONITOR_TYPE, MONITOR_LEVEL, SMS_FLAG,GROUP_ID) values(%s,%s,%s,%d,%d,%d)‘
sqlresult = cur.fetchall()
print sqlresult
conn.commit()
cur.close()
conn.close()
pyfmysql(‘test‘,‘127.0.0.1‘,1,2,0,6)
==========json=============
import json
newd={‘four‘: ‘192.168.0.10‘, ‘second‘: ‘192.168.0.5‘, ‘third‘: ‘192.168.0.7‘, ‘first‘: ‘192.168.0.2‘}
ojson=json.dumps(newd)
file=open(‘/tmp/jsonfile‘,‘w‘)
file.write(ojson)
f= open(r‘/tmp/jsonfile‘)
jsonobj = json.load(f)
oldd=eval(str(jsonobj))
f.close
=========shutil==================
import shutil
shutil.copy("1","2")
shutil.rmtree("42")
=========cStringIO===============
import cStringIO
输入:
s=cStringIO.StringIO()
s.write("you are a girl")
输出:
print s.getvalue()
或者
s.seek(0)
print s.read()
=============time=================
import time
passt = datetime.datetime.now() - datetime.timedelta(minutes=10)
curtime2 = passt.strftime(‘%Y%m%d%H‘)
==============urllib=================
import urllib
>>> ourl=urllib.urlopen(‘http://www.baidu.com‘)
>>> print ourl.info()
>>> for line in ourl:
print line,
>>> google.close()
import urllib
print urllib.urlopen(‘http://www.google.com‘).read()
============urllib2================
#!/bin/env python
import urllib2
# set up authentication info
authinfo = urllib2.HTTPBasicAuthHandler()
authinfo.add_password(realm=‘PDQ Application‘,
uri=‘http://10.0.0.1:8091/index.html‘,
user=‘admin‘,
passwd=‘admin‘)
#proxy_support = urllib2.ProxyHandler({"http" : "http://ahad-haam:3128"})
# build a new opener that adds authentication and caching FTP handlers
opener = urllib2.build_opener(authinfo,urllib2.CacheFTPHandler)
# install it
urllib2.install_opener(opener)
f = urllib2.urlopen(‘http://10.0.0.1:8091/index.html#sec=servers‘)
text=f.read()
print text