TweetFollow Us on Twitter

Mac in the Shell: The man Show

Volume Number: 23 (2007)
Issue Number: 05
Column Tag: Mac in the Shell

Mac in the Shell: The man Show

Learning shell utilities with and without man

By Edward Marczak

Introduction

Documentation. The ugly reality is that it's usually an afterthought for a project, if completed at all. We like to code, we like to connect systems, but rarely do we like to document the work. man ("manual") pages, the built-in documentation system, have thousands of entries for shell utilities. Depending on the author, these entries range from well-written, humorous and pleasurable reading, down to sparse, terse and frustrating. Sometimes, the simple act of giving usage examples would make all the difference in usefulness and clarity. While I can't cover every shell utility here, I would like to point out some that you should know about, but that may not have the best documentation or just lack examples.

networksetup

Just as the name implies, networksetup is a utility to configure the network interfaces on a Mac OS X machine. There's no man page for this one at all. By default, it's not even in your path. Currently, under OS 10.4 ("Tiger"), you'll find networksetup located at: /System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Support/networksetup (whew!). There is, though, a usage statement printed if you run the command but lists no options and provides no examples.

Since OS X uses configd to inform the system of its current configuration state, the old-school utilities, such as ifconfig don't really work too well. Oh, yes, they can read the current state of the network, but setting it is another matter. This will work for a little bit, at least until configd receives a change event and reconfigures things for you.

networksetup uses terminology that is closer to the OS X GUI than traditional devices, too. First thing you typically need to figure out are the names of the network services being offered -- a.k.a. the interface names:

# networksetup -listallnetworkservices
An asterisk (*) denotes that a network service is disabled.
Bluetooth
Built-in Ethernet
Built-in FireWire
AirPort
Parallels Host-Guest
Parallels NAT
VPN (L2TP)

(You do, by the way, need admin level privileges to run this utility). You'll note that these names correspond to the names in the Network System Pane:


Figure 1 -- Interface names

If you rename the interface in the Network Pane, networksetup will see it that way, too. A possibly more useful list, if you're on a machine that you're not familiar with yet, is gained from the -listnetworkservice order switch. It shows both the interface name and the order that OS X uses it:

# networksetup -listnetworkserviceorder
An asterisk (*) denotes that a network service is disabled.
(1) Bluetooth
(Hardware Port: Bluetooth, Device: Bluetooth-Modem)
(2) Built-in Ethernet
(Hardware Port: Built-in Ethernet, Device: en0)
(3) Built-in FireWire
(Hardware Port: Built-in FireWire, Device: fw0)
(4) AirPort
(Hardware Port: AirPort, Device: en1)
(5) Parallels Host-Guest
(Hardware Port: Parallels Host-Guest, Device: en2)
(6) Parallels NAT
(Hardware Port: Parallels NAT, Device: en3)
(7) VPN (L2TP)
(Hardware Port: Windows L2TP, Device: )

This list is a great reminder that routes may be overridden by the order of interfaces.

Well, how about setting up the device? There are switches that act like each of the settings in the GUI:


Figure 2 -- How d'ya like your interface?

Probably of most interest is "-setmanual". To configure the built-in Ethernet interface to have an IPv4 address of 192.168.50.77, with a subnet mask of 255.255.255.0 and a default gateway of 192.168.50.1, you'd use this:

networksetup -setmanual "Built-in Ethernet" 192.168.50.77 255.255.255.0 192.168.50.1

One nice trick that doesn't seem apparent from the usage help, but has worked for me (up through 10.4.9), is that the router is optional. This is critically important when you're configuring an interface that will be active along with another.

The second option in our list is "-setmanualwithdhcprouter". This is just like "-setmanual", without being able to specify the subnet or router:

networksetup -setmanual "Built-in Ethernet" 192.168.50.77

Setting an interface to use DHCP is simple:

networksetup --setdhcp "AirPort"

You can also supply a client id after the interface name, if necessary. You can also clear the current client id by using "Empty" as the client ID name.

Similar to "-setdhcp" is "-setbootp". The command is the same as "-setdhcp", however, bootp doesn't support a client id, so, nor does this command.

Finally, "-setnetworkserviceenabled" roughly corresponds to "Off". This can turn the service "off" or "on":

networksetup -setnetworkserviceenabled "Bluetooth" off

If you run this while the Network Pane is open in the GUI, the GUI will alert you with, "Your network settings have been changed by another application" -- just something to be aware of. It then places an asterisk next to the name of the interface when using "-listallnetworkservices" and "-listnetworkserviceorder".

Finally, there are some very useful Airport specific commands. Different than enabling or disabling the interface, you can also turn power to the Airport off completely:

networksetup -setairportpower off

Of course, you can turn it back on with the same switch and a parameter of "on". You can also check the current state with "-getairportpower".

Of greater use, though, is the ability to programmatically set which network to connect to, using "-setairportnetwork":

networksetup -setairportnetwork "BigNet" SekurePa$$wd

Here too, you can find out the current state with a 'get' variant:

networksetup -getairportnetwork
Current AirPort Network: SuperAirNet

The networksetup command is very powerful and very thorough! In addition to the options I covered here, you can do anything that you can do in the GUI: create VLANs, turn AppleTalk on or off, set proxy configuration and more. It's a good command to be familiar with for scripting, remote setup and just to do things the "OS X way!"

scp

"scp" is the secure copy program. It's part of the ssh suite, which means that any remote machine you can connect to via ssh, you can also copy programs to and from. While there is a man page for this one, it doesn't have example usage. Also, I find that not enough people know about or use it -- even those who use ssh on a regular basis. scp is simple, really. To copy a local file to a remote machine, use this:

scp local_file my_id@server.example.com:/path/to/file/filename

You'll be asked for a password from the remote machine. Then, given permission on the remote, you'll see a progress meter that shows the file in transit. In my example, "my_id" is the id you use on the remote machine. (For those of you that may want to date yourself, unlike ssh, scp does not accept the "-l" (ell) switch to pass in your credentials -- a switch that ssh supplies to make the transition from telnet easier!).

The colon character (":") separates the hostname from the path. This can be a relative path, too. The starting location is the remote id's home directory. Also, like ssh, if unspecified, your current id is supplied. So, if I wanted to copy a file to my home directory on my test box, I could simplify the command down to this:

scp local_file lycaeum.radiotope.com:

Do note the trailing colon character. Without it, you'll just make a local copy of the file -- in this case, named "lycaeum.radiotope.com".

To copy from a remote machine, just reverse the order of the files, putting remote information first. To copy "filename" from the remote to your machine as "local_file", try this:

scp my_id@remote.example.com:/path/to/file/filename local_file

Again, to use the same name as the remote, simply omit it on the local side:

scp lycaeum.radiotope.com:program-4.7.6.tar.gz ./

If you're thinking of using this in an unattended script, you'll need to authenticate via keys so that you're not prompted for a password. While there are plenty of examples on the web of how to do this, for the sake of completeness, here is the short version:

Open up a shell on the local computer, and log into the correct local account.

Generate a public-private keypair by typing "ssh-keygen -t rsa". Leave the passphrase empty. This creates the files "id_rsa" and "id_rsa.pub" in the .ssh directory in this account's home directory.

Copy only id_rsa.pub to the remote machine using scp.

Login to the remote machine, and add the contents of id_rsa.pub to ~/.ssh/authorized_keys. You can use redirection to do this, as the authorized_keys file may already exist: cat id_rsa.pub >> ~/.ssh/authorized_keys

Logout of the remote machine, and test the setup using ssh. Try to ssh back into the remote machine. This time, you should not be prompted for a password.

Using keys in this manner, you'll be able to setup scp copies in an unattended script.

ssh and File Copy Programs

You may use ssh every day. You may use some of its more advanced features. But it is impossible to Know ssh. For every feature that you use, there seems to be another that you didn't know even existed. Did you know that ssh accepts input on standard in (stdin) and will simply shove it through the tunnel, popping it out on the other side?

What does that mean to us? Well, you can just gather up your data and pipe it to ssh:

tar czf - /path/to/file | ssh

Of course, we need to do something with it once it gets to the other side. How about expanding it somewhere? Let's imagine that we wanted to tar up the local /www directory and get it to a remote machine with its hierarchy intact:

tar czf - /www | ssh "cd /; tar xzfvp -"

Now, tar is a very nice solution -- most of the time. It's had a bit of an on-again off-again brokenness to it under OS X regarding resource fork copying. As I write this article, using OS X 10.4.9 Intel, tar works very nicely for copying resource forks. One other huge advantage to tar is that it preserves dates on copy. But, in fact, ditto will do this too, along with preserving all of the other OS X-specific data that it normally does. A simple example is a webloc file, which typically is resource-fork only (text clippings are also resource fork only). Fire up Safari, load a page and then drag the icon from the location bar to your desktop. Now you have a resource fork only file to work with:

$ cd Desktop
$ ls -l Weather\ Map.webloc 
-rw-r--r--   1 marczak  marczak  0 Apr 15 08:33 Weather Map.webloc
$ ls -l Weather\ Map.webloc/..namedfork/rsrc
-rw-r--r--   1 marczak  marczak  837 Apr 15 08:33 Weather Map.webloc/..namedfork/rsrc

Let's move this file to a remote machine using ditto. Again, I'm going to copy to my test server (lycaeum) and rely on the fact that by default, ssh plops me into my home directory. If you want to write the data elsewhere, replace the "./" path with one that suits you (and you have permission for). Here it is:

ditto -c Weather\ Map.webloc - | ssh lycaeum.radiotope.com ditto -x - ./

Log into the remote server and check out the date, time and other file attributes -- they'll all stay intact (however, not ACLs, as expected).

Machine Info

I'll leave you with two commands that can display information about the software and hardware on a given machine: sw_vers and system_profiler. Not that these are complex or need a lot of explanation, but just to know that they exist. If I could count all of the times I see a question about getting system information on a tech mailing list, I probably wouldn't be writing this!

sw_vers is the simpler of the two. With no options, it dumps out the product name, version and the build number:

$ sw_vers 
ProductName:    Mac OS X Server
ProductVersion: 10.4.9
BuildVersion:   8P135

You can pass in switches to limit the amount of information returned:

$ sw_vers -buildVersion
8P135

Filtering the information is certainly useful if you need this information in a script.

system_profiler is the shell equivalent of the GUI System Profiler.app. Like sw_vers, just used on its own, it gives you a good deal of info. Try it! (There's way too much output to print here). You can parse through this data on your own. If you're only looking for a specific bit of info, you can pass in filters that do just this:

$ system_profiler SPMemoryDataType
Memory:
    BANK 0/DIMM0:
      Size: 2 GB
      Type: DDR2 SDRAM
      Speed: 667 MHz
      Status: OK
    BANK 1/DIMM1:
      Size: 1 GB
      Type: DDR2 SDRAM
      Speed: 667 MHz
      Status: OK

You can get a list of data types with the "-listdatatypes" switch. If you want more than one type at once, go ahead and pass in those types:

system_profiler SPDisplaysDataType SPAirPortDataType SPPowerDataType

sw_vers and system_profiler are both great commands when accessing a remote machine that you may not be familiar with -- especially when someone is sitting at the console and you don't want to ask them for the information!

Summary

I regularly use the commands and techniques presented here. While the information is typically in the man page, useful examples don't always accompany that information. Sometimes, you just need to experiment with a command -- on a test system, of course -- until you have it figured out. Sometimes there are alternatives to man. Many GNU utilities have an info page that's different than the man page, if one even exists. Try "info emacs", for example. Press 'q' to get out of info's display. Of course, MacTech and publications like it (are there any?) present good alternatives to man pages as well. I hope this article was a good step in that direction for anyone reading it.

Media of the month: well, it's not going to be a Leopard title, as we're going to see a little delay there! However, there's plenty to be read before then. Don't get all stressed out about it. Instead, find some entertaining reading, like the "Lord of the Rings" trilogy. OK, not necessarily short reading, but I'm always surprised by how many people have not read these books. The movies were fine, but the books capture something different.

Until next month, enjoy!


Ed Marczak owns Radiotope, a technology consulting company that brings enterprise solutions to small and medium sized businesses. He is also the Executive Editor for MacTech magazine. Outside of technology, Ed likes to spend time with his family, and to practice counting.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »

Price Scanner via MacPrices.net

You can save $300-$480 on a 14-inch M3 Pro/Ma...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer new Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more

Jobs Board

IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
Top Secret *Apple* System Admin - Insight G...
Job Description Day to Day: * Configure and maintain the client's Apple Device Management (ADM) solution. The current solution is JAMF supporting 250-500 end points, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.