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

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.