简介
笔者主要解决的问题是,在家或者出差有多台笔记本电脑,需要频繁修改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 对应的是节点名称(也就是服务名称)
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 网络加速
本脚本不用配置任何东西,直接下载运行即可
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保存即可