python獲取繫結的IP,並動態指定出口IP

2021-09-07 06:18:58 字數 2455 閱讀 5291

在做採集器的過程中,經常會遇到ip限制的情況,這時候可以通過切換ip能繼續訪問。

如果是多ip的伺服器,那麼可以通過切換出口ip來實現。

1.首先是如何獲取伺服器繫結的ip 

import netifaces as ni

def getlocalethips():

for dev in ni.inte***ces():

if dev.startswith('eth0'):

ip=ni.ifaddresses(dev)[2][0]['addr']

if ip not in iplist:

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.***.xx'

def bound_socket(*a, **k):

sock = true_socket(*a, **k)

sock.bind((ipbind, 0))

return sock

socket.socket = bound_socket

response = urllib2.urlopen('')

html = response.read()

ip=re.search(r'code.(.*?)..code',html)

print ip.group(1)

後面這個是通過訪問ip.cn來驗證實際外網ip, 正則原來是r'(.*?)'的,由於部落格的**衝突,所以就改了下。

參考自:

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.inte***ces():

if dev.startswith('eth0'):

ip=ni.ifaddresses(dev)[2][0]['addr']

if ip not in iplist:

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('***.xx.xx.***')

js事件繫結並獲取元素

dom事件繫結的幾種方式 html中直接繫結 利用html事件屬性。html中繫結事件叫做內聯繫結事件,不利於分離。不能解綁 js中直接繫結 利用dom操作。js中直接繫結稱為賦值繫結函式,缺點是只能繫結一次。解綁ele.nclick null addeventlistener 注意去掉on,通過r...

自動檢測IP並繫結網域名稱

因使用路由器工具上的花生殼檢測ip不准,估計是isp運營商封了花生殼的檢測 寫了個指令碼,自動檢測當前ip並繫結網域名稱 coding utf 8 created on 2015年1月5日 author osborn import urllib.request import re import ti...

Python 獲取本地IP

使用撥號上網的話,一般都有乙個本地ip和乙個外網ip,使用python可以很容易的得到這兩個ip 使用gethostbyname和gethostbyname ex兩個函式可以實現 import socket localip socket.gethostbyname socket.gethostnam...