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

适用场景:

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

脚本使用:

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

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

脚本源码:

 1 #!/bin/bash - 
 2 #===============================================================================
 3 #
 4 #          FILE: hostupdate
 5 # 
 6 #         USAGE: ./hostupdate 
 7 # 
 8 #   DESCRIPTION: 实时更新自己电脑上的hosts,加速网络的访问。
 9 # 
10 #       OPTIONS: ---
11 #  REQUIREMENTS: ---
12 #          BUGS: ---
13 #         NOTES: ---
14 #        AUTHOR: linkscue(scue), 
15 #  ORGANIZATION: 
16 #       CREATED: 2013年08月10日 22时58分48秒 HKT
17 #      REVISION:  ---
18 #===============================================================================
19 
20 rm -f /tmp/host_new*
21 host_new=/tmp/host_new$$
22 
23 # 1. 获取旧hosts文件来源
24 if [[ -f "$1" ]]; then
25     ref_host="$1"                               # 参考的host来源,建议smarthosts
26 else
27     ref_host=/etc/hosts                         # 默认从/etc/hosts上获取链接参考
28 fi
29 
30 touch $host_new && tail -f $host_new &
31 
32 # 2. 更新hosts
33 echo -e "\e[0;35m --> 开始更新hosts文件\e[0m" # purple
34 cat $ref_host | while read line; do
35     if [[ ${line:0:1} == '#' ]] || [[ ${#line} == 0 ]] \
36         || [[ $(echo $line | grep localhost) != "" ]] \
37         || [[ $(echo $line | grep $HOSTNAME) != "" ]]; then
38         echo $line >> $host_new
39     else
40         addr=$(echo $line|awk '{print $2}')
41         link=$(nslookup "$addr" | sed '/^$/d' | sed -n '$p' | sed -n 's/Address: //gp')
42         if [[ "$link" != "" ]]; then
43             printf "%-19s%s\n" $link $addr >> $host_new
44         fi
45     fi
46 done
47 
48 # 3. 复制至 /etc/hosts
49 echo -en "\e[0;35m --> 更新hosts文件完毕,是否将新文件 $host_new 移动至 /etc/hosts[Y/n]:\e[0m" # purple
50 read -p "" reply
51 if [[ ${reply} != "n" ]]; then
52     sudo mv /etc/hosts{,.bak}
53     sudo cp $host_new /etc/hosts
54 fi
55 echo -e "\e[0;36m --> 全部操作完成,Enjoy!\e[0m" # cyan
hostupdate.sh

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值