intro to the command line: mac admin edition · intro to the command line: mac admin edition-or-how...

42
Intro to the Command Line: Mac Admin Edition -or- How I Learned To Stop Worrying And Actually Read The Manpages Nick McSpadden Client Systems Manager Schools of the Sacred Heart, San Francisco Thursday, May 3, 12

Upload: vucong

Post on 17-Jun-2019

294 views

Category:

Documents


0 download

TRANSCRIPT

Intro to the Command Line: Mac Admin Edition

-or-How I Learned To Stop Worrying And Actually Read The Manpages

Nick McSpaddenClient Systems Manager

Schools of the Sacred Heart, San Francisco

Thursday, May 3, 12

Intro to the Command Line: Mac Admin Edition

-or-How I Learned To Stop Worrying And Actually Read The Manpages

Nick McSpaddenClient Systems Manager

Schools of the Sacred Heart, San Francisco

Thursday, May 3, 12

The Command LineIt’s like a toolbelt that has its own toolbelt

Some workflows are much easier through CLI than through GUI.

Example: changing permissions for a large number of files at once

Would you rather click Get Info 20 times in a row, or would you rather type chmod 644 /path/*?

Thursday, May 3, 12

The Command LineIt’s like a toolbelt that has its own toolbelt

Just about any information you’ll ever need about CLI tools is available right on your computer already.

Everything else is online.

Resources: eBooks, websites, mailing lists, IRC

https://developer.apple.com/library/mac/#documentation/darwin/reference/manpages/

Never hesitate to ask for help! Don’t reinvent the wheel, ask someone else how the wheel was invented.

Thursday, May 3, 12

The Command LineIt’s like a toolbelt that has its own toolbelt

Accessing the Command Line:

/Applications/Utilities/Terminal.app

Single User Mode (Command-S at startup) - this environment is a bit different, so not everything will function the same way

Add a new admin account: rm /var/db/.AppleSetupDone

Third party Terminal apps - iTerm

SSH remote access - Generally much easier and faster to set up than a GUI-based remote control like Screen Sharing / ARD.

Thursday, May 3, 12

RTFM: Read The F____ ManualGet to the know the Man, he’s on your side this time

man <command> will provide information, syntax, and instructions for almost everything

Manpages for UNIX commands are very helpful - they provide lots of examples (of course, never the ones you need right now)

UNIX commands have been around for a while, so most people have figured out their permutations - check online for ideas

ine

Thursday, May 3, 12

RTFM: Read The F____ ManualGet to the know the Man, he’s on your side this time

Apple-specific commands tend to have slightly less useful manpages (frankly, some of them are just obtuse)

Apple commands have a lot of undocumented features. Those features may not stick around in a future update, so be wary of scripting them in

For a quick refresher, try using -h or -help, which usually provides syntax guidelines

abulous

Thursday, May 3, 12

The Shell - In BriefWe’ll skip this if people are already familiar

What is the shell?

It’s your command line environment.

It’s your interpreter.

It takes input from stdin (what you type) or a file and figures out what to do with it.

Examples: sh, csh, tcsh, ksh, bash

By default, Mac OS X uses bash.

Thursday, May 3, 12

The Shell - In BriefWe’ll skip this if people are already familiar

cd, ls, pwd

cp, mv, rm, mkdir

locate

nano/pico, vi

cat, echo

ssh, scp

Thursday, May 3, 12

The Shell - The Path to SuccessA word about full paths vs. short paths

When do we use the full path to a command instead of just typing in the command name?

The $PATH environmental variable isn’t always set in development environments (DeployStudio / NetBoot situations)

Avoid ambiguity at all times, be as specific in your scripts as possible

Thursday, May 3, 12

The Shell - The Path to SuccessA word about full paths vs. short paths#!/bin/bash

diskutil=“/usr/sbin/diskutil”networksetup=“/usr/sbin/networksetup”

ComputerName=`$networksetup -getcomputername`

$diskutil rename / $ComputerName

exit 0

Thursday, May 3, 12

The Shell - The Path to SuccessA word about full paths vs. short paths

#!/bin/bash

ComputerName=`/usr/sbin/networksetup -getcomputername`

/usr/sbin/diskutil rename / $ComputerName

exit 0

Thursday, May 3, 12

So what do we Mac Admins actually want to use in the Terminal?

Thursday, May 3, 12

Administrator’s Basic ToolboxWorking with admin privileges

sudo - getting admin privileges

sudo su, or sudo -s gives you a root shell

Edit /etc/sudoers to add accounts to the sudo list

With anything, be careful when using sudo! There’s no undo feature!

sudo rm -rf * is just one typo away from making you very sad

Thursday, May 3, 12

Administrator’s Basic ToolboxChecking for software updates

softwareupdate

--CatalogURL lets you specify a catalog file (this is not listed in the manpages)

softwareupdate -l --CatalogURL <URL> to list all available updates from a specific catalog

softwareupdate -i -a to install all updates

softwareupdate -i <name> to install specific updates

Reboot manually when done

Thursday, May 3, 12

Administrator’s Basic ToolboxCollecting system information

system_profiler

The complete system profile. Use -listDataTypes to see how you can narrow down results

system_profiler SPHardwareDataType - basic hardware info

Supports XML export

Thursday, May 3, 12

Administrator’s Basic ToolboxInstalling packaged software

installer

installer -pkg /Path/To/Package.pkg -target /

installer -pkg /Path/To/Folder/*.pkg -target /

For signed packages, requires a valid certificate - invalid certs can only be circumvented via the GUI. (Package Apocalypse 2012)

Thursday, May 3, 12

Administrator’s Basic ToolboxLook at what’s running

top and ps

top is Activity Monitor in CLI form

ps lists running processes. Use ps auxww to get a list of all running processes without limiting it to window width

ps auxww | grep <name> for finding specific applications or processes

Use kill to end processes

Thursday, May 3, 12

Administrator’s Basic ToolboxAccessing network shares

mount_afp

Step 1: mkdir /Volumes/ShareName

Step 2: mount_afp afp://username@server/ShareName /Volumes/ShareName

Step 3: umount /Volumes/ShareName, then rmdir /Volumes/ShareName

Thursday, May 3, 12

Administrator’s Basic ToolboxWorking with file access

chmod and chown

chown to change owner/group, chmod to change permissions

chown nmcspadden:staff /path/to/file

chmod 644 /path/to/file

chmod +w /path/to/file

chmod o-x /path/to/file

Learn both of chmod forms: numeric value & written value

Thursday, May 3, 12

System Setup And ConfigurationScheduled and repeated events

launchd, launchctl

Launchd is a whole different can of worms. There are other sessions to talk about this in depth, and plenty of online documentation.

sudo launchctl list to see all running system agents

launchctl list to see all user agents

launchctl load, launchctl unload, launchctl stop to interact with launch agents / daemons

Thursday, May 3, 12

System Setup And ConfigurationFor the Apple Remote Desktop users

kickstart

Configuration for Apple Remote Desktop agent

/System/Library/CoreServices/RemoteManagement/ARDAgent.app/Contents/Resources/kickstart

kickstart -configure -allowAccessFor -specifiedUsers

kickstart -activate -configure -access -on -users “admin” -privs all -restart -agent

No man page, use -help

Thursday, May 3, 12

System Setup And ConfigurationInternet and network access

networksetup

The master tool for network configuration

networksetup -setairportpower en1 off

networksetup -setairportnetwork en1 ssid password

networksetup -setnetworkserviceenabled FireWire off

networksetup -setv6off Ethernet

There’s an option for pretty much everything

Thursday, May 3, 12

System Setup And ConfigurationEnergy and sleep settings

pmset

Power management settings, Energy Saver

pmset -b sleep 30 displaysleep 5 disksleep 10

pmset repeat shutdown MTWRF 19:00:00

pmset -g to get information about the current settings

pmset -g sched

Making any changes requires sudo, but -g is free

Thursday, May 3, 12

I Am Become Mac ManagerControlling preferences (plists)

defaults and /usr/libexec/PlistBuddy

defaults modifies plist settings, especially Apple-created ones

Critical for startup / scripted configurations

defaults read /Path/To/Plist.plist KeyName

defaults write /Path/To/Plist.plist KeyName Value

PlistBuddy has an interactive shell, and is more comprehensive

Thursday, May 3, 12

I Am Become Mac ManagerPeople see this and think I’m a hacker

defaults write /Library/Preferences/com.apple.SoftwareUpdate CatalogURL http://softwareupdateserver.apple.edu/content/catalogs/others/index-leopard-snowleopard.merged-1.sucatalog

/usr/libexec/PlistBuddy -c print /Library/Preferences/com.apple.SoftwareUpdate.plist

Thursday, May 3, 12

I Am Become Mac Manager“My printer isn’t working, what do I do? This is an emergency!”

lpr, lpoptions, lpadmin, lpstat

lpadmin for configuring/adding/removing printers; lpoptions for specifying driver options; lpstat for print queue status

lpadmin -p PrinterName -d Description -L Location - E -v lpd://printerAddress -P “HPLaserJet 4250.gz” -o HPOption_Tray3=Tray3_500

lpoptions -d PrinterName - default printer

Thursday, May 3, 12

I Am Become Mac Manager“Turn your computer on, I’ll add your printer remotely.”

#!/bin/bashprName=“HP LJ 4250”prDescription=“It’s kinda short and stocky, plastic gray color...”prLocation=“Printing Office”prAddress=“10.1.30.102”prPPD=“HP LaserJet 4250.gz”

lpadmin -p “${prName}” -D “${prDescription}” -L “${prLocation}” -E -v lpd://“${prAddress}” -P “/Library/Printers/PPDs/Contents/Resources/$prPPD” -o HPOption_Tray3=Tray3_500

lpoptions -d “${prName}”Thursday, May 3, 12

I Am Become Mac ManagerIt’s just more satisfying when you control everything

mcxrefresh and mcxquery are MCX (managed preferences) related

mcxquery for determining what preferences are being managed for a given user/group/computer

mcxrefresh for refreshing MCX for changes

mcxrefresh -n nobody for refreshing system changes

Thursday, May 3, 12

I Am Become File System ManagerMove things around

CpMac and MvMac to copy/move Mac files while preserving forks

ditto to make an exact copy of file/directory structure

ditto foo bar copies the contents of foo into bar

cp -r foo bar copies foo itself into bar

ditto -rsrc /directory/A /directory/B while keeping all resources

Thursday, May 3, 12

I Am Become File System ManagerWhere on earth did that licensing file go?

fs_usage

Monitor the file system in realtime (requires sudo)

Incredibly useful for tracking down wayward installers that drop things in weird places

Deployed applications not launching? Check what files are missing!

Thursday, May 3, 12

I Am Disk Utility, Destroyer of WorldsPart 1: Disk Images

hdiutil

The CLI version of Disk Utility’s disk image handler. Read the manpages carefully!

hdiutil attach diskimage.dmg -readonly -owners off

Mount a disk image as readonly with ownership ignored

hdiutil create, hdiutil convert, hdiutil burn

diskutil is used for repairing local disks, not disk images!

Thursday, May 3, 12

I Am Disk Utility, Destroyer of WorldsSon of Part 1: Erasing Your Hard Drives

diskutil

The other half of Disk Utility

Erase, reformat, repartition, resize, RAID

diskutil repairPermissions /

diskutil eraseVolume HFS+ UntitledHFS /Volumes/SomeDisk

Be careful with this, it’s your file system.

Thursday, May 3, 12

Incorporating Other ElementsAdding other scripting languages to your work

osascript invokes AppleScript

When it comes to interacting with GUI elements, AppleScript is king

osascript <<EndofMyScript

do a whole bunch of stuff

EndofMyScript

Thursday, May 3, 12

Account ManagementFor the famous and cool people

dscl

Manage directory services information. Create/delete acounts, change search policy, import MCX - it’s got it all.

Research and learn this tool thoroughly, it’s incredibly useful for anyone using Directory Services.

dscl . -create /Users/newuser

dscl . -list /Users/

Thursday, May 3, 12

Account ManagementFor the beautiful and successful

createhomedir

Does what you think it does

Once an account is generated using dscl or OD/AD, this will copy the standard user template so the user can actually log in

createhomedir -c for all local home paths only

Does not affect currently existing home directories

Thursday, May 3, 12

dscl . -create /Users/newuserdscl . -create /Users/newuser UniqueID “1010”dscl . -create /Users/newuser RealName “New Guy”dscl . -create /Users/newuser NFSHomeDirectory /Users/newuserdscl . -create /Users/newuser PrimaryGroupID 20

dscl . -passwd /Users/newuser passwordcreatehomedir -c

# If you want it to be an admin account, set the PrimaryGroupID to 80 instead

Thursday, May 3, 12

Wake Up, Neo, The Matrix Has YouInteracting with the outside world

curl - easy way of downloading files from webservers

dig - uses your DNS to check IPs of hostnames

hostname - lists/sets the hostname of the local machine

hostname -s PSUMac.psu.edu

This doesn’t change the Sharing name!

dscacheutil -flushcache - the classic DNS cache flush

Thursday, May 3, 12

We are Server AdminsAnd so can you

serveradmin

Step 1: Read the manpage!

Step 2: Must be run as root (su or sudo)

serveradmin settings <service> to see all variables

serveradmin settings <service>:<key> to see the value of a key

serveradmin command <service>:command=<query>

<query> is a very specific list of commands - and they’re buried

Thursday, May 3, 12

We are Server AdminsAutopilot to Cool

https://help.apple.com/advancedserveradmin/mac/10.7/

Lots of useful data there for managing Lion server in general. Serveradmin commands are listed with each service.

http://manuals.info.apple.com/en/command_line_admin_v10.5.pdf

It’s split up throughout the whole document, but the PDF contains lists of all the available commands for various services (as of 10.5). It may be the most comprehensive source currently available.

Thursday, May 3, 12

We are Server AdminsFun tricks to show off at parties

From afp548.com: Using serveradmin to backup and restore your configs (http://www.afp548.com/article.php?story=20070625095016407)

Simple backup:sudo serveradmin settings all > serverconfig.backup

Simple restore:sudo serveradmin settings < serverconfig.backup

You can do this with individual services as well.

Thursday, May 3, 12

Thanks for coming!

Thursday, May 3, 12