Linux下Python擷取IP地址的代碼_python

來源:互聯網
上載者:User

《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 pythonimport socketdef 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 pythonimport re,urllib2class 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-8try: 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 dataexcept: print "Usage:%s IP" % sys.argv[0]
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.