Skip to content

Instantly share code, notes, and snippets.

@syshack
Created September 1, 2012 03:38
Show Gist options
  • Select an option

  • Save syshack/3563397 to your computer and use it in GitHub Desktop.

Select an option

Save syshack/3563397 to your computer and use it in GitHub Desktop.
服务器批量执行命令
#!/bin/env python
#-*- coding:utf-8 -*-
import os,sys
import socket
import subprocess
import shlex
#----------------------------------------------------------------------
def serve(HOST="",PORT=50007):
"""建立socket"""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
pid = str(os.getpid())
pidfile = "/var/client.pid"
file(pidfile,'w+').write("%s\n" % pid)
except Exception,e:
print e
while True:
conn, addr = s.accept()
data = conn.recv(1024)
try:
cmd = shlex.split(data)
p = subprocess.Popen(cmd,stderr=subprocess.PIPE,stdout=subprocess.PIPE)
(out,erro) =p.communicate()
feed_back = str(p.returncode)
conn.send(feed_back)
except :
pass
#feed_back = out + erro
conn.close()
#----------------------------------------------------------------------
def daemonize():
"""daeamonize"""
stdin='/dev/null'
stderr='/dev/null'
OPERATION_FAILED = 1
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError, e:
return OPERATION_FAILED
# decouple from parent environment
os.setsid()
os.umask(0)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError, e:
return OPERATION_FAILED
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = file(stdin, 'r')
se = file(stderr, 'a+', 0)
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
if __name__ == "__main__":
daemonize()
serve("127.0.0.1",50007)
#-*- coding: utf-8-*-
'''多进程版'''
from optparse import OptionParser
from multiprocessing import Process, Queue
import socket
#----------------------------------------------------------------------
def sendcmd(host,cmd):
"""send message to client"""
s = socket.socket()
#连接客户端
try:
s.connect((host,50007))
#推送命令
s.send(cmd)
#获取命令返回值
feed_back = s.recv(1024)
s.close()
return feed_back
except Exception,e:
return "Error: ",e
#----------------------------------------------------------------------
def worker(cmd,input,output):
"""Worker"""
for host in iter(input.get, 'STOP'):
result = sendcmd(host,cmd)
output.put(host+":"+str(result))
if __name__ == "__main__":
#socket 超时时间
timeout = 5
socket.setdefaulttimeout(timeout)
#进程数
NUMBER_OF_PROCESSES=10
#获取选项
opts = OptionParser()
#-d指定客户端ip
opts.add_option("-d", action="store", type="string", default="all_host",dest="host")
#-c指定要执行的命令
opts.add_option("-c", action="store", type="string", dest="cmd")
(option,value) = opts.parse_args()
#获取host和cmd
host = option.host
cmd = option.cmd
#如果没有指定client,读配置文件
if host == "all_host":
h_list = open('list','r')
all_host = h_list.read().split('\n')
h_list.close()
#task queue
task_queue = Queue()
#Result queue
result_queue = Queue()
#submit tasks
for host in all_host:
task_queue.put(host)
#Start worker processes
for i in range(NUMBER_OF_PROCESSES):
p=Process(target=worker, args=(cmd,task_queue, result_queue))
p.start()
# Get and print results
for i in range(len(all_host)):
print "\t",result_queue.get()
# Tell child processes to stop
for i in xrange(NUMBER_OF_PROCESSES):
task_queue.put('STOP')
#如果指定了client,向指定client推送
else:
result = sendcmd(host,cmd)
print host+":\t"+str(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment