简体   繁体   中英

Changing DNS server for Python script

I'm writing a script that is going to be run from a server at my University.
The purpose of the script is to check websites and record their HTTP status code and IP-Address. This works fine generally, but I am encountering a problem I have a hard time solving:
When run from my local machine outside the university network, everything works.
When I run the script from inside the network, one particular site is not resolved. For some reason the DNS server at my university can't do the lookup. I have no control over that machine, so I'm looking for a way around it.

Is it possible to change which DNS server the script uses, when written like below? If not, how should I go about this instead?

The relevant code:

import requests
import httplib
import socket

def getresponse(self,*args,**kwargs):
    response = self._old_getresponse(*args,**kwargs)
    if self.sock:
        response.peer = self.sock.getpeername()
    else:
        response.peer = None
    return response


httplib.HTTPConnection._old_getresponse = httplib.HTTPConnection.getresponse
httplib.HTTPConnection.getresponse = getresponse

def check_peer(resp):
    orig_resp = resp.raw._original_response
    if hasattr(orig_resp,'peer'):
        return getattr(orig_resp,'peer')

r = requests.get("http://www.stackoverflow.com")
try:    
    ip = check_peer(r)
except TypeError:
    ip = socket.gethostbyname_ex(site)

Python 'requests' library - define specific DNS? says it is possible, though patching occurs at the urllib level and not at the requests level.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM