实现目标:
通过控制端,可以实现N台主机执行同一操作。
具体代码如下:
1、控制端代码
[root@361way tmp]# vim client.py #!/usr/bin/env python import socket,os,sys ost=sys.argv[1] ▽ort=4567 for host in os.popen('cat ip.list').readlines(): print host s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect((host,port)) while 1: data=sys.argv[2] if not data: break s.sendall(data) data=s.recv(1024) if not data: break print data s.close()
2、被控制端代码
[root@localhost tmp]# vim server.py #!/usr/bin/env python import socket,os host='' port=4567 s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) s.bind((host,port)) s.listen(1) print "Server is running on port %d; press ctrl-c to terminate." % port while 1: clientsock,clientaddr=s.accept() print "connect from %s" % str(clientaddr) clientfile=clientsock.makefile('rw',0) data=clientsock.recv(1024) command=os.popen(data).read() clientfile.write("%s" % command) clientfile.close() 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
“即可。示例如下:
[root@361way tmp]# python client.py ip.list ifconfig 192.168.0.106 eth0 Link encap:Ethernet HWaddr 52:54:00:D8:F3:E7 inet addr:192.168.0.106 Bcast:192.168.0.255 Mask:255.255.255.0 inet6 addr: fe80::5054:ff:fed8:f3e7/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:627 errors:0 dropped:0 overruns:0 frame:0 TX packets:262 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:71041 (69.3 Kb) TX bytes:55281 (53.9 Kb) 192.168.0.110 eth0 Link encap:Ethernet HWaddr 52:54:00:D7:F8:E7 inet addr:192.168.0.110 Bcast:192.168.0.255 Mask:255.255.255.0 inet6 addr: fe80::5054:ff:fed7:f8e7/64 Scope:Link UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1 RX packets:770 errors:0 dropped:0 overruns:0 frame:0 TX packets:438 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:1000 RX bytes:87223 (85.1 KiB) TX bytes:69993 (68.3 KiB)
代码已放到github上。
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/117623.html