Linux下Python获取IP地址

《lnmp一键安装包》中需要获取ip地址,有2种情况:如果服务器只有私网地址没有公网地址,这个时候获取的IP(即私网地址)不能用来判断服务器的位置,于是取其网关地址用来判断服务器在国内还是国外(脚本为了使国内用户快速下载,yum源自动设置成163,这个情况就需要获取网关地址);如果服务器有公网地址,这时获取的IP地址可用来直接判断服务器地理位置。

获取服务器IP,如果有公网地址就取公网地址,没有公网地址就取私网网址

下面是之前我用shell来获取本地IP脚本:

  1. IP=`ifconfig | grep ‘inet addr:’ | cut -d: -f2 | grep -v ^10\. | grep -v ^192\.168 | grep -v ^172\. | \
  2. grep -v ^127\. | awk ‘{print  $1}’ | awk ‘{print;exit}’`
  3. [ ! -n “$IP” ] && IP=`ifconfig | grep ‘inet addr:’ | cut -d: -f2 | grep -v ^127\. | \
  4. awk ‘{print  $1}’ | awk ‘{print;exit}’`

Python版:get_ipaddr.py:

  1. #!/usr/bin/env python
  2. import socket
  3. def Get_local_ip():
  4.     “””
  5.     Returns the actual ip of the local machine.
  6.     This code figures out what source address would be used if some traffic
  7.     were to be sent out to some well known address on the Internet. In this
  8.     case, a Google DNS server is used, but the specific address does not
  9.     matter much.  No traffic is actually sent.
  10.     “””
  11.     try:
  12.         csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  13.         csock.connect((‘8.8.8.8’, 80))
  14.         (addr, port) = csock.getsockname()
  15.         csock.close()
  16.         return addr
  17.     except socket.error:
  18.         return “127.0.0.1”
  19. if __name__ == “__main__“:
  20.     IPADDR = Get_local_ip()
  21.     print IPADDR

有公网地址直接获取,没有公网地址就获取网关地址(用于判断IP地址的地理位置):get_public_ipaddr.py

  1. #!/usr/bin/env python
  2. import re,urllib2
  3. class Get_public_ip:
  4.     def getip(self):
  5.         try:
  6.             myip = self.visit(“http://ip.chinaz.com/getip.aspx”)
  7.         except:
  8.             try:
  9.                 myip = self.visit(“http://ipv4.icanhazip.com/”)
  10.             except:
  11.                 myip = “So sorry!!!”
  12.         return myip
  13.     def visit(self,url):
  14.         opener = urllib2.urlopen(url)
  15.         if url == opener.geturl():
  16.             str = opener.read()
  17.         return re.search(‘\d+\.\d+\.\d+\.\d+’,str).group(0)
  18. if __name__ == “__main__“:
  19.     getmyip = Get_public_ip()
  20.     print getmyip.getip()

判断服务器IP地理位置: get_ipaddr_state.py

  1. #!/usr/bin/env python
  2. #coding:utf-8
  3. try:
  4.     import sys,urllib2,json
  5.     apiurl = “http://ip.taobao.com/service/getIpInfo.php?ip=%s” % sys.argv[1]
  6.     content = urllib2.urlopen(apiurl).read()
  7.     data = json.loads(content)[‘data’]
  8.     code = json.loads(content)[‘code’]
  9.     if code == 0:
  10.         print data[‘country_id’]
  11.     else:
  12.         print data
  13. except:
  14.     print “Usage:%s IP” % sys.argv[0]
Sat Oct 19 22:12:04 CST 2013

【AD】炭云:768元/年/1GB内存/20GB SSD空间/2TB流量/500Mbps-1Gbps端口/独立IPv4/KVM/广州移动

【AD】美国洛杉矶CN2 VPS/香港CN2 VPS/日本CN2 VPS推荐,延迟低、稳定性高、免费备份_搬瓦工vps