[脚本工具] 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保存即可

参考资料 & 致谢

目录
相关文章
|
28天前
|
Linux Shell Python
Linux执行Python脚本
Linux执行Python脚本
27 1
|
1天前
|
数据采集 数据可视化 数据挖掘
R语言与Python:比较两种数据分析工具
【4月更文挑战第25天】R语言和Python是目前最流行的两种数据分析工具。本文将对这两种工具进行比较,包括它们的历史、特点、应用场景、社区支持、学习资源、性能等方面,以帮助读者更好地了解和选择适合自己的数据分析工具。
|
3天前
|
Linux 网络安全 开发工具
【超详细!超多图!】【代码管理】Python微信公众号开发(3)- 服务器代码上传Github
【超详细!超多图!】【代码管理】Python微信公众号开发(3)- 服务器代码上传Github
10 0
|
8天前
|
机器学习/深度学习 数据挖掘 计算机视觉
python数据分析工具SciPy
【4月更文挑战第15天】SciPy是Python的开源库,用于数学、科学和工程计算,基于NumPy扩展了优化、线性代数、积分、插值、特殊函数、信号处理、图像处理和常微分方程求解等功能。它包含优化、线性代数、积分、信号和图像处理等多个模块。通过SciPy,可以方便地执行各种科学计算任务。例如,计算高斯分布的PDF,需要结合NumPy使用。要安装SciPy,可以使用`pip install scipy`命令。这个库极大地丰富了Python在科学计算领域的应用。
12 1
|
8天前
|
数据可视化 数据挖掘 Python
Python中数据分析工具Matplotlib
【4月更文挑战第14天】Matplotlib是Python的数据可视化库,能生成多种图表,如折线图、柱状图等。以下是一个绘制简单折线图的代码示例: ```python import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5] y = [2, 4, 6, 8, 10] plt.figure() plt.plot(x, y) plt.title('简单折线图') plt.xlabel('X轴') plt.ylabel('Y轴') plt.show() ```
13 1
|
8天前
|
数据采集 SQL 数据可视化
Python数据分析工具Pandas
【4月更文挑战第14天】Pandas是Python的数据分析库,提供Series和DataFrame数据结构,用于高效处理标记数据。它支持从多种数据源加载数据,包括CSV、Excel和SQL。功能包括数据清洗(处理缺失值、异常值)、数据操作(切片、过滤、分组)、时间序列分析及与Matplotlib等库集成进行数据可视化。其高性能底层基于NumPy,适合大型数据集处理。通过加载数据、清洗、分析和可视化,Pandas简化了数据分析流程。广泛的学习资源使其成为数据分析初学者的理想选择。
15 1
|
14天前
|
测试技术 开发者 Python
Python中的装饰器:优雅而强大的函数修饰工具
在Python编程中,装饰器是一种强大的工具,用于修改函数或方法的行为。本文将深入探讨Python中装饰器的概念、用法和实际应用,以及如何利用装饰器实现代码的优雅和高效。
|
17天前
|
JSON 测试技术 持续交付
自动化测试与脚本编写:Python实践指南
【4月更文挑战第9天】本文探讨了Python在自动化测试中的应用,强调其作为热门选择的原因。Python拥有丰富的测试框架(如unittest、pytest、nose)以支持自动化测试,简化测试用例的编写与维护。示例展示了使用unittest进行单元测试的基本步骤。此外,Python还适用于集成测试、系统测试等,提供模拟外部系统行为的工具。在脚本编写实践中,Python的灵活语法和强大库(如os、shutil、sqlite3、json)助力执行复杂测试任务。同时,Python支持并发、分布式执行及与Jenkins、Travis CI等持续集成工具的集成,提升测试效率和质量。
|
24天前
|
存储 监控 异构计算
【Python】GPU内存监控脚本
【Python】GPU内存监控脚本
|
24天前
|
Ubuntu Unix Linux
【Linux/Ubuntu】Linux/Ubuntu运行python脚本
【Linux/Ubuntu】Linux/Ubuntu运行python脚本