首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

Linux 最快目錄共享方案:Python SimpleHTTPServer 一分鐘搭建臨時文件服務器

     編輯:關於C語言

為什麼選 SimpleHTTPServer?

對比傳統方案:

方案部署複雜度依賴適用場景
FTP (vsftpd)高 (配置文件、用戶、權限、防火牆)額外安裝生產環境長期服務
NFS/Samba高 (內核模塊、導出配置、掛載)套件安裝持久化網絡存儲
SimpleHTTPServer極低 (單命令)Python 內建臨時、快速、內網分享

核心特性

  • ✅ Python 2/3 內建模塊,無需安裝 (Linux/macOS 預裝)
  • ✅ 當前目錄即為服務根目錄
  • ✅ 存在 index.html 則作為首頁,否則 自動列出目錄結構
  • ✅ 支援斷點續傳 (Range 請求)
  • ✅ 單命令啟動,Ctrl+C 即停

使用方法 (Python 2)

# 1. 進入待分享目錄
cd /home/abc/project_files

# 2. 啟動 (默認 8000 端口)
python -m SimpleHTTPServer

# 3. 或指定端口
python -m SimpleHTTPServer 8080

# 輸出示例
Serving HTTP on 0.0.0.0 port 8000 ...
192.168.20.33 - - [09/Jan/2016 15:13:28] "GET / HTTP/1.1" 200 -
192.168.20.33 - - [09/Jan/2016 15:13:54] "GET /jdk-7u79-linux-x64.tar.gz HTTP/1.1" 200 -

使用方法 (Python 3)

# 模塊合併為 http.server
python3 -m http.server 8000

# 綁定特定 IP (僅本機訪問)
python3 -m http.server 8000 --bind 127.0.0.1

# 指定服務目錄 (不進入目錄)
python3 -m http.server 8000 --directory /path/to/share

客戶端訪問

  • 瀏覽器:https://:8000/
  • 命令行下載:wget https://:8000/file.tar.gz
  • 編程訪問:requests.get()、curl 等

防火牆配置 (關鍵步驟)

# Ubuntu/Debian (ufw)
sudo ufw allow 8000/tcp

# CentOS/RHEL (firewalld)
sudo firewall-cmd --add-port=8000/tcp --permanent
sudo firewall-cmd --reload

# 通用 iptables
sudo iptables -A INPUT -p tcp --dport 8000 -j ACCEPT

# 使用完畢關閉
sudo ufw delete allow 8000/tcp

進階用法

1. 後台運行與日誌

# 後台運行,日誌重定向
nohup python3 -m http.server 8000 > server.log 2>&1 &

# 查看進程
ps aux | grep http.server

# 停止
kill $(pgrep -f "http.server 8000")

2. 添加基本認證 (簡易保護)

# 建立 .htaccess 風格密碼文件 (需安裝 http.server 非標準擴展)
# 更推薦:使用 nginx/Apache 反向代理添加 auth_basic

3. 支援 HTTPS (自簽證書)

# 生成自簽證書
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 365 -nodes

# Python 3 啟動 HTTPS
python3 -c "
import http.server, ssl
server = http.server.HTTPServer(('0.0.0.0', 4443), http.server.SimpleHTTPRequestHandler)
server.socket = ssl.wrap_socket(server.socket, keyfile='key.pem', certfile='cert.pem', server_side=True)
server.serve_forever()
"

4. Windows 環境使用

# 安裝 Python (勾選 Add to PATH)
# 打開 CMD/PowerShell 進入目錄
python -m http.server 8000

# 防火牆:Windows Defender 防火牆 → 允許應用 → Python → 勾選專用/公用網絡

安全警示 ⚠️

  1. 無認證:任何能訪問端口的設備可瀏覽/下載所有文件
  2. 無加密:HTTP 明文傳輸,敏感數據嚴禁使用
  3. 目錄遍歷:舊版本可能存在路徑遍歷漏洞,保持 Python 更新
  4. 僅限可信網絡:絕不在公網直接暴露
  5. 臨時使用:用完即關,不作為長期服務

替代方案快速對比

工具命令特點
Node.js http-servernpx http-server -p 8000需 Node 環境、功能豐富 (緩存、壓縮、CORS)
PHP 內建服務器php -S 0.0.0.0:8000支援 PHP 腳本執行
Ruby WEBrickruby -run -e httpd . -p 8000Ruby 環境
Go 靜態服務器go run serve.go單二進制、高效能
busybox httpdhttpd -f -p 8000 -h .嵌入式/容器極簡

「SimpleHTTPServer 是開發者工具箱中的瑞士軍刀——不完美,但關鍵時刻最好用。」

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved