国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Linux下Python獲取IP地址的代碼

2020-02-23 06:16:25
字體:
來源:轉載
供稿:網友

《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]
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 京山县| 西丰县| 阳东县| 惠水县| 新蔡县| 德庆县| 宁波市| 廊坊市| 巫山县| 吉林市| 辰溪县| 老河口市| 夏津县| 新蔡县| 泰顺县| 花莲市| 鹤山市| 舒兰市| 贡觉县| 新巴尔虎右旗| 应城市| 延寿县| 昌平区| 屏南县| 益阳市| 奇台县| 孝义市| 福建省| 浦北县| 武宣县| 宣武区| 华阴市| 武川县| 广平县| 广丰县| 曲麻莱县| 竹山县| 大荔县| 娄烦县| 厦门市| 宜丰县|