Linux下Python获取IP地址的代码
程序员文章站
2022-06-08 09:49:17
《lnmp一键安装包》中需要获取ip地址,有2种情况:如果服务器只有私网地址没有公网地址,这个时候获取的ip(即私网地址)不能用来判断服务器的位置,于是取其网关地址用来判断...
《lnmp一键安装包》中需要获取ip地址,有2种情况:如果服务器只有私网地址没有公网地址,这个时候获取的ip(即私网地址)不能用来判断服务器的位置,于是取其网关地址用来判断服务器在国内还是国外(脚本为了使国内用户快速下载,yum源自动设置成163,这个情况就需要获取网关地址);如果服务器有公网地址,这时获取的ip地址可用来直接判断服务器地理位置。
获取服务器ip,如果有公网地址就取公网地址,没有公网地址就取私网网址
下面是之前我用shell来获取本地ip脚本:
ip=`ifconfig | grep 'inet addr:' | cut -d: -f2 | grep -v ^10\. | grep -v ^192\.168 | grep -v ^172\. | \ grep -v ^127\. | awk '{print $1}' | awk '{print;exit}'` [ ! -n "$ip" ] && ip=`ifconfig | grep 'inet addr:' | cut -d: -f2 | grep -v ^127\. | \ awk '{print $1}' | awk '{print;exit}'`
python版:get_local_ip.py:
#!/usr/bin/env python import socket def get_local_ip(): """ returns the actual ip of the local machine. this code figures out what source address would be used if some traffic were to be sent out to some well known address on the internet. in this case, a google dns server is used, but the specific address does not matter much. no traffic is actually sent. """ try: csock = socket.socket(socket.af_inet, socket.sock_dgram) csock.connect(('8.8.8.8', 80)) (addr, port) = csock.getsockname() csock.close() return addr except socket.error: return "127.0.0.1" if __name__ == "__main__": local_ip = get_local_ip() print local_ip
有公网地址直接获取,没有公网地址就获取网关地址(用于判断ip地址的地理位置):get_public_ip.py
#!/usr/bin/env python import re,urllib2 class get_public_ip: def getip(self): try: myip = self.visit("http://www.whereismyip.com/") except: try: myip = self.visit("http://www.ip138.com/ip2city.asp") except: myip = "so sorry!!!" return myip def visit(self,url): opener = urllib2.urlopen(url) if url == opener.geturl(): str = opener.read() return re.search('\d+\.\d+\.\d+\.\d+',str).group(0) if __name__ == "__main__": getmyip = get_public_ip() print getmyip.getip()
判断服务器ip地理位置: get_ip_area.py
#!/usr/bin/env python #coding:utf-8 try: import sys,urllib2,json apiurl = "http://ip.taobao.com/service/getipinfo.php?ip=%s" % sys.argv[1] content = urllib2.urlopen(apiurl).read() data = json.loads(content)['data'] code = json.loads(content)['code'] if code == 0: print data['country_id'] else: print data except: print "usage:%s ip" % sys.argv[0]