항복 하시겠습니까? 절대로!
시간 후에 ... 아직까지 약간의 손이 필요하고, 약간의 작은 움푹 들어간 곳과 긁힌 자국이 지금까지 나는 볼 수 있지만, 원래 실행하고 싶었던 방식으로 실행되고 있습니다.
동시에 랩퍼와 서버의 일종이며, 강화 된 몇 가지 타당성 및 보안 검사가 포함되어 있으며 현재는 쉼표로 구분 된 단일 매개 변수, 문자열 (원하는 이름 하위 프로세스 스크립트)와 숫자 (예 : sayhello,2000
)를 매개 변수로 사용합니다. 아직 아직 JSON이 추가되지 않았지만 현재는 필요하지 않습니다.
그것은 어떤 파이썬 프레임 워크없이 작동하지만, JQuery와 AJAX 및 상시 관측소와 WSGIserver, 클라이언트 측에 (나중에에 필요하므로, 아직 다른 시스템에 테스트하지 다른 URL, 테스트)
이로써 당신 ' 세 개의 파일을 찾을 수 있습니다. ajax.html
, server.py
및 testscript sayhello.py
.
사전에 추가 힌트, 경고 또는 개선을 보내 주셔서 감사합니다. 너가 좋아하길 바래.
ajax.html
<html>
<head>
<title>Ajax POST to python</title>
</head>
<body>
send message: <input type="text" id="message" value="" size="10" placeholder="string,number"> <input type=button id="send" value="send">
<br />
response: <span id="response"></span>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$("input#send").click(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost:8080',
crossDomain: true,
data: $('input#message').val(),
dataType: 'text',
timeout: 3000,
success: function(responseData, textStatus, jqXHR)
{
$('span#response').html(responseData);
},
error: function (responseData, textStatus, errorThrown)
{
console.warn(responseData, textStatus, errorThrown);
alert('failed - ' + textStatus);
}
});
});
</script>
</html>
#!/usr/bin/env python
import threading
from subprocess import Popen, PIPE
from pathlib import Path
from wsgiref.simple_server import make_server
PORT = 8080
REQUEST_METHOD = "POST"
def myapp(env, http_stuff):
if env['REQUEST_METHOD'] == REQUEST_METHOD:
try:
request_body_size = int(env['CONTENT_LENGTH'])
request_body = env['wsgi.input'].read(request_body_size)
except (TypeError, ValueError):
request_body = "0"
try:
#---------------------------security/plausibility
allowed_scripts = ["sayhello","count_apples","get_scale_weight","etc."]
el = request_body.split(",");
arg_filename = str(el[0].strip())
arg_num = int(el[1].strip())
if not (arg_filename in allowed_scripts):
arg_filename = ""
if isinstance(arg_num, int):
arg_num = str(arg_num)
else:
arg_num = ""
#---------------------------script exists ?
my_file = Path(arg_filename+".py")
if my_file.is_file():
output = "no valid output."
#---------------------------subprocess
proc = Popen(["python", arg_filename+".py",arg_num], shell=False, stdout=PIPE, stderr=PIPE)
output = proc.communicate()[0]
#---------------------------more stuff
response_body = output
else:
response_body = "["+request_body+"] is not allowed !"
except:
response_body = "some other error"
else:
response_body = "no POST data"
status = '200 OK'
#---------------------------header with CORS support
headers = [('Content-type', 'text/plain'),
("Access-Control-Allow-Origin", "*")]
http_stuff(status, headers)
return response_body
def start_server():
httpd = make_server("", PORT, myapp)
httpd.serve_forever()
if __name__ == "__main__":
start_server()
sayhello.py server.py
#!/usr/bin/env python
import sys
print "I am sayhello.py and I say HELLO "+sys.argv[1]
당신은이 지역의 정적 파일을 제공 할 목적으로 SimpleHTTPServer를 사용하지 마십시오 . 당신은 적절하게 wsgi 응용 프로그램을 구현해야합니다. 아마도 Django 나 Flask 같은 것을 사용했을 것입니다. – spectras
이 엔드 포인트를 발견하면 누군가가 쉽게'main.py & rm -rf'를 할 수 있기 때문에 보안 취약점에 대해 생각하고 있기를 바랍니다. 그리고 이것에 대한 @pectpectras에 동의합니다. Django 또는 Flask를 사용하여 Python webapp을 개발하십시오. –
왜 아파치를 사용하지 않으시겠습니까? –