2

ローカルネットワーク上に家族用のシンプルな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と同じなので、それは何もありません

4

1 に答える 1

7

のデフォルトモードは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())

このwithステートメントは、ファイルハンドルのリークを修正します。または(Python <2.5の場合)、f.close()手動で呼び出すことができます。

os.path.join(ファイルの先頭で必要になる場合がありimport os.pathます)は、文字列の連結よりもクリーンなファイル名構築メカニズムです。結果のファイル名が予想されるディレクトリにあることを確認することで、システム上のすべてのファイルをだれでも読み取ることができるパストラバーサルの脆弱性を防ぎます。

于 2012-01-06T01:08:51.123 に答える