Mac Network Commands Cheat Sheet

After writing up the presentation for MacSysAdmin in Sweden, I decided to go ahead and throw these into a quick cheat sheet for anyone who’d like to have them all in one place. Good luck out there, and stay salty. Get an ip address for en0: ipconfig getifaddr en0 Same thing, but setting and echoing a variable: ip=`ipconfig getifaddr en0` ; echo $ip View the subnet mask of en0: ipconfig getoption en0 subnet_mask View the dns server for en0: ipconfig getoption en0 domain_name_server Get information about how en0 got its dhcp on: ipconfig getpacket en1 View some network info: ifconfig en0 Set en0 to have an ip address of and a subnet mask of ifconfig en0 inet netmask Show a list of locations on the computer: networksetup -listlocations Obtain the active location the system is using: networksetup -getcurrentlocation Create a network location called Work and populate it with information from the active network connection: networksetup -createlocation Work populate Delete a network location called Work: networksetup -deletelocation Work Switch the active location to a location called Work: networksetup -switchlocation Work Switch the active location to a location called Work, but also show the GUID of that location so we can make scripties with it laters: scselect Work List all of the network interfaces on the system: networksetup -listallnetworkservices Rename the network service called Ethernet to the word Wired: networksetup -renamenetworkservice Ethernet Wired Disable a network interface: networksetup -setnetworkserviceenabled off Change the order of your network services: networksetup -ordernetworkservices “Wi-Fi” “USB Ethernet” Set the interface called Wi-Fi to obtain it if it isn’t already networksetup -setdhcp Wi-Fi Renew dhcp leases: ipconfig set en1 BOOTP && ipconfig set en1 DHCP ifconfig en1 down && ifconfig en1 up Renew a dhcp lease in a script: echo "add State:/Network/Interface/en0/RefreshConfiguration temporary" | sudo scutil Configure a manual static ip address: networksetup -setmanual Wi-Fi Configure the dns servers for a given network interface: networksetup -setdnsservers Wi-Fi Obtain the dns servers used on the Wi-Fi interface: networksetup -getdnsservers Wi-Fi Stop the application layer firewall: launchctl unload /System/Library/LaunchAgents/
launchctl unload /System/Library/LaunchDaemons/ Start the application layer firewall: launchctl load /System/Library/LaunchDaemons/
launchctl load /System/Library/LaunchAgents/ Allow an app to communicate outside the system through the application layer firewall: socketfilterfw -t
“/Applications/FileMaker Pro/FileMaker Pro” See the routing table of a Mac: netstat -nr Add a route so that traffic for communicates over the network interface: route -n add Log bonjour traffic at the packet level: sudo killall -USR2 mDNSResponder Stop Bonjour: launchctl unload -w /System/Library/LaunchDaemons/
 Start Bojour: launchctl load -w /System/Library/LaunchDaemons/ Put a delay in your pings: ping -i 5 Ping the hostname 5 times and then stop the ping: ping -c 5 Flood ping the host: ping -f localhost Set the packet size during your ping: ping -s 100 Customize the source IP during your ping: ping -S View disk performance: iostat -d disk0 Get information about the airport connection on your system: /System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -I Scan the available Wireless networks: /System/Library/PrivateFrameworks/Apple80211.framework/Versions/A/Resources/airport -s Trace the path packets go through: traceroute Trace the routes without looking up names: traceroute -n Trace a route in debug mode: traceroute -d View information on all sockets: netstat -at View network information for ipv6: netstat -lt View per protocol network statistics: netstat -s View the statistics for a specific network protocol: netstat -p igmp Show statistics for network interfaces: netstat -i View network information as it happens (requires ntop to be installed): ntop Scan port 80 of /System/Library/CoreServices/Applications/Network\ 80 80 Port scan stealthily: nmap -sS -O Establish a network connection with nc -v 80 Establish a network connection with over port 2195 /usr/bin/nc -v -w 15 2195 Establish a network connection with only allowing ipv4 /usr/bin/nc -v -4 2196 Setup a network listener on port 2196 for testing: /usr/bin/nc -l 2196 Capture some packets: tcpdump -nS Capture all the packets: tcpdump -nnvvXS Capture the packets for a given port: tcpdump -nnvvXs 548 Capture all the packets for a given port going to a given destination of tcpdump -nnvvXs 548 dst Capture the packets as above but dump to a pcap file: tcpdump -nnvvXs 548 dst -w /tmp/myfile.pcap Read tcpdump (cap) files and try to make them human readable: tcpdump -qns 0 -A -r /var/tmp/capture.pcap What binaries have what ports and in what states are those ports: lsof -n -i4TCP Make an alias for looking at what has a listener open, called ports: alias ports='lsof -n -i4TCP | grep LISTEN' Report back the name of the system: hostname Flush the dns cache: dscacheutil -flushcache Clear your arp cache: arp -ad View how the Server app interprets your network settings: serveradmin settings network Whitelist the ip address /Applications/ -w Finally, the script shows information about a Macs network configuration. Both active and inactive network interfaces are listed, in the order that they are used by the OS and with a lot of details (MAC-address, interface name, router, subnet mask etc.).

A Well Caffeinated Command Line

One of the big things in OS X Mountain Lion is how the system handles sleeping and sleeping events. For example, Power Nap means that now, Push Notifications still work when the lid is shut provided that the system is connected to a power source. This ties into Notification Center, how the system displays those Push Notifications to users. Sure, there’s tons of fun stuff for Accessibility, Calendar, contacts, Preview, Messages, Gatekeeper, etc. But a substantial underpinning that changed is how sleep is managed. And the handling of sleep extends to the command line. This manifests itself in a very easy to use command line utility called caffeinate. Ironically, caffeinate is similar to the sleep command, except it will keep the GUI awake in the event that Mountain Lion wants to take a nap (I’m not saying it should not be used as a replacement for sleep btw). To just get an idea of what it does, run the caffeinate command, followed by a -t operator and then let’s say the number 2: caffeinate -t 2 The system can’t go to sleep automatically now, for two seconds. The command will sit idle for those two seconds and then return you to a prompt. Now, extend that to about 10000: caffeinate -t 10000 While the command runs, manually put the system to sleep. Note that the system will go to sleep manually but not automatically. Now, there are different ways that a Mac can go to sleep. Use the -d option to prevent the display from sleeping or -i to prevent the system from going into an idle sleep. The -s is similar to -i but only impactful when the AC power is connected while the -u option deals with user inactivity. Overall, a fun little command. It’s just another little tool in an ever-growing arsenal of options.

Using The serverinfo Command To Get, Well, Server Info In Mountain Lion Server

OS X Mountain Lion Server comes with the /usr/sbin/serverinfo command. The serverinfo command can be pretty useful when you’re looking to programmatically obtain information about the very basic state of an OS X Server. The first option indicates whether the Server app has been downloaded from the app store, which is the –software option: serverinfo --software When used, this option reports the following if the can be found: This system has server software installed. Or if the software cannot be found, the following is indicated: This system does NOT have server software installed. The –productname option can be used to determine the name of the software app: serverinfo --productname If you change the name of the app from Server then the serverinfo won’t work any longer, so the output should always be the following: Server The –shortversion command returns the version of the Server app being used: serverinfo --shortversion The output will not indicate a build number, but instead the version of the app on the computer the command is run on: 2.0.23 To see the build, use the –buildversion option: serverinfo --buildversion The output shows the build of server, which doesn’t necessarily match the OS X build number: 12S307 Just because the Server app has been downloaded doesn’t mean the Server setup assistant has been run. To see if it has, use the –configured option: serverinfo --configured The output indicates whether the system is running as a server or just has the app installed (e.g. if you’re using it to connect to another server: This system has server software configured. You can also output all of the information into a single, easy to script against property list using the –plist option: serverinfo --plist The output is a list of each of the other options used: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" ""> <plist version="1.0"> <dict> <key>IsOSXServerVolume</key> <true/> <key>IsOSXServerVolumeConfigured</key> <true/> <key>IsServerHardware</key> <false/> <key>LocalizedServerProductName</key> <string>Server</string> <key>ServerBuildVersion</key> <string>12S307</string> <key>ServerPerformanceModeEnabled</key> <true/> <key>ServerVersion</key> <string>2.0.23</string> </dict> </plist> The Server Root can reside in a number of places. To see the path (useful when scripting commands that are relative to the ServerRoot: serverinfo --prefix By default, the output is as follows: /Applications/ You can also see whether the system is running on actual hardware desgnated by Apple for servers using the –hardware option: serverinfo --hardware The output simply indicates if the hardware shipped with OS X Server on it from Apple: This system is NOT running on server hardware. The –perfmode option indicates whether or not the performance mode has been enabled, dedicating resources to binaries within the Server app: serverinfo --perfmode If the performance mode has not been enabled then the output will be as such: Server performance mode is NOT enabled. To enable performance mode, you can also use serverinfo. This is the only task that the command does that can make any changes to the system and as such is the only time you need to elevate privileges: sudo serverinfo --setperfmode 1 Finally, set the boolean value to 0 to disable. sudo serverinfo --setperfmode 0

profiles -x: The Most Important New Feature In Mountain Lion!!!

There are a lot of cool new features in Mountain Lion. But the most important finds its way to us through how you can use the profiles command. If you can believe it (moment of suspense), the profiles command now supports a -x option that allows administrators to see what version of the profiles command is being run. OMGOMGOMGPWNIESOMGOMGOMG!!! profiles -x Since the profiles command appeared in Lion, the rev in Mountain Lion would arguably 2.0. Actually, if you check your output it’s 2.00!!! There ya’ go. Value, baby. That’s what Mountain Lion is all aboot! Other than that, the commands are about the same as when I wrote about them in Lion.

Opening a Terminal Window From, Well, Terminal

Terminal is a great application. And we usually use Terminal for editing scripts and invoking things. But what about invoking Terminal from, well, Terminal. For starters, let’s look at opening a Terminal session to the root of the boot volume (aka /): open -a Terminal / The -a option, when used with the open command, allows you to define which application that the item defined in the following position will open in. For example, you could open an XML file in Xcode open -a Xcode /usr/share/postgresql/pg_hba.conf.sample You could then open Terminal by passing other commands into the command. For example, to open a new Terminal window to the current working directory: open -a Terminal `pwd` Of course, you could accomplish the same thing with: open -a Terminal . Or pass the output of other commands through the open command. For example, the following command opens a new file in TextEdit that contains the output of an ls command: ls | open -f Adding -g to any of this leaves the new window in the background rather than bringing it to the foreground, which is the default behavior. Finally, open can also be used to open URLs, but I’ve covered that sort of use for open in the past.

The OS X Application Layer Firewall Part 3: Lion

In a couple of previous articles I looked at automating the Application Layer Firewall in OS X. These are pretty common articles that get back-linked to the site, so I decided to update them earlier, rather than later, in the Lion release. The tools to automate firewall events from the command line are still stored in /usr/libexec/ApplicationFirewall. And you will still use socketfilterfw there for much of the heavy lifting. However, now there are much more helpful and functional options in socketfilterfw that will allow you to more easily script the firewall. Some tricks I’ve picked up with alf scripting:
  • Configure the firewall fully before turning it on (especially if you’re doing so through something like Casper or Absolute Manage where you might kick yourself out of your session otherwise).
  • Whatever you do, you can always reset things back to defaults by removing file from /Library/Preferences replacing it /usr/libexec/ApplicationFirewall/
  • Configure global settings, then per-application settings
  • To debug: “/usr/libexec/ApplicationFirewall/socketfilterfw -d”
In /usr/libexec/ApplicationFirewall is the Firewall command, the binary of the actual application layer firewall and socketfilterfw, which configures the firewall. To configure the firewall to block all incoming traffic: /usr/libexec/ApplicationFirewall/socketfilterfw --setblockall on A couple of global options that can be set. Stealth Mode: /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode on Firewall logging: /usr/libexec/ApplicationFirewall/socketfilterfw --setloggingmode on To start the firewall: /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate on While it would be nice to think that that was going to be everything for everyone, it just so happens that some environments actually need to allow traffic. Therefore, traffic can be allowed per signed binary. To allow signed applications: /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsigned on This will allow all TRUSTEDAPPS. The –listapps option shows the status of each filtered application: /usr/libexec/ApplicationFirewall/socketfilterfw --listapps This shows the number of exceptions, explicitly allowed apps and signed exceptions as well as process names and allowed app statuses. There is also a list of TRUSTEDAPPS, which will initially be populated by Apple tools with sharing capabilities (e.g. httpd & smbd). If you are enabling the firewall using a script, first sign your applications that need to allow sharing but are not in the TRUSTEDAPPS section by using the -s option along with the application binary (not the .app bundle): /usr/libexec/ApplicationFirewall/socketfilterfw -s /Applications/ Once signed, verify the signature: /usr/libexec/ApplicationFirewall/socketfilterfw -v /Applications/ Once signed, trust the application using the –add option: /usr/libexec/ApplicationFirewall/socketfilterfw --add /Applications/ To see a list of trusted applications. You can do so by using the -l option as follows: /usr/libexec/ApplicationFirewall/socketfilterfw -l If, in the course of your testing, you determine the firewall just isn’t for you, disable it: /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate off Or to manually stop it using launchctl (should start again with a reboot): launchctl unload /System/Library/LaunchAgents/ launchctl unload /System/Library/LaunchDaemons/ If you disable the firewalll using launchctl, you may need to restart services for them to work again.

Setting up CHAP on LeftHand w/ CLI

LeftHand Storage uses the cliq command line for configuring their devices. cliq isn’t necessarily interactive and so we end up needing to specify the username, password and IP of the device with each command (although you can setup a key as well if you’re going to be doing automated tasks). One task that I’ve found to be pretty common is to use cliq to enable Chap authentication for volumes. To do so you’ll use the assignVolumeChap verb. Along with the assignVolumeChap verb you will need a number of options, each with an = for the payload of the option and delimited with a space between them. When using the assignVolumeChap verb you will need to supply a volume that you will be enabling authentication on, which is done using the volumeName option. You will also need to assign a password that will be entered on devices in order to connect to the target/volume, done using the targetSecret option. With most commands you will also need to specify the address of the storage node, the administrative user for that storage node and the password for it as well, these done using login, userName and passWord options respectively. You can obtain information about volumes using the getLocalVolumes verb:
cliq getLocalVolumes
To put all of these together, let’s look at an example where the storage node has an IP address of, an administrative user name of admin and an administrative password of ADMINPASSWORD. For this storage node we have a volume that we have created called MYSHAREDVOLUME and want to use a password of PASSWORDFORLUN to access it.
cliq assignVolumeChap volumeName=MYSHAREDVOLUME targetSecret=PASSWORDFORLUN login= userName=admin passWord=ADMINPASSWORD
Some other important verbs we’ve had to use are createCluster, connectVolume, configureRaid, createRemoteSnapshot (which is good to do before making any changes btw) and of course, createVolume (which you would need to do before assigning authentication to the volume). Each item that has a create typically has an associated delete (eg – deleteVolume, deleteRaid, etc) and an associated modify (eg – modifyVolume, modifyRaid, etc), which can be used to remove the added item and edit it (respectively). Overall, there are a lot of verbs that can be used with cliq, making it a somewhat robust scripting interface if you need to automate events. Another verb I find that I use a lot when I’m first setting up a device is the getPerformanceStats verb, which has a single option in interval, the number of milliseconds between sampling the performance statistics.

Clariion/Navisphere CLI

A Clariion can be managed using the /opt/Navisphere/bin/navicli command. You can obtain information about the environment using the -h option followed by the IP address of the IP of the Clariion and then a number of get verbs. For example, to get all of the settings for the Clariion at navicli -h getall Or to get LUN information navicli -h getlun You can also use getagent, getarrayuid, getcache, getconfig, getcontrol, getcrus, getdisk, getlog, getloop, getrg, getsniffer, getsp, getsptime and while it doesn’t start with get, lunmapinfo will obtain information about the LUN mappings. For example, to see a LUN mapped to a UID using the same host as above, you would use the following, replacing YOURUID with the UID for the storage group in question navicli -h storagegroup -list -uid YOURUID One task I always do is to set the name of an array. For e navicli -h arrayname KRYPTED_CLARiiON You can also use navicli to manage day to day operations. For example, to clear out logs and statistics you can use the following respectively: navicli -h clearlog navicli -h clearstats And then you can of course configure any of the devices that you can get information for using the get* commands. For example, to create two RAID groups, you can use the createrg verb, followed by an ID for the group and then the disks that will be part of the RAID group (IDs can be obtained using the getdisk verb). navicli -h createrg 0 0_0_0 0_0_1 0_0_2 0_0_3 0_0_4 navicli -h createrg 1 0_0_5 0_0_6 0_0_7 0_0_8 0_1_0 Once you have created RAID groups, you’ll want to use the bind verb on the new RAID groups, and in so doing tell them what RAID level to run at, with r0, r1 and rb being RAID 0, RAID 1 & RAID 5 respectively. For example to set RAID group 0 and 1 to RAID 5: navicli -h bind r5 0 -rg 0 navicli -h bind r5 0 -rg 1 Note: The only flag we were really using was -h. But when you’re writing scripts against navicli it’s pretty helpful to use the -m which only shows values as the result of commands, which can cut down on the amount of scripting you have to do… Note 2: If you’re working with an arbitrated loop then also make sure to review the navicli alpha command set. For example: navicli -h alpa -get

Reading Address Book from the Command Line

There isn’t an easy-to-use command line interface to the Address Book. You can use AppleScript with it, but not necessarily the command line. This isn’t to say there isn’t an AddressBook framework waiting for someone to use it. Well, Scott Stevenson posted a tool on his blog, Theocacao. This tool is pretty rudimentary but can be useful for a few basic tasks, and provides a nice framework for the development of a larger tool. Basically, abtool has one positional parameter – a search string. Using that it will look for a pattern in the name. It doesn’t search any of the other fields, use wildcards, nor allow for changing of any of the information in any of the fields. But it does give you the ability to pull a phone number and email address for a user who matches your query. Overall it’s a nice little tool that allows you to do something you otherwise might need to use osascript to do.

Command Line System Information

When you click on About This Mac and then click on More Info… you see the Apple System Profiler.  This tool, dating back to the Classic OS (prehistory so-to-speak) can be used to access a wide variety of information about your system, including installed hardware, software and some settings.  Some of this information can also be obtained through other tools.  For example, the networksetup command can obtain a wide variety of information about various network settings.  But it helps to have one tool to query for any information you may need about a computer (well, much of the information you may need).   While it is fairly straight forward to sit down and and open Apple System Profiler and look for information, this can be fairly tedious to do en masse.  Luckily, there is a command line version of the Apple System Profiler, aptly named system_profiler.  This command can be used to view any of the information from the Apple System Profiler, which you can then parse and use in scripts in a variety of ways.  This allows you to, for example, go far beyond what Apple Remote Desktop can provide in terms of reports and even write relevant information from systems into an out-of-band database, common in enterprise environments looking to centralize asset management for Macs into an existing Windows or Linux solution. Using the system_profiler command is fairly straight forward.  If you just run system_profiler then it will show you far more information than you can likely use.  Essentially, every field from Apple System Profiler will be displayed, including installed Frameworks, Fonts, Extensions, etc.  Therefore, a healthy dose of grep can help immensely.  But what do you grep for?  Well, find a field in Apple System Profiler and note the section it’s in under the Contents column of the application.  Then, run the following command:
system_profiler -listdatatypes
You should see an output similar to the following (notice the similarity with the items from the GUI):
SPHardwareDataType SPNetworkDataType SPSoftwareDataType SPParallelATADataType SPAudioDataType SPBluetoothDataType SPDiagnosticsDataType SPDiscBurningDataType SPFibreChannelDataType SPFireWireDataType SPDisplaysDataType SPHardwareRAIDDataType SPMemoryDataType SPPCCardDataType SPPCIDataType SPParallelSCSIDataType SPPowerDataType SPPrintersDataType SPSASDataType SPSerialATADataType SPUSBDataType SPAirPortDataType SPFirewallDataType SPNetworkLocationDataType SPModemDataType SPNetworkVolumeDataType SPApplicationsDataType SPExtensionsDataType SPFontsDataType SPFrameworksDataType SPLogsDataType SPManagedClientDataType SPPrefPaneDataType SPStartupItemDataType SPUniversalAccessDataType
Now if you match up the item from the Contents section of the graphical app to the one most closely resembling it from this list you should have where that information is going to be stored.  For example, let’s say that we want to know which computers have a 3rd party (non-Apple) System Preference pane installed.  Well, we can pull this from the SPPrefPaneDataType and then constrain our search to those containing the string 3rd.  Therefore, if the results of the following command show you anything at all then you have a third party System Preference Pane installed:
system_profiler SPPrefPaneDataType | grep 3rd
From here you can get far more detailed.  If you are running this en masse you’ll likely want to include the computer name, part of SPSoftwareDataType.  Then let’s say we wanted to know which systems had Flip4Mac installed – we could run the following:
system_profiler SPSoftwareDataType | grep “Computer Name”; system_profiler SPPrefPaneDataType | grep Flip4Mac 
With regular expressions we can actually get really detailed information out of system_profiler and then normalize the data for inclusion into our database; perhaps adding a , for a delimiter, etc.