In the process of doing the collector, often encounter the situation of IP restrictions, this time can be switched through the IP can continue to access.
If it is a multi-IP server, then you can switch the export IP to achieve.
1. First, how to obtain the server-bound 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 ()
Need to introduce Netifaces module, installation method Easy_install Netifaces
2. Binding the egress IP for the socket
#-*-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)
After this is to verify the actual extranet IP by accessing the ip.cn, which is the R ' <code> (. *?) </code> ', because of the blog code conflicts, so changed.
Reference from: Http://stackoverflow.com/questions/1150332/source-interface-with-python-and-urllib2
3. I implemented the random bound egress 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. Invoking the sample
bindipobj= Bindip () #随机切换IPbindIpObj. RANDOMIP () #得到当前IPprint bindipobj.getip () #得到本机IP数print bindipobj.getipscount () #切换到指定IPprint bindipobj. Changeip (' xxx.xx.xx.xxx ')
Python gets the bound IP and dynamically specifies the egress IP