zoukankan      html  css  js  c++  java
  • 〖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
    " $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
  • 相关阅读:
    Python学习【第五篇】:面向对象及相关
    Python之路【第四篇】:模块
    Python之路【第三篇】:python基础(二)
    Python之路【第二篇】:Python基础(一)
    Python之路【第一篇】:Python简介和入门
    Open-source Tutorial
    Algorithms
    Mathematics Base
    Mathematics Base
    Open-source Tutorial
  • 原文地址:https://www.cnblogs.com/scue/p/3587836.html
Copyright © 2011-2022 走看看