python擷取綁定的IP,並動態指定出口IP

來源:互聯網
上載者:User

標籤:

在做採集器的過程中,經常會遇到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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.