Overview of common Python modules for server operations

Source: Internet
Author: User

Recently began to review the use of Python, the server operations commonly used modules of the use of the instantiation of the overview.

==========sort=========================python  sort; Ls=[1,31,13,141,41]ls.sort () Print ls tuple sort:>> > lst=[(' Wyl ', +), (' hjj ', +), (' Zs ', "), (' Lisi ', +)]>>> sorted (lst,key=lambda lst: lst[1],reverse=true) [(' Hjj ',  25),  (' Wyl ',  24),  (' Zs ',  22),  (' Lisi ',  14)] Dictionary sort: >>> 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 module:import paramikodef  SSH (host,cmd):          #host  =  ' 192.168.0.213 '           user =  ' Root '           s&Nbsp;= 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 MULTIPROCESSINGDEF BINGFA (PICMIP):         srealmount=set (SSH (PICMIP, "mount|awk  ' $1~/192.168.0.7/{print $1}"). Rstrip (). Split ("\ n"))          #print  Srealmount         shortlist=list (Slocalmountls&nbsP;- 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 module: Import mysqldbdef 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 ')         &nbsP;        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  jsonnewd={' 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 shutilshutil.copy ("1", "2") Shutil.rmtree ("=========cstringio===============import")  cstringio input: S=cstringio.stringio () s.write ("You are a girl") Output: Print s.getvalue () or S.seek (0) print s.read () =============time=================import timepasst =  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 &nBsp;ourl.info () >>> for line in ourl:print line,>>>  Google.close () import urllibprint urllib.urlopen (' http://www.google.com '). Read () ============urllib2== ==============#!/bin/env pythonimport urllib2# set up authentication  Infoauthinfo = 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 handlersopener =  urllib2.build_opener (AUTHINFO,URLLIB2. Cacheftphandler) # install iturllib2.install_opener (opener) F = urllib2.urlopen (' HTTP// 10.0.0.1:8091/index.html#sec=servers ') Text=f.read () Print text


This article is from the Linux system maintenance blog, so be sure to keep this source http://linuxadmin.blog.51cto.com/2683824/1587115

Overview of common Python modules for server operations

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.