Linux 临时和永久修改DNS方法

 3年前     731  

文章目录

    1、修改DNS配置:

    方法一(临时修改,重启失效)

    修改下面文件:
    vi /etc/resolv.conf

    加入想要修改的DNS:
    nameserver 1.1.1.1
    nameserver 8.8.8.8

    如果多个DNS,就一行一个,修改之后保存退出即可;

    此方法修改后即刻生效,但重启后失效
     
    方法二(生成钩子阻止DHCP修改resolv.conf)

    Debian/Ubuntu下生成 nodnsupdate 文件:

    nano /etc/dhcp/dhclient-enter-hooks.d/nodnsupdate

    按 i 键粘贴以下代码后 :wq 保存:

    #!/bin/sh
    make_resolv_conf(){
        :
    }

    给文件 nodnsupdate 添加可执行权限:

    chmod +x /etc/dhcp/dhclient-enter-hooks.d/nodnsupdate

    重启系统,现在你就可以修改 /etc/resolv.conf 文件而且不会担心被回滚了。

     
    方法三(写保护锁定resolv.conf文件)

    rm -f /etc/resolv.conf
    editor /etc/resolv.conf

    #填写上指定的DNS服务器:
    nameserver 1.1.1.1
    nameserver 1.0.0.1

    chattr +i /etc/resolv.conf

    此时resolv.conf文件的内容就会被锁定不会被重启覆盖,想要解锁的话运行:

    chattr -i /etc/resolv.conf

     
    2、使修改的 DNS 生效:

    修改完保存了并不是立即生效的。输入下面命令使配置生效:

    # 使网卡配置生效
    /etc/init.d/networking restart

    # 使 DNS 生效
    /etc/init.d/resolvconf restart

    查看是否已经生效:

    systemd-resolve --status

    如果已经变成了你设置的DNS,那就设置成功了。

     
    3、nslookup解析命令 验证DNS是否修改成功:

    安装nslookup:

    #Ubuntu
    apt-get install dnsutils

    #Debian
    apt-get update
    apt-get install dnsutils

    #Centos
    yum install bind-utils

    使用方法(以解析www.baidu.com为例):

    nslookup www.baidu.com

    说明:
    nslookup 你需要解析的域名

    示例:

    root@ubuntu:~# nslookup www.baidu.com
    Server:         8.8.8.8
    Address:        8.8.8.8#53

    结果显示当前首选DNS为8.8.8.8。

    您可能感兴趣的