获取mac地址,内网ip,当前ip位置信息

复制代码
import json
import socket
import time
import requests
from urllib.parse import quote

class Home_Url():
    def get_mac(self):
        from psutil import net_if_addrs
        mac = ''
        info = net_if_addrs()
        for k, v in info.items():
            if k not in ['以太网', 'en0'] and '以太网' not in str(k):
                continue
            print(k)
            for i in v:
                if '-' in i[1] or ':' in i[1]:
                    if len(i[1]) == 17:
                        mac = str(i[1]).lower()
                        break
        if not mac:
            node = uuid.getnode()
            mac = uuid.UUID(int=node).hex[-12:]
            mac = '-'.join([mac[i:i + 2] for i in range(0, len(mac) + 2 // 2, 2)])[:-1]
        return mac

    def get_external_ip(self):
        external_ip = None
        url1 = 'https://ipinfo.io/json'
        url2 = 'https://checkip.amazonaws.com/json'
        url3 = 'https://api.ipify.org/?format=json'
        url4 = 'https://api64.ipify.org'
        url5 = 'http://ip-api.com/json/?lang=zh-CN'
        urls = [url1, url2, url4, url3, url5]
        headers = {
            'Accept': '*/*',
            'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.47'
        }
        for url in urls:
            try:
                proxies = {"http": None, "https": None}
                res = requests.get(url, headers=headers, proxies=proxies, timeout=25)
                if res.text.count('{') > 0:
                    response = json.loads(res.text)
                    external_ip = response.get('ip') or response.get('query')
                else:
                    external_ip = res.text
                if external_ip.strip():
                    return external_ip.strip()
            except:
                pass
        return external_ip

    def get_city_region(self):
        # 获取当前ip位置信息
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'
        }
        url = 'https://whois.pconline.com.cn/ipJson.jsp?json=true'
        try:
            res = requests.get(url, headers=headers, timeout=5)
            response = json.loads(res.text)
            city = response['city']
            return city
        except:
            return ''

    def get_mac_address(self):
        mac = self.get_mac()
        print('mac:', mac)
        # 获取主机名
        hostname = socket.gethostname()
        # 内网IP地址
        # intranet_ip = socket.gethostbyname(hostname)
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        intranet_ip = s.getsockname()[0]
        # 外网ip
        try:
            external_ip = self.get_external_ip()
        except:
            external_ip = '127.0.0.1'
        return mac, hostname, intranet_ip, external_ip
   
    def run(self):
        mac, hostname, intranet_ip, external_ip = self.get_mac_address()

if __name__ == '__main__':
    start = Home_Url()
    start.run()
相关推荐
Wellijohn2 小时前
Python 容器选型实测:list.insert(0) 慢 925 倍,in 慢 6000 倍
python
新*2 小时前
标题全变成一级?靠编号规律找回章节边界
python·正则表达式·pdf解析·文本处理
高洁014 小时前
多源数据融合:把零散信号拼成一致图景
人工智能·python·机器学习·transformer·迁移学习
郝学胜-神的一滴5 小时前
Effective Python 条款41:试Mix‑In组合式开发
开发语言·pytorch·python·pycharm·numpy
吃我一窝jio5 小时前
Python与Redis集合深度解析
开发语言·redis·笔记·python
龙腾AI白云7 小时前
多源数据融合:把零散信号拼成一致图景
大数据·人工智能·python·机器学习·知识图谱
艾派森7 小时前
深度学习实战-基于VGG19的健康和白化珊瑚图像分类识别模型
人工智能·python·深度学习·分类
鲸渔7 小时前
【AI Agent系列课程26-Python 基础26】复盘:Python 接口开发知识清单
开发语言·python·ai编程
2401_868534788 小时前
55 个热门网络面试问题及答案
网络·python
aifannihao8 小时前
ON CONFLICT 冲突后返回空:sqlite3 实测 get-or-create
数据库·python·postgresql·sqlite3·标准库