bma*_*ign 2 python http httpserver basehttprequesthandler
我在本地网络上为我的家人创建了一个简单的http服务器,当我添加一个html文件和png图片并试图查看HTML文件时,我的图像无法加载.
它说:
"图像'的http:// ...:255/header.png’无法显示,因为它包含的错误."
这是我的一些代码
elif self.path.endswith(".bm"): #our dynamic content
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
f= open(curdir + sep + self.path)
ren = self.render(f.read())
self.wfile.write(ren)
return
elif self.path.endswith('.png'):
print "IMAGE WANTED!"
self.send_response(200)
self.send_header('Content-type', 'image/png')
self.end_headers()
f = open(curdir + sep + self.path)
self.wfile.write(f.read())
return
elif self.path.endswith('.jpg'):
print "IMAGE WANTED!"
self.send_response(200)
self.send_header('Content-type', 'image/jpeg')
self.end_headers()
f= open(curdir + sep + self.path)
print f.read()
self.wfile.write(f.read())
return
elif self.path.endswith(".esp"):
self.send_response(200)
self.send_header('Content-type', 'text/plain')
self.end_headers()
self.wfile.write("This Format Is Not Supported Any More, Upgrade To BM Script")
return
Run Code Online (Sandbox Code Playgroud)
他们都工作,除了png和jpeg部分.BM脚本我做了自己,和esp一样,所以这没什么
默认模式open是 'r',表示读取文本数据并在Windows上执行自动EOL转换.替换f = open(curdir + sep + self.path); self.wfile.write(f.read())为
fn = os.path.normpath(os.path.join(curdir, self.path))
if not fn.startswith(abspath + os.path.sep):
raise Exception('Path traversal attempt')
with open(fn, 'rb') as f:
self.wfile.write(f.read())
Run Code Online (Sandbox Code Playgroud)
该with语句修复了文件句柄的泄漏.或者(在Python <2.5上),您可以f.close()手动调用.
os.path.join(您可能需要import os.path在文件的开头)是比字符串连接更清晰的文件名构造机制.检查生成的文件名是否在您期望的目录中可以防止路径遍历漏洞,该漏洞允许任何人读取系统上的所有文件.