【Ubuntu】在Ubuntu中设置永久的DNS

1、问题描述

ping不通域名,比如“ping www.baidu.com”时,报错“ping: unknown host www.baidu.com”。这是因为ubuntu默认情况下没有设置DNS。
在ubuntu上设置DNS的方法,修改“/etc/resolv.conf”,添加“nameserver 8.8.8.8”,但是重启后就失效了。

2、原因查找

在“/etc/resolv.conf”中开头有如下内容:

# Dynamic resolv.conf(5) file for glibc resolver(3) generated by resolvconf(8)
#     DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN

这里已经明确说明,resolv.conf是由resolvconf命令动态生成的,不要编辑这个文件。

resolvconf是什么?

resolvconf 是"域名服务信息"管理工具,说白了就是管理ubuntu系统的DSN,包括添加、删除、更新、使能或禁止更新等。
使用方法:resolvconf (-d IFACE|-a IFACE|-u|–enable-updates|–disable-updates|–updates-are-enabled)
可以使用man查看详细信息:man resolvconf

如何生成的resolv.conf?

ubunut启动后调用初始化脚本:/etc/init.d/resolvconf start

 83   start)
 84     # The "start" method should only be used at boot time.
 85     # Don't run this on package upgrade, for example.
 86     log_action_begin_msg "Setting up resolvconf"
 87     # Wipe runtime directories in case they aren't on a tmpfs
 88     wipe_runtime_directories
 89     # Create runtime directories in case they are on a tmpfs
 90     create_runtime_directories
 91     # Request a postponed update (needed in case the base file has content).
 92     :> "$POSTPONED_UPDATE_FLAGFILE" || log_action_end_msg_and_exit 1 "failed requesting update"
 93     # Enable updates and perform the postponed update.
 94     resolvconf --enable-updates || log_action_end_msg_and_exit 1 "failed to enable updates"
 95     log_action_end_msg_and_exit 0
 96     ;;

对上面这段脚本的解释:
首先,注释里面提示==/etc/init.d/resolvconf start==只能在系统启动时调用一次,因为它会在/run/中创建resolvconf及相关文件目录。
wipe_runtime_directories:清除/run/resolvconf目录
create_runtime_directories:创建/run/resolvconf/interface目录
:> “$POSTPONED_UPDATE_FLAGFILE” 创建文件 /run/resolvconf/postponed-update,这个文件下面会用到。
resolvconf --enable-updates:resolvconf路径是/sbin/resolvconf
/sbin/resolvconf也是一个脚本,执行 --enable-updates 选项

--enable-updates)
 : >| "$ENABLE_UPDATES_FLAGFILE" || exit 1
 if [ -e "$POSTPONED_UPDATE_FLAGFILE" ] ; then
    (update_and_exit -u) || :
  fi
  exit 0

对上面这段脚本的解释:
创建文件 /run/resolvconf/enable-updates;
如果文件 /run/resolvconf/postponed-update存在,则执行(update_and_exit -u),这个文件在上面的步骤中已经创建;
update_and_exit函数如下

 56 update_and_exit()
 57 {
 58     rm -f "$POSTPONED_UPDATE_FLAGFILE"
 59     exec run-parts ${1:+--arg="$1"} ${2:+--arg="$2"} /etc/resolvconf/update.d
 60 }

删除:/run/resolvconf/postponed-update
run-parts功能:批量执行目录下的脚本;
/etc/resolvconf/update.d下只有一个脚本libc;
libc功能是用 /etc/resolvconf/resolv.conf.d 目录下的三个文件head、base、tail生成/run/resolvconf/resolv.conf,并创建软链接/etc/resolv.conf

3、解决方法

要想设置永久的DNS,一个正经的办法是修改 /etc/resolvconf/resolv.conf.d/base

nameserver 8.8.8.8
nameserver 8.8.4.4

修改完后执行:

/sbin/resolvconf -u

再重启后就不用再设置DNS了

发布了324 篇原创文章 · 获赞 266 · 访问量 42万+

猜你喜欢

转载自blog.csdn.net/u010168781/article/details/105559182