Linux下Python获取IP地址的代码

yipeiwu_com6年前Python基础

《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]

相关文章

Python常用模块用法分析

本文较为详细的讲述了Python中常用的模块,分享给大家便于大家查阅参考之用。具体如下: 1.内置模块(不用import就可以直接使用) 常用内置函数: help(obj) 在线帮助,...

python3.6+selenium实现操作Frame中的页面元素

python3.6+selenium实现操作Frame中的页面元素

有时网页中会嵌套一个或者多个Frame,此时我们直接去找嵌套在Frame里面的元素会抛出异常,所以在操作的时候我们需要将页面焦点切换到Frame里面,下面我们就以一个实例演示一下! 首先...

解决Python命令行下退格,删除,方向键乱码(亲测有效)

一、出现原因:readline模块没有安装 二、解决方式: # 安装readline模块 yum -y install readline-devel # 进入Python安装目录 c...

pycharm的console输入实现换行的方法

pycharm的console输入实现换行的方法

有时输出内容很多,没有自动换行,如下图所示: 可以点击下图按钮,即可自动换行: 以上这篇pycharm的console输入实现换行的方法就是小编分享给大家的全部内容了,希望能给大家一...

详解Python 序列化Serialize 和 反序列化Deserialize

详解Python 序列化Serialize 和 反序列化Deserialize 序列化 (serialization) 序列化是将对象状态转换为可保持或传输的格式的过程。与序列化相对的是...