How to manage DNS in NetworkManager via console (nmcli)?

Solution 1:

Here is the command to modify an existing connection.

nmcli con mod $connectionName ipv4.dns "8.8.8.8 8.8.4.4"

connectionName can be found by command: nmcli con. In the question case, it will be "System eth0"

If you want to ignore automatically configured nameservers and search domains, ie the settings passed from DHCP.

nmcli con mod $connectionName ipv4.ignore-auto-dns yes

Finally, to enable the changes, bring the connection down then up:

nmcli con down $connectionName
nmcli con up $connectionName

Verify with cat /etc/resolv.conf. You should not edit /etc/resolv.conf manually as it is generated by NetworkManager service, it is likely to get overridden at any given time.

Useful nmcli manual

Solution 2:

there is good TUI tool developed by red hat named nmtui that you really should try. it is pre-installed on various distros, nowadays, but if it is not on yours, try:

  sudo yum install networkmanager-tui

it uses a curses based text interface - accessible from the command line. nmcli is only especially necessary when writing scripts, and has larger room for error due to the larger variety of possible input.

Solution 3:

In addition to setting the ipv4.dns property described above...

To exclude the DHCP provided DNS servers...set the ipv4.ignore-auto-dns property to yes.

nmcli con mod <connectionName> ipv4.ignore-auto-dns yes

To enable the changes, bring the connection down then up:

nmcli con down <connectionName>
nmcli con up <connectionName>

Verify with cat /etc/resolv.conf

Solution 4:

Just in case I have done a little script to do that automatically (here with google DNS) for every ethernet/wireless connections:

nmcli -g name,type connection  show  --active | awk -F: '/ethernet|wireless/ { print $1 }' | while read connection
do
  nmcli con mod "$connection" ipv6.ignore-auto-dns yes
  nmcli con mod "$connection" ipv4.ignore-auto-dns yes
  nmcli con mod "$connection" ipv4.dns "8.8.8.8 8.8.4.4"
  nmcli con down "$connection" && nmcli con up "$connection"
done

At the end, the wireless connections will be lost. You have to reconnect and voilà !