问题:

1、本人工作主要做自动化,经常要去Linux后台进行一些脚本操作,有时要去后台执行命令,如果逐个登陆比较费事,效率会大打折扣

2、虽然有可以直接去后台执行命令的AW,但是该AW存在很多问题,而且遇到交互式操作时不能很好的解决

基于以上问题,通过Python写了一个简单的CLI Agent,就叫做TestAgent吧,主要思路:

1、采用POST消息发送到TestAgent,TestAgent进行解析

2、TestAgent接受到消息后,把消息体存为一个文件

3、将文件更改为可执行的,然后启动一个进程去执行脚本

4、如果执行成功将结果返回给客户端,如果失败,同样将错误输出也返回给客户端

5、在POST消息的头域中可以设置超时时间,如果超时,返回“time out”,并将启动的进程给杀掉

代码如下:

1 #! /usr/bin/env python

2 importcommands3 importsocket4 importtime5 importos6 importmultiprocessing7 importuuid8 from BaseHTTPServer importBaseHTTPRequestHandler,HTTPServer9

10 #HTTPServer的监听端口

11 PORT=12345

12

13 classHttpHandler(BaseHTTPRequestHandler):14 tmpfile=''

15 #处理POST消息

16 defdo_POST(self):17 printself.path18 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.tmpfile32 #执行脚本

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=040 while i<41 if return>

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 defScriptWorker(self,script):58 #执行脚本,返回状态码和输出

59 (status,result)=commands.getstatusoutput(script)60 printscript61 printresult62 #如果成功返回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进行测试

1、执行简单命令

2、执行的命令不存在

3、执行一个Python脚本

4、执行一个超时的脚本

5、执行一个带有timeout头域的脚本

至此,基本所有功能都验证过了

PS:该程序理论上可以执行任何脚本,只要脚本的解释器写正确

使用时一般会再写个monitor脚本,放在crontab中,这样就完全可以不登陆服务器了,可以自动拉起TestAgent

希望该程序可以帮助大家,^v^ !!

地址:https://github.com/litlefirefly/TestAgent

41>
Logo

电影级数字人,免显卡端渲染SDK,十行代码即可调用,工业级demo免费开源下载!

更多推荐