調べてみるとPythonではHTTPPasswordMgrWithDefaultRealm、HTTPBasicAuthHandlerを使うのが定石らしいが、
画像のURLを開くだけなので、httpリクエストにBASIC認証のヘッダを自己で追加してみた。
# -*- coding: utf-8 -*- # tslcam.py 2011.2.6 import base64 import re import urllib2 def get_image(url): result = re.match(r"(http://)(?P.*):(?P .*)@(.*)", url) if result: (user, passwd) = result.group('user', 'passwd') url = "".join(result.group(1, 4)) req = urllib2.Request(url) req.add_header("Authorization", "Basic " + base64.encodestring(user+":"+passwd)) print user,passwd else: req = urllib2.Request(url) print req.get_full_url() response = urllib2.urlopen(req, timeout=5) image_data = response.read() return image_data if __name__ == "__main__": import random # TS-LCAM url = "http://user1:passwd2@192.168.1.3/m/standard/CamImg%02d.jpg" % random.randint(0,99) image_data = get_image(url) if image_data: with open("tslcam.jpg", 'wb') as f: f.write(image_data) # TS-MCAM url = "http://user3:passwd4@192.168.1.4/m/goform/capture?%d" % random.randint(0,9999) image_data = get_image(url) if image_data: with open("tsmcam.jpg", 'wb') as f: f.write(image_data)
0 件のコメント:
コメントを投稿