linux通过Python获取本机的ip,mac,网关,子网掩码,网卡名

Posted LiangShaoY

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了linux通过Python获取本机的ip,mac,网关,子网掩码,网卡名相关的知识,希望对你有一定的参考价值。

1.通过模块netifaces获取,当系统为Windows时,可能会有报错现象

import os
import sys

try:
    import netifaces
except ImportError:
    try:
        command_to_execute = "pip install netifaces || easy_install netifaces"
        os.system(command_to_execute)
    except OSError:
        print "Can NOT install netifaces, Aborted!"
        sys.exit(1)
    import netifaces

routingGateway = netifaces.gateways()[default][netifaces.AF_INET][0]
routingNicName = netifaces.gateways()[default][netifaces.AF_INET][1]

for interface in netifaces.interfaces():
    if interface == routingNicName:
        # print netifaces.ifaddresses(interface)
        routingNicMacAddr = netifaces.ifaddresses(interface)[netifaces.AF_LINK][0][addr]
        try:
            routingIPAddr = netifaces.ifaddresses(interface)[netifaces.AF_INET][0][addr]
            # TODO(Guodong Ding) Note: On Windows, netmask maybe give a wrong result in ‘netifaces‘ module.
            routingIPNetmask = netifaces.ifaddresses(interface)[netifaces.AF_INET][0][netmask]
        except KeyError:
            pass

display_format = %-30s %-20s
print display_format % ("Routing Gateway:", routingGateway)
print display_format % ("Routing NIC Name:", routingNicName)
print display_format % ("Routing NIC MAC Address:", routingNicMacAddr)
print display_format % ("Routing IP Address:", routingIPAddr)
print display_format % ("Routing IP Netmask:", routingIPNetmask)

2.获取外网ip

!/usr/bin/env python
# 通过访问查询ip的网址,在响应页面正则获取ip地址,网站需要时常更新,在页面不能出现多个ip
import re,urllib2
class Get_public_ip:
    def getip(self):
        try:
            myip = self.visit("http://www.bejson.com/httputil/queryip/")
        except:
            try:
                myip = self.visit("https://www.8684.cn/ip")
            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()

3.在知道网卡时候可以很快获取局域网内的ip

import struct
import fcntl
import socket

def getip(ethname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0X8915, struct.pack(256s, ethname[:15]))[20:24])

if __name__ == __main__:
    print getip(enp3s0)
# enp3s0 是ifconfig后看出来的

4.获取出的是127的,不太好,不明白应用场景

import socket

#获取计算机名称
hostname=socket.gethostname()
#获取本机IP
ip=socket.gethostbyname(hostname)
print(ip)

以上是关于linux通过Python获取本机的ip,mac,网关,子网掩码,网卡名的主要内容,如果未能解决你的问题,请参考以下文章

Linux中用shell编程获取IP地址及MAC地址

Python根据IP地址获取MAC地址

python获取linux本机IP

获取本机IPmac地址计算机名

Linux 项目 shell 自动获取报告本机IP | 通过shell 自动获取报告本机IP

java如何查询本机ip地址和mac地址