[脚本工具] Python 局域网Hosts实现DDNS / Github网速增强

简介: [脚本工具] Python 局域网Hosts实现DDNS / Github网速增强

简介

笔者主要解决的问题是,在家或者出差有多台笔记本电脑,需要频繁修改Ip来连接这台笔记本上面服务。

  • 该脚本通过一键映射hosts 直接通过域名访问 (只会更新或者替换目标host的IP映射,其他的不会动)
  • 在winddows 开发并平台可以正常运行,原则上支持CentOS但是没有测试

方法 / 步骤

一: 安装python3 环境

安装资源 一键安装, 本文不再赘述

1.1 Windows 放行host修改权限

找到host文件(右击) -> 切换到“安全”Tab栏" -> 编辑 (添加Everyone 并勾选完全控制-> 应用并且确定)

回到安全Tab栏->高级-> 更改所有者->输入everyone ->确定 -> 确定

然后就可以更改了

二: 脚本编码

2.1 局域网DDNS(基于主机名称)

本脚本需要填写:url_node_dict :

主要填写自局域网hosts的主机名称 key映射后的url ,value 对应的是节点名称(也就是服务名称)

hostsBySvrName.py

import os
import socket
import platform

# key对应的是映射后的url(保持唯一性) value 对应的是节点名称(也就是服务名称)

url_node_dict = {'nas.com':'YGC-NAS',
                 'mws.com':'THINK-YANG',
                 'mwsvm0.com': 'mwsvm0'}


node_name_list = url_node_dict.values()
# windows 的默认hosts路径


HOSTS_PATH = "C:/Windows/System32/drivers/etc/hosts"
flushdns = "ipconfig /flushdns"
node_nameip_dict = {}


def platformAdapter():
    if ("Linux" ==  platform.system()):
        hostsPath ="/etc/hosts"
        # CentOS需要提前安装 nscd 
        flushdns = "nscd -i hosts"


def findSvrIpByName():
    for node_name in node_name_list:
        try:
            node_ip = socket.gethostbyname(node_name)
            print("host: " + node_name + " IP: " + node_ip)
            node_nameip_dict[node_name] = node_ip
        except:
            print("node: " + node_name + " IP not found")



def udpateHostInfo():
    if not bool(node_nameip_dict):
        print('node_nameip_dict is null')
        os.system.exit()

    updatedHostIp = set()
    newHostContents = ""
    with open(r''+ HOSTS_PATH, 'r', encoding='UTF-8') as filerReader:
        lines = filerReader.readlines()
        for currLine in lines:
            hosts_old_ip_url = currLine.split(" ")
            old_url = hosts_old_ip_url[1].strip('\n')
            if (old_url in url_node_dict.keys()):
                currLine = currLine.replace(currLine, node_nameip_dict[url_node_dict[old_url]]+" "+ old_url + "\n")
            newHostContents += currLine
    with open(r''+ HOSTS_PATH, 'w', encoding='UTF-8') as fileWriter:
        fileWriter.write(newHostContents)

# 打印文本已替换
platformAdapter()
findSvrIpByName()
udpateHostInfo()

os.system(flushdns)
print("hosts is update")
os.system('pause')

2.2 Github 网络加速

本脚本不用配置任何东西,直接下载运行即可

enhance_github.py

import os
import platform

import requests
from requests import exceptions

# key对应的是映射后的url(保持唯一性) value 对应的是节点名称(也就是服务名称)

ENHANCE_GITHUB_URL = "https://gitlab.com/ineo6/hosts/-/raw/master/next-hosts"

# 备用地址
ENHANCE_GITHUB_URL_BAK = "https://raw.hellogithub.com/hosts"

new_url_ip_dic = {}
HOSTS_PATH = "C:/Windows/System32/drivers/etc/hosts"
DNS_FLUSH = "ipconfig /flushdns"

node_name_ip_dict = {}


def platformAdapter():
    if ("Linux" == platform.system()):
        HOSTS_PATH = "/etc/hosts"
        # CentOS需要提前安装 nscd
        DNS_FLUSH = "nscd -i hosts"


def load_github_hosts():
    resp_context = ""
    try:
        resp_context = requests.session().get(ENHANCE_GITHUB_URL).text
    except exceptions.HTTPError as e:
        # 备用地址
        print(e)
        resp_context = requests.session().get(ENHANCE_GITHUB_URL_BAK).text
    except exceptions.Timeout as ee:
        print(ee)
    if bool(resp_context):
        context_lines = resp_context.split("\n")
        for line in context_lines:
            if (bool(line)) and not line.startswith("#"):
                ip_url_list = line.split()
                new_url_ip_dic[ip_url_list[1]] = ip_url_list[0]
            else:
                continue
        print(new_url_ip_dic)


updated_url = []


def update_hosts():
    if not bool(new_url_ip_dic):
        print('new_url_ip_dic is null')
        os.system.exit()
    newHostContents = ""
    with open(r'' + HOSTS_PATH, 'r', encoding='UTF-8') as filerReader:
        lines = filerReader.readlines()
        for currLine in lines:
            hosts_old_ip_url = currLine.split(" ")
            old_url = hosts_old_ip_url[1].strip('\n')
            if (old_url in new_url_ip_dic.keys()):
                currLine = currLine.replace(currLine, new_url_ip_dic[old_url] + " " + old_url + "\n")
                updated_url.append(old_url)
            newHostContents += currLine
    # 对待添加的IP进行添加
    ready_add_url_ip = new_url_ip_dic.keys() - updated_url
    if not bool(ready_add_url_ip):
        for curr_url in ready_add_url_ip:
            newHostContents += new_url_ip_dic[curr_url] + " " + curr_url + "\n"
            print(new_url_ip_dic[curr_url] + " " + curr_url + "is added")
    with open(r'' + HOSTS_PATH, 'w', encoding='UTF-8') as fileWriter:
        fileWriter.write(newHostContents)


if __name__ == '__main__':
    platformAdapter()
    load_github_hosts()
    update_hosts()
    os.system(DNS_FLUSH)
    print("hosts is update")
    os.system('pause')

三: 关于放行相关代理

作者使用小猫,在下面设置放行刚刚添加的host主机地址就可以了

在这里插入图片描述

  • 脚本内容如图所示

在这里插入图片描述
然后右下加点击save保存即可

参考资料 & 致谢

目录
相关文章
|
存储 缓存 测试技术
理解Python装饰器:简化代码的强大工具
理解Python装饰器:简化代码的强大工具
|
程序员 测试技术 开发者
Python装饰器:简化代码的强大工具
Python装饰器:简化代码的强大工具
402 92
|
机器学习/深度学习 编解码 Python
Python图片上采样工具 - RealESRGANer
Real-ESRGAN基于深度学习实现图像超分辨率放大,有效改善传统PIL缩放的模糊问题。支持多种模型版本,推荐使用魔搭社区提供的预训练模型,适用于将小图高质量放大至大图,放大倍率越低效果越佳。
972 3
|
人工智能 自然语言处理 安全
Python构建MCP服务器:从工具封装到AI集成的全流程实践
MCP协议为AI提供标准化工具调用接口,助力模型高效操作现实世界。
1971 1
|
算法 安全 数据安全/隐私保护
Python随机数函数全解析:5个核心工具的实战指南
Python的random模块不仅包含基础的随机数生成函数,还提供了如randint()、choice()、shuffle()和sample()等实用工具,适用于游戏开发、密码学、统计模拟等多个领域。本文深入解析这些函数的用法、底层原理及最佳实践,帮助开发者高效利用随机数,提升代码质量与安全性。
1511 0
|
API 数据安全/隐私保护 Python
拼多多批量上架软件, 电商一键上货发布工具,python电商框架分享
多线程批量上传架构,支持并发处理商品数据 完整的拼多多API签名和token管理机制
|
安全 API 数据安全/隐私保护
|
Java API 数据安全/隐私保护
淘宝一键上货发布软件,淘宝批量发布上架工具, 淘宝批量上架脚本【python】
这个Python脚本实现了以下功能: 完整的淘宝API调用封装
|
机器人 数据安全/隐私保护 Python
淘宝批量发货发布工具, 淘宝批量上传商品软件, 淘宝批量上架软件【python】
使用Selenium实现自动化操作淘宝卖家后台 支持三种核心功能

推荐镜像

更多