python获取绑定的IP,并动态指定出口IP

在做采集器的过程中,经常会遇到IP限制的情况,这时候可以通过切换IP能继续访问。

如果是多IP的服务器,那么可以通过切换出口Ip来实现。

1.首先是如何获取服务器绑定的IP 

import netifaces as ni
def 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 socket
import urllib2
import re
true_socket = socket.socket

ipbind='xx.xx.xxx.xx'

def bound_socket(*a, **k):
sock = true_socket(*a, **k)
sock.bind((ipbind, 0))
return sock

socket.socket = bound_socket

response = 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 socket
import random
import netifaces as ni

true_socket = socket.socket
ipList=[]

class getLocalIps():
global ipList
def 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,ipList

def bound_socket(self,*a, **k):
sock = true_socket(*a, **k)
sock.bind((self.ip, 0))
return sock

def changeIp(self,ipaddress):
self.ip=ipaddress
if not self.ip=='':
socket.socket = self.bound_socket
else:
socket.socket = true_socket

def 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.ip

def getIpsCount(self):
return len(ipList)


 

4.调用示例

bindIpObj= bindIp()
#随机切换IP
bindIpObj. randomIp()
#得到当前IP
print bindIpObj.getIp()
#得到本机IP数
print bindIpObj.getIpsCount()
#切换到指定IP
print bindIpObj. changeIp('xxx.xx.xx.xxx')
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值