日常工作中,主要是通過ssh終端(putty等)遠程開發,經常涉及到傳輸文件,因為本地系統為Win10,所以沒辦法利用強大的linux腳本來進行文件傳輸。之前用過python的SimpleHttp模塊寫了一個簡單的文件服務器(http://www.cnblogs.com/sxhlinux/p/6694904.html),但是缺少GUI,且仍然依賴curl等相關命令。所以,就想着寫一個簡單的http文件服務器,滿足普通的文件上傳、下載文件。
代碼采用python 3.4版本,結構如下

代碼如下
#### server.py ####
#!/usr/bin/python3 import sys from http.server import BaseHTTPRequestHandler, HTTPServer, CGIHTTPRequestHandler if __name__ == '__main__': try: handler = CGIHTTPRequestHandler handler.cgi_directories = ['/cgi-bin', '/htbin'] port = int(sys.argv[1]) print('port is %d'% port) server = HTTPServer(('', port), handler) print('Welcome to my website !') server.serve_forever() except KeyboardInterrupt: print ('^C received, shutting down server') server.socket.close()
#### index.html ####
<!DOCTYPE html> <html> <meta charset="utf-8"> <head> <title>File Server</title> </head> <body> <form action="/cgi-bin/download.py" method="get"> 要下載的文件: <input type="text" name="filename" /> <input type="submit" value="download"> </form> <form enctype="multipart/form-data" action="/cgi-bin/upload.py" method="post"> 要上傳的文件: <input type="file" name="filename" /> <input type="submit" value="upload"> </form> </body> </html>
#### download.py ####
#!/usr/bin/python3 import os import sys import cgi form = cgi.FieldStorage() filename = form.getvalue('filename') dir_path = "/home/sxhlinux/data/" target_path = dir_path + str(filename) if os.path.exists(target_path) == True: print ('Content-Type: application/octet-stream') print ('Content-Disposition: attachment; filename = "%s"' % filename) sys.stdout.flush() fo = open(target_path, "rb") sys.stdout.buffer.write(fo.read()) fo.close() else: print("""\ Content-type: text/html\n <html> <head> <meta charset="utf-8"> <title>File server</title> </head> <body> <h1> %s doesn't exist in the server: files in the server list below: </h1>""" % filename) for line in os.popen("ls -lh ~/data/"): name = line.strip().split(' ', 8) if len(name) == 9: print('''<form action="/cgi-bin/download.py" method="get"> %s <input type="submit" name="filename" value="%s"> </form>''' % (line, name[8])) print('</body> <html>')
#### upload.py ####
#!/usr/bin/python3 import cgi, os form = cgi.FieldStorage() item = form['filename'] if item.filename: fn = os.path.basename(item.filename) open('/home/sxhlinux/data/' + fn, 'wb').write(item.file.read()) msg = 'File ' + fn + ' upload successfully !' else: msg = 'no file is uploaded ' print("""\ Content-type: text/html\n <html> <head> <meta charset="utf-8"> <title>Hello world</title> </head> <body> <h2>名稱: %s</h2> </body> <html> """ % (msg,))
將上述代碼按照前面的目錄結構放好,然后執行命令
nohup /usr/bin/python3 server.py 8001 >/dev/null & 啟動文件服務端,監聽8001端口,遠程可以在瀏覽器中 輸入 http://SERVER_ADDR:8001 來訪問該文件服務器進行相關的文件上傳下載操作。
注:
附件中是整個demo的代碼(
download.py,upload.py兩個文件中的目錄路徑 /home/sxhlinux/data 需要改成自己要存儲文件的文件夾路徑),有興趣的小伙伴可以下載修改,剛學習python,歡迎大家多多提意見。