使用python远程操作linux服务器

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

概述

  • 功能:实现同时对多台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
root@192.168.0.75'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]#

本文地址

参考资料

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值