Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

Automatically update locate db on-demand UNIX
This hint provides a method to automatically insure that the locate db is not too old (but only) whenever you use the locate command (in Terminal or a script).

The hint:
  • a) uses sudo to update the db as root,
  • b) assumes you're using bash as your shell interpreter,
  • c) sets an alias so as to be transparent,
  • d) adds "-i" to your locate command, making it case-insensitive,
  • e) considers the db outdated if it's older than an hour, (actually 3600 seconds, which you can change of course.)
Using your favorite text editor add the following line to the file called ~/.bash_profile. It's inside your Home directory as indicated but hidden. If it doesn't already exist you can create a new text file and save it to that path and name.
alias locate='if [ $((`date +%s`-`eval $(stat -s /var/db/locate.database); echo $st_mtime`)) -gt 3600 ]; then echo "locate: db is too old!">/dev/stderr; sudo /usr/libexec/locate.updatedb; fi; locate -i'

[crarko adds: Note that in creating the command alias you slightly change the meaning of the locate command; you can use a different alias if you want to keep both ways around and update manually. You lose some of the value of the hint if you do that.]
  Post a comment  •  Comments (5)  
  • Currently 3.00 / 5
  • 1
  • 2
  • 3
  • 4
  • 5
  (2 votes cast)
 
[8,278 views] Email Article To a Friend View Printable Version
10.7: View Linux SMB servers in Path Finder UNIX
I use Path Finder for some fancier features, but since upgrading to Lion, I could not see my Linux SMB server in the side panel. After waiting for their Lion patch with no change, I figured out a very simple solution.

For whatever reason, Path Finder can't find or list Samba servers like it did in Snow Leopard. But, if you either install or modify an Avahi daemon on the SMB server, and advertize SMB services, Path Finder will see the server again.

After installing the Avahi daemon in a manner appropriate for your distribution, just create and save this simple file to /etc/avahi/services (on the server):
<?xml version="1.0" standalone='no'?>
<!DOCTYPE service-group SYSTEM "avahi-service.dtd">

   Samba Shares on %h
   
       _smb._tcp
       139
This worked as is for me, and the server popped up in Path Finder within seconds, and remains in the side panel even after all the shared mounts were removed.

Hope this helps someone else who is sick of opening a Finder window just to connect to another share, or is sick of hitting Command-K every few minutes.

[crarko adds: I haven't tested this one. I'd guess this is because Lion no longer uses Samba for SMB support. Note: there was originally a link in the hint to a Gentoo Linux wiki as a source for this fix, but that site seems to have crashed. Avahi is a multicast DNS zeroconf (Bonjour-compatible) service discovery system. As the hint suggests, you should be able to find it for most Linux distributions.]
  Post a comment  •  Comments (3)  
  • Currently 5.00 / 5
  • 1
  • 2
  • 3
  • 4
  • 5
  (2 votes cast)
 
[4,844 views] Email Article To a Friend View Printable Version
Automatically cd to active Finder directory in new Terminal window UNIX
There exist small apps that will open a new Terminal window or tab and automatically cd to the directory of the active Finder window. This hint describes a way to have the Terminal always cd to the directory of the active Finder window whenever you open a new Terminal window or tab -- without the use of an app or any other third-party solution.

In other words, whenever you open a Terminal window or tab, if there is an open Finder window, the Terminal will start in the directory shown in the Finder window.

To make this happen, all you need to do is add the following line somewhere in your .bash_profile file in your home directory:
cd `osascript -e 'tell application "Finder" to if window 1 exists then if target of window 1 as string is not ":" then get POSIX path of (target of window 1 as alias)'`
To edit your .bash_profile file, open Terminal and enter the command:

open ~/.bash_profile -a TextEdit

Paste the code on an empty line anywhere in the file, and save the file. If Terminal complains that .bash_profile doesn't exist, create it with this command:

touch ~/.bash_profile

Then edit it as described.

If you want a quick way to cd to the active Finder directory manually, add the following code to your .bash_profile:
alias cdf='cd `osascript -e "tell application \"Finder\" to if window 1 exists then if target of window 1 as string is not \":\" then get POSIX path of (target of window 1 as alias)"`'
Upon opening a new Terminal window, you'll be able to cd to the active Finder directory by just entering cdf at the prompt. If you'd rather use a different shortcut, substitute your own string in the above code, after 'alias ' and before the equals sign.

(The alias hint is similar to this hint, but discovered independently.)

Note: If you use the 'cdf' alias when there is no open Finder window, or when the active Finder window is showing something other than a directory, you will be taken to your home directory.

[crarko adds: I tested this, and it works as described.]
  Post a comment  •  Comments (14)  
  • Currently 4.50 / 5
  • 1
  • 2
  • 3
  • 4
  • 5
  (6 votes cast)
 
[5,262 views] Email Article To a Friend View Printable Version
10.7: Disable alternate screen use in xterm terminals UNIX
In Lion the xterm terminal settings have been updated and now emacs, vi, less, pine, and more, among others use the 'alternate screen' feature in which the screen is cleared after the process quits. Here is a way to restore the previous behaviour, in which the final screen remains in the scrollback.

I found this in a post by Chris Johnsen, who explains how it works.

For example let us suppose that you are using the default terminal: xterm-256color. (See Terminal.app>>Preferences>>Settings>>Advanced.) At the command line type:

infocmp | sed -e 's/[sr]mcup=[^,]*,//' > /tmp/noaltscreen-terminfo

Press Return and then type:

tic -o ~/.terminfo/ /tmp/noaltscreen-terminfo

This creates a file ~/.terminfo/78/xterm-256color in your home directory. When you open a new Terminal.app window the local file is used, while other users get the default Lion behavior.

[crarko adds: I haven't tested this one. In the referenced post above it is also suggested that the command man something | more will accomplish the same effect just for man pages without changing the overall behavior of the terminal.]
  Post a comment  •  Comments (5)  
  • Currently 4.33 / 5
  • 1
  • 2
  • 3
  • 4
  • 5
  (3 votes cast)
 
[3,789 views] Email Article To a Friend View Printable Version
Running winexe on the Mac UNIX
If you are a Unix admin and also have to maintain Windows servers, you will find winexe a must command line utility to have in your arsenal.

Until recently I have been able to do this only on Linux boxes. I have compiled it and it works great however, on Mac OS X I have not had any luck until a few days I came across this site. There are also links provided to the winexe binary packages here.

So, once you install it, the usage is simple:

Here is a quick exemple.

To get the route table on the Windows machine (using your correct IP address and other appropriate information):

winexe -U YOURDOMAIN/YourAccount%YourPassword //172.16.2.xxx 'route print'

If you want to start a Windows service:

winexe -U YOURDOMAIN/YourAccount%YourPassword //172.16.2.xxx 'net start "Service Name"'

Or to kill a Windows service:

winexe -U YOURDOMAIN/YourAccount%YourPassword //172.16.2.xxx 'Process.exe -k 1110'

[crarko adds: I haven't tried this, but the first link will get you to the source code (GPL) so you can examine and build it for yourself. The second link points to a number of useful tools you can run in Terminal to work with Windows machines. I did a quick check of MacPorts and Fink and they didn't seem to have winexe, at least not as a standalone package.]
  Post a comment  •  Comments (3)  
  • Currently 4.00 / 5
  • 1
  • 2
  • 3
  • 4
  • 5
  (2 votes cast)
 
[5,171 views] Email Article To a Friend View Printable Version
10.7: Use Terminal proxy icons in zsh UNIX
The useful site macosxautomation.com reveals that Terminal.app in Lion can use proxy icons, those document icons to the left of the window title in many apps. Right-clicking on that icon opens a menu and you can open your current directory (or its parents) in the Finder. You can also drag the proxy icon onto the desktop to create an alias to your current directory.

If you don't use bash (the default shell on Mac OS X), you won't see the new proxy icons, though.

Here's how I extended the proxy icons feature to zsh. To work, your shell has to use special escape codes to pass the current directory to Terminal.app. This is the same mechanism used to set custom title bars.

Apple placed code in /etc/bashrc to support proxy icons. With slight modification, that code can go into your ~/.zshrc and do the same thing:
update_terminal_cwd() {
    # Identify the directory using a "file:" scheme URL,
    # including the host name to disambiguate local vs.
    # remote connections. Percent-escape spaces.
    local SEARCH=' '
    local REPLACE='%20'
    local PWD_URL="file://$HOSTNAME${PWD//$SEARCH/$REPLACE}"
    printf '\e]7;%s\a' "$PWD_URL"
}
autoload add-zsh-hook
add-zsh-hook chpwd update_terminal_cwd
update_terminal_cwd
The update_terminal_cwd function is Apple's, taken from /etc/bashrc. The last three lines are mine. They set up the proxy icon at the beginning of the shell session, and cause it to be updated every time you change directory. The code to do that in bash won't work in zsh.

[crarko adds: I haven't tested this one.]
  Post a comment  •  Comments (4)  
  • Currently 5.00 / 5
  • 1
  • 2
  • 3
  • 4
  • 5
  (1 vote cast)
 
[4,115 views] Email Article To a Friend View Printable Version
10.7: Re-enable syslogd for incoming connections UNIX
I like to have all my logs in one place, so I was using syslogd's network listening on my 10.6 Server to let my router send its logs to it. After updating to 10.7 the plist was reverted to its default state, preventing what I was used to. This hint explains what to do, to get it working again.

First make a backup of the plist, then do the following:

Convert it to XML so it's editable:

sudo plutil -convert xml1 /System/Library/LaunchDaemons/com.apple.syslogd.plist

Edit the file; I used pico with this command (you can also use TextWrangler, etc.):

sudo pico /System/Library/LaunchDaemons/com.apple.syslogd.plist

You need to insert this key:
<key>NetworkListener</key>
 <dict>
        <key>SockServiceName</key>
        <string>syslog</string>
        <key>SockType</key>
        <string>dgram</string>
 </dict>
Convert the plist back to binary format: 2br sudo plutil -convert binary1 /System/Library/LaunchDaemons/com.apple.syslogd.plist

Unload and reload syslogd:

sudo launchctl unload /System/Library/LaunchDaemons/com.apple.syslogd.plist
sudo launchctl load /System/Library/LaunchDaemons/com.apple.syslogd.plist


Afterwards check Console.app for incoming logs from your router, etc.

[crarko adds: I haven't tested this one.]
  Post a comment  •  Comments (11)  
  • Currently 3.75 / 5
  • 1
  • 2
  • 3
  • 4
  • 5
  (4 votes cast)
 
[9,454 views] Email Article To a Friend View Printable Version
View currently open network connections UNIX
Do you *know* what ports you have open on your machine or your server? Do you know what processes are communicating with what machines on the net, and as which user? If you are curious about these things, this script might be for you!

This is a bash-script that runs in the background (via launchd) and gathers information about what currently open network connections your machine have, both outgoing and incoming (listening) ports. It does so every two minutes. When the script is run by root, it gathers the data; when run as any other user it displays the data.

You can use this in conjunction with GeekTool to always see the data on your screen. Here is the script:
#!/bin/bash
# Script to install open_ports.sh
# 2011-05-05 / Peter Mˆller, Datavetenskap, LTH
# Location: 
# http://fileadmin.cs.lth.se/cs/Personal/Peter_Moller/scripts/open_ports_install.sh


# Make sure the user is "root"
if [ ! "$USER" = "root" ] ; then
  echo "Must be run by root!"
  echo "Exiting..."
  exit 1
fi

# BINDIR points to the "binary"
BINDIR="/usr/bin"
# PREFIX points to where all the datafiles are stored
PREFIX="/Library/cs.lth.se/OpenPorts"
# IP_CACHE is a growing list of IP-addresses and their geo location. 
# Since this is being used by other scripts, it's not in the OpenPorts directory
IP_CACHE="/Library/cs.lth.se/ip_cache.txt"
# EXTERN stores the computers "external" address. Checked hourly
EXTERN="$PREFIX/ExternIP.txt"
# FILE4 stores current IPv4-ESTABLISHED connections. Generated every two minutes!
FILE4="$PREFIX/ip4.txt"
# FILE6 stores current IPv6-ESTABLISHED connections. Generated every two minutes!
FILE6="$PREFIX/ip6.txt"
# FILE_LISTEN stores current LISTEN connections. Generated every two minutes!
FILE_LISTEN="$PREFIX/listen.txt"
# CHECKSUM stores a sha1-checksum for the lsof-binary. Cheched every two houres
CHECKSUM="$PREFIX/Checksum.txt"
# IP_LOCATE_CACHE is a temporary file that stores the geo location of the computers external address
IP_LOCATE_CACHE="$PREFIX"/ip_locate_cache.txt


# Fetch and launch the launchd-component
echo "Fetching launchd-component"
curl -o /Library/LaunchDaemons/se.lth.cs.open_ports.plist http://fileadmin.cs.lth.se/cs/Personal/Peter_Moller/scripts/se.lth.cs.open_ports.plist
chmod 644 /Library/LaunchDaemons/se.lth.cs.open_ports.plist
launchctl load /Library/LaunchDaemons/se.lth.cs.open_ports.plist
launchctl start se.lth.cs.open_ports
echo
echo

# fetch the script
echo "Fetching main script"
ScriptName="open_ports.sh"
curl -o /tmp/${ScriptName} http://fileadmin.cs.lth.se/cs/Personal/Peter_Moller/scripts/${ScriptName}
curl -o /tmp/${ScriptName}.sha1 http://fileadmin.cs.lth.se/cs/Personal/Peter_Moller/scripts/${ScriptName}.sha1
if [ "$(openssl sha1 /tmp/${ScriptName} | awk '{ print $2 }')" = "$(less /tmp/${ScriptName}.sha1)" ]; then
  mv /tmp/${ScriptName} ${BINDIR}/${ScriptName}
  chmod 755 ${BINDIR}/${ScriptName}
else
  echo "Checksum does NOT match!! Installation aborted!"
  exit 1
fi
echo
echo

# Create the directory for the files and set the access rights
mkdir -p "$PREFIX"
chmod 755 "$PREFIX"
touch "$FILE4" "$FILE6" "$IP_CACHE" "$IP_LOCATE_CACHE"
chmod 666 "$FILE4" "$FILE6" "$IP_CACHE" "$IP_LOCATE_CACHE"

echo "Done installing base parts of \"open_ports.sh\". Now proceeding to install GeekTool"
echo

echo "Fetching GeekTool"
# Get GeekTook
curl -o /tmp/GeekTool.dmg http://update.tynsoe.org/geektool3/Public/GeekTool%203.0.dmg
hdiutil mount /tmp/GeekTool.dmg
open /Volumes/GeekTool\ 3/
say "Done installing base parts of open ports. Now you will have to install GeekTool yourself"

exit 0
Installation
  • Save the install script.
  • Start Terminal.
  • Become root: if you are a normal user, type sudo adminusernamne and then sudo -i; if you are an admin user, type sudo -i.
  • Set access rights for the install script: chmod 755 open_ports_install.sh (you must locate it).
  • Run the script: ./open_ports_install.sh.
  • The installation is normally quick. It ends with GeekTool being opened. To install it, double-click its .PrefPane
  • In GeekTool: click the icon named "Shell" and drag it to an empty part of the desktop (must be free of windows). Size it as well.
  • A "Properties" window opens. What you need to enter is:
    • Command: open_ports.sh
    • Refresh every: 120 s
    • Change font to a monospace one (I'm using Menlo and white font color)
  • Now you may close GeekTool
Note that GeekTool doesn't move things around if you change the number of monitors (for instance a portable computer with external displays). It will, however be visible again when you restore the monitor setting.

Also note that the script will start automatically after a reboot.

Update the script

The script auto-updates once per week. You can also update the script manually by running, as root, the following command in a terminal window:

open_ports.sh -u

It will fetch the latest version of the script and install it (if it is different that what you have). If you already have the latest version it will tell you!

You'll find the script and further information here.

Oh, and it runs on Linux as well (the exact same script -- different installer though). It also updates itself every two weeks if there's a new version available.

[crarko adds: I haven't tested this one.]
  Post a comment  •  Comments (21)  
  • Currently 1.28 / 5
  • 1
  • 2
  • 3
  • 4
  • 5
  (18 votes cast)
 
[8,269 views] Email Article To a Friend View Printable Version
A script to automatically open a Terminal window to its directory UNIX
How many times have you been to a folder in Finder and needed a Terminal window open to that folder? For me, the answer was many. So, I wrote little AppleScript to take care of it automatically.

This script works by opening a Terminal window and cd'ing into the directory the script was in. Just copy the script into every folder you want to use if from; it's got a tiny footprint. Here's the code:
set myPath to (do shell script "dirname " & quoted form of (POSIX path of (path to me) as string)) as string
tell application "Terminal"
  activate
  do script ("cd " & quoted form of myPath)
end tell
Paste this into AppleScript Editor and save it as an application. Copy it into each folder you'll want to use it with.

I recommend naming it something like " Terminal" (the space in front will make it float to the top of a list of files).

And, it will Just Work. Double-click the app and Terminal will open with a new window cd'd to the folder where you just were in Finder.

[crarko adds: I tested this, and it works as described. We've run hints of this type before; here is another method.]
  Post a comment  •  Comments (25)  
  • Currently 2.70 / 5
  • 1
  • 2
  • 3
  • 4
  • 5
  (10 votes cast)
 
[6,069 views] Email Article To a Friend View Printable Version
Unix mail notifications via Growl UNIX
This tip lets you get a notification through Growl whenever new Unix mail arrives, with the subject of the mail. I get Unix mail as a result of run cron-jobs. I use cron because whether you have lingon or not; it is far easier to schedule a job with cron.

When there is something that I really want to watch from a process run by cron I do:

echo "the very interesting stuff" |mail -s "IMPORTANT" myusername

or some other Unix command to send the same mail message.

The problem is that I have to manually go into Unix mail and manually check if there is any new mail or not, and sometimes I just forget to do that.

Therefor I have made a notification in Growl via a launchd job and an AppleScript.

Prerequisites: You need to have installed Growl and Growl helper.

The lanchd process checks if your /var/mail/You mail file has changed, and if it has, the launchd process will run the script below and die until next time a new mail arrives and changes the mailfile. The AppleScript makes Growl show that there is a new mail with subject line of the last arrived mail in the bezel window.

Installation:

This script creates a Growl notification and must be placed somewhere on your disk. I have folder named .UserAgents for that purpose; to keep them collected. And a folder named .Processess for the jobs I run through cron via Cronnix.

The script must be installed via a property list file looking like the one given after the shell script below, except that you have to adjust it to insert the correct path for both the shell script and your mailfile.

You must also set its executable bit with the command chmod u+x from a Terminal window.
--------UnixMailNotifier.sh
#!/bin/bash
export mvar=`mail -H |tail -1 |sed -n 's/(..*")([^"][^"].*)(["].*)/2/p'`
/usr/bin/osascript <<-EOF 2>/dev/null 1>&2
  tell application "GrowlHelperApp"
    try
      set the allNotificationsList to ¬
        {"Unix Mail Notification"}
      set the enabledNotificationsList to ¬
        {"Unix Mail Notification"}
      register as application ¬
        "Growls Unix Mail Notification" all notifications allNotificationsList ¬
        default notifications enabledNotificationsList ¬
        icon of application "Terminal.app"
      
      --  Send a Notification...
      notify with name ¬
        "Unix Mail Notification" title ¬
        "Unix Mail Notification" description ¬
        "Subject: $mvar" application name "Growls Unix Mail Notification" icon of application "Terminal.app"
      
    on error the error_message number the error_number
      display dialog "Error: " & the error_number & ". " & the error_message buttons {"Cancel"} default button 1
    end try
    
  end tell
EOF
The property list file which must be installed in ~/Library/LaunchAgents looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>com.You.UnixMailNotifier</string>
  <key>Program</key>
  <string>/Users/You/.UserAgents/UnixMailNotifier.sh</string>
  <key>ProgramArguments</key>
  <array>
    <string>/Users/You/.UserAgents/UnixMailNotifier.sh</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <dict>
    <key>SuccessfulExit</key>
    <false/>
  </dict>
  <key>WatchPaths</key>
  <array>
    <string>/var/mail/You</string>
  </array>
</dict>
</plist>
After you have saved the property list file as (for instance) com.You.UnixMailNotification.plist you must start it with:

launchctl load com.you.UnixMailNotification.plist.

From there on you should get a notification whenever you get a Unix mail.

[crarko adds: I haven't tested this one. If there are any errors in either the script or the plist please let me know via the comments and I will correct them.]
  Post a comment  •  Comments (7)  
  • Currently 3.50 / 5
  • 1
  • 2
  • 3
  • 4
  • 5
  (2 votes cast)
 
[4,111 views] Email Article To a Friend View Printable Version