Connect to a server through proxy with socket libr

2019-09-15 23:51发布

问题:

I'd like to use socket library to connect to a server (not necessary a webserver) through an http proxy. Is it possible?

For example (with requests library):

import requests

r = requests.get("http://www.google.com", #but not necessary to http port.
                 proxies={"http": "http://ipproxy:portproxy"})

-UPDATE-

import urllib.request

pr = "ipproxy:portproxy"

while True:
    try:
        proxy = urllib.request.ProxyHandler({'http': pr})
        opener = urllib.request.build_opener(proxy)
        urllib.request.install_opener(opener)
        url = "ftp://ip" # or ssh:// or some other port
        data = None
        headers = {}
        req = urllib.request.Request(url, data, headers)
        print ("Request sent")
    except:
        print ("An error occurred")

回答1:

It is possible for most types of connections (HTTP and FTP etc., possibly HTTPS, although this is a bit more tricky) using the urllib module with a ProxyHandler object.