背景
用的服务器的权限控制比较严格, 一般的文件上传方式用不了。 而且很多软件在mac 还可能用不了。 最近在用 mac pro m1, 有时候挺心塞的(有的软件用不了,折腾重装很久才好)。
但是Linux服务器(用的centos 较多), 一般都有python, 如果没有python, 很多命令是用不了, 比如yum 。
所以自己就用python写了个文件上传的程序。
程序
server.py
#coding=utf-8
from BaseHTTPServer import BaseHTTPRequestHandler
import urllib
import cgi
import os
g_page = '''
<!DOCTYPE HTML> <html>
<head><title>Get page</title></head>
<body>
<p>If you are not the system staff, please close this page ! </p>
<br />
<p>
{content}
<br/>
</p>
<a href="/xyzxyz/">Back to Home </a>
</body>
</html>
'''
class PostHandler(BaseHTTPRequestHandler):
def do_GET(self):
path = self.path
query = urllib.splitquery(path)
self.send_response(200)
self.send_header("Content-type","text/html")
self.send_header("test","This is test!")
self.end_headers() # 之后不能再设置header 否则浏览器会报错
buf = '''<!DOCTYPE HTML>
<html>
<head><title>Get page</title></head>
<body>
<p>If you are not the system staff, please close this page ! </p>
<hr />
<form action="/xyzxyz/post_page" enctype="multipart/form-data" method="post">
<input type="file" name="filename" /><br />
<input type="password" name="code" /><br />
<input type="submit" value="POST" />
</form>
</body>
</html>'''
self.wfile.write(buf)
def do_POST(self):
path = self.path
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST',
# 'CONTENT_TYPE':self.headers['Content-Type'],
'CONTENT_TYPE': 'multipart/form-data'
}
)
self.send_response(200)
self.end_headers()
fileitem = form['filename']
try:
if form["code"].value != "password":
self.wfile.write(g_page.format(content='Code failed !'))
return
except Exception as e:
print("code exception: ",e)
self.wfile.write( g_page.format(content='Code exception !'))
return
if fileitem.filename:
fn = os.path.basename(fileitem.filename)
open('./files/' + fn, 'wb').write(fileitem.file.read())
self.wfile.write( g_page.format(content='Success !'))
else:
self.wfile.write(g_page.format(cotent="Failed !"))
return
def StartServer():
from BaseHTTPServer import HTTPServer
sever = HTTPServer(("",10000),PostHandler)
sever.serve_forever()
if __name__=='__main__':
StartServer()
命令执行:
python server.py
python - verison 2.x
就可以从外网向内网上传文件啦