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

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... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.