Python 一行命令启动HTTP服务器
快速启动
Python 3.x
python3 -m http.server 8000
Python 2.x
python -m SimpleHTTPServer 8000
启动后,浏览器访问 http://localhost:8000 即可。

常用场景
1. 指定端口
python3 -m http.server 8080
2. 绑定特定IP
python3 -m http.server 8000 --bind 192.168.1.100
3. 指定目录
# 先cd到目标目录,或者直接用 -d 参数
python3 -m http.server 8000 -d /path/to/dir
4. 后台运行
nohup python3 -m http.server 8000 &
5. 限制访问(只允许本地)
python3 -m http.server 8000 --bind 127.0.0.1
实用技巧
传文件
临时传文件给同事,在文件目录启动:
cd /path/to/share
python3 -m http.server 8000
对方直接浏览器下载,比U盘快。
调试前端
本地开发静态页面,CDN挂了?直接本地起服务:
python3 -m http.server 8000
解决跨域问题,页面正常加载。
局域网共享
查看本机IP:
ip addr | grep inet
然后在其他设备访问 http://本机IP:8000。
注意事项
- 防火墙要放行对应端口
- 生产环境别用,没认证没加密
- 大文件传输建议用
rsync或scp - 默认只读,不能上传
进阶玩法
带上传功能的服务器
import http.server
import cgi
class UploadHandler(http.server.SimpleHTTPRequestHandler):
def do_POST(self):
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD':'POST'}
)
with open(form['file'].filename, 'wb') as f:
f.write(form['file'].file.read())
self.send_response(200)
self.end_headers()
if __name__ == '__main__':
http.server.HTTPServer(('', 8000), UploadHandler).serve_forever()
保存为 server.py,运行:
python3 server.py
自定义端口和目录的别名
加个shell函数到 ~/.bashrc:
function pyserve() {
port=${1:-8000}
dir=${2:-.}
echo "Serving $dir on http://localhost:$port"
python3 -m http.server $port -d "$dir"
}
以后直接:
pyserve 8080 /tmp
总结
Python内置HTTP服务器是日常开发中最实用的工具之一,传文件、调试页面、临时共享,一行命令搞定。记住几个参数,效率翻倍。
💻 安全运维 / Linux运维 / 渗透测试 技术支持
业务需求可联系博客作者
