实现目标

通过控制端,可以实现N台主机执行同一操作。

具体代码如下

1、控制端代码

 1[root@361way tmp]# vim client.py
 2#!/usr/bin/env python
 3import socket,os,sys
 4  ost=sys.argv[1]
 5ort=4567
 6for host in os.popen('cat ip.list').readlines():
 7  print host
 8  s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 9  s.connect((host,port))
10  while 1:
11    data=sys.argv[2]
12    if not data:
13        break
14    s.sendall(data)
15    data=s.recv(1024)
16    if not data:
17        break
18    print data
19  s.close()

2、被控制端代码

 1[root@localhost tmp]# vim server.py
 2#!/usr/bin/env python
 3import socket,os
 4host=''
 5port=4567
 6s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
 7s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
 8s.bind((host,port))
 9s.listen(1)
10print "Server is running on port %d; press ctrl-c to terminate." % port
11while 1:
12    clientsock,clientaddr=s.accept()
13    print "connect from %s" % str(clientaddr)
14    clientfile=clientsock.makefile('rw',0)
15    data=clientsock.recv(1024)
16    command=os.popen(data).read()
17    clientfile.write("%s" % command)
18    clientfile.close()
19    clientsock.close()

3、操作方法

ip.list里写server端的IP地址,每行一个,如:

1.1.1.1
2.2.2.2

使用方法,将server.py部署于目标主机上,执行server.py;客户端执行 python client.py ip.list “command”即可。示例如下:

 1[root@361way tmp]# python client.py ip.list ifconfig
 2192.168.0.106
 3eth0      Link encap:Ethernet  HWaddr 52:54:00:D8:F3:E7
 4          inet addr:192.168.0.106  Bcast:192.168.0.255  Mask:255.255.255.0
 5          inet6 addr: fe80::5054:ff:fed8:f3e7/64 Scope:Link
 6          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
 7          RX packets:627 errors:0 dropped:0 overruns:0 frame:0
 8          TX packets:262 errors:0 dropped:0 overruns:0 carrier:0
 9          collisions:0 txqueuelen:1000
10          RX bytes:71041 (69.3 Kb)  TX bytes:55281 (53.9 Kb)
11192.168.0.110
12eth0      Link encap:Ethernet  HWaddr 52:54:00:D7:F8:E7
13          inet addr:192.168.0.110  Bcast:192.168.0.255  Mask:255.255.255.0
14          inet6 addr: fe80::5054:ff:fed7:f8e7/64 Scope:Link
15          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
16          RX packets:770 errors:0 dropped:0 overruns:0 frame:0
17          TX packets:438 errors:0 dropped:0 overruns:0 carrier:0
18          collisions:0 txqueuelen:1000
19          RX bytes:87223 (85.1 KiB)  TX bytes:69993 (68.3 KiB)

代码已放到github上