〖Linux〗实时更新 hosts 文件的脚本

时间:2023-03-08 19:04:00

适用场景:

  下载了一个smarthosts的hosts文件,但hosts文件过旧导致一些ip地址已失效无法访问网络。

脚本使用:

  ./hostsupdate # 直接从 /etc/hosts 中获得需要更新的域名

  ./hostsupdate /path/to/hosts # 从指定路径中获得需要更新的域名

脚本源码:

 #!/bin/bash -
#===============================================================================
#
# FILE: hostupdate
#
# USAGE: ./hostupdate
#
# DESCRIPTION: 实时更新自己电脑上的hosts,加速网络的访问。
#
# OPTIONS: ---
# REQUIREMENTS: ---
# BUGS: ---
# NOTES: ---
# AUTHOR: linkscue(scue),
# ORGANIZATION:
# CREATED: 2013年08月10日 22时58分48秒 HKT
# REVISION: ---
#=============================================================================== rm -f /tmp/host_new*
host_new=/tmp/host_new$$ # . 获取旧hosts文件来源
if [[ -f "$1" ]]; then
ref_host="$1" # 参考的host来源,建议smarthosts
else
ref_host=/etc/hosts # 默认从/etc/hosts上获取链接参考
fi touch $host_new && tail -f $host_new & # . 更新hosts
echo -e "\e[0;35m --> 开始更新hosts文件\e[0m" # purple
cat $ref_host | while read line; do
if [[ ${line::} == '#' ]] || [[ ${#line} == 0 ]] \
|| [[ $(echo $line | grep localhost) != "" ]] \
|| [[ $(echo $line | grep $HOSTNAME) != "" ]]; then
echo $line >> $host_new
else
addr=$(echo $line|awk '{print $2}')
link=$(nslookup "$addr" | sed '/^$/d' | sed -n '$p' | sed -n 's/Address: //gp')
if [[ "$link" != "" ]]; then
printf "%-19s%s\n" $link $addr >> $host_new
fi
fi
done # . 复制至 /etc/hosts
echo -en "\e[0;35m --> 更新hosts文件完毕,是否将新文件 $host_new 移动至 /etc/hosts[Y/n]:\e[0m" # purple
read -p "" reply
if [[ ${reply} != "n" ]]; then
sudo mv /etc/hosts{,.bak}
sudo cp $host_new /etc/hosts
fi
echo -e "\e[0;36m --> 全部操作完成,Enjoy!\e[0m" # cyan

hostupdate.sh

相关文章