使用python远程操作linux服务器

摘要  功能:实现同时对多台linux服务器通过ssh执行同一命令。 技术基础: python pexpect,部支持windows。

目录[-]

  • 概述
  • 主脚本
  • ssh 登陆类库
  • 实例
  • 本文地址
  • 参考资料
  • 概述

    • 功能:实现同时对多台linux服务器通过ssh执行同一命令。

    • 技术基础: python pexpect,部支持windows。

    • 参数:

      • 固定参数pwd:远程服务器密码,用户名目前写死是root,可自行修改。

      • 可选参数-c CMDS:要执行的命令,比如:"ls -l","cd /home/test && test.py&如果不选择,会从当前目前的cmd.txt读取。

      • 可选参数-s SERVERS:目标服务器,比如192.168.0.1,最后一位数可以用-表示一个区间,分号用于分割不同的ip。如果不选择,会从当前目前的ip.txt读取。

    主脚本

    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    #!/usr/bin/python# -*- coding: utf-8 -*-# Author:         Rongzhong Xu# CreateDate: 2014-05-06import argparseimport common# deal with argumentsparser = argparse.ArgumentParser()parser.add_argument('pwd', action="store",help=u'password')parser.add_argument('-c', dest='cmds', action="store", help=u'command')parser.add_argument('-s', dest='servers', action="store", help=u'hosts')parser.add_argument('--version', action='version',
         version = '%(prog)s 1.1 Rongzhong xu 2014 05 08' )options  =  parser.parse_args()servers  =  [] if  options.servers:
         raw_server  =  options.servers.split( ';' )
         for  server  in  raw_server:
             if  '-'  in  server:
                 server_list  =  server.split( '.' )
                 base  =  '.' .join(server_list[: 3 ])
                 indices  =  server_list[ - 1 ].split( '-' )
                 start, end  =  indices             for  item  in  range ( int (start), int (end) + 1 ):
                     servers.append( '{0}.{1}' . format (base,item))
                     
             else :
                 servers.append(server)  else :
         for  item  in  open ( 'ip.txt' ):
             servers.append(item)   
             cmds  =  []         if  options.cmds:
         cmds.append(options.cmds) else :
         for  item  in  open ( 'cmd.txt' ):
             servers.append(item)            
         for  host  in  servers:
         print 
         print ( "*" * 80 )
         print ( "\nConnect to host: {0}" . format (host))
         =  common.Ssh()
         c.connect(host, 'root' ,options.pwd)
         for  item  in  cmds:
             c.command(item)
         c.close()

    ssh 登陆类库

    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    class  Ssh( object ):
         
         client  =  None
     
         @ classmethod
         def  connect( cls ,ip,username = "root" ,password = "123456" , prompt = ']#' ,
             silent = False ):
     
             # Ssh to remote server
             ssh_newkey  =  'Are you sure you want to continue connecting'
             child  =  pexpect.spawn( 'ssh ' +  username  +  '@' +  ip, maxread = 5000 )
             
             =  1
             # Enter password
             while  i ! =  0 :
                 =  child.expect([prompt,  'assword:*' , ssh_newkey, pexpect.TIMEOUT, 
                     'key.*? failed' ])
                 if  not  silent:
                     print  child.before,child.after,            
                 if  = =  0 # find prompt
                     pass      
                 elif  = =  1 # Enter password
                     child.send(password  + "\r" )  
                 if  = =  2 # SSH does not have the public key. Just accept it.
                     child.sendline ( 'yes\r' )               
                 if  = =  3 # Timeout
                     raise  Exception( 'ERROR TIMEOUT! SSH could not login. ' )
                 if  = =  4 # new key
                     print  child.before,child.after,
                     os.remove(os.path.expanduser( '~' ) + '/.ssh/known_hosts' )                     
     
             Ssh.client  =  child        
     
     
     
         @ classmethod
         def  command( cls ,cmd, prompt = ']#' , silent = False ):
             Ssh.client. buffer  =  ''
             Ssh.client.send(cmd  +  "\r" )
             #Ssh.client.setwinsize(400,400)
             Ssh.client.expect(prompt)
             if  not  silent:        
                 print  Ssh.client.before, Ssh.client.after,
             return  Ssh.client.before, Ssh.client.after    
         
         def  close( cls ,):
             Ssh.client.close()

    实例

    ?
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    # ./batch.py -husage: batch.py [-h] [-c CMDS] [-s SERVERS] [--version] pwdpositional arguments:  pwd         password
     
    optional arguments:
       -h, --help  show this help message and  exit
       -c CMDS      command
       -s SERVERS  hosts
       --version   show program's version number and  exit
     
    # ./batch.py password -s "192.168.0.71-76;123.1.149.26" -c "cat /etc/redhat-release"
     
    ********************************************************************************
     
    Connect to host: 192.168.0.71
    Last login: Thu May  8 17:04:02 2014 from 183.14.8.49
    [root@localhost ~ ] # cat /etc/redhat-release
    CentOS release 5.8 (Final)
    [root@localhost ~ ] #
    ********************************************************************************
     
    Connect to host: 192.168.0.72
    Last login: Thu May  8 17:03:05 2014 from 192.168.0.232
    [root@localhost ~ ] # cat /etc/redhat-release
    CentOS release 5.8 (Final)
    [root@localhost ~ ] #
    ********************************************************************************
     
    Connect to host: 192.168.0.73
    Last login: Thu May  8 17:02:29 2014 from 192.168.0.232
    [root@localhost ~ ] # cat /etc/redhat-release
    CentOS release 5.8 (Final)
    [root@localhost ~ ] #
    ********************************************************************************
     
    Connect to host: 192.168.0.74
    Last login: Thu May  8 17:02:32 2014 from 192.168.0.232
    [root@localhost ~ ] # cat /etc/redhat-release
    CentOS release 5.8 (Final)
    [root@localhost ~ ] #
    ********************************************************************************
     
    Connect to host: 192.168.0.75
    [email protected]'s p assword:  
    Last login: Thu May  8 17:02:56 2014 from 192.168.0.232[root@localhost ~ ] # cat /etc/redhat-releaseCentOS release 6.4 (Final)[root@localhost ~ ]#********************************************************************************
     
    Connect to host: 192.168.0.76
    Last login: Thu May  8 17:03:00 2014 from 192.168.0.232[root@localhost ~ ] # cat /etc/redhat-releaseCentOS release 5.8 (Final)[root@localhost ~ ]#********************************************************************************
     
    Connect to host: 123.1.149.26
    Last login: Thu May  8 16:46:56 2014 from 183.56.157.199[root@LINUX ~ ] # cat /etc/redhat-releaseRed Hat Enterprise Linux Server release 6.5 (Santiago)[root@LINUX ~ ]#[root@AutoTest batch]#

    本文地址

    • http://automationtesting.sinaapp.com/blog/python_code_linux_control

    • 本站地址:python自动化测试http://automationtesting.sinaapp.com python开发自动化测试群113938272和开发测试群6089740 微博 http://weibo.com/cizhenshi

    • 关于评论:禁止非登录用户评论,可以使用用户名test密码test登录后评论,评论请尽可能留下联系方式,多谢!

    参考资料

    • 英文文档主页:http://pexpect.readthedocs.org/en/latest/

    • 库下载:https://pypi.python.org/pypi/pexpect/


    你可能感兴趣的:(使用python远程操作linux服务器)