我正在尝试使用urllib3动态覆盖目标主机的IP地址,而我正在传递客户端证书。这是我的代码:
import urllib3
conn = urllib3.connection_from_url('https://MYHOST', ca_certs='ca_crt.pem', key_file='pr.pem', cert_file='crt.pem', cert_reqs='REQUIRED')
response = conn.request('GET', 'https://MYHOST/OBJ', headers={"HOST": "MYHOST"})
print(response.data)
我正在考虑使用传输适配器,但我不确定如何在不使用会话的情况下执行此操作。
有任何想法或帮助吗?
答案 0 :(得分:0)
我想我们可以按照此处提供的解决方案:Python 'requests' library - define specific DNS?
因此,一种令人讨厌的方法是通过添加将主机名覆盖到我们想要的IP地址:
from urllib3.util import connection
import urllib3
hostname = "MYHOST"
host_ip = "10.10.10.10"
_orig_create_connection = connection.create_connection
def patched_create_connection(address, *args, **kwargs):
overrides = {
hostname: host_ip
}
host, port = address
if host in overrides:
return _orig_create_connection((overrides[host], port), *args, **kwargs)
else:
return _orig_create_connection((host, port), *args, **kwargs)
connection.create_connection = patched_create_connection
conn = urllib3.connection_from_url('https://MYHOST', ca_certs='ca_crt.pem', key_file='pr.pem', cert_file='crt.pem', cert_reqs='REQUIRED')
response = conn.request('GET', 'https://MYHOST/OBJ', headers={"HOST": "MYHOST"})
print(response.data)
但是,再次基于发布的链接,更好的实现方法是使用适当的适配器来覆盖IP地址。