Monday, October 15, 2007

Using Bash Script to check for a server connection in OS X

Many thanks to robinwmills over at macosxhints forums for the assist on this. I needed a script which would check for a server connection, and if that server was not present, attach the server with a name and password.

The issue here is that smb connections from an OS X box to a Samba/Windows box often just quit. It is a known issue requiring you to jump through fiery hoops to re-establish the smb connection. All I needed to do was dump some csv files to a location and let SQL Server 2005 handle the rest.

Here is the code:
#!/bin/bash
#checks to see if share is mounted
stat /L/windows >& /dev/null
if ( $status ) then
echo 'setting up mount on /L'
osascript -e 'mount volume "smb://domain;username:password@10.0.0.0/share"'
else
echo 'alive'
fi
#file manupilation
umount /Volumes/share

From what robinwmills explains:
stat does soemthing like ls - it lists directory/file information. I can't remember why I used stat instead of ls, however I don't think there was any special reason.

Anyway, I have the Share "L" on /Volumes/L (and a sym link /L -> /Volumes/L)

stat /L/windows >& /dev/null

says "pipe stdout and errout from stat to no-where". stat sets $status to 0 for success. So I can test to see if there is a windows directory on L. If you don't use the /L symlink trick, you could do stat /Volumes/L/windows >& /dev/null


What I did was establish the connection (authenticating to the domain controller) for only the amount of time needed to copy the files, then disconnect by umount'ing the volume. I'm sure there was probably a more graceful way of handling the disconnect, but it gets the job done. I had not yet ever used applescript from the shell before, that turned out to be quite handy, as well as the line for connecting to the share with a domain, username, and password. I just passed this off to my local cron bad boy, and this is running like a charm. I have used shell in applescript - I will definitely have to read up more on this.

I found it difficult peering through the search engines for this type of solution, so I will make sure that it get the proper tags.

Enjoy!

No comments: