前言

最初做这个原因的是因为如何发布后查看实时日志,当然这种方案并不是当项目发布后查看日子的最佳方案,不过也可以给大家参考下。感谢以色列大神aviv给的指导,谢谢。

SocketServer方式实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/python

from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import SocketServer
import argparse
import json
import subprocess

class LogServer(BaseHTTPRequestHandler):
def do_GET(self):
try:
with open("/var/log/message.log", 'r') as log_fd:
log = log_fd.read()

self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(log)

except Exception as e:
self.send_response(500)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(e.message)

def do_POST(self):
try:
content_length = int(self.headers.getheader('content-length', 0))
body = self.rfile.read(content_length)
data = json.loads(body)
stdout = subprocess.check_output(data['command'], shell=True)

self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(stdout)

except Exception as e:
self.send_response(500)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(e.message)

def run_log_server(port):
server_address = ('', port)
httpd = HTTPServer(server_address, LogServer)
print('starting server on port %d' % port)
httpd.serve_forever()

if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("port", type=int)
args = parser.parse_args()
run_log_server(args.port)
执行参数:

POST JSON 例如:

1
2
3
{
"command": "df -h"
}


flask实现方法

1
2
3
4
5
6
7
8
9
10
11
12
13
#coding:utf-8

from flask import Flask,request
app = Flask(__name__)
import os
import subprocess
@app.route('/',methods=['POST'])
def hello_world():
print request.data
cmd = subprocess.check_output(request.data, shell=True)
return cmd
if __name__ == '__main__':
app.run()

Comments

2017-08-19