Configuring network settings in Linux via gsettings/script/terminal

Solution 1:

You can use the nmcli tool to edit connections through NetworkManager.

For example, say you want to create an ethernet connection for device: enp1s0.

  • IP: 192.168.1.10

  • gateway: 192.168.1.1

  • DNS: 8.8.8.8

  • connection name: "net-enp1s0"

sudo nmcli con add con-name "net-enp1s0" ifname enp1s0 type ethernet ipv4.method manual ip4 192.168.1.10/24 gw4 192.168.1.1 ipv4.dns 8.8.8.8 

or as a script (you will need to use sudo to run this script):

#!/bin/bash
nmcli con add \
con-name "net-enp1s0" \
ifname enp1s0 \
type ethernet \
ipv4.method manual \
ip4 192.168.1.10/24 \
gw4 192.168.1.1 \
ipv4.dns 8.8.8.8

These are the options:

  • con = connection

  • add = add

  • con-name "net-enp1s0" = connection id

  • ifname enp1s0 = connection interface-name

  • type ethernet = connection type

  • ipv4.method manual = use static IP

  • ip4 192.168.1.10/24 = local ipv4 address and netmask (24=255.255.255.0)

  • gw4 192.168.1.1 = gateway

  • ipv4.dns 8.8.8.8 = DNS server


You can also edit an existing connection.

Configuration file for our "net-enp1s0" connection is: /etc/NetworkManager/system-connections/net-enp1s0. The file should look like this:

[connection]
id=net-enp1s0
uuid=5099a1ae-1ae0-42d7-acf8-178ef3772f4f
type=ethernet
interface-name=enp1s0
permissions=

[ethernet]
mac-address-blacklist=

[ipv4]
address1=192.168.1.10/24,192.168.1.1
dns=8.8.8.8;
dns-search=
method=manual

[ipv6]
addr-gen-mode=stable-privacy
dns-search=
method=auto

If you edit the configuration file for a network, you can run the following command to apply the changes:

sudo nmcli con reload

The following example is for a WPA wireless connection with PSK named "coffee-shop" on a network named "freewifi" using the password "freepassword":

sudo nmcli con add con-name "coffee-shop" type wifi ifname wlp2s0 ssid "freewifi" -- wifi-sec.key-mgmt wpa-psk wifi-sec.psk "freepassword" ipv4.method manual ip4 192.168.1.10/24 gw4 192.168.1.1 ipv4.dns 8.8.8.8 

Here it is as a script:

#!/bin/bash
nmcli con add \
con-name "coffee-shop" \
type wifi \
ifname wlp2s0 \
ssid "freewifi" \
-- wifi-sec.key-mgmt wpa-psk \
wifi-sec.psk "freepassword" \
ipv4.method manual \
ip4 192.168.1.10/24 \
gw4 192.168.1.1 \
ipv4.dns 8.8.8.8

Links:

  • Wifi example based on this answer by user @cody-G

  • NetworkManager nmcli documentation at gnome.org

  • CertDepot tutorial "RHEL7: Configure IPv4 addresses"

Also, this Arch Linux wiki page has a list of nmcli examples.

The CertDepot tutorial is for RedHat but pretty much all of the nmcli stuff applies to Ubuntu. However, Ubuntu configuration files are in /etc/NetworkManager/system-connections and you can directly edit these files.