NetworkManger 管理網絡


一、NetworkManger簡介

Networkmanager 是2004年由 Red Hat 軟件公司發起開發的網絡連接管理軟件,旨在讓使用者輕松地管理網絡連接並在多個網絡間進行切換(特別是無線網絡)。NetworkManager 是首個使用 D-BusHALGNU/Linux 桌面工具,使用者無需使用管理員權限,即可直接通過面板狀態通知區的小圖標查看連接的網絡(包括個無線網絡)的信息、切換使用的網絡,以及處理 WEP/WPA 的密碼。從0.7版本開始 NetworkManager 便可以管理 3G、EVDO、HSDPA、RTTx1、EDGE連線。FedoraCore3 開始收錄 NetworkManager,Ubuntu 則從 Ubuntu 6.06 LTS (Dapper)開始收錄 NetworkManager ,Red Hat Enterprise Linux 從7.0版本開始使用 NetworkManager 取代 system-config-service 作為圖形化網絡配置工具。

 NetworkManager 工具包括以下幾種:

  • NetworkManager Applet (nm-applet ):在面板狀態通知區顯示小圖標並報告網絡連接狀態;
  • nmcli:命令行網絡接口配置工具;
  • nm-connection-editor:NetworkManager 的圖形化前端;
  • nmtui 在文本模式下的 NetworkManager 前端。

NetworkManager 可以用於以下類型的連接:Ethernet,VLANS,Bridges,Bonds,Teams,Wi-Fi,mobile boradband (如移動3G)以及 IP-over-InfiniBand。 針對與這些網絡類型,NetworkManager 可以配置他們的網絡別名,IP 地址,靜態路由,DNS,VPN連接以及很多其它的特殊參數。可以用命令行工具 nmcli 來控制 NetworkManager。nmcli的功能要比 ifconfig 強大、復雜的多。

 在rhel7上,同時支持network.service和NetworkManager.service (簡稱NM)。默認情況下,這2個服務都是開啟的,可能會產生沖突,許多人都會將NM禁用掉只保留network。在rhel8上默認是不安裝network的,因此只能通過NM進行網絡配置和管理。但rhel8依然支持network.service,需要自行安裝。

二、安裝啟動服務

 若 NetworkManager 沒有預安裝在Linux 上,可以使用 dnf 軟件包管理工具進行安裝,安裝啟動命令如下:

dnf install NetworkManager
systemctl start NetworkManager
systemctl enable NetworkManager

三、3種網絡配置方法

 在講3種配置方法前,需要先明白ifcfg和NM connection的關聯:雖然network.service被廢棄了,但是redhat為了兼容傳統的ifcfg,通過NM進行網絡配置時候,會自動將connection同步到ifcfg配置文件中。也可以通過nmcli c reload或者nmcli c load /etc/sysconfig/network-scripts/ifcfg-ethX的方式來讓NM讀取ifcfg配置文件到connection中。因此ifcfg和connection是一對一的關系,另外上面有提到,connection和device是多對一的關系。

  1. 手工配置ifcfg,通過NM來生效
  2. 通過NM自帶工具配ip,比如nmcli
  3. 手工配置ifcfg,通過傳統network.service來生效

建議:

 推薦使用使用nmcli配置網卡,nmcli可以支持tab補全一些信息,不太容易出錯,就是出現錯誤也是無法應用到網卡的配置中的。nmcli也會自動生成一些必要的配置信息,不用去記憶和手動輸入配置,方便可靠。

 使用nmcli修改完配置可用如下命令重載或生效

nmcli c reload           ## 重載所有ifcfg到connection(不會立即生效)
nmcli c up eth0         ## 生效配置。如果之前沒有eth0的connection,則上一步reload后就已經自動生效了

四、nmcli使用

nmcli是命令行的NetworkManager工具,自動把配置寫到/etc/sysconfig/network-scripts/目錄下面。RHEL7 與 CentOS 7之前的網絡管理是通過 ifcfg 文件配置管理接口(device),而現在是通過NetworkManager服務管理連接(connection)。一個接口(device)可以有多個連接(connection),但是同時只允許一個連接(connection)處於激活(active )狀態。但有一個問題,重啟服務器后默認激活那個連接,我沒查到相關的資料,如果是服務器建議一個網口對於一個連接。
簡單理解就是,一個連接就是(connection)就是/etc/sysconfig/network-scripts/目錄下的一個配置文件,接口(device)是物理設備,一個物理設置可以擁有多個配置文件,但只能有一個配置文件屬於使用(active)狀態;配置文件的生成與使用狀態均由NetworkManager控制。當然,依舊支持ifcfg文件配置管理網絡,但不推薦。

nmcli語法:

nmcli [ OPTIONS ] OBJECT { COMMAND | help }

OPTIONS 包含的選項

選項 說明
-t | --terse 簡潔輸出模式,該模式適合計算機(腳本)處理
-p | --pretty 詳細輸出模式,該模式適合用戶閱讀
-m | --mode {tabular | multiline} 在表格和多行輸出之間切換,默認是表格
-f | --fields {field1,field2... | all | common} 這個選項用於指定應該打印哪些字段(列名)。有效的字段名對於特定的命令是不同的
All用於打印命令中所有有效的字段值。Common用於打印命令中常用字段的值
-e | --escape {yes | no} 是否在簡潔表格模式下轉義:和\字符。轉義字符是\
-v | --version Show nmcli version
-a | --ask 要求輸入缺少參數
-w | --wait seconds 設置超時等待時間
-h | --help 打印幫助信息

 OBJECT和COMMAND可以用全稱也可以用簡稱,最少可以只用一個字母,建議用頭三個字母。OBJECT里面我們平時用的最多的就是connection和device,還有其他的選項在里暫時不介紹,這里需要簡單區分一下connection和device。

1、顯示連接信息

nmcli connection show

 連接屬於邏輯概念,可理解為網卡的配置文件,相當於ifcfg-ethX。可以簡寫為nmcli c。一個網卡可以對應多個配置文件,也就是一個device可以對應於多個connection,但同一時間只能啟用其中一個connection。這樣的好處是針對一個網絡接口,我們可以設置多個網絡連接,比如靜態IP和動態IP,再根據不同的場景激活不同的連接以實現不同的網絡配置,而不像以前還要修改網卡的配置文件。

nmcli connection說明

[root@192 ~]# nmcli connection show
NAME    UUID                                  TYPE      DEVICE
ens160  971cbab5-08ed-4ef5-b60e-9e04bda7bbfd  ethernet  ens160
virbr0  a942ad37-19a1-476d-990c-6ae678ad546b  bridge    virbr0
ens224  ce02cb40-350a-4393-9c7d-2aca68c5cdc4  ethernet  --

     
 每一行是一個連接,前兩個連接是激活狀態
 第一列是connection名字(連接名稱)簡稱con-name(注意con-name不是網卡名,很多時候con-name和網卡名並不相同如:System ens192)
 第二列是connection的UUID
 第三列是connection的網絡類型
 最后一列才是device name,也就是網卡名稱,可通過nmcil d查看device

對connection做操作時需要指定標識,標識可以是con-name、UUID、如果存在ifcfg文件則也可以用ifcfg的完整路徑,即/etc/sysconfig/network-scripts/ifcfg-ethX,如下示例:

nmcli c show ensX
nmcli c show 971cbab5-08ed-4ef5-b60e-9e04bda7bbfd
nmcli c show /etc/sysconfig/network-scripts/ifcfg-ensX

2、nmcli device

 設備,是網絡設備的接口,可理解為實際存在的網卡(包括物理網卡和虛擬網卡)。可以簡寫為nmcli d

 在NM里,有2個維度:連接(connection)和設備(device),這是多對一的關系。想給某個網卡配ip,首先NM要能納管這個網卡。設備里存在的網卡(即 nmcli d可以看到的),就是NM納管的。接着,可以為一個設備配置多個連接(即 nmcli c可以看到的),每個連接可以理解為一個ifcfg配置文件,那么如前面說的,一個device可以擁有多個連接,也就是可以擁有多個配置文件。同一時刻,一個設備只能有一個連接活躍。可以通過 nmcli c up 切換連接,在 up 一個device 的連接時另外一個活躍的 連接會自動 down 。

3、connection有2種狀態:

▷ 活躍(帶顏色字體):表示當前該connection生效
▷ 非活躍(正常字體):表示當前該connection不生效

4、device有4種常見狀態:

connected:已被NM納管,並且當前有活躍的connection
disconnected:已被NM納管,但是當前沒有活躍的connection
unmanaged:未被NM納管
unavailable:不可用,NM無法納管,通常出現於網卡link為down的時候(比如ip link set ethX down)

5、device d s 輸出說明

下面的三個命令效果是一樣的

[root@192 ~]# nmcli d s
DEVICE      TYPE      STATE         CONNECTION 
ens160      ethernet  已連接        ens160     
virbr0      bridge    連接(外部)  virbr0     
ens224      ethernet  已斷開        --         
lo          loopback  未托管        --         
virbr0-nic  tun       未托管        --         
[root@192 ~]# nmcli d status
DEVICE      TYPE      STATE         CONNECTION 
ens160      ethernet  已連接        ens160     
virbr0      bridge    連接(外部)  virbr0     
ens224      ethernet  已斷開        --         
lo          loopback  未托管        --         
virbr0-nic  tun       未托管        --         
[root@192 ~]# nmcli device status
DEVICE      TYPE      STATE         CONNECTION 
ens160      ethernet  已連接        ens160     
virbr0      bridge    連接(外部)  virbr0     
ens224      ethernet  已斷開        --         
lo          loopback  未托管        --         
virbr0-nic  tun       未托管        --         

 每一行表示一個網絡設備的接口
 第一列表示設備接口的名稱
 第二列表示設備接口的類型
 第三列表示設備接口狀態
 最后一列表示connection的名字,“--”表示設備未使用

6、激活設備的連接

nmcli d connect device-name

 由NM對指定網卡進行管理,同時刷新該網卡對應的活躍connection(如果之前有修改過connection配置);如果有connection但是都處於非活躍狀態,則自動選擇一個connection並將其活躍;如果沒有connection,則自動生成一個並將其活躍。

7、disconnect 設備的連接

nmcli d disconnect device-name

 讓NM暫時不管理指定網卡,此操作不會變更實際網卡的link狀態,只會使對應的connection變成disconnected(非活躍)。若重啟系統則又會自動connect。另外,如果手工將該網卡的connection全部刪掉,該網卡狀態也會自動變為disconnected。

8、刷新connection

nmcli d reapply device-name

 專門用於刷新connection,前提是網卡的device處於connected狀態,否則會報錯。

9、設置device自動連接和自動管理

nmcli d set ethX autoconnect yes|no managed yes|no

 可以設置是否自動連接和是否自動管理,但經測試只能用於當前開機狀態,如果這2個參數都設置為no,然后重啟系統,又會自動恢復成connected和managed yes的狀態。所以該命令用途不大。注意事項:如果managed設置為no,那么nmcli c reload會讀取配置文件,但是不會立即生效,接着如果執行nmcli c up ethX,就會立即生效,同時managed自動變為yes。

 重啟系統自動恢復成connected和managed yes的狀態,這種邏輯並不實用也不夠合理,牛人已將此問題提交給redhat,據回復,這么設計是因為目前沒有一個有效的手段來證明“我是我”,比如當網卡重新拔插到其他插槽時候,網卡名有很大可能性會發生變化,因此無法確定關機前設置的是對應開機后的哪個網卡,目前暫無辦法解決。

10、nmcli命令為網絡連接配置靜態路由

命令如下,UUID可以換成conn-name。

nmcli connection modify 9f45e94f-1726-dd68-8a33-8022f72b550f +ipv4.routes "10.211.40.0/24 10.211.40.89"

示例:
這是當前主機的靜態路由

[root@Rehat8.2 network-scripts]# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.29.1    0.0.0.0         UG    101    0        0 ens224
0.0.0.0         192.168.35.1    0.0.0.0         UG    101    0        0 ens224
10.211.0.0      200.200.65.1    255.255.0.0     UG    100    0        0 ens192
10.211.6.0      192.168.35.1    255.255.255.0   UG    101    0        0 ens224
10.211.40.88    0.0.0.0         255.255.255.248 U     102    0        0 ens256
10.212.0.0      200.200.65.1    255.255.0.0     UG    100    0        0 ens192
192.168.29.1    0.0.0.0         255.255.255.255 UH    101    0        0 ens224
192.168.35.0    0.0.0.0         255.255.255.0   U     101    0        0 ens224
200.200.0.0     200.200.65.1    255.255.0.0     UG    100    0        0 ens192
200.200.65.0    0.0.0.0         255.255.255.0   U     100    0        0 ens192

這是手動vim編輯添加的網卡ens256的路由配置文件

[root@Rehat8.2 ~]# cd /etc/sysconfig/network-scripts/
[root@Rehat8.2 network-scripts]# cat route-ens256 
ADDRESS1=10.211.40.0
NETMASK1=255.255.255.0
GATEWAY1=10.211.40.89
ADDRESS2=10.211.74.0
NETMASK2=255.255.255.0
GATEWAY2=10.211.40.89
ADDRESS3=10.70.0.0
NETMASK3=255.255.0.0
GATEWAY3=10.211.40.89
ADDRESS4=10.254.0.0
NETMASK4=255.255.0.0
GATEWAY4=10.211.40.89

試圖通過ifup ens256命令來使route-ens256生效沒有成功,即使nmcli c reload 重載配置后用 ifup ens256 或nmcli c up ens256也沒辦法使配置生效,具體原因還不清楚。但在network管理下的網絡開始可以通過up/down網卡來使網卡的配置和路由配置生效的。

[root@Rehat8.2 network-scripts]# ifup ens256
Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/10)
[root@Rehat8.2 network-scripts]# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.29.1    0.0.0.0         UG    101    0        0 ens224
0.0.0.0         192.168.35.1    0.0.0.0         UG    101    0        0 ens224
10.211.0.0      200.200.65.1    255.255.0.0     UG    100    0        0 ens192
10.211.6.0      192.168.35.1    255.255.255.0   UG    101    0        0 ens224
10.211.40.88    0.0.0.0         255.255.255.248 U     102    0        0 ens256
10.212.0.0      200.200.65.1    255.255.0.0     UG    100    0        0 ens192
192.168.29.1    0.0.0.0         255.255.255.255 UH    101    0        0 ens224
192.168.35.0    0.0.0.0         255.255.255.0   U     101    0        0 ens224
200.200.0.0     200.200.65.1    255.255.0.0     UG    100    0        0 ens192
200.200.65.0    0.0.0.0         255.255.255.0   U     100    0        0 ens192

使用nmcli命令為網絡連接配置靜態路由,再 ifup ens256 或 nmcli c up ens256 使配置生效,這次成功了。看來最好還是用nmcli命令去編輯網絡配置。

[root@Rehat8.2 network-scripts]# nmcli connection show
NAME           UUID                                  TYPE      DEVICE 
System ens224  e4014630-448b-5ad3-4992-f4678202147c  ethernet  ens224 
System ens192  03da7500-2101-c722-2438-d0d006c28c73  ethernet  ens192 
System ens256  9f45e94f-1726-dd68-8a33-8022f72b550f  ethernet  ens256 
[root@Rehat8.2 network-scripts]# nmcli connection modify 9f45e94f-1726-dd68-8a33-8022f72b550f +ipv4.routes "10.211.40.0/24 10.211.40.89"
[root@Rehat8.2 network-scripts]# nmcli connection modify 9f45e94f-1726-dd68-8a33-8022f72b550f +ipv4.routes "10.211.74.0/24 10.211.40.89"
[root@Rehat8.2 network-scripts]# nmcli connection modify 9f45e94f-1726-dd68-8a33-8022f72b550f +ipv4.routes "10.70.0.0/16 10.211.40.89"
[root@Rehat8.2 network-scripts]# nmcli connection modify 9f45e94f-1726-dd68-8a33-8022f72b550f +ipv4.routes "10.254.0.0/16 10.211.40.89"
[root@Rehat8.2 network-scripts]# cat route-ens256
ADDRESS0=10.211.40.0
NETMASK0=255.255.255.0
GATEWAY0=10.211.40.89
ADDRESS1=10.211.74.0
NETMASK1=255.255.255.0
GATEWAY1=10.211.40.89
ADDRESS2=10.70.0.0
NETMASK2=255.255.0.0
GATEWAY2=10.211.40.89
ADDRESS3=10.254.0.0
NETMASK3=255.255.0.0
GATEWAY3=10.211.40.89
[root@Rehat8.2 network-scripts]# ifup ens256
Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/11)
[root@Rehat8.2 network-scripts]# route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.29.1    0.0.0.0         UG    101    0        0 ens224
0.0.0.0         192.168.35.1    0.0.0.0         UG    101    0        0 ens224
10.70.0.0       10.211.40.89    255.255.0.0     UG    102    0        0 ens256
10.211.0.0      200.200.65.1    255.255.0.0     UG    100    0        0 ens192
10.211.6.0      192.168.35.1    255.255.255.0   UG    101    0        0 ens224
10.211.40.0     10.211.40.89    255.255.255.0   UG    102    0        0 ens256
10.211.40.88    0.0.0.0         255.255.255.248 U     102    0        0 ens256
10.211.74.0     10.211.40.89    255.255.255.0   UG    102    0        0 ens256
10.212.0.0      200.200.65.1    255.255.0.0     UG    100    0        0 ens192
10.254.0.0      10.211.40.89    255.255.0.0     UG    102    0        0 ens256
192.168.29.1    0.0.0.0         255.255.255.255 UH    101    0        0 ens224
192.168.35.0    0.0.0.0         255.255.255.0   U     101    0        0 ens224
200.200.0.0     200.200.65.1    255.255.0.0     UG    100    0        0 ens192
200.200.65.0    0.0.0.0         255.255.255.0   U     100    0        0 ens192

11、clone 連接

命令如下:

nmcli connection clone e4014630-448b-5ad3-4992-f4678202147c ens224:1

示例:
ifcfg-ens224:0是我手動copy的ifcfg-ens224,編輯后up這個配置一直報錯,通過這種方式新建一個連接似乎不太靠譜。不過nmcli提供了克隆連接的功能,我們試試看。

[root@Rehat8.2 network-scripts]# ls
ifcfg-ens192  ifcfg-ens224  ifcfg-ens224:0  ifcfg-ens256  route-ens192  route-ens224  route-ens256
[root@Rehat8.2 network-scripts]# nmcli c s
NAME           UUID                                  TYPE      DEVICE 
System ens224  e4014630-448b-5ad3-4992-f4678202147c  ethernet  ens224 
System ens192  03da7500-2101-c722-2438-d0d006c28c73  ethernet  ens192 
System ens256  9f45e94f-1726-dd68-8a33-8022f72b550f  ethernet  ens256 
[root@Rehat8.2 network-scripts]# nmcli connection clone e4014630-448b-5ad3-4992-f4678202147c ens224:1
System ens224 (e4014630-448b-5ad3-4992-f4678202147c) cloned as ens224:1 (a944108a-26ad-4337-8c94-ac8b8225dd09).
[root@Rehat8.2 network-scripts]# nmcli c s
NAME           UUID                                  TYPE      DEVICE 
System ens224  e4014630-448b-5ad3-4992-f4678202147c  ethernet  ens224 
System ens192  03da7500-2101-c722-2438-d0d006c28c73  ethernet  ens192 
System ens256  9f45e94f-1726-dd68-8a33-8022f72b550f  ethernet  ens256 
ens224:1       a944108a-26ad-4337-8c94-ac8b8225dd09  ethernet  --     			#這是新克隆的連接
[root@Rehat8.2 network-scripts]# ls		
ifcfg-ens192  ifcfg-ens224  ifcfg-ens224:0  ifcfg-ens224-1  ifcfg-ens256  route-ens192  route-ens224  route-ens224-1  route-ens256
[root@Rehat8.2 network-scripts]# 
[root@Rehat8.2 network-scripts]# cat #ifcfg-ens224-1克隆是自動生成的配置,可使用nmcli修改
MTU=1360
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=none
IPADDR=192.168.35.74
PREFIX=24
GATEWAY=192.168.29.1
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens224:1
UUID=a944108a-26ad-4337-8c94-ac8b8225dd09
DEVICE=ens224
ONBOOT=yes

12、修改連接ip地址

修改連接ens224:1的IP地址
命令:

nmcli connection modify ens224:1 ipv4.addresses 192.168.35.37/24
[root@Rehat8.2 network-scripts]# nmcli connection modify ens224:1 ipv4.addresses 192.168.35.37/24
[root@Rehat8.2 network-scripts]# cat ifcfg-ens224-1 
MTU=1360
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=none
IPADDR=192.168.35.37
PREFIX=24
GATEWAY=192.168.29.1
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens224:1
UUID=a944108a-26ad-4337-8c94-ac8b8225dd09
DEVICE=ens224
ONBOOT=yes

 激活連接ens224:1,則連接System ens224自動由連接狀態變為斷開狀態,因為一個device只能有一個活動的連接。這一點和network管理的網絡不一樣,network管理的網絡可以為一個網卡配置多個配置文件並同時生效。NetwokManager管理的網絡要實現一個網卡多個IP只能在一個連接中配置多個IP,而不能配置多連接。

[root@Rehat8.2 network-scripts]# nmcli connection up ens224:1
Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/15)
[root@Rehat8.2 network-scripts]# ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens192: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1360 qdisc mq state UP group default qlen 1000
    link/ether 00:50:56:9c:d9:1d brd ff:ff:ff:ff:ff:ff
    inet 200.200.65.167/24 brd 200.200.65.255 scope global noprefixroute ens192
       valid_lft forever preferred_lft forever
    inet6 fe80::250:56ff:fe9c:d91d/64 scope link 
       valid_lft forever preferred_lft forever
3: ens224: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1360 qdisc mq state UP group default qlen 1000
    link/ether 00:50:56:9c:ad:7a brd ff:ff:ff:ff:ff:ff
    inet 192.168.35.37/24 brd 192.168.35.255 scope global noprefixroute ens224
       valid_lft forever preferred_lft forever
    inet6 fe80::26fd:a5b2:df21:ec10/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
4: ens256: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 00:50:56:9c:22:c4 brd ff:ff:ff:ff:ff:ff
    inet 10.211.40.93/29 brd 10.211.40.95 scope global noprefixroute ens256
       valid_lft forever preferred_lft forever
    inet6 fe80::14bc:ff19:5aca:6cf3/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever
[root@Rehat8.2 network-scripts]# nmcli connection show
NAME           UUID                                  TYPE      DEVICE 
ens224:1       a944108a-26ad-4337-8c94-ac8b8225dd09  ethernet  ens224 
System ens192  03da7500-2101-c722-2438-d0d006c28c73  ethernet  ens192 
System ens256  9f45e94f-1726-dd68-8a33-8022f72b550f  ethernet  ens256 
System ens224  e4014630-448b-5ad3-4992-f4678202147c  ethernet  --     

13、添加ip

nmcli connection modify "System ens224" +ipv4.addresses 192.168.35.37/24 
或
nmcli connection modify "System ens224" ip4 192.168.35.37/24
[root@192 ~]# nmcli connection modify "ens224" -ipv4.addresses 192.168.10.10/24
錯誤:修改連接 "ens224" 失敗:ipv4.addresses: "method=manual" 不允許這個屬性為空
[root@192 ~]# nmcli connection modify "ens224" +ipv4.addresses 192.168.10.11/24,192.168.10.12/24
[root@192 ~]# cat /etc/sysconfig/network-scripts/ifcfg-ens224
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens224
UUID=ce02cb40-350a-4393-9c7d-2aca68c5cdc4
DEVICE=en224
ONBOOT=no
DNS1=223.5.5.5
IPADDR=192.168.10.10
PREFIX=24
BOOTPROTO=none
IPADDR1=192.168.10.11
PREFIX1=24
IPADDR2=192.168.10.12
PREFIX2=24

14、添加網關

[root@192 ~]# nmcli connection modify ens224 +ipv4.gateway 192.168.10.1
[root@192 ~]# cat /etc/sysconfig/network-scripts/ifcfg-ens224
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens224
UUID=ce02cb40-350a-4393-9c7d-2aca68c5cdc4
DEVICE=en224
ONBOOT=no
DNS1=223.5.5.5
IPADDR=192.168.10.10
PREFIX=24
BOOTPROTO=none
IPADDR1=192.168.10.11
PREFIX1=24
IPADDR2=192.168.10.12
PREFIX2=24
GATEWAY=192.168.10.1

15、刪除ip

nmcli connection modify "System ens224" -ipv4.addresses 192.168.35.37
[root@Rehat8.2 network-scripts]# nmcli connection modify "System ens224" -ip4 192.168.35.37   #用這個命令刪不掉
[root@Rehat8.2 network-scripts]# cat ifcfg-ens224
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
DEVICE=ens224
IPADDR=192.168.35.74
PREFIX=24
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
ONBOOT=yes
GATEWAY=192.168.29.1
MTU=1360
IPADDR1=192.168.35.37
PREFIX1=32
NAME="System ens224"
UUID=e4014630-448b-5ad3-4992-f4678202147c
[root@Rehat8.2 network-scripts]# nmcli connection modify "System ens224" -ipv4.addresses 192.168.35.37
[root@Rehat8.2 network-scripts]# cat ifcfg-ens224	#可以看到這行IPADDR1=192.168.35.37已經刪掉了
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=static
DEVICE=ens224
IPADDR=192.168.35.74
PREFIX=24
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
ONBOOT=yes
GATEWAY=192.168.29.1
MTU=1360
NAME="System ens224"
UUID=e4014630-448b-5ad3-4992-f4678202147c

16、創建一個連接(connection)

nmcli c add type ethernet con-name ens160:1 ifname ens160 ipv4.addresses '192.168.1.100/24,192.168.1.101/32' ipv4.routes '10.0.0.0/8 192.168.1.1,192.168.0.0/16 192.168.1.1' ipv4.gateway 192.168.1.1 ipv4.dns '8.8.8.8,4.4.4.4' ipv4.method manual

▪ type ethernet:創建連接時候必須指定類型,類型有很多,可以通過 nmcli c add type-h看到,這里指定為ethernet。
▪ con-name 后面接連接的名稱,名字可以任意定義,無需和網卡名相同,對應ifcfg文件中的NAME=
▪ ifname 后面接網卡名,必須是在 nmcli d里能看到的。
▪ ipv4.addresses '192.168.1.100/24,192.168.1.101/32':配置2個ip地址,分別為192.168.1.100/24和192.168.1.101/32
▪ ipv4.routes '10.0.0.0/8 192.168.1.10,192.168.0.0/16 192.168.1.11',配置給連接的路由,在如下示例中對應route-ens160-1中生成的內容
▪ ipv4.gateway 192.168.1.254:網關為192.168.1.254
▪ ipv4.dns '8.8.8.8,4.4.4.4':dns為8.8.8.8和4.4.4.4
▪ ipv4.method manual:配置靜態IP。ipv4.method對應ifcfg文件內容的BOOTPROTO,ipv4.method默認為auto,對應為BOOTPROTO=dhcp,這種時候如果指定ip,就可能導致網卡同時有dhcp分配的ip和靜態ip。設置為manual表示BOOTPROTO=none,即只有靜態ip。

[root@Redhat8 ~]# cd /etc/sysconfig/network-scripts/
[root@Redhat8 network-scripts]# ll
total 20
-rw-r--r--. 1 root root 281 May 21 10:42 ifcfg-ens160
-rw-r--r--. 1 root root 366 May 25 16:46 ifcfg-ens192
-rw-r--r--. 1 root root 281 May 20 17:47 ifcfg-ens192.bak
-rw-r--r--. 1 root root 190 May 21 16:44 route-ens192
-rw-r--r--. 1 root root  66 May 20 15:02 route-ens224
[root@Redhat8 network-scripts]# 
[root@Redhat8 network-scripts]# 
[root@Redhat8 network-scripts]# nmcli c add type ethernet con-name ens160:1 ifname ens160 ipv4.addresses '192.168.1.100/24,192.168.1.101/32' ipv4.routes '10.0.0.0/8 192.168.1.1,192.168.0.0/16 192.168.1.1' ipv4.gateway 192.168.1.1 ipv4.dns '8.8.8.8,4.4.4.4' ipv4.method manual
Connection 'ens160:1' (46ee2f64-9a7c-4009-ad8d-a4a4034916b6) successfully added.
[root@Redhat8 network-scripts]# ls
ifcfg-ens160  ifcfg-ens160-1  ifcfg-ens192  ifcfg-ens192.bak  route-ens160-1  route-ens192  route-ens224
[root@Redhat8 network-scripts]# cat ifcfg-ens160-1
TYPE=Ethernet
PROXY_METHOD=none
BROWSER_ONLY=no
BOOTPROTO=none
IPADDR=192.168.1.100
PREFIX=24
IPADDR1=192.168.1.101
PREFIX1=32
GATEWAY=192.168.1.1
DNS1=8.8.8.8
DNS2=4.4.4.4
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
IPV6_ADDR_GEN_MODE=stable-privacy
NAME=ens160:1
UUID=46ee2f64-9a7c-4009-ad8d-a4a4034916b6
DEVICE=ens160
ONBOOT=yes
[root@Redhat8 network-scripts]# cat route-ens160-1
ADDRESS0=10.0.0.0
NETMASK0=255.0.0.0
GATEWAY0=192.168.1.1
ADDRESS1=192.168.0.0
NETMASK1=255.255.0.0
GATEWAY1=192.168.1.1
[root@Redhat8 network-scripts]#

五、Tips

  1. nmcli命令支持tab補全,但是需要yum install bash-completion

  2. 如果希望NM不要納管網卡,只有一個辦法最徹底最靠譜,就是自己寫ifcfg,內容加上NM_CONTROLLED=no,這樣該device的狀態就會始終保持unmanaged。nmcli c up、nmcli c reload、nmcil c load都不會對其起任何作用。

  3. NM只能對link狀態為up的網卡進行操作,如果手動ip link set ethX down,那么NM就無法對該網卡做任何操作(即使nmcli d connect也沒有用)。

  4. 對於RHEL8,可以通過yum install network-scripts來安裝傳統的network.service,不過redhat說了,在下一個rhel的大版本里將徹底廢除,因此不建議使用network.service。

  5. 手工創建新的ifcfg或者在ifcfg里修改ip等配置,NM不會自動讀取,需要手工執行nmcli c reload或者nmcli c load /etc/sysconfig/network-scripts/ifcfg-ethX。這一點可能和其他系統的NM行為不太一樣,但這種做法實則更適合服務器。

  6. 不手工配置ifcfg,使用默認的dhcp情況下,網卡的增減是不會自動生成ifcfg,此時nmcli c看到的con-name將類似'System ethX'或者'Wired connection 1'。

  7. NetworkManager支持3種獲取dhcp的方式:dhclient、dhcpcd、internal,當/etc/NetworkManager/NetworkManager.conf配置文件中的[main]部分沒配置dhcp=時候,默認使用internal(rhel7/centos7默認是dhclient)。internal是NM內部實現的dhcp客戶端。

  8. 關於手動指定網關ip的方法,經過實測,/etc/sysconfig/network中的GATEWAY僅在3種情況下有效:NM_CONTROLLED=no或ipv4.method manual或從ipv4.method manual第一次轉到ipv4.method auto時候。建議:當NM_CONTROLLED=no時,將網關寫在/etc/sysconfig/network(GATEWAY);當使用NM時候,使用nmcli c命令配置網關(比如nmcli c modify ethX ipv4.gateway 192.168.1.1)。

  9. NM默認會從dhcp里獲取dns信息,並修改/etc/resolv.conf,如果不想讓NM管理/etc/resolv.conf,則只需在/etc/NetworkManager/NetworkManager.conf里的[main]里增加dns=none即可。

  10. 如果想讓NM不要自動管理新網卡(比如不要給新網卡獲取ip地址),則只需在/etc/NetworkManager/NetworkManager.conf里的[main]里增加no-auto-default=*即可,改完后通過systemctl restart NetworkManager或者重啟系統來生效。除了手工在NetworkManager.conf里加配置,也可以yum install NetworkManager-config-server,這會生成/usr/lib/NetworkManager/conf.d/00-server.conf,內容為如下截圖。建議使用前者方案,因為后者的ingore-carrier是不被推薦的參數。

  11. nmcli c m 命令修改的都是配置連接(配置文件),不會即時生效,需要手動使其生效。有三種方法:
    立即生效網卡配置

nmcli nmcli connection up conn-name
nmcli device connect device-name
nmcli device reapply device-name

六、man nmcli

其實最准確、全面、權威的還是官方的手冊,學習nmcli一定不能錯過官方的man手冊,我就摘一份大家順便看一下。

NMCLI(1)                                                General Commands Manual                                                NMCLI(1)

NAME
       nmcli - command-line tool for controlling NetworkManager

SYNOPSIS
       nmcli [OPTIONS...] {help | general | networking | radio | connection | device | agent | monitor} [COMMAND] [ARGUMENTS...]

DESCRIPTION
       nmcli is a command-line tool for controlling NetworkManager and reporting network status. It can be utilized as a replacement
       for nm-applet or other graphical clients.  nmcli is used to create, display, edit, delete, activate, and deactivate network
       connections, as well as control and display network device status. See nmcli-examples(7) for ready to run nmcli examples.

       Typical uses include:

       ·   Scripts: Utilize NetworkManager via nmcli instead of managing network connections manually.  nmcli supports a terse output
           format which is better suited for script processing. Note that NetworkManager can also execute scripts, called "dispatcher
           scripts", in response to network events. See NetworkManager(8) for details about these dispatcher scripts.

       ·   Servers, headless machines, and terminals: nmcli can be used to control NetworkManager without a GUI, including creating,
           editing, starting and stopping network connections and viewing network status.

OPTIONS
       -a | --ask
           When using this option nmcli will stop and ask for any missing required arguments, so do not use this option for
           non-interactive purposes like scripts. This option controls, for example, whether you will be prompted for a password if it
           is required for connecting to a network.

       -c | --colors {yes | no | auto}
           This option controls color output (using terminal escape sequences).  yes enables colors, no disables them, auto only
           produces colors when standard output is directed to a terminal. The default value is auto.

           The actual colors used are configured as described in terminal-colors.d(5). Please refer to the COLORS section for a list of
           color names supported by nmcli.

           If the environment variable NO_COLOR is set (to any value), then coloring is disabled with mode "auto". Explicitly enabling
           coloring overrides the environment variable.

       --complete-args
           Instead of conducting the desired action, nmcli will list possible completions for the last argument. This is useful to
           implement argument completion in shell.

           The exit status will indicate success or return a code 65 to indicate the last argument is a file name.

           NetworkManager ships with command completion support for GNU Bash.

       -e | --escape {yes | no}
           Whether to escape : and \ characters in terse tabular mode. The escape character is \.

           If omitted, default is yes.

       -f | --fields {field1,field2... | all | common}
           This option is used to specify what fields (column names) should be printed. Valid field names differ for specific commands.
           List available fields by providing an invalid value to the --fields option.  all is used to print all valid field values of
           the command.  common is used to print common field values of the command.

           If omitted, default is common.

       -g | --get-values {field1,field2... | all | common}
           This option is used to print values from specific fields. It is basically a shortcut for --mode tabular --terse --fields and
           is a convenient way to retrieve values for particular fields. The values are printed one per line without headers.

           If a section is specified instead of a field, the section name will be printed followed by colon separated values of the
           fields belonging to that section, all on the same line.

       -h | --help
           Print help information.

       -m | --mode {tabular | multiline}
           Switch between tabular and multiline output:

           tabular
               Output is a table where each line describes a single entry. Columns define particular properties of the entry.

           multiline
               Each entry comprises multiple lines, each property on its own line. The values are prefixed with the property name.

           If omitted, default is tabular for most commands. For the commands producing more structured information, that cannot be
           displayed on a single line, default is multiline. Currently, they are:

           ·   nmcli connection show ID

           ·   nmcli device show

       -p | --pretty
           Output is pretty. This causes nmcli to produce easily readable outputs for humans, i.e. values are aligned, headers are
           printed, etc.

       -s | --show-secrets
           When using this option nmcli will display passwords and secrets that might be present in an output of an operation. This
           option also influences echoing passwords typed by user as an input.

       -t | --terse
           Output is terse. This mode is designed and suitable for computer (script) processing.

       -v | --version
           Show nmcli version.

       -w | --wait seconds
           This option sets a timeout period for which nmcli will wait for NetworkManager to finish operations. It is especially useful
           for commands that may take a longer time to complete, e.g. connection activation.

           Specifying a value of 0 instructs nmcli not to wait but to exit immediately with a status of success. The default value
           depends on the executed command.

GENERAL COMMANDS
       nmcli general {status | hostname | permissions | logging} [ARGUMENTS...]

       Use this command to show NetworkManager status and permissions. You can also get and change system hostname, as well as
       NetworkManager logging level and domains.

       status
           Show overall status of NetworkManager. This is the default action, when no additional command is provided for nmcli general.

       hostname [hostname]
           Get and change system hostname. With no arguments, this prints currently configured hostname. When you pass a hostname, it
           will be handed over to NetworkManager to be set as a new system hostname.

           Note that the term "system" hostname may also be referred to as "persistent" or "static" by other programs or tools. The
           hostname is stored in /etc/hostname file in most distributions. For example, systemd-hostnamed service uses the term
           "static" hostname and it only reads the /etc/hostname file when it starts.

       permissions
           Show the permissions a caller has for various authenticated operations that NetworkManager provides, like enable and disable
           networking, changing Wi-Fi and WWAN state, modifying connections, etc.

       logging [level level] [domains domains...]
           Get and change NetworkManager logging level and domains. Without any argument current logging level and domains are shown.
           In order to change logging state, provide level and, or, domain parameters. See NetworkManager.conf(5) for available level
           and domain values.

NETWORKING CONTROL COMMANDS
       nmcli networking {on | off | connectivity} [ARGUMENTS...]

       Query NetworkManager networking status, enable and disable networking.

       on, off
           Enable or disable networking control by NetworkManager. All interfaces managed by NetworkManager are deactivated when
           networking is disabled.

       connectivity [check]
           Get network connectivity state. The optional check argument tells NetworkManager to re-check the connectivity, else the most
           recent known connectivity state is displayed without re-checking.

           Possible states are:

           none
               the host is not connected to any network.

           portal
               the host is behind a captive portal and cannot reach the full Internet.

           limited
               the host is connected to a network, but it has no access to the Internet.

           full
               the host is connected to a network and has full access to the Internet.

           unknown
               the connectivity status cannot be found out.

RADIO TRANSMISSION CONTROL COMMANDS
       nmcli radio {all | wifi | wwan} [ARGUMENTS...]

       Show radio switches status, or enable and disable the switches.

       wifi [on | off]
           Show or set status of Wi-Fi in NetworkManager. If no arguments are supplied, Wi-Fi status is printed; on enables Wi-Fi; off
           disables Wi-Fi.

       wwan [on | off]
           Show or set status of WWAN (mobile broadband) in NetworkManager. If no arguments are supplied, mobile broadband status is
           printed; on enables mobile broadband, off disables it.

       all [on | off]
           Show or set all previously mentioned radio switches at the same time.

ACTIVITY MONITOR
       nmcli monitor

       Observe NetworkManager activity. Watches for changes in connectivity state, devices or connection profiles.

       See also nmcli connection monitor and nmcli device monitor to watch for changes in certain devices or connections.

CONNECTION MANAGEMENT COMMANDS
       nmcli connection {show | up | down | modify | add | edit | clone | delete | monitor | reload | load | import | export}
                        [ARGUMENTS...]

       NetworkManager stores all network configuration as "connections", which are collections of data (Layer2 details, IP addressing,
       etc.) that describe how to create or connect to a network. A connection is "active" when a device uses that connection's
       configuration to create or connect to a network. There may be multiple connections that apply to a device, but only one of them
       can be active on that device at any given time. The additional connections can be used to allow quick switching between
       different networks and configurations.

       Consider a machine which is usually connected to a DHCP-enabled network, but sometimes connected to a testing network which uses
       static IP addressing. Instead of manually reconfiguring eth0 each time the network is changed, the settings can be saved as two
       connections which both apply to eth0, one for DHCP (called default) and one with the static addressing details (called testing).
       When connected to the DHCP-enabled network the user would run nmcli con up default , and when connected to the static network
       the user would run nmcli con up testing.

       show [--active] [--order [+-]category:...]
           List in-memory and on-disk connection profiles, some of which may also be active if a device is using that connection
           profile. Without a parameter, all profiles are listed. When --active option is specified, only the active profiles are
           shown.

           The --order option can be used to get custom ordering of connections. The connections can be ordered by active status
           (active), name (name), type (type) or D-Bus path (path). If connections are equal according to a sort order category, an
           additional category can be specified. The default sorting order is equivalent to --order active:name:path.  + or no prefix
           means sorting in ascending order (alphabetically or in numbers), - means reverse (descending) order. The category names can
           be abbreviated (e.g.  --order -a:na).

       show [--active] [id | uuid | path | apath] ID...
           Show details for specified connections. By default, both static configuration and active connection data are displayed. When
           --active option is specified, only the active profiles are taken into account. Use global --show-secrets option to display
           secrets associated with the profile.

           id, uuid, path and apath keywords can be used if ID is ambiguous. Optional ID-specifying keywords are:

           id
               the ID denotes a connection name.

           uuid
               the ID denotes a connection UUID.

           path
               the ID denotes a D-Bus static connection path in the format of /org/freedesktop/NetworkManager/Settings/num or just num.

           apath
               the ID denotes a D-Bus active connection path in the format of /org/freedesktop/NetworkManager/ActiveConnection/num or
               just num.

           It is possible to filter the output using the global --fields option. Use the following values:

           profile
               only shows static profile configuration.

           active
               only shows active connection data (when the profile is active).

           You can also specify particular fields. For static configuration, use setting and property names as described in nm-
           settings-nmcli(5) manual page. For active data use GENERAL, IP4, DHCP4, IP6, DHCP6, VPN.

           When no command is given to the nmcli connection, the default action is nmcli connection show.

       up [id | uuid | path] ID [ifname ifname] [ap BSSID] [passwd-file file]
           Activate a connection. The connection is identified by its name, UUID or D-Bus path. If ID is ambiguous, a keyword id, uuid
           or path can be used. When requiring a particular device to activate the connection on, the ifname option with interface name
           should be given. If the ID is not given an ifname is required, and NetworkManager will activate the best available
           connection for the given ifname. In case of a VPN connection, the ifname option specifies the device of the base connection.
           The ap option specify what particular AP should be used in case of a Wi-Fi connection.

           If --wait option is not specified, the default timeout will be 90 seconds.

           See connection show above for the description of the ID-specifying keywords.

           Available options are:

           ifname
               interface that will be used for activation.

           ap
               BSSID of the AP which the command should connect to (for Wi-Fi connections).

           passwd-file
               some networks may require credentials during activation. You can give these credentials using this option. Each line of
               the file should contain one password in the form:

                   setting_name.property_name:the password

               For example, for WPA Wi-Fi with PSK, the line would be

                   802-11-wireless-security.psk:secret12345

               For 802.1X password, the line would be

                   802-1x.password:my 1X password

               nmcli also accepts wifi-sec and wifi strings instead of 802-11-wireless-security. When NetworkManager requires a
               password and it is not given, nmcli will ask for it when run with --ask. If --ask was not passed, NetworkManager can ask
               another secret agent that may be running (typically a GUI secret agent, such as nm-applet or gnome-shell).

       down [id | uuid | path | apath] ID...
           Deactivate a connection from a device without preventing the device from further auto-activation. Multiple connections can
           be passed to the command.

           Be aware that this command deactivates the specified active connection, but the device on which the connection was active,
           is still ready to connect and will perform auto-activation by looking for a suitable connection that has the 'autoconnect'
           flag set. Note that the deactivating connection profile is internally blocked from autoconnecting again. Hence it will not
           autoconnect until reboot or until the user performs an action that unblocks autoconnect, like modifying the profile or
           explicitly activating it.

           In most cases you may want to use device disconnect command instead.

           The connection is identified by its name, UUID or D-Bus path. If ID is ambiguous, a keyword id, uuid, path or apath can be
           used.

           See connection show above for the description of the ID-specifying keywords.

           If --wait option is not specified, the default timeout will be 10 seconds.

       modify [--temporary] [id | uuid | path] ID {option value | [+|-]setting.property value}...
           Add, modify or remove properties in the connection profile.

           To set the property just specify the property name followed by the value. An empty value ("") resets the property value to
           the default.

           See nm-settings-nmcli(5) for complete reference of setting and property names, their descriptions and default values. The
           setting and property can be abbreviated provided they are unique.

           If you want to append an item or a flag to the existing value, use + prefix for the property name or alias. If you want to
           remove items from a container-type or flag property, use - prefix. For certain properties you can also remove elements by
           specifying the zero-based index(es). The + and - modifiers only have a real effect for properties that support them. These
           are for example multi-value (container) properties or flags like ipv4.dns, ip4, ipv4.addresses, bond.options,
           802-1x.phase1-auth-flags etc.

           The connection is identified by its name, UUID or D-Bus path. If ID is ambiguous, a keyword id, uuid or path can be used.

       modify [--temporary] [id | uuid | path] ID remove setting
           Removes a setting from the connection profile.

       add [save {yes | no}] {option value | [+|-]setting.property value}...
           Create a new connection using specified properties.

           You need to describe the newly created connections with the property and value pairs. See nm-settings-nmcli(5) for the
           complete reference. The syntax is the same as of the nmcli connection modify command.

           To construct a meaningful connection you at the very least need to set the connection.type property (or use the type alias)
           to one of known NetworkManager connection types:

           ·   ethernet

           ·   wifi

           ·   wimax

           ·   pppoe

           ·   gsm

           ·   cdma

           ·   infiniband

           ·   bluetooth

           ·   vlan

           ·   bond

           ·   bond-slave

           ·   team

           ·   team-slave

           ·   bridge

           ·   bridge-slave

           ·   vpn

           ·   olpc-mesh

           ·   adsl

           ·   tun

           ·   ip-tunnel

           ·   macvlan

           ·   vxlan

           ·   dummy

           The most typical uses are described in the EXAMPLES section.

           Aside from the properties and values two special options are accepted:

           save
               Controls whether the connection should be persistent, i.e. NetworkManager should store it on disk (default: yes).

           --
               If a single -- argument is encountered it is ignored. This is for compatibility with older versions on nmcli.

       edit {[id | uuid | path] ID | [type type] [con-name name] }
           Edit an existing connection or add a new one, using an interactive editor.

           The existing connection is identified by its name, UUID or D-Bus path. If ID is ambiguous, a keyword id, uuid, or path can
           be used. See connection show above for the description of the ID-specifying keywords. Not providing an ID means that a new
           connection will be added.

           The interactive editor will guide you through the connection editing and allow you to change connection parameters according
           to your needs by means of a simple menu-driven interface. The editor indicates what settings and properties can be modified
           and provides in-line help.

           Available options:

           type
               type of the new connection; valid types are the same as for connection add command.

           con-name
               name for the new connection. It can be changed later in the editor.

           See also nm-settings-nmcli(5) for all NetworkManager settings and property names, and their descriptions; and nmcli-
           examples(7) for sample editor sessions.

       clone [--temporary] [id | uuid | path] ID new_name
           Clone a connection. The connection to be cloned is identified by its name, UUID or D-Bus path. If ID is ambiguous, a keyword
           id, uuid or path can be used. See connection show above for the description of the ID-specifying keywords.  new_name is the
           name of the new cloned connection. The new connection will be the exact copy except the connection.id (new_name) and
           connection.uuid (generated) properties.

           The new connection profile will be saved as persistent unless --temporary option is specified, in which case the new profile
           won't exist after NetworkManager restart.

       delete [id | uuid | path] ID...
           Delete a configured connection. The connection to be deleted is identified by its name, UUID or D-Bus path. If ID is
           ambiguous, a keyword id, uuid or path can be used. See connection show above for the description of the ID-specifying
           keywords.

           If --wait option is not specified, the default timeout will be 10 seconds.

       monitor [id | uuid | path] ID...
           Monitor connection profile activity. This command prints a line whenever the specified connection changes. The connection to
           be monitored is identified by its name, UUID or D-Bus path. If ID is ambiguous, a keyword id, uuid or path can be used. See
           connection show above for the description of the ID-specifying keywords.

           Monitors all connection profiles in case none is specified. The command terminates when all monitored connections disappear.
           If you want to monitor connection creation consider using the global monitor with nmcli monitor command.

       reload
           Reload all connection files from disk. NetworkManager does not monitor changes to connection. So you need to use this
           command in order to tell NetworkManager to re-read the connection profiles from disk when a change was made to them.

       load filename...
           Load/reload one or more connection files from disk. Use this after manually editing a connection file to ensure that
           NetworkManager is aware of its latest state.

       import [--temporary] type type file file
           Import an external/foreign configuration as a NetworkManager connection profile. The type of the input file is specified by
           type option.

           Only VPN configurations are supported at the moment. The configuration is imported by NetworkManager VPN plugins.  type
           values are the same as for vpn-type option in nmcli connection add. VPN configurations are imported by VPN plugins.
           Therefore the proper VPN plugin has to be installed so that nmcli could import the data.

           The imported connection profile will be saved as persistent unless --temporary option is specified, in which case the new
           profile won't exist after NetworkManager restart.

       export [id | uuid | path] ID [file]
           Export a connection.

           Only VPN connections are supported at the moment. A proper VPN plugin has to be installed so that nmcli could export a
           connection. If no file is provided, the VPN configuration data will be printed to standard output.

DEVICE MANAGEMENT COMMANDS
       nmcli device {status | show | set | connect | reapply | modify | disconnect | delete | monitor | wifi | lldp} [ARGUMENTS...]

       Show and manage network interfaces.

       status
           Print status of devices.

           This is the default action if no command is specified to nmcli device.

       show [ifname]
           Show detailed information about devices. Without an argument, all devices are examined. To get information for a specific
           device, the interface name has to be provided.

       set [ifname] ifname [autoconnect {yes | no}] [managed {yes | no}]
           Set device properties.

       connect ifname
           Connect the device. NetworkManager will try to find a suitable connection that will be activated. It will also consider
           connections that are not set to auto connect.

           If no compatible connection exists, a new profile with default settings will be created and activated. This differentiates
           nmcli connection up ifname "$DEVICE" from nmcli device connect "$DEVICE"

           If --wait option is not specified, the default timeout will be 90 seconds.

       reapply ifname
           Attempt to update device with changes to the currently active connection made since it was last applied.

       modify ifname {option value | [+|-]setting.property value}...
           Modify the settings currently active on the device.

           This command lets you do temporary changes to a configuration active on a particular device. The changes are not preserved
           in the connection profile.

           See nm-settings-nmcli(5) for the list of available properties. Please note that some properties can't be changed on an
           already connected device.

       disconnect ifname...
           Disconnect a device and prevent the device from automatically activating further connections without user/manual
           intervention. Note that disconnecting software devices may mean that the devices will disappear.

           If --wait option is not specified, the default timeout will be 10 seconds.

       delete ifname...
           Delete a device. The command removes the interface from the system. Note that this only works for software devices like
           bonds, bridges, teams, etc. Hardware devices (like Ethernet) cannot be deleted by the command.

           If --wait option is not specified, the default timeout will be 10 seconds.

       monitor [ifname...]
           Monitor device activity. This command prints a line whenever the specified devices change state.

           Monitors all devices in case no interface is specified. The monitor terminates when all specified devices disappear. If you
           want to monitor device addition consider using the global monitor with nmcli monitor command.

       wifi [list [--rescan | auto | no | yes] [ifname ifname] [bssid BSSID]]
           List available Wi-Fi access points. The ifname and bssid options can be used to list APs for a particular interface or with
           a specific BSSID, respectively.

           By default, nmcli ensures that the access point list is no older than 30 seconds and triggers a network scan if necessary.
           The --rescan can be used to either force or disable the scan regardless of how fresh the access point list is.

       wifi connect (B)SSID [password password] [wep-key-type {key | phrase}] [ifname ifname] [bssid BSSID] [name name]
       [private {yes | no}] [hidden {yes | no}]
           Connect to a Wi-Fi network specified by SSID or BSSID. The command finds a matching connection or creates one and then
           activates it on a device. This is a command-line counterpart of clicking an SSID in a GUI client. If a connection for the
           network already exists, it is possible to bring up (activate) the existing profile as follows: nmcli con up id name. Note
           that only open, WEP and WPA-PSK networks are supported if no previous connection exists. It is also assumed that IP
           configuration is obtained via DHCP.

           If --wait option is not specified, the default timeout will be 90 seconds.

           Available options are:

           password
               password for secured networks (WEP or WPA).

           wep-key-type
               type of WEP secret, either key for ASCII/HEX key or phrase for passphrase.

           ifname
               interface that will be used for activation.

           bssid
               if specified, the created connection will be restricted just for the BSSID.

           name
               if specified, the connection will use the name (else NM creates a name itself).

           private
               if set to yes, the connection will only be visible to the user who created it. Otherwise the connection is system-wide,
               which is the default.

           hidden
               set to yes when connecting for the first time to an AP not broadcasting its SSID. Otherwise the SSID would not be found
               and the connection attempt would fail.

       wifi hotspot [ifname ifname] [con-name name] [ssid SSID] [band {a | bg}] [channel channel] [password password]
           Create a Wi-Fi hotspot. The command creates a hotspot connection profile according to Wi-Fi device capabilities and
           activates it on the device. The hotspot is secured with WPA if device/driver supports that, otherwise WEP is used. Use
           connection down or device disconnect to stop the hotspot.

           Parameters of the hotspot can be influenced by the optional parameters:

           ifname
               what Wi-Fi device is used.

           con-name
               name of the created hotspot connection profile.

           ssid
               SSID of the hotspot.

           band
               Wi-Fi band to use.

           channel
               Wi-Fi channel to use.

           password
               password to use for the created hotspot. If not provided, nmcli will generate a password. The password is either WPA
               pre-shared key or WEP key.

               Note that --show-secrets global option can be used to print the hotspot password. It is useful especially when the
               password was generated.

       wifi rescan [ifname ifname] [ssid SSID...]
           Request that NetworkManager immediately re-scan for available access points. NetworkManager scans Wi-Fi networks
           periodically, but in some cases it can be useful to start scanning manually (e.g. after resuming the computer). By using
           ssid, it is possible to scan for a specific SSID, which is useful for APs with hidden SSIDs. You can provide multiple ssid
           parameters in order to scan more SSIDs.

           This command does not show the APs, use nmcli device wifi list for that.

       wifi show-password [ifname ifname]
           Show the details of the active Wi-Fi networks, including the secrets.

       lldp [list [ifname ifname]]
           Display information about neighboring devices learned through the Link Layer Discovery Protocol (LLDP). The ifname option
           can be used to list neighbors only for a given interface. The protocol must be enabled in the connection settings.

SECRET AGENT
       nmcli agent {secret | polkit | all}

       Run nmcli as a NetworkManager secret agent, or polkit agent.

       secret
           Register nmcli as a NetworkManager secret agent and listen for secret requests. You do usually not need this command,
           because nmcli can handle secrets when connecting to networks. However, you may find the command useful when you use another
           tool for activating connections and you do not have a secret agent available (like nm-applet).

       polkit
           Register nmcli as a polkit agent for the user session and listen for authorization requests. You do not usually need this
           command, because nmcli can handle polkit actions related to NetworkManager operations (when run with --ask). However, you
           may find the command useful when you want to run a simple text based polkit agent and you do not have an agent of a desktop
           environment. Note that running this command makes nmcli handle all polkit requests, not only NetworkManager related ones,
           because only one polkit agent can run for the session.

       all
           Runs nmcli as both NetworkManager secret and a polkit agent.

COLORS
       Implicit coloring can be disabled by an empty file /etc/terminal-colors.d/nmcli.disable.

       See terminal-colors.d(5) for more details about colorization configuration. The logical color names supported by nmcli are:

       connection-activated
           A connection that is active.

       connection-activating
           Connection that is being activated.

       connection-disconnecting
           Connection that is being disconnected.

       connection-invisible
           Connection whose details is the user not permitted to see.

       connectivity-full
           Conectivity state when Internet is reachable.

       connectivity-limited
           Conectivity state when only a local network reachable.

       connectivity-none
           Conectivity state when the network is disconnected.

       connectivity-portal
           Conectivity state when a captive portal hijacked the connection.

       connectivity-unknown
           Conectivity state when a connectivity check didn't run.

       device-activated
           Device that is connected.

       device-activating
           Device that is being configured.

       device-disconnected
           Device that is not connected.

       device-firmware-missing
           Warning of a missing device firmware.

       device-plugin-missing
           Warning of a missing device plugin.

       device-unavailable
           Device that is not available for activation.

       device-disabled
           Device is disabled by software or hardware kill switch.

       manager-running
           Notice that the NetworkManager daemon is available.

       manager-starting
           Notice that the NetworkManager daemon is being initially connected.

       manager-stopped
           Notice that the NetworkManager daemon is not available.

       permission-auth
           An action that requires user authentication to get permission.

       permission-no
           An action that is not permitted.

       permission-yes
           An action that is permitted.

       prompt
           Prompt in interactive mode.

       state-asleep
           Indication that NetworkManager in suspended state.

       state-connected-global
           Indication that NetworkManager in connected to Internet.

       state-connected-local
           Indication that NetworkManager in local network.

       state-connected-site
           Indication that NetworkManager in connected to networks other than Internet.

       state-connecting
           Indication that NetworkManager is establishing a network connection.

       state-disconnected
           Indication that NetworkManager is disconnected from a network.

       state-disconnecting
           Indication that NetworkManager is being disconnected from a network.

       wifi-signal-excellent
           Wi-Fi network with an excellent signal level.

       wifi-signal-fair
           Wi-Fi network with a fair signal level.

       wifi-signal-good
           Wi-Fi network with a good signal level.

       wifi-signal-poor
           Wi-Fi network with a poor signal level.

       wifi-signal-unknown
           Wi-Fi network that hasn't been actually seen (a hidden AP).

       disabled
           A property that is turned off.

       enabled
           A property that is turned on.

ENVIRONMENT VARIABLES
       nmcli's behavior is affected by the following environment variables.

       LC_ALL
           If set to a non-empty string value, it overrides the values of all the other internationalization variables.

       LC_MESSAGES
           Determines the locale to be used for internationalized messages.

       LANG
           Provides a default value for the internationalization variables that are unset or null.

INTERNATIONALIZATION NOTES
       Be aware that nmcli is localized and that is why the output depends on your environment. This is important to realize especially
       when you parse the output.

       Call nmcli as LC_ALL=C nmcli to be sure the locale is set to C while executing in a script.

       LC_ALL, LC_MESSAGES, LANG variables specify the LC_MESSAGES locale category (in that order), which determines the language that
       nmcli uses for messages. The C locale is used if none of these variables are set, and this locale uses English messages.

EXIT STATUS
       nmcli exits with status 0 if it succeeds, a value greater than 0 is returned if an error occurs.

       0
           Success – indicates the operation succeeded.

       1
           Unknown or unspecified error.

       2
           Invalid user input, wrong nmcli invocation.

       3
           Timeout expired (see --wait option).

       4
           Connection activation failed.

       5
           Connection deactivation failed.

       6
           Disconnecting device failed.

       7
           Connection deletion failed.

       8
           NetworkManager is not running.

       10
           Connection, device, or access point does not exist.

       65
           When used with --complete-args option, a file name is expected to follow.

EXAMPLES
       This section presents various examples of nmcli usage. If you want even more, please refer to nmcli-examples(7) manual page.

       nmcli -t -f RUNNING general
           tells you whether NetworkManager is running or not.

       nmcli -t -f STATE general
           shows the overall status of NetworkManager.

       nmcli radio wifi off
           switches Wi-Fi off.

       nmcli connection show
           lists all connections NetworkManager has.

       nmcli -p -m multiline -f all con show
           shows all configured connections in multi-line mode.

       nmcli connection show --active
           lists all currently active connections.

       nmcli -f name,autoconnect c s
           shows all connection profile names and their auto-connect property.

       nmcli -p connection show "My default em1"
           shows details for "My default em1" connection profile.

       nmcli --show-secrets connection show "My Home Wi-Fi"
           shows details for "My Home Wi-Fi" connection profile with all passwords. Without --show-secrets option, secrets would not be
           displayed.

       nmcli -f active connection show "My default em1"
           shows details for "My default em1" active connection, like IP, DHCP information, etc.

       nmcli -f profile con s "My wired connection"
           shows static configuration details of the connection profile with "My wired connection" name.

       nmcli -p con up "My wired connection" ifname eth0
           activates the connection profile with name "My wired connection" on interface eth0. The -p option makes nmcli show progress
           of the activation.

       nmcli con up 6b028a27-6dc9-4411-9886-e9ad1dd43761 ap 00:3A:98:7C:42:D3
           connects the Wi-Fi connection with UUID 6b028a27-6dc9-4411-9886-e9ad1dd43761 to the AP with BSSID 00:3A:98:7C:42:D3.

       nmcli device status
           shows the status for all devices.

       nmcli dev disconnect em2
           disconnects a connection on interface em2 and marks the device as unavailable for auto-connecting. As a result, no
           connection will automatically be activated on the device until the device's 'autoconnect' is set to TRUE or the user
           manually activates a connection.

       nmcli -f GENERAL,WIFI-PROPERTIES dev show wlan0
           shows details for wlan0 interface; only GENERAL and WIFI-PROPERTIES sections will be shown.

       nmcli -f CONNECTIONS device show wlp3s0
           shows all available connection profiles for your Wi-Fi interface wlp3s0.

       nmcli dev wifi
           lists available Wi-Fi access points known to NetworkManager.

       nmcli dev wifi con "Cafe Hotspot 1" password caffeine name "My cafe"
           creates a new connection named "My cafe" and then connects it to "Cafe Hotspot 1" SSID using password "caffeine". This is
           mainly useful when connecting to "Cafe Hotspot 1" for the first time. Next time, it is better to use nmcli con up id "My
           cafe" so that the existing connection profile can be used and no additional is created.

       nmcli -s dev wifi hotspot con-name QuickHotspot
           creates a hotspot profile and connects it. Prints the hotspot password the user should use to connect to the hotspot from
           other devices.

       nmcli dev modify em1 ipv4.method shared
           starts IPv4 connection sharing using em1 device. The sharing will be active until the device is disconnected.

       nmcli dev modify em1 ipv6.address 2001:db8::a:bad:c0de
           temporarily adds an IP address to a device. The address will be removed when the same connection is activated again.

       nmcli connection add type ethernet autoconnect no ifname eth0
           non-interactively adds an Ethernet connection tied to eth0 interface with automatic IP configuration (DHCP), and disables
           the connection's autoconnect flag.

       nmcli c a ifname Maxipes-fik type vlan dev eth0 id 55
           non-interactively adds a VLAN connection with ID 55. The connection will use eth0 and the VLAN interface will be named
           Maxipes-fik.

       nmcli c a ifname eth0 type ethernet ipv4.method disabled ipv6.method link-local
           non-interactively adds a connection that will use eth0 Ethernet interface and only have an IPv6 link-local address
           configured.

       nmcli connection edit ethernet-em1-2
           edits existing "ethernet-em1-2" connection in the interactive editor.

       nmcli connection edit type ethernet con-name "yet another Ethernet connection"
           adds a new Ethernet connection in the interactive editor.

       nmcli con mod ethernet-2 connection.autoconnect no
           modifies 'autoconnect' property in the 'connection' setting of 'ethernet-2' connection.

       nmcli con mod "Home Wi-Fi" wifi.mtu 1350
           modifies 'mtu' property in the 'wifi' setting of 'Home Wi-Fi' connection.

       nmcli con mod em1-1 ipv4.method manual ipv4.addr "192.168.1.23/24 192.168.1.1, 10.10.1.5/8, 10.0.0.11"
           sets manual addressing and the addresses in em1-1 profile.

       nmcli con modify ABC +ipv4.dns 8.8.8.8
           appends a Google public DNS server to DNS servers in ABC profile.

       nmcli con modify ABC -ipv4.addresses "192.168.100.25/24 192.168.1.1"
           removes the specified IP address from (static) profile ABC.

       nmcli con import type openvpn file ~/Downloads/frootvpn.ovpn
           imports an OpenVPN configuration to NetworkManager.

       nmcli con export corp-vpnc /home/joe/corpvpn.conf
           exports NetworkManager VPN profile corp-vpnc as standard Cisco (vpnc) configuration.

NOTES
       nmcli accepts abbreviations, as long as they are a unique prefix in the set of possible options. As new options get added, these
       abbreviations are not guaranteed to stay unique. For scripting and long term compatibility it is therefore strongly advised to
       spell out the full option names.

BUGS
       There are probably some bugs. If you find a bug, please report it to your distribution or upstream at
       https://gitlab.freedesktop.org/NetworkManager/NetworkManager.

SEE ALSO
       nmcli-examples(7), nm-settings-nmcli(5), nm-online(1), NetworkManager(8), NetworkManager.conf(5), nm-applet(1), nm-connection-
       editor(1), terminal-colors.d(5).

NetworkManager 1.26.0  

參考:
https://www.cnblogs.com/pipci/p/12562227.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM