Python HTTP 网页服务器
我在本地网络上为我的家人搭建了一个简单的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
除了PNG和JPEG部分,其他都能正常工作。我自己写的BM脚本和ESP也是一样,所以这部分没有问题。
1 个回答
7
默认情况下,open
函数是以 'r'
模式打开的,这表示它是用来读取文本数据的,并且在Windows系统上会自动处理换行符的问题。你可以把 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())
使用 with
语句可以避免文件句柄泄漏的问题。或者在Python 2.5之前的版本,你可以手动调用 f.close()
来关闭文件。
os.path.join
(你可能需要在文件开头加上 import os.path
)是一种比简单拼接字符串更好的构建文件名的方法。检查生成的文件名是否在你预期的目录中,可以防止出现路径遍历漏洞,这种漏洞可能让任何人都能读取你系统上的所有文件。