僅列出所有可用網路介面的設備名稱

僅列出所有可用網路介面的設備名稱

我想獲取 Linux 伺服器上所有可用網路設備名稱的清單。我想

ifconfig

可以完成這項工作,但是 ifconfig 會產生相當多的輸出:

eth0      Link encap:Ethernet  Hardware Adresse 08:00:27:fc:5c:98  
          inet Adresse:192.168.2.222  Bcast:192.168.2.255  Maske:255.255.255.0
          inet6-Adresse: fe80::a00:27ff:fefc:5c98/64 Gültigkeitsbereich:Verbindung
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metrik:1
          RX packets:329 errors:0 dropped:0 overruns:0 frame:0
          TX packets:177 errors:0 dropped:0 overruns:0 carrier:0
          Kollisionen:0 Sendewarteschlangenlänge:1000 
          RX bytes:41496 (40.5 KiB)  TX bytes:32503 (31.7 KiB)

eth1      Link encap:Ethernet  Hardware Adresse 08:00:27:e9:35:7d  
          [...]

eth2      Link encap:Ethernet  Hardware Adresse 08:00:27:ff:db:fe  
          [...]

lo        Link encap:Lokale Schleife  
          [...]

我想要實現的是一個類似的列表

eth0
eth1
eth2
lo

或者甚至更好

eth0
eth1
eth2

我認為這可以透過「cat」、「sed」和「grep」的組合來完成,但我根本不知道如何刪除不必要的資訊。

答案1

試試一下:

ifconfig -a | sed 's/[ \t].*//;/^$/d'

這將省略lo

ifconfig -a | sed 's/[ \t].*//;/^\(lo\|\)$/d'

答案2

另一個選擇是:

ip -o link show | awk -F': ' '{print $2}'

或者可能:

ls /sys/class/net

答案3

只需使用 /sys/class/net 並刪除路徑:

$ basename -a /sys/class/net/*
eth0
eth1
lo
ppp0
tun0

更現代的方法是使用 iproute json 輸出和解析器,例如:

$ ip -j link |jq -r '.[].ifname'
lo
wlp0s20f3
enp0s31f6
virbr0
virbr0-nic

這允許您過濾掉環回介面:

$ ip -j link |jq -r '.[].ifname | select(. != "lo")'
wlp0s20f3
enp0s31f6
virbr0
virbr0-nic

答案4

ls /sys/class/net/
eth0  eth1  eth2  lo

或如果您只需要 eth*

ls /sys/class/net/eth*
eth0
eth1
eth2

相關內容