您的位置:首页 > 编程语言 > Python开发

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

2016-04-07 23:54 916 查看
在做采集器的过程中,经常会遇到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')
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: