问题:html
一、本人工做主要作自动化,常常要去Linux后台进行一些脚本操做,有时要去后台执行命令,若是逐个登录比较费事,效率会大打折扣python
二、虽然有能够直接去后台执行命令的AW,可是该AW存在不少问题,并且遇到交互式操做时不能很好的解决git
基于以上问题,经过Python写了一个简单的CLI Agent,就叫作TestAgent吧,主要思路:github
一、采用POST消息发送到TestAgent,TestAgent进行解析服务器
二、TestAgent接受到消息后,把消息体存为一个文件restful
三、将文件更改成可执行的,而后启动一个进程去执行脚本curl
四、若是执行成功将结果返回给客户端,若是失败,一样将错误输出也返回给客户端socket
五、在POST消息的头域中能够设置超时时间,若是超时,返回“time out”,并将启动的进程给杀掉测试
代码以下:ui
1 #! /usr/bin/env python 2 import commands 3 import socket 4 import time 5 import os 6 import multiprocessing 7 import uuid 8 from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer 9 10 #HTTPServer的监听端口 11 PORT=12345 12 13 class HttpHandler(BaseHTTPRequestHandler): 14 tmpfile='' 15 #处理POST消息 16 def do_POST(self): 17 print self.path 18 content_len = int(self.headers.getheader('content-length',0)) 19 #获取timeout 20 timeout = int(self.headers.getheader('timeout',0)) 21 if timeout==0: 22 timeout=5 23 #解析消息并存储为文件 24 script=self.rfile.read(content_len) 25 x=uuid.uuid4() 26 self.tmpfile="."+str(x.int) 27 fd=open(self.tmpfile,'w') 28 fd.write(script) 29 fd.close() 30 os.system("chmod +x "+self.tmpfile) 31 script="./"+self.tmpfile 32 #执行脚本 33 self.ExecuteScript(script,timeout) 34 35 def ExecuteScript(self,script,timeout=5): 36 #启动另外一个进程执行脚本 37 p=multiprocessing.Process(target=self.ScriptWorker,args=(script,)) 38 p.start() 39 i=0 40 while i<timeout: 41 if(not p.is_alive()): 42 return "successful" 43 else: 44 time.sleep(1) 45 i=i+1 46 #超时的话终止进程并杀掉执行任务的进程 47 p.terminate() 48 os.system("kill -9 "+str(p.pid)) 49 self.send_error(400,"time out") 50 self.request.shutdown(socket.SHUT_RDWR) 51 self.request.close() 52 #删除临时文件 53 if self.tmpfile != '': 54 os.system("rm "+self.tmpfile) 55 self.tmpfile='' 56 57 def ScriptWorker(self,script): 58 #执行脚本,返回状态码和输出 59 (status,result)=commands.getstatusoutput(script) 60 print script 61 print result 62 #若是成功返回200,若是失败返回400 63 if status == 0: 64 self.send_response(200) 65 else: 66 self.send_response(400) 67 self.send_header('Content-type','text/html') 68 self.end_headers() 69 self.wfile.write(result) 70 #删除临时文件 71 if self.tmpfile != '': 72 os.system("rm "+self.tmpfile) 73 self.tmpfile='' 74 75 if __name__=='__main__': 76 os.system('rm .*') 77 server_address=('0.0.0.0',PORT) 78 http_server=HTTPServer(server_address,HttpHandler) 79 http_server.serve_forever() 80
测试:
采用curl或者restful client进行测试
一、执行简单命令
二、执行的命令不存在
三、执行一个Python脚本
四、执行一个超时的脚本
五、执行一个带有timeout头域的脚本
至此,基本全部功能都验证过了
PS:该程序理论上能够执行任何脚本,只要脚本的解释器写正确
使用时通常会再写个monitor脚本,放在crontab中,这样就彻底能够不登录服务器了,能够自动拉起TestAgent
但愿该程序能够帮助你们,^v^ !!
地址:https://github.com/litlefirefly/TestAgent