Welcome

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

What next?
1. Bookmark us with del.icio.us or Digg Us!
2. Subscribe to this site's RSS feed
3. Browse the site.
4. Post your own code snippets to the site!

Block internet traffic to specified web sites on the fly

man 8 route
/sbin/route -n get default
/sbin/route -n get default | grep -w gateway
/sbin/route -n get default | grep interface | awk '{print $NF}'

/usr/bin/dig +short www.web_site.com                                 # get IPNUM
/usr/bin/sudo /sbin/route -n add -host IPNUM 127.0.0.1 -blackhole    # block IPNUM
/usr/sbin/netstat -rn | grep IPNUM                                   # show routing table
/usr/bin/sudo /sbin/route delete IPNUM 127.0.0.1                     # undo blocking


function blocksite() {
   declare ipaddr ipnum
   if [[ "${1//localhost/}" == '' ]] || [[ "${1//127.0.0.1/}" == '' ]]; then 
      printf "%s\n" 'Argument "localhost" is not permitted!'
      return 1
   fi
   ipnum=$(/usr/bin/dig +short "${1}" | /usr/bin/sed -E -n -e 's/^(([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3})$/\1/p'; exit ${PIPESTATUS[0]})
   if [[ $? -ne 0 ]] || [[ -z "${ipnum}" ]]; then 
      printf "%s\n%s\n" "Are you connected to the internet?" "man dig could not find the IP address of: ${1}"
      return 1
   fi
   OIFS=${IFS}
   IFS=$' \t\n'
   for ipaddr in ${ipnum//[[:cntrl:]]/ }; do
      /usr/bin/sudo /sbin/route -n add -host ${ipaddr} 127.0.0.1 -blackhole >/dev/null 2>&1
   done
   export IFS=${OIFS}
   printf "%s\n" "... blocking internet access to site: ${1} with IP address: ${ipnum//[[:cntrl:]]/, }"
   return 0
}


function unblocksite() {
   declare ipaddr ipnum
   if [[ "${1//localhost/}" == '' ]] || [[ "${1//127.0.0.1/}" == '' ]]; then 
      printf "%s\n" 'Argument "localhost" is not permitted!'
      return 1
   fi
   ipnum=$(/usr/bin/dig +short "${1}" | /usr/bin/sed -E -n -e 's/^(([[:digit:]]{1,3}\.){3}[[:digit:]]{1,3})$/\1/p'; exit ${PIPESTATUS[0]})
   if [[ $? -ne 0 ]] || [[ -z "${ipnum}" ]]; then 
      printf "%s\n%s\n" "Are you connected to the internet?" "man dig could not find the IP address of: ${1}"
      return 1
   fi
   OIFS=${IFS}
   IFS=$' \t\n'
   for ipaddr in ${ipnum//[[:cntrl:]]/ }; do
      /usr/bin/sudo /sbin/route delete ${ipaddr} 127.0.0.1 >/dev/null 2>&1
   done
   export IFS=${OIFS}
   printf "%s\n" "... unblocking internet access to site: ${1} with IP address: ${ipnum//[[:cntrl:]]/ }"
   return 0
}


function unblockall() {
   declare ipaddr ipnums
   ipnums=$(/usr/sbin/netstat -rnf inet | /usr/bin/awk '{ if ( $2 == "127.0.0.1" && $3 == "UGHSB" ) print $1 }'; exit ${PIPESTATUS[0]})
   if [[ $? -ne 0 ]] || [[ -z "${ipnums}" ]]; then 
      printf "%s\x21\n" "No IP addresses to unblock"
      return 1
   fi
   OIFS=${IFS}
   IFS=$' \t\n'
   for ipaddr in ${ipnums//[[:cntrl:]]/ }; do
      /usr/bin/sudo /sbin/route delete ${ipaddr} 127.0.0.1 >/dev/null 2>&1
   done
   export IFS=${OIFS}
   printf "%s\n" "... unblocking internet access to IP addresses: ${ipnums//[[:cntrl:]]/ }"
   return 0
}


function showblocked() {
   ipnums=$(/usr/sbin/netstat -rnf inet | /usr/bin/awk '{ if ( $2 == "127.0.0.1" && $3 == "UGHSB" ) print $1 }'; exit ${PIPESTATUS[0]})
   printf "%s\n" "Blocked IP addresses: ${ipnums//[[:cntrl:]]/, }"
   return 0
}



blocksite codesnippets.joyent.com
netstat -rnf inet | grep UGHSB
showblocked
open http://codesnippets.joyent.com
unblocksite codesnippets.joyent.com

blocksite codesnippets.joyent.com
blocksite www.google.com
netstat -rnf inet | grep UGHSB
showblocked
open http://www.google.com
unblockall

Enable internet traffic via specified ports through ipfw

# cf. Example ipfw ruleset, http://codesnippets.joyent.com/posts/show/1267

# choose appropriate numbers for num1 & num2 according to your ipfw ruleset

/usr/bin/sudo /sbin/ipfw list
/usr/sbin/sysctl -n net.inet.ip.fw.autoinc_step

function free_ipfw_rule_num() {
   declare -i num1=6701 num2=6799 lastipfwnum
   if [[ $(/usr/sbin/sysctl -n net.inet.ip.fw.autoinc_step) -ne 100 ]]; then 
      printf "%s\x21\n" "sysctl -n net.inet.ip.fw.autoinc_step is not set to 100"
      return 1
   fi
   lastipfwnum=$(/usr/bin/sudo /sbin/ipfw list | /usr/bin/tail -n 2 | /usr/bin/head -n 1 | /usr/bin/awk '{print $1}')
   if [[ $num2 -ge $lastipfwnum ]]; then 
      printf "%s\x21\n" "${num2} is greater than or equal to ${lastipfwnum}"
      return 1
   fi
   while $(/usr/bin/sudo /sbin/ipfw show ${num1} &>/dev/null) ; do
      let "num1 += 1"
      if [[ $num1 -gt $num2 ]]; then num1=; break; return 1; fi
   done
   printf "%s\n" "${num1}"
   return 0
}


function openport() {
   declare portnum rulenum
   if [[ $# -ne 1 ]]; then printf "%s\n" "Wrong number of arguments: $#"; return 1; fi
   portnum="${1//[^[:digit:]]/}"
   if [[ -z $portnum ]]; then printf "%s\n" "No valid port number given: ${1}"; return 1; fi
   if [[ $portnum -gt 65535 ]]; then printf "%s\n" "Given port number is greater than 65535: ${portnum}"; return 1; fi
   rulenum=$(free_ipfw_rule_num)
   /usr/bin/sudo /sbin/ipfw -q add ${rulenum} allow all from any to any dst-port ${portnum} keep-state
   printf "%s\n" "... opening ipfw rule no. ${rulenum} for internet access via port ${portnum}"
   return 0
}


function closeport() {
   declare portnum rulenum
   if [[ $# -ne 1 ]]; then printf "%s\n" "Wrong number of arguments: $#"; return 1; fi
   portnum="${1//[^[:digit:]]/}"
   if [[ -z $portnum ]]; then printf "%s\n" "No valid port number given: ${1}"; return 1; fi
   if [[ $portnum -gt 65535 ]]; then printf "%s\n" "Given port number is greater than 65535: ${portnum}"; return 1; fi
   rulenum=$(/usr/bin/sudo /sbin/ipfw list | /usr/bin/awk "/from +any +to +any +dst-port +${portnum} +keep-state[[:space:]]*$/ {print \$1}")
   if [[ -z "${rulenum}" ]]; then printf "%s\n" "No ipfw rule for port number: ${portnum}"; return 1; fi
   /usr/bin/sudo /sbin/ipfw -q delete ${rulenum}
   printf "%s\n%s\n" "... deleting ipfw rule no. ${rulenum//[[:cntrl:]]/ }" "... closing internet access via port: ${portnum}"
   return 0
}


openport 43
openport 43
openport 43

/usr/bin/sudo /sbin/ipfw show [rulenum]     # ... allow ip from any to any dst-port 43 keep-state

closeport 43

List whois servers on Mac OS X

defaults domains | tr ',' '\n' | nl
defaults domains | tr ',' '\n' | grep -i network
defaults find network | egrep '^Found'
defaults find whois | egrep '^Found'
defaults find server | egrep '^Found'

defaults read com.apple.NetworkUtility
defaults read ~/Library/Preferences/com.apple.NetworkUtility NUWhoisSelectedServer
defaults read com.apple.NetworkUtility NUWhoisServers | awk -F '"' '/"/{print $2}' | nl

defaults read com.apple.NetworkUtility NUWhoisServers | awk -F '"' '/"/{print $2}' | xargs -I '{}' \
     bash -c 'ipaddr="$(/usr/bin/dig +short {})"; printf "%s\n" "${ipaddr//[[:cntrl:]]/, }"'

defaults read com.apple.NetworkUtility NUWhoisServers | awk -F '"' '/"/{print $2}' | xargs -I '{}' \
     bash -c 'ipaddr="$(/usr/bin/dig +short {})"; printf "%s  --  %s\n" "{}" "${ipaddr//[[:cntrl:]]/, }"'

Create & resolve Mac-type aliases from the command line

# See:
# - http://osxutils.sourceforge.net
# - http://www.sveinbjorn.org/osxutils_docs
# - http://developer.apple.com/technotes/tn/tn1188.html

/usr/local/bin/mkalias -r /path/to/file /path/to/mac-alias
/usr/local/bin/hfsdata -e /path/to/mac-alias

httpd.conf snippet to append to get mod_jk tomcat apache running with apache2 in Leopard 10.5

# Load mod_jk module
# Update this path to match your modules location

LoadModule jk_module /usr/libexec/apache2/mod_jk.so
# Where to find workers.properties
# Update this path to match your conf directory location (put workers.properties next to httpd.conf)
JkWorkersFile /private/etc/apache2/workers.properties
# Where to put jk shared memory
# Update this path to match your local state directory or logs directory
JkShmFile /var/log/apache2/mod_jk.shm
# Where to put jk logs
# Update this path to match your logs directory location (put mod_jk.log next to access_log)
JkLogFile /var/log/apache2/mod_jk.log
# Set the jk log level [debug/error/info]
JkLogLevel info
# Select the timestamp log format
JkLogStampFormat "[%a %b %d %H:%M:%S %Y] "
# Send everything for context /examples to worker named ajp13 (ajp13)
# These are determined by tomcat apache configuration, the path below determines which part of your site will serve .jsp files.
JKMount /jqia/* ajp13

workers.properties file in /private/etc/apache2/ to get mod_jk apache tomcat running with apache2 in Leopard 10.5

#
# The workers that jk should create and work with
#
worker.list=ajp13

#
# Defining a worker named ajp13 and of type ajp13
# Note that the name and the type do not have to match.
#
worker.ajp13.type=ajp13
worker.ajp13.host=localhost
worker.ajp13.port=8009

Enable access to specified web sites through ipfw

# cf. Example ipfw ruleset, http://codesnippets.joyent.com/posts/show/1267

# choose appropriate numbers for num1 & num2 according to your ipfw ruleset

/usr/bin/sudo /sbin/ipfw list
/usr/sbin/sysctl -n net.inet.ip.fw.autoinc_step

function free_ipfw_rule_num() {
   declare -i num1=6701 num2=6799 lastipfwnum
   if [[ $(/usr/sbin/sysctl -n net.inet.ip.fw.autoinc_step) -ne 100 ]]; then 
      printf "%s\x21\n" "sysctl -n net.inet.ip.fw.autoinc_step is not set to 100"
      return 1
   fi
   lastipfwnum=$(/usr/bin/sudo /sbin/ipfw list | /usr/bin/tail -n 2 | /usr/bin/head -n 1 | /usr/bin/awk '{print $1}')
   if [[ $num2 -ge $lastipfwnum ]]; then 
      printf "%s\x21\n" "${num2} is greater than or equal to ${lastipfwnum}"
      return 1
   fi
   while $(/usr/bin/sudo /sbin/ipfw show ${num1} &>/dev/null) ; do
      let "num1 += 1"
      if [[ $num1 -gt $num2 ]]; then num1=; break; return 1; fi
   done
   printf "%s\n" "${num1}"
   return 0
}


function opensite() {
   declare ipnum ipfwnum
   if [[ $# -eq 0 ]] || [[ $# -gt 2 ]]; then printf "%s\n" "Wrong number of arguments: $#"; return 1; fi
   ipnum=$(/usr/bin/dig +short ${1} 2>/dev/null | /usr/bin/tail -n 1; exit ${PIPESTATUS[0]})
   if [[ $? -ne 0 ]] || [[ -z "${ipnum}" ]]; then 
      printf "%s\n%s\n" "Are you connected to the internet?" "man dig could not find the IP address of: ${1}"
      return 1
   fi
   ipfwnum=$(free_ipfw_rule_num)
   if [[ $# -eq 1 ]]; then
      /usr/bin/sudo /sbin/ipfw -q add ${ipfwnum} allow { src-ip "${ipnum}" or dst-ip "${ipnum}" } keep-state
      printf "%s\n" "... opening ipfw rule no. ${ipfwnum} for internet access to site: ${1}"
   elif [[ $# -eq 2 ]]; then
      /usr/bin/sudo /sbin/ipfw -q add ${ipfwnum} allow { src-ip "${ipnum}" or dst-ip "${ipnum}" } dst-port "${2//[^[:digit:]]/}" keep-state
      printf "%s\n" "... opening ipfw rule no. ${ipfwnum} for internet access to site: ${1} on port ${2}"
   fi
   return 0
}


function closesite() {
   declare ipnum rulenum
   if [[ "${1//localhost/}" == '' ]]; then printf "%s\n" 'Argument "localhost" is not permitted!'; return 1; fi
   ipnum=$(/usr/bin/dig +short "${1}" 2>/dev/null | /usr/bin/tail -n 1; exit ${PIPESTATUS[0]})
   if [[ $? -ne 0 ]] || [[ -z "${ipnum}" ]]; then 
      printf "%s\n%s\n" "Are you connected to the internet?" "man dig could not find the IP address of: ${1}"
      return 1
   fi
   rulenum=$(/usr/bin/sudo /sbin/ipfw list | /usr/bin/awk "/${ipnum}/ {print \$1}")
   if [[ -z "${rulenum}" ]]; then printf "%s\n" "No ipfw rule for: ${1}"; return 1; fi
   /usr/bin/sudo /sbin/ipfw -q delete ${rulenum}
   printf "%s\n%s\n" "... deleting ipfw rule no. ${rulenum//[[:cntrl:]]/ }" "... closing internet access to site: ${1}"
   return 0
}



# usage: 
# opensite [www.website.com] [optional: portnumber]
# closesite [www.website.com]

# example: http://wooledge.org:8000/BashFAQ

host wooledge.org
dig +short wooledge.org

opensite wooledge.org
opensite wooledge.org
opensite wooledge.org
opensite wooledge.org

closesite wooledge.org


opensite wooledge.org 8080
/usr/bin/sudo /sbin/ipfw show [rule no.]
closesite wooledge.org


#--------------------------------------------


man bash | less -p PIPESTATUS
help set | sed -E "s/(pipefail)/$(printf '\e[1m\\1\e[m')/"

set +o pipefail

ls asx 2>&1 | egrep '.'
echo $?

ls asx 2>&1 | egrep '.'
echo ${PIPESTATUS[*]} 

set -o pipefail

ls asx 2>&1 | egrep '.'
echo $?

ls asx 2>&1 | egrep '.'
echo ${PIPESTATUS[*]} 


# remove all non-numeric characters from a string
str="74n237k ab454c e 4 6 6g6fg6d66d"
echo ${#str}
echo ${str}
echo ${str//[^[:digit:]]/}


# yet another way to the check the reachability of a web site
man scutil
scutil --help
scutil -r www.website.com
scutil -r 127.0.0.1 209.85.129.147

Command line audio players for Mac OS X

For information on how to install MacPorts see here and here.
# qtplay & mpg123

export PATH="/opt/local/bin:/opt/local/lib:/opt/local/include:/opt/local/man:${PATH}"
alias port=/opt/local/bin/port

port list | grep -i audio

port info qtplay 
port info mpg123

/usr/bin/sudo port -c install qtplay
/usr/bin/sudo port -c install mpg123

mpg123 file.MP3

qtplay file.MP3
qtplay 'http://file.mp3'
qtplay 'http://file.mov'     # http://www.apple.com/trailers/


#-----------------------------------------


# play, http://www.hieper.nl/html/play.html

export PATH="/usr/local/bin:${PATH}"

# create /usr/local/bin
/usr/bin/sudo /bin/mkdir -p /usr/local/bin
/usr/bin/sudo /usr/sbin/chown root:wheel /usr/local /usr/local/bin
/usr/bin/sudo /bin/chmod 0755 /usr/local /usr/local/bin

cd ~/Desktop
curl -L -O http://www.hieper.nl/downloads/play.dmg
hdiutil mount ~/Desktop/play.dmg
open -a Safari '/Volumes/play 1.3/readme.html'
/usr/bin/sudo /bin/cp -i '/Volumes/play 1.3/play' /usr/local/bin
ls -l /usr/local/bin/play
hdiutil unmount '/Volumes/play 1.3'

play ~/Music/Winterreise/Gute\ Nacht.mp3

# listen to the first 10 seconds of each Schubert song on your computer
mdfind "kMDItemComposer == Schubert" | play -vt 10


#-------------------------------------------------------------


# afplay
# compile & install afplay and related command line audio tools (Mac OS X 10.4.11)
# requires Xcode, http://developer.apple.com/tools/xcode/index.html

ls -1 /usr/bin/af*     # Mac OS X 10.5
ls -1 /usr/bin/au* 

# Mac OS X 10.4
open /Developer/Examples/CoreAudio/Services/AudioFileTools/AudioFileTools.xcodeproj
# ... then just press "Build"

ls -l /Developer/Examples/CoreAudio/Services/AudioFileTools/build/Development-Panther/* | nl
ls -1 /Developer/Examples/CoreAudio/Services/AudioFileTools/build/Development-Panther/* | nl


#/usr/bin/find /Developer/Examples/CoreAudio/Services/AudioFileTools/build/Development-Panther -mindepth 1 | \
#     /usr/bin/xargs -I '{}' /usr/bin/sudo /bin/cp -i '{}' /usr/local/bin

/bin/ls -1 /Developer/Examples/CoreAudio/Services/AudioFileTools/build/Development-Panther/* | \
     /usr/bin/xargs -I '{}' /usr/bin/sudo /bin/cp -i '{}' /usr/local/bin

ls -l /usr/local/bin/af*
ls -l /usr/local/bin/au*

afconvert
afinfo
afinterleave
afplay
afrecord
auprocess
auprofile


# background music
# cf. http://codesnippets.joyent.com/posts/show/1508
/usr/bin/screen -d -m afplay "/path/to/file.MP3"

kill -HUP $$
kill -HUP $PPID
killall -HUP Terminal


apropos audio
apropos sound

# set global Mac OS X sound output volume
# see http://osxutils.sourceforge.net
man setvolume   
setvolume 50

seticon - set icon of Mac OS X files

# See:
# http://osxutils.sourceforge.net
# http://www.sveinbjorn.org/osxutils_docs

cd ~/Desktop
curl -L -O http://surfnet.dl.sourceforge.net/sourceforge/osxutils/osxutils1.7.pkg.zip
unzip -qq osxutils1.7.pkg.zip
open -a Installer osxutils1.7.pkg

/bin/mkdir -p ~/Desktop/IconDir
/bin/cp /Library/Desktop\ Pictures/Nature{/Ladybug.jpg,'/Evening Reflections.jpg'} ~/Desktop/IconDir
/usr/bin/sips -i ~/Desktop/IconDir/*

/usr/bin/touch ~/Desktop/IconDir/testfile.txt
/bin/chmod 0777 ~/Desktop/IconDir/*

ls -l ~/Desktop/IconDir/*

open ~/Desktop/IconDir

# set icon
/usr/local/bin/seticon ~/Desktop/IconDir/Ladybug.jpg ~/Desktop/IconDir/testfile.txt

# update file system changes of open Finder window
/usr/local/bin/wsupdate ~/Desktop/IconDir/testfile.txt
#/bin/mv ~/Desktop/IconDir{/testfile.txt,/tmp.txt} && /bin/mv ~/Desktop/IconDir{/tmp.txt,/testfile.txt} 


# set icon
/usr/local/bin/seticon ~/Desktop/IconDir/'Evening Reflections'.jpg ~/Desktop/IconDir
/usr/local/bin/wsupdate ~/Desktop/IconDir

/bin/chmod -R 0755 ~/Desktop/IconDir
ls -al ~/Desktop/IconDir/*


# geticon
sips -i file.jpg
geticon -t icns file.jpg


# list files with resource forks
# cf. http://www.entropy.ch/blog/Mac+OS+X/2005/03/30/,
# http://forums.macosxhints.com/showthread.php?t=70224 and
# "can UNIX resolve OS X aliases?", http://forums.macosxhints.com/showthread.php?t=19960

cd ~/Desktop/IconDir
ls -1 | while IFS= read -r i; do if [[ -s ${i}/..namedfork/rsrc ]]; then ls -l "${i}/..namedfork/rsrc"; fi; done
find . -mindepth 1 -maxdepth 1 -type f -exec test -s {}/..namedfork/rsrc \; -print
find . -mindepth 1 -maxdepth 1 -type f -exec test -s {}/..namedfork/rsrc \; -print0 | xargs -0 -n1 -I '{}' ls -l '{}'/..namedfork/rsrc
find . -mindepth 1 -maxdepth 1 -type f -exec test -s {}/..namedfork/rsrc \; -print0 | xargs -0 -n1 -I '{}' sed -n -e 'l' '{}'/..namedfork/rsrc
find . -mindepth 1 -maxdepth 1 -type f -exec test -s {}/..namedfork/rsrc \; -print0 | xargs -0 -n1 -I '{}' ruby -n -e 'p $_.to_s' '{}'/..namedfork/rsrc
find . -mindepth 1 -maxdepth 1 -type f -exec test -s {}/..namedfork/rsrc \; -print0 | xargs -0 -n1 -I '{}' strings '{}'/..namedfork/rsrc

# delete resource fork
find . -type f -maxdepth 1 -exec test -s {}/..namedfork/rsrc \; -print0 | xargs -0 -I '{}' /bin/cp /dev/null '{}/..namedfork/rsrc'

ditto --norsrc file.jpg{,.bak}
ditto --norsrc file.jpg.bak file.jpg

# some additional resource fork tools
man Rez
man DeRez
man RezWack     # create a flattened file from resource and data fork
man UnRezWack
man SplitForks
man FixupResourceForks

/Developer/Tools/Rez --help
/Developer/Tools/DeRez --help
/Developer/Tools/RezWack --help
/Developer/Tools/UnRezWack --help
/Developer/Tools/SplitForks --help
/System/Library/CoreServices/FixupResourceForks --help

ls -1 /Developer/Tools/*
/Developer/Tools/RezDet --help
/Developer/Tools/RezDet -d file; echo $?
/Developer/Tools/RezDet -s file; echo $?

man CpMac | less -N -j -9 -p 'As of Mac OS X 10.4' 
man MvMac | less -N -j -11 -p 'As of Mac OS X 10.4' 

# http://tclresource.sourceforge.net
man tclresource


Further information:

- Mac 101: Change Your Icons
- Mac OS X: Changing the Icon for a File Type
- How Do I Change File Icons And The Default Application On My Mac?
- Set Icon
- Mac Icon FAQ
- Setting an Icon From the CLI
- osxutils Documentation
- Aliases, symbolic links, Path Finder aliases... Help!
- BlueHarvest
- Making Resource-Fork-Aware Backups with rsync on Mac OS X

dotmacsyncclient

Sync with .Mac (MobileMe) from the command line

locate *dotmacsyncclient

/usr/bin/sudo /bin/ln -is /System/Library/CoreServices/dotmacsyncclient /usr/bin/dotmacsyncclient
dotmacsyncclient
dotmacsyncclient --version
dotmacsyncclient --listclients