1.测试环境:
Linux debian11 5.10.0-13-amd64
Python3.9
2.代码
要修改的参数:
- 备选IP。 hosts=[]
- 下载链接,用于测试下载速度。 download_url =""
- 要替换IP的域名。 domain = ""
- 下载超时时间,默认5min。 if time.time() - start_time > 300:
- 脚本日志,logging.basicConfig()。
import os
import time
import requests
import logging
# 请注意,由于hosts文件的修改需要root权限,因此请确保以root用户身份运行此脚本。
# 下载链接:
# https://xxxx
# 备选host:
# 2620:1ec:8fa::10 xxxx-my.sharepoint.com
# 13.107.136.10 xxxx-my.sharepoint.com
# 13.107.138.10 xxxx-my.sharepoint.com
# 52.105.246.55 xxxx-my.sharepoint.com
#
# 实现自动修改hosts文件以保持最大下载速度。添加详细中文注释。在以下情况下记录日志:
# 修改hosts文件时。
# 文件下载完成时,包括下载速度。
# 文件下载超时时。
# 选择最快的IP并修改hosts文件时。
# 如果没有找到有效的下载速度时。
#
# step1:从备选host中按顺序选取一条覆盖/etc/hosts 内xxxx-my.sharepoint.com的原有ip。
# step2:下载上述链接的文件,下载停止条件:下载完毕或者在5min内没有下载完成,则停止下载。并记录平均下载速度, 以MB/S显示。然后删除下载的文件。如果备选host没有测试完则继续step1测试剩余的ip下载速度。
# step3:统计备选host中每个host ip的下载速度,选取下载最快的那个ip覆盖xxxx-my.sharepoint.com的ip
# 配置日志
logging.basicConfig(filename='/root/Tools/speed2hosts/speed2hosts.log', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
# 备选host
hosts = [
"13.107.136.10",
"13.107.138.10",
"52.105.246.55",
"2620:1ec:8fa::10"
]
# 下载链接
download_url = "https://xxxx"
# hosts文件路径
hosts_file = "/etc/hosts"
# Sharepoint域名
domain = "xxxx-my.sharepoint.com"
def modify_hosts(ip):
with open(hosts_file, 'r') as file:
lines = file.readlines()
with open(hosts_file, 'w') as file:
for line in lines:
if domain not in line:
file.write(line)
file.write(f"{ip} {domain}\n")
logging.info(f"修改hosts文件: {ip} 覆盖 {domain}")
def download_file(url, timeout=300):
local_filename = url.split('/')[-1]
start_time = time.time()
try:
with requests.get(url, stream=True, timeout=timeout) as r:
r.raise_for_status()
with open(local_filename, 'wb') as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
# 如果下载时间超过5分钟,停止下载
if time.time() - start_time > 300:
raise TimeoutError("下载超时")
end_time = time.time()
download_time = end_time - start_time
file_size = os.path.getsize(local_filename) / (1024 * 1024) # 转换为MB
download_speed = file_size / download_time # MB/s
logging.info(f"文件下载完成: {local_filename}, 平均下载速度: {download_speed:.2f} MB/s")
os.remove(local_filename)
return download_speed
except TimeoutError as e:
logging.warning("文件下载超时")
if os.path.exists(local_filename):
os.remove(local_filename)
return None
except Exception as e:
logging.error(f"下载错误: {e}")
if os.path.exists(local_filename):
os.remove(local_filename)
return None
def main():
best_ip = None
best_speed = 0
for ip in hosts:
modify_hosts(ip)
time.sleep(3)
speed = download_file(download_url)
if speed:
if speed > best_speed:
best_speed = speed
best_ip = ip
logging.info(f"{ip} 的下载速度为: {speed:.2f} MB/s" if speed else f"{ip} 下载失败")
if best_ip:
modify_hosts(best_ip)
logging.info(f"选择最快的IP: {best_ip} 覆盖 {domain},速度: {best_speed:.2f} MB/s")
else:
logging.error("未找到有效的下载速度")
if __name__ == "__main__":
main()
3.定时运行
通过crontab定时执行脚本,保持最优的hosts。
crontab -e
添加以下参数,每间隔1小时执行一次。
0 */1 * * * /usr/bin/python3 /root/speed2hosts.py >> /root/speed2hosts.txt 2>&1
/usr/bin/python3为python位置
/root/speed2hosts.py为脚本位置
/root/speed2hosts.txt 为crontab执行脚本时产生的日志
Comments NOTHING