13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonでbasic認証付きのhttpプロキシを経由する時のハマりポイント

Last updated at Posted at 2014-12-25

pythonでbasic認証付きのhttpプロキシを経由する時のハマりポイント

2.7.x系です。
urllib2でhttpプロキシを経由する際に、basic認証が掛かってる場合。

ターゲットのサーバに認証が掛かってる場合

client => proxy => target
                ↑ここ

これはリファレンスとか普通にググると出てくるやつを真似すればおk。

# !/usr/bin/env python

import urllib2

proxy = urllib2.ProxyHandler({
  'http': 'http://username:password@proxy:8080'
})
auth = urllib2.HTTPBasicAuthHandler()
opener = urllib2.build_opener(proxy, auth)
urllib2.install_opener(opener)

conn = urllib2.urlopen('http://target/')
print conn.read()

これで、Proxy-Authorization ヘッダが付与される。

プロキシサーバにbasic認証が掛かってる場合

client => proxy => target
       ↑ここ

この場合、Proxy-Authorization ヘッダじゃなくて Authorization ヘッダを付与しないとならない。
が、いくら調べても試してもHandler使ったやり方が出てこなかったので、
仕方ないので手でヘッダを計算して付与する事でなんとか解決。

# !/usr/bin/env python

import urllib2
import base64

proxy = urllib2.ProxyHandler({
  'http':'http://proxy:8080'
})
opener = urllib2.build_opener(proxy)
base64string = base64.encodestring('%s:%s' % ("username", "password"))
opener.addheaders = [ ("Authorization", "Basic %s" % base64string) ]

conn = opener.open('http://target/')
print conn.read()

Handlerを使ったちゃんとした解決方法無いのかな。

ちなみに

pip requests
使うと
Proxy-Authorization の挙動だった。

# !/usr/bin/env python

import requests

proxies = {
    "http": "http://username:password@proxy:8080",
}

ret = requests.get("http://target/", proxies=proxies)
print ret
13
12
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?