標籤:
在做採集器的過程中,經常會遇到IP限制的情況,這時候可以通過切換IP能繼續訪問。
如果是多IP的伺服器,那麼可以通過切換出口Ip來實現。
1.首先是如何擷取伺服器綁定的IP
import netifaces as nidef getLocalEthIps():for dev in ni.interfaces():if dev.startswith(‘eth0‘):ip=ni.ifaddresses(dev)[2][0][‘addr‘]if ip not in ipList:ipList.append(ip)print getLocalEthIps()
需要引入netifaces模組,安裝方法easy_install netifaces
2.為socket綁定出口IP
# -*- coding=utf-8 -*-import socketimport urllib2import retrue_socket = socket.socketipbind=‘xx.xx.xxx.xx‘def bound_socket(*a, **k):sock = true_socket(*a, **k)sock.bind((ipbind, 0))return socksocket.socket = bound_socketresponse = urllib2.urlopen(‘http://www.ip.cn‘)html = response.read()ip=re.search(r‘code.(.*?)..code‘,html)print ip.group(1)
後面這個是通過訪問ip.cn來驗證實際外網IP, 正則原來是r‘<code>(.*?)</code>‘的,由於部落格的代碼衝突,所以就改了下。
參考自:http://stackoverflow.com/questions/1150332/source-interface-with-python-and-urllib2
3.我實現的隨機綁定出口IP
#!/usr/bin/python# -*- coding: utf-8 -*-import socketimport randomimport netifaces as nitrue_socket = socket.socketipList=[]class getLocalIps():global ipListdef getLocalEthIps(self):for dev in ni.interfaces():if dev.startswith(‘eth0‘):ip=ni.ifaddresses(dev)[2][0][‘addr‘]if ip not in ipList:ipList.append(ip)class bindIp():ip=‘‘global true_socket,ipListdef bound_socket(self,*a, **k):sock = true_socket(*a, **k)sock.bind((self.ip, 0))return sockdef changeIp(self,ipaddress):self.ip=ipaddressif not self.ip==‘‘:socket.socket = self.bound_socketelse:socket.socket = true_socketdef randomIp(self):if len(ipList)==0:getLocalIpsFunction=getLocalIps()getLocalIpsFunction.getLocalEthIps()if len(ipList)==0:return_ip=random.choice(ipList)if not _ip==self.ip:self.changeIp(_ip)def getIp(self):return self.ipdef getIpsCount(self):return len(ipList)
4.調用樣本
bindIpObj= bindIp()#隨機切換IPbindIpObj. randomIp()#得到當前IPprint bindIpObj.getIp()#得到本機IP數print bindIpObj.getIpsCount()#切換到指定IPprint bindIpObj. changeIp(‘xxx.xx.xx.xxx‘)
python擷取綁定的IP,並動態指定出口IP