欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

mac command delete remembed network 终端命令 删除已记住的网络连接 有大用 有大大用 有大大大用


empty_remembered_networks

#!/bin/bash

for I in {0..4}; do

  echo en${I};

  sudo networksetup -listpreferredwirelessnetworks en${I} > /dev/null

  if [ $? = 0 ]; then

    wifi_device=`sudo networksetup -listpreferredwirelessnetworks en${I}`

    echo $wifi_device | xargs -I {}  sudo networksetup -removepreferredwirelessnetwork en${I} {}

  fi

done








   


   

How do I delete a saved wifi network, when unable to use the Network panel/GUI in System pref?    


   


   


   

Asked 
Modified 5 years, 3 months ago    
Viewed 20k times
4
               

I need to delete a saved public wifi network, which my computer keeps trying to connect to when I'm at home, but I can't open my Network preferences and do it trough the GUI, due to an error in my MacOS installation (see linked question below for details).

I'm guessing there might be a way to do it, through Terminal or digging into a .plist, but haven't been able to find any non-GUI guides to this through searching, so how can this be done?

Why does my Network preference pane freeze every time I open it?                    

System info: MacBook Pro (Retina, 15-inch, Mid 2015) MacOS Sierra 10.12.6 (16G29)


                                   
Improve this question                                    
edited Feb 20, 2018 at 9:48                                
asked Feb 19, 2018 at 22:28                                
ssssaaaa's user avatar                                    
                               
ssssaaaa                                    
3541 gold badge3 silver badges16 bronze badges                                    
Add a comment                
               

1 Answer  正确答案                     

               
8
                   

You can check the list of preferred networks with the command:

sudo networksetup -listpreferredwirelessnetworks en1                        

You can then copy the name of the wifi you want to remove from the list and use the command (replacing wifi_name ( 就是 SSID ) with the name of the wifi):

sudo networksetup -removepreferredwirelessnetwork en1 wifi_name                        

Note: en1 is usually the device name of the single wifi card in a mac that also has a ethernet port. To be sure of the device name use the command:
sudo networksetup -listallhardwareports
to list the various network devices and their denomination.

                                       
Improve this answer                                        
edited Feb 20, 2018 at 21:03                                    
answered Feb 20, 2018 at 0:34                                    
Gio Valerio's user avatar                                        
                                   
Gio Valerio                                        
8014 silver badges9 bronze badges                                        
  • Is there a place I can find other possible device names for my wifi card? When running `-listpreferredwirelessnetworks en1´ I get the error "en1 is not a Wi-Fi interface. ** Error: Error obtaining wireless information." 
    – ssssaaaa                                        
     Feb 20, 2018 at 9:38                                    
  • Just realised I hadn't added my device specs to this post, so have done that now, hopefully that helps. 
    – ssssaaaa                                        
     Feb 20, 2018 at 9:47                                    
  • 1                                    
    sudo networksetup -listallhardwareports gives you the list of the devices 
    – Gio Valerio                                        
     Feb 20, 2018 at 15:17                                    
  • 1                                    
    updated the answer 
    – Gio Valerio                                        
     Feb 20, 2018 at 18:50                                    
  • 1                                    
    could also be en0, that's the case on a 2019 MBP at least. but yes, -listallhardwareports shows that too, after I got en1 is not a Wi-Fi interface.. 
    – Italian Philosophers 4 Monica                                        
     Oct 3, 2022 at 1:49                                     
Show 1 more comment                    

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged 


           

来自   https://apple.stackexchange.com/questions/315911/how-do-i-delete-a-saved-wifi-network-when-unable-to-use-the-network-panel-gui-i            


           


           

How to find the currently connected network service from the command line?            


           

I would like to find out which of the available network services (e.g. Ethernet or Wi-Fi) is currently active. In this screenshot from the Network Preferences, you can see that Wi-Fi is currently active (the green dot):

Network Preferences                            

How can I get that information from the command line?

The networksetup command allows me to list the available network services:

$ networksetup -listallnetworkservices
An asterisk (*) denotes that a network service is disabled.
Ethernet
FireWire
Wi-Fi
                           

It can also show some details on the service, like the device name:

$ networksetup -listnetworkserviceorder
An asterisk (*) denotes that a network service is disabled.
(1) Ethernet
(Hardware Port: Ethernet, Device: en0)

(2) FireWire
(Hardware Port: FireWire, Device: fw0)

(3) Wi-Fi
(Hardware Port: Wi-Fi, Device: en1)
                           

Unfortunately, the info on which service is active (the green dot from the screenshot) is not available in this info. Is there another command that I could use to get this information?

                                           
Improve this question                                            
edited Dec 9, 2021 at 5:38                                        
ccpizza's user avatar                                            
                                       
ccpizza                                            
2,7253 gold badges34 silver badges36 bronze badges                                            
asked Jun 16, 2015 at 20:00                                        
nwinkler's user avatar                                            
                                       
nwinkler                                            
8,70623 gold badges45 silver badges68 bronze badges                                            
Add a comment                        
                               

11 Answers

                               
7
                           

Simply issue

    ifconfig
                               

List all network interfaces and their status.

                                               
Improve this answer                                                
answered Jun 16, 2015 at 20:30                                            
fd0's user avatar                                                
                                           
fd0                                                
10.2k3 gold badges29 silver badges46 bronze badges                                                
  • True - each record contains a status field that either has active or inactive as a value. 
    – nwinkler                                                
     Jun 17, 2015 at 6:18                                            
  • 1                                            
    It will give you false result if you are sharing your internet. Suppose your are sharing ethernet internet via wifi then status for both Ethernet and wifi will be "active" 
    – Harshal Chaudhari                                                
     Jan 2, 2017 at 10:18                                            
  • 5                                            
    This doesn't show you which service is being used - both wifi and ethernet will show as 'active' if you have both enabled and an ethernet cord plugged in. 
    – tog22                                                
     May 19, 2017 at 18:00                                            
  • 1                                            
    This is quite handy for checking if a connection is not connected. For example my ethernet is generally only connected at work. So I can deduce I am at home by this not being in the list. ifconfig | grep $(networksetup -listnetworkserviceorder | grep 'Ethernet, Device' | sed -E "s/.*(en[0-9]).*/\1/"). Then I can switch locations based on the above being empty. 
    – Chris Rymer                                                
     Nov 16, 2017 at 21:28                                            
  • This simply lists all network interfaces not network services. 
    – algal                                                
     Sep 3, 2018 at 22:55                                             
Add a comment                            
                               
23
                           

Put it all together, I wrote a script to accomplish this task:

#!/bin/bash

while read -r line; do
    sname=$(echo "$line" | awk -F  "(, )|(: )|[)]" '{print $2}')
    sdev=$(echo "$line" | awk -F  "(, )|(: )|[)]" '{print $4}')
    #echo "Current service: $sname, $sdev, $currentservice"
    if [ -n "$sdev" ]; then
        ifout="$(ifconfig "$sdev" 2>/dev/null)"
        echo "$ifout" | grep 'status: active' > /dev/null 2>&1
        rc="$?"
        if [ "$rc" -eq 0 ]; then
            currentservice="$sname"
            currentdevice="$sdev"
            currentmac=$(echo "$ifout" | awk '/ether/{print $2}')

            # may have multiple active devices, so echo it here
            echo "$currentservice, $currentdevice, $currentmac"
        fi
    fi
done <<< "$(networksetup -listnetworkserviceorder | grep 'Hardware Port')"

if [ -z "$currentservice" ]; then
    >&2 echo "Could not find current service"
    exit 1
fi
                               

The script first get a service list from networksetup command, then check if each service is in active status from ifconfig.

Name the script to networkservice.sh for example, then execute it to get the current network service you are on.

$ bash networkservice.sh
USB 10/100/1000 LAN, en4, 00:e0:4a:6b:4d:0c
Wi-Fi, en0, 8c:85:90:a0:4b:ec
                           
                                               
Improve this answer                                                
edited Jun 23, 2020 at 8:24                                            
answered Jan 14, 2016 at 4:06                                            
Reorx's user avatar                                                
                                           
Reorx                                                
3412 silver badges4 bronze badges                                                
  • I had to pipe the first line to tac to iterate through the interfaces in reverse order because I often have WiFi connected as well as a USB ethernet adapter (which is the preferred device in Network). In this case I want the most preferred active devise to be printed: services=$(networksetup -listnetworkserviceorder | grep 'Hardware Port' | tac) 
    – ghr                                                
     Aug 1, 2016 at 22:07                                             
  • @ghr that doesn't make any sense, networksetup -listnetworkserviceorder already outputs "the most preferred device" first... 
    – Motsel                                                
     Mar 1, 2019 at 10:37                                            
  • Looks like I ended up modifying the above script a little so that it only prints out 1 service, rather than any connected. I had to tac so that later (non-preferred) services wouldn't overwrite $currentservice. Should have been clearer in that original comment. 
    – ghr                                                
     Mar 2, 2019 at 16:59                                            
  • 1                                            
    can confirm that this is still the best answer in these trying times when most computers are connected to VPN, either fully tunnelled or not, where other answers may return the device name for the VPN tunnel tunX. 
    – Dials Mavis                                                
     Jun 3, 2020 at 2:01                                            
  • Note this script uses hardware port names which are generally the same as service names, but can fail if you manually rename or if you have multiple services with the same hardware port name, typical for USB Ethernet. This gist has an amended version to fix this issue. 
    – Stewart Adam                                                
     Feb 11, 2022 at 20:38                                             
Add a comment                            
                               
17
                           

I won't pretend to have the answer to this question sorted, but this but this maybe helpful.

You can ask how it currently will route packets to something:

$ route get example.com | grep interface
interface: en8
                               

And then you can ask what "Network Service" is managing that interface:

$ networksetup -listnetworkserviceorder | grep en8
(Hardware Port: Broadcom NetXtreme Gigabit Ethernet Controller, Device: en8)
                               

But honestly, I doubt that a "Network Services" is one to one with a hardware port. And some interfaces, tun0 for example, do not have a "Network Service". Well at least sometimes they don't.

                                               
Improve this answer                                                
edited May 1, 2017 at 6:27                                            
nohillside's user avatar                                                
                                           
nohillside                                                
94.7k40 gold badges201 silver badges247 bronze badges                                                
answered May 1, 2017 at 3:42                                            
Ben Hyde's user avatar                                                
                                           
Ben Hyde                                                
3092 silver badges5 bronze badges                                                
Add a comment                            
                               
8
                           

The scutil --nwi command lists interfaces and scutil --dns command gives you all the network routing information you'll need to map hardware interface labels to network routes.

A little awk and grep can pretty it up if you need to script the information or pare it down. Start with gripping for "if_index" if you're curious.

There’s not much that is simple about networking since you can have multiple addresses assigned to one interface and more than one connection to the internet. The default route is often the correct answer, but with VPN and apps hard coding things like DNS over HTTP and more, default Carrie’s less weight than it did ten years ago when macOS was called OS X.

                                               
Improve this answer                                                
edited Jan 25, 2022 at 15:21                                            
answered Jun 16, 2015 at 20:10                                            
bmike's user avatar                                                
                                           
bmike                                                
229k78 gold badges407 silver badges893 bronze badges                                                
  • That looks useful - I'll play around with that! 
    – nwinkler                                                
     Jun 16, 2015 at 20:15                                            
Add a comment                            
                               
3
                           

Just in case someone else stumbles across this like I did the code below may be more of what you are looking for.

This is to expand on PeterVP's answer; also visible here.

#!/bin/sh

clear
sExternalMACALService="http://dns.kittell.net/macaltext.php?address="

# List all Network ports
NetworkPorts=$(ifconfig -uv | grep '^[a-z0-9]' | awk -F : '{print $1}')
#echo $NetworkPorts

# Function to convert IP Subnet Mask to CIDR
mask2cdr ()
{
# Assumes there's no "255." after a non-255 byte in the mask
local x=${1##*255.}
set -- 0^^^128^192^224^240^248^252^254^ $(( (${#1} - ${#x})*2 )) ${x%%.*}
x=${1%%$3*}
echo $(( $2 + (${#x}/4) ))
}

# Get remote/public IP address
remoteip=$(dig +short myip.opendns.com @resolver1.opendns.com)

# Get computer name
computername=$(scutil --get ComputerName)

# Get serial number
sSerialNumber=$(system_profiler SPHardwareDataType |grep "Serial Number (system)" |awk '{print $4}'  | cut -d/ -f1)
#echo $sSerialNumber

# Get operating system name and version - Start
OSvers1=$( sw_vers -productVersion | cut -d. -f1 )
OSvers2=$( sw_vers -productVersion | cut -d. -f2 )
OSvers3=$( sw_vers -productVersion | cut -d. -f3 )
case $OSvers2 in
8)
OSName="Mountain Lion"
;;
9)
OSName="Mavericks"
;;
10)
OSName="Yosemite"
;;
11)
OSName="El Capitan"
;;
12)
OSName="Sierra"
;;
default)
OSName="Unknown"
;;
esac
# Get operating system name and version - Stop


echo "$computername"
echo "--------------"
echo "      Computer OS:  Mac OS X - $OSName $OSvers1.$OSvers2.$OSvers3"
echo "    Computer Name:  $computername"
echo "Current User Name:  $(whoami)"
echo "    Serial Number:  $sSerialNumber"

if [[ $remoteip ]]; then
echo "Remote IP Address:  $remoteip\n"
else
echo "Remote IP Address:  Unable To Determine\n"
fi

for val in $NetworkPorts; do   # Get for all available hardware ports their status
activated=$(ifconfig -uv "$val" | grep 'status: ' | awk '{print $2}')
#echo $activated
label=$(ifconfig -uv "$val" | grep 'type' | awk '{print $2}')
#echo $label
#ActiveNetwork=$(route get default | grep interface | awk '{print $2}')
ActiveNetworkName=$(networksetup -listallhardwareports | grep -B 1 "$label" | awk '/Hardware Port/{ print }'|cut -d " " -f3- | uniq)
#echo $ActiveNetwork
#echo $ActiveNetworkName
state=$(ifconfig -uv "$val" | grep 'status: ' | awk '{print $2}')
#echo $state
ipaddress=$(ifconfig -uv "$val" | grep 'inet ' | awk '{print $2}')
# echo $ipaddress

if [[ -z $(ifconfig -uv "$val" | grep 'link rate: ' | awk '{print $3, $4}' | sed 'N;s/\n/ up /' ) ]]; then
networkspeed="$(ifconfig -uv "$val" | grep 'link rate: ' | awk '{print $3}' ) up/down"
else
networkspeed="$(ifconfig -uv "$val" | grep 'link rate: ' | awk '{print $3, $4}' | sed 'N;s/\n/ up /' ) down"
fi

#echo $networkspeed
macaddress=$(ifconfig -uv "$val" | grep 'ether ' | awk '{print $2}')
#echo $macaddress
macal=$(curl -s "$sExternalMACALService$macaddress")
#echo $macal
quality=$(ifconfig -uv "$val" | grep 'link quality:' | awk '{print $3, $4}')
#echo $quality
netmask=$(ipconfig getpacket "$val" | grep 'subnet_mask (ip):' | awk '{print $3}')
#echo $netmask
router=$(ipconfig getpacket "$val" | grep 'router (ip_mult):' | sed 's/.*router (ip_mult): {\([^}]*\)}.*/\1/')
#echo $router
DHCPActive=$(networksetup -getinfo "Wi-Fi" | grep DHCP)
#echo $DHCPActive
dnsserver=$(networksetup -getdnsservers "$ActiveNetworkName" | awk '{print $1, $2}' | sed 'N;s/\n//' )
#echo $dnsserver

if [ "$activated" = 'active' ]; then
#echo "Network Port is Active"
if [[ $ipaddress ]]; then
echo "$ActiveNetworkName ($val)"
echo "--------------"
# Is this a WiFi associated port? If so, then we want the network name
if [ "$label" = "Wi-Fi" ]; then
WiFiName=$(/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -I | grep '\sSSID:' | sed 's/.*: //')
#echo $WiFiName
echo "     Network Name:  $WiFiName"
fi

echo "       IP Address:  $ipaddress"
echo "      Subnet Mask:  $netmask"
echo "           Router:  $router"
echo "          IP CIDR:  $ipaddress/$(mask2cdr $netmask)"

if [[ -z $dnsserver ]]; then
if [[ $DHCPActive ]]; then
echo "       DNS Server:  Set With DHCP"
else
echo "       DNS Server:  Unknown"
fi
else
echo "       DNS Server:  $dnsserver"
fi

echo "      MAC-address:  $macaddress ($macal)"
echo "    Network Speed:  $networkspeed"
echo "     Link quality:  $quality"
echo " "
fi

# Don't display the inactive ports.
fi

done
                           
                                               
Improve this answer                                                
edited Dec 9, 2021 at 5:41                                            
Glorfindel's user avatar                                                
                                           
Glorfindel                                                
3,9147 gold badges32 silver badges47 bronze badges                                                
answered Feb 27, 2017 at 19:05                                            
David Kittell's user avatar                                                
                                           
David Kittell                                                
1312 bronze badges                                                
  • In my script I've replaced public query with: set public (dig +short myip.opendns.com @resolver1.opendns.com) My reasoning for this is that a dns server (like opendns) is less likely to be down than a website and is faster. And I removed the sleep statement. No need to wait for the dns-server reply. Execution time for my script 177 ms. Yours takes 5.237 seconds, but does more of course. Still a big difference. 
    – PeterVP                                                
     May 1, 2017 at 16:09                                             
  • Great suggestion 
    – David Kittell                                                
     May 2, 2017 at 19:32                                            
  • This assumes that network services have the same names as their underlying hardware ports. networksetup -getdnsservers ... takes a network service name, which can sometimes be different than the hardware port passed to it in this script. You can see them all with -listnetworkserviceorder 
    – Chris                                                
     Sep 13, 2021 at 21:28                                             
Add a comment                            
                               
3
                           

Building on the other answers and comments (read: I didnt make this), this can be condensed into a single line:

networksetup -listnetworkserviceorder  |grep -B1 "$(route get example.com | awk "/interface/ {print \$2}")"                                

All it does is tell us which interface is being used, within the context of your configured Interface Order.

I use it in a shell alias:

# determine which network interface is being used
alias whichif='networksetup -listnetworkserviceorder  |grep -B1 "$(route get example.com | awk "/interface/ {print \$2}")"'
                               

Usage

$> whichif
(1) Thunderbolt Ethernet Slot 2
(Hardware Port: Thunderbolt Ethernet Slot 2, Device: en7)
                               

After switching interfaces:

$> whichif
(2) Wi-Fi
(Hardware Port: Wi-Fi, Device: en0)
                           
                                               
Improve this answer                                                
edited Jan 25, 2022 at 15:13                                            
answered Dec 16, 2021 at 17:05                                            
mikewaters's user avatar                                                
                                           
mikewaters                                                
2032 silver badges6 bronze badges                                                
  • the second grep can be done inside awknetworksetup -listnetworkserviceorder  |grep -B1 "$(route get example.com | awk "/interface/ {print \$2}")" 
    – ccpizza                                                
     Jan 24, 2022 at 9:43                                             
  • @ccpizza I love it!! 
    – mikewaters                                                
     Jan 25, 2022 at 15:10                                            
  • @ccpizza Yours is better, as its the same command on the cli and in the shell alias (wrt ~~quoting~~ escaping). I've updated our answer. 
    – mikewaters                                                
     Jan 25, 2022 at 15:14                                             
  • 3                                            
    If you want just the network service name: networksetup -listnetworkserviceorder  | awk  "/$(route get example.com | awk '/interface/ {print $2}')/{sub(/\([0-9]+\)\ /,\"\",a); print a} {a=\$0}" 
    – Pierz                                                
     May 10, 2022 at 9:25                                            
  • This also work for just getting the network service name: networksetup -listnetworkserviceorder  |grep -B1 "$(route get 1.1.1.1 | awk '/interface/ {print $2}')" | awk -F'\\) ' '/\([0-9]+\)/ {print $2}' 
    – Chris                                                
     Oct 25, 2022 at 20:18                                            
Show 1 more comment                            
                               
2
                           

Not sure if this is helpful to anyone, but as I was tinkering with the same question, I came to this solution:

ifconfig | grep flags=8863 | grep -v bridge                                

The output will look something like this, and lists only the ethernet ports and wifi that are in active use:

en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
en1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
                               

If you'd like to see the assigned IPv4 address as well:

ifconfig | grep 'flags=8863\|inet ' | grep -v 'bridge\|127.0.0.1'                                

Which produces something like this;

en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
    inet 192.168.2.147 netmask 0xffffff00 broadcast 192.168.2.255
en1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
    inet 192.168.2.244 netmask 0xffffff00 broadcast 192.168.2.255
                               

Another alternative:                                

scutil --nwi                                

Which shows the online network devices the last line actually shows the currently active network interfaces:

Network information

IPv4 network interface information
     en0 : flags      : 0x5 (IPv4,DNS)
           address    : 192.168.2.147
           reach      : 0x00000002 (Reachable)
     en1 : flags      : 0x5 (IPv4,DNS)
           address    : 192.168.2.244
           reach      : 0x00000002 (Reachable)

   REACH : flags 0x00000002 (Reachable)

IPv6 network interface information
   No IPv6 states found


   REACH : flags 0x00000000 (Not Reachable)

Network interfaces: en0 en1
                               

Further processing, if needed, is up to you. :-)


Note:

Mind you that I'm not an expert on the flags (8863). You can find the flag details in the if.h header file - Spotlight is your friend in finding "if.h". I found mine for example here:

/Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/Kernel.framework/Versions/A/Headers/net/if.h
                               

which will show you what the flags mean (keep in mind: hexadecimal);

#define IFF_UP          0x1             /* interface is up */
#define IFF_BROADCAST   0x2             /* broadcast address valid */
#define IFF_DEBUG       0x4             /* turn on debugging */
#define IFF_LOOPBACK    0x8             /* is a loopback net */
#define IFF_POINTOPOINT 0x10            /* interface is point-to-point link */
#define IFF_NOTRAILERS  0x20            /* obsolete: avoid use of trailers */
#define IFF_RUNNING     0x40            /* resources allocated */
#define IFF_NOARP       0x80            /* no address resolution protocol */
#define IFF_PROMISC     0x100           /* receive all packets */
#define IFF_ALLMULTI    0x200           /* receive all multicast packets */
#define IFF_OACTIVE     0x400           /* transmission in progress */
#define IFF_SIMPLEX     0x800           /* can't hear own transmissions */
#define IFF_LINK0       0x1000          /* per link layer defined bit */
#define IFF_LINK1       0x2000          /* per link layer defined bit */
#define IFF_LINK2       0x4000          /* per link layer defined bit */
#define IFF_ALTPHYS     IFF_LINK2       /* use alternate physical connection */
#define IFF_MULTICAST   0x8000          /* supports multicast */
                           
                                               
Improve this answer                                                
edited Sep 13, 2019 at 13:45                                            
answered Sep 12, 2019 at 16:23                                            
Hanzaplastique's user avatar                                                
                                           
Hanzaplastique                                                
2831 gold badge2 silver badges10 bronze badges                                                
Add a comment                            
                               
1
                           

Taken from Find Detailed Wi-Fi Connection History from Command Line of Mac OS X | OSXDaily:

For modern versions of Mac OS X, OS X Yosemite 10.10 and newer, use the following:

defaults read /Library/Preferences/SystemConfiguration/com.apple.airport.preferences |grep LastConnected -A 7
                               

Hit return and you’ll instantly see the comprehensive listing of wireless network connection details.

You get a lot of info on the history of connections, including the details for current one.

Not perfect but you get the info that you're looking for - and a lot of extra info more!

                                               
Improve this answer                                                
answered Dec 25, 2015 at 22:06                                            
JJarava's user avatar                                                
                                           
JJarava                                                
1,2462 gold badges16 silver badges28 bronze badges                                                
  • 1                                            
    You are assuming a Wi-Fi connection which is not necessarily the case for all scenarios. 
    – ccpizza                                                
     Dec 16, 2021 at 18:01                                            
Add a comment                            
                               
1
                           

Here's a fish shell script I wrote:

function netinfo -d "get network information"

  # Get public ip address
  set public (dig +short myip.opendns.com @resolver1.opendns.com)
  set hostname (uname -n)

  if test -z "$public" # We got an empty string, meaning:
    set public "No Internet connection available"
  end

  echo ''
  echo "    Public IP: $public"
  echo "     Hostname: $hostname"
  echo ''

  # Get all available hardware ports
  set ports (ifconfig -uv | grep '^[a-z0-9]' | awk -F : '{print $1}')

  # Get for all available hardware ports their status
  for val in $ports
    set activated (ifconfig -uv $val | grep 'status: ' | awk '{print $2}')

    # We want information about active network ports...
    if test $activated = 'active' ^/dev/null
      set ipaddress (ifconfig -uv $val | grep 'inet ' | awk '{print $2}')

      # and of these, the ones with an IP-address assigned to it
      if test -n "$ipaddress" ^/dev/null

        # Do we have an IP address?
        # Then give us the information
        set label (ifconfig -uv $val | grep 'type' | awk '{print $2}')
        set macaddress (ifconfig -uv $val | grep 'ether ' | awk '{print $2}')
        set quality (ifconfig -uv $val | grep 'link quality:' | awk '{print $3, $4}')
        set netmask (ipconfig getpacket $val | grep 'subnet_mask (ip):' | awk '{print $3}')
        set router (ipconfig getpacket $val | grep 'router (ip_mult):' | sed 's/.*router (ip_mult): {\([^}]*\)}.*/\1/')
        set dnsserver (ipconfig getpacket $val | grep 'domain_name_server (ip_mult):' | sed 's/.*domain_name_server (ip_mult): {\([^}]*\)}.*/\1/')

        # Header for the network interfaces
        echo -n $label ; echo -n ' ('; echo -n $val ; echo ')'
        echo "--------------"

        # Is this a WiFi associated port? If so, then we want the network name
        switch $label
          case Wi-Fi
            # Get WiFi network name
            set wifi_name (/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -I | grep '\sSSID:' | sed 's/.*: //')
            echo " Network Name: $wifi_name"
            # Networkspeed for Wi-Fi
            set networkspeed (/System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -I | grep lastTxRate: | sed 's/.*: //' | sed 's/$/ Mbps/')
          case '*'
            # Networkspeed  for other ports
            set networkspeed (ifconfig -uv $val | grep 'link rate:' | awk '{print $3, $4}')
        end

        echo "   IP-address: $ipaddress"
        echo "  Subnet Mask: $netmask"
        echo "       Router: $router"
        echo "   DNS Server: $dnsserver"
        echo "  MAC-address: $macaddress"
        echo "Network Speed: $networkspeed"
        echo " Link quality: $quality"
        echo ''
      end

      # Don't display the inactive ports.
    else if test $activated = 'inactive' ^/dev/null
    end
  end
end
                               

It shows all active network interfaces and relevant data.

Comment out what you don't want/need

                                               
Improve this answer                                                
edited Nov 17, 2017 at 19:43                                            
answered May 18, 2016 at 12:23                                            
PeterVP's user avatar                                                
                                           
PeterVP                                                
1,1508 silver badges8 bronze badges                                                
  • 2                                            
    Might be easier to define a echo_italic shell function instead of wrapping all these echos in set_color calls. 
    – nohillside                                                
     May 2, 2017 at 11:54                                            
  • All set_color commands can be removed. They're just 'decorative'. 
    – PeterVP                                                
     May 6, 2017 at 18:14                                            
  • 1                                            
    Removed set_color commands & put variables inside echo statements 
    – PeterVP                                                
     Nov 20, 2017 at 20:04                                            
Add a comment                            
                               
1
                           

Solution based on the input provided in all the other answers.

#################################
# get MacOS network device name
function get_network_device() {
  scutil --nwi | awk -F': ' '/Network interfaces/ {print $2;exit;}'
}

#################################
# get MacOS network service name: takes network device name as 1st arg
function get_service_name() {
  /usr/sbin/networksetup -listnetworkserviceorder | awk -v DEV="$1" -F': |,' '$0~ DEV  {print $2;exit;}'
}

NETWORK_DEVICE_NAME="$(get_network_device)"
NETWORK_SERVICE_NAME="$(get_service_name "$NETWORK_DEVICE_NAME")"

echo "${NETWORK_SERVICE_NAME}"
                               

The exit in in the first line makes sure only the first active network device is taken in case there are more than one.                                    

                                               
Improve this answer                                                
edited Mar 17, 2022 at 20:23                                            
answered Dec 8, 2021 at 18:13                                            
ccpizza's user avatar                                                
                                           
ccpizza                                                
2,7253 gold badges34 silver badges36 bronze badges                                                
Add a comment                            
                               
0
                           

list all connected network service name:

#!/bin/bash

# gsed: brew install gnu-sed
scutil --nwi | awk -F': ' '/Network interfaces/ {print $2;}' | gsed 's/ /\n/g' | while read interface; 
do
    echo "interface: $interface"
    # awk: print pre line of matched line
    networksetup -listnetworkserviceorder | awk "/$interface/{print a}{a=\$0}" | gsed 's/([0-9])//g' | while read networkservicename; do
        
        echo "networkservicename: $networkservicename"
        
    done;
done;
                           
                                               
Improve this answer                                                
edited Jun 1 at 3:20                                            
answered Jun 1 at 3:18                                            
user497367's user avatar                                                
                                           
user497367                                                
11 bronze badge                                                
Add a comment                            

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged                         

来自  https://apple.stackexchange.com/questions/191879/how-to-find-the-currently-connected-network-service-from-the-command-line                        


                       


                       

[Mac] 用networksetup 指令,取得与设定Wi-Fi 无线网路的连线状态                            


                               


                       

最近用Keyboard Maestro写在Mac 上自动登入公司VPN 的脚本,                        

不过偶尔遇到一些例外状况要处理,                        

像今天是遇到Wi-fi 网路被我手动关闭,导致脚本执行失败…                        

因此要想个方法,来侦测Wi-fi 的状况,以及将Wi-fi 打开~                        

 

在网路上找了一下,原来Mac 内建的networksetup 指令就能做到这些事了~                        

举例来说,可以用networksetup -listallnetworkservice 列出所有的网路类型:                        


                       

testuser@localhost ~ $ networksetup -listallnetworkservices
An asterisk ( * ) denotes that a network service is disabled.
MT65xx Preloader
Ethernet
FireWire
Wi-Fi
Bluetooth PAN
Thunderbolt Bridge
                       

 

可以看到有个网路类型是“Wi-Fi”,接着用networksetup -getinfo 可以取得相关资讯,                        

像是目前的IP address、Wi-Fi ID 等等~                        

如果是要侦测Wi-Fi 有没有成功连上网路的话,搜寻下面的输出里面,                        

有没有IP address 之类的字串加上一个合法的IP 位址就行了:                        


                       

testuser@localhost ~ $ networksetup -getinfo Wi-Fi
DHCP Configuration
IP address: 10.1.2.3
Subnet mask: 255.255.252.0
Router: 10.1.2.254
Client ID:
IPv6: Automatic
IPv6 IP address: none
IPv6 Router: none
Wi-Fi ID: 11:22:33:44:55:66
                       

 

如果要操作Wi-Fi 设备的话,得先知道设备的名称,                        

这个设备的名称在每台电脑上都有可能不一样(不像“Wi-Fi” 这个网路类型是每台Mac 都应该有的),                        

因此要用networksetup -listallhardwareports 来列出所有的网路设备,                        

像我们可以从下面的输出中,得知Wi-Fi 的网卡设备是en1:                        


                       

testuser@localhost ~ $ networksetup -listallhardwareports
Hardware Port: Ethernet
Device: en0
Ethernet Address: 11:11:11:11:15:85
Hardware Port: FireWire
Device: fw0
Ethernet Address: 22:22:22:22:fe:6a:59:dc
Hardware Port: Wi-Fi
Device: en1
Ethernet Address: 33:33:33:33:aa:8e
Hardware Port: Bluetooth PAN
Device: en3
Ethernet Address: 44:44:44:44:aa:8f
Hardware Port: Thunderbolt 1
Device: en2
Ethernet Address: 55:55:55:55:9d:c0
Hardware Port: Thunderbolt Bridge
Device: bridge0
Ethernet Address: 66:66:66:66:9d:c0
VLAN Configurations 
===================
                       

 

接着用networksetup -getairportpower 就能得知目前Wi-Fi 设备是不是开启的:                        

                       

testuser@localhost ~ $ networksetup -getairportpower en1
Wi-Fi Power ( en1 ) : Off
                       

 

用networksetup -setairportpower 就能开关指定的Wi-Fi 设备:                        


                       

networksetup -setairportpower en1 on
                       

 

用networksetup -getairportpower 再看一次,果真Wi-Fi 设备已经被打开啰:                        


                       

testuser@localhost ~ $ networksetup -getairportpower en1
Wi-Fi Power ( en1 ) : On
                       

 

参考资料:Managing WIFI connections using the Mac OSX terminal command line                        



                       


                       


                       

来自  https://ephrain.net/mac-%E7%94%A8-networksetup-%E6%8C%87%E4%BB%A4%EF%BC%8C%E5%8F%96%E5%BE%97%E8%88%87%E8%A8%AD%E5%AE%9A-wi-fi-%E7%84%A1%E7%B7%9A%E7%B6%B2%E8%B7%AF%E7%9A%84%E9%80%A3%E7%B7%9A%E7%8B%80%E6%85%8B/                        


                       


                       

How to pull the "en0" from this: 'networksetup -listallhardwareports'                            

Ask Question                            
Asked 
Modified 5 years ago                            
Viewed 247 times
0
                                       

when I run this: networksetup -listallhardwareports I get this (MACs removed):

Hardware Port: USB 10/100/1000 LAN
Device: en18
Ethernet Address: 

Hardware Port: Wi-Fi
Device: en0
Ethernet Address: 

Hardware Port: Bluetooth PAN
Device: en8
Ethernet Address: 

Hardware Port: Thunderbolt 1
Device: en3
Ethernet Address: 

Hardware Port: Thunderbolt 2
Device: en1
Ethernet Address: 

Hardware Port: Thunderbolt 3
Device: en4
Ethernet Address: 

Hardware Port: Thunderbolt 4
Device: en2
Ethernet Address: 

Hardware Port: Thunderbolt Bridge
Device: bridge0
Ethernet Address: 

VLAN Configurations
                                           

I'm looking to pull the Device ID and only Device ID from the Wi-Fi NIC, IE: en0

I know this can be done with a little grepping, sedding and awking. That is what I was hoping I could get some assistance with.

Thanks in advance,

Dev

                                                           
Edit                                                            
Get updates on questions and answers
asked May 17, 2018 at 17:06                                                        
AudibleScion's user avatar                                                            
                                                       
AudibleScion                                                            
114 bronze badges                                                            
  • Kindly always show us your expected output in CODE TAGS as well as your efforts too in your posts. 
    – RavinderSingh13                                                            
     May 17, 2018 at 17:11                                                        
Add a comment                                        
                               

2 Answers

                               
0
                                           

This appears to do it:

networksetup -listallhardwareports | awk '/Wi-Fi|AirPort/{getline; print $NF}'
                                           
                                                               
Edit                                                                
answered May 17, 2018 at 17:48                                                            
AudibleScion's user avatar                                                                
                                                           
AudibleScion                                                                
114 bronze badges                                                                
Add a comment                                            
                               
0
                                           

Though not that clear, could you please try following and let me know if this helps you.

your_command | awk '/Hardware Port: Wi-Fi/{getline;print "Device id: "$2}' 
                                           
                                                               
Edit                                                                
answered May 17, 2018 at 17:10                                                            
RavinderSingh13's user avatar                                                                
                                                           
RavinderSingh13                                                                
130k14 gold badges57 silver badges93 bronze badges                                                                
  • Thanks....the output from this networksetup -listallhardwareports | awk '/Hardware Port: Wi-Fi/{getline;print "Device id: "$2}' Is: Device id: en0 
    – AudibleScion                                                                
     May 17, 2018 at 17:46                                                             
Add a comment                                            
                               

Your Answer


                                   

来自  https://stackoverflow.com/questions/50396973/how-to-pull-the-en0-from-this-networksetup-listallhardwareports                                    


                    


                                   

               


                       

  • macOS:从网络设备名称获取设备名

先从ifconfig命令说起,这个命令后面可以跟上一个叫做interface的参数,就可以查看该interface所代表的网络设备的网络情况,比如:                 

ifconfig en0; ifconfig en1               

一般来说,从这里很难看出这个en0和en1那个是无线网卡、那个是有线网。尤其是新版的laptop没有有线网卡,那么en0就是无线网卡。            

为了动态获得WiFi对应的是哪个设备,我们需要使用networksetup命令的帮助。            

networksetup命令有一个-listallhardwareports的命令,给出下面形式的系统网络配置信息:            

    


https://stackoverflow.com/questions/50396973/how-to-pull-the-en0-from-this-networksetup-listallhardwareports


先从ifconfig命令说起,这个命令后面可以跟上一个叫做interface的参数,就可以查看该interface所代表的网络设备的网络情况,比如:

ifconfig en0; ifconfig en1

一般来说,从这里很难看出这个en0和en1那个是无线网卡、那个是有线网。尤其是新版的laptop没有有线网卡,那么en0就是无线网卡。


           

为了动态获得WiFi对应的是哪个设备,我们需要使用networksetup命令的帮助。

networksetup命令有一个-listallhardwareports的命令,给出下面形式的系统网络配置信息:


           

  1. $ networksetup -listallhardwareports
  2. Hardware Port: Ethernet
  3. Device: en0
  4. Ethernet Address: 10:dd:b1:d0:78:98
  5. Hardware Port: FireWire
  6. Device: fw0
  7. Ethernet Address: 44:fb:42:ff:fe:55:7f:ea
  8. Hardware Port: Wi-Fi
  9. Device: en1
  10. Ethernet Address: 88:1f:a1:10:75:7e
  11. Hardware Port: Bluetooth PAN
  12. Device: en3
  13. Ethernet Address: a8:bb:cf:0e:6e:71
  14. Hardware Port: Thunderbolt 1
  15. Device: en2
  16. Ethernet Address: d2:00:15:57:fe:a0
  17. Hardware Port: Thunderbolt 网桥
  18. Device: bridge0
  19. Ethernet Address: d2:00:15:57:fe:a0
  20. VLAN Configurations
  21. ===================
           

如果运行networksetup -h,还可以看到最开始的命令行,比如:networksetup -listallnetworkservices。在往下看,networksetup命令行中有好多称呼,什么networksevice, device, device name, service name等等。看到这里,可以感受到macOS内部对于网络接口的混乱称呼,而且还有hardware ports, 在加上ifconfig中的interface,真不知道他们到底是什么鬼,干嘛搞出这多名词。

其实,只要记住,他们就是两类,一类是设备名,一类是服务名


           

  • 设备名有:interface, device, device name

  • 服务名有:hardware ports, networksevice, service name

           

我们的任务就是在服务名和设备名之间转化。本文所想描述的是从服务名获得相应的设备名,从而可以使用ifconfig之类的命令操作给设备。


           

1 最简单的命令行:


           


           

wifi=$(/usr/sbin/networksetup -listallhardwareports | /usr/bin/awk '/Wi-Fi|AirPort/ {getline; print $NF}')
           

上面一行可以说是,最简单的一行了,主要使用了awk命令。但是他有一个假设就是输出行的顺序必须是


           

  1. Hardware Port: Wi-Fi
  2. Device: en1
还有一点需要注意的,在老版本的mac OS X中,最早使用Airport代表Wi-Fi的,该命令更通用。


           

2 bash数组示范

下面我们使用bash的数组功能做一个函数获得任意服务名对应的设备名:

function findDevice()

{

                           mDev="$1"

                           IFS=$'\n'

                           port=($(networksetup -listallhardwareports | grep "Hardware"))

                           devices=($(networksetup -listallhardwareports | grep "Device"))

                           # echo ${port[@]}, ${devices[@]}

                           for (( count=0; count<${#port[@]}; count++ )); do

                           [[ "${port[$count]}" = *"$mDev"* ]] && { echo ${devices[$count]} | awk -F ": " '{print $2}'; break; } || true

                           done

                           exit 0

}


           


虽说通过上一节的命令也可以定义一个函数,但是这个例子可以演示数组的用法,而且不会依赖于networksetup命令显示中各行的前后顺序

用法:


           

  1. wifi=$(findDevice "Wi-Fi")
  2. echo "Wi-Fi=($wifi)"
  3. found=$(findDevice "Thunderbolt")
  4. echo "Thunderbolt=($found)"

最后:

结合airport命令可以对WiFi进行详尽的配置:


           

/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport /usr/sbin/airport $wifi prefs


           

               

来自  https://blog.csdn.net/cneducation/article/details/79138236            


           

普通分类: