nmcli网络配置详解

nmcli 是 NetworkManager 的命令行工具。nm 代表 NetworkManager,cli 代表 Command-Line 命令行。

NetworkManager 的配置文件(通常位于/etc/NetworkManager/system-connections/

NetworkManager运行服务

#查看运行状态:
systemctl status NetworkManager
#启动:
systemctl start NetworkManager
#重启:
systemctl restart NetworkManager
#关闭:
systemctl stop NetworkManager
#查看是否开机启动:
systemctl is-enabled NetworkManager
#开机启动:
systemctl enable NetworkManager
#禁止开机启动:
systemctl disable NetworkManager

注意:NetworkManager 中开头的 N 和中间的 M 必须大写。

nmcli基础命令

信息查询

#显示目前网络详细
nmcli
#显示所有连接
nmcli connection show
#显示可用连接
nmcli connection show --active
#显示device(网卡设备)的详细信息
nmcli device status
#指定查询设备状态
nmcli device connect eth0

网络配置

#按界面配置
nmtui

wifi操作

#显示可用的wifi
nmcli device wifi list
#连接wifi
nmcli device wifi connect "$SSID" password "$PASSWORD" ifname wlan0
#连接wifi输入密码
nmcli --ask device wifi connect "$SSID"
#带EAP认证连接
命令比较复杂,暂无命令
#断开设备连接
nmcli device disconnect ens160
#连接到一个设备
nmcli device connect ens160

有线网络

#创建新的连接
#type ethernet: 网络类型为以太网。
#con-name br0: 连接名称为 br0
#ifname eth01: 接口名称为 eth01
#ipv4.method manual: 使用手动配置 IPv4 地址。
#ipv4.address "192.168.1.2/24": 设置 IPv4 地址为 192.168.1.2,子网掩码为 24。
#gw4 192.168.31.1: 设置网关为 192.168.31.1。

nmcli connection add ifname eth01 con-name br0 type ethernet ip4 192.168.1.2/24 gw4 192.168.3.1
#激活连接上线
nmcli connection up br0
#设置DNS服务
nmcli connection modify br0 ipv4.dns "114.114.114.114 8.8.8.8"
#修改连接IP地址
nmcli connection modify br0 ipv4.addr 10.0.0.210/24

#第二种方式
#创建有效连接
nmcli connection add ifname eth01 con-name br0 type ethernet
#也可用直接配置ip、网关、dns
nmcli connection modify br0 ipv4.addresses 192.168.1.2/24 ipv4.getway 192.168.3.1 ipv4.dns 114.114.114.114

#配置动态IP地址(DHCP)
nmcli connection add type ethernet con-name br0 ifname eth01 ipv4.method auto
nmcli connection up eth01

常规操作

#启动和关闭连接
nmcli connection up br0
nmcli connection down br0
#删除网络
nmcli connection delete br0
#修改IP地址及网关
nmcli connection modify br0 ipv4.addresses 200.100.100.100/24 ipv4.getway 200.100.100.1
#添加dns
nmcli connection modify br0 +ipv4.dns 114.114.114.114
#删除dns
nmcli connection modify br0 -ipv4.dns 114.114.114.114
#添加ip
nmcli connection modify br0 +ipv4.addresses 10.10.10.10/24
#删除ip
nmcli connection modify br0 -ipv4.addresses 10.10.10.10/24
#修改连接配置后重新激活
nmcli connecti reload

nmcli桥接

# 创建一个桥接网卡
## autoconnect yes:表示这个网络连接在系统启动或者网络可用时自动连接(autoconnect),这里设置为yes,即自动连接。
nmcli connection add type bridge autoconnect yes con-name br1 ifname br1

# 为桥接网卡配置静态IP地址
nmcli connection mod br1 ip4 192.168.2.150/24 ipv4.method manual

# 为桥接网卡配置网关
nmcli connection mod br1 gw4 192.168.2.1

# 为桥接网卡配置DNS
nmcli connection mod br1 ipv4.dns 8.8.8.8 +ipv4.dns 8.8.4.4

# 添加网桥从属设备
# 将接口 enp1s0 加入到名为 br1 的桥接接口中
nmcli connection add type bridge-slave autoconnect yes con-name xxo ifname enp1s0 master br1

# 激活网桥br1配置
nmcli connection up br1