Showing posts with label unix shell. Show all posts
Showing posts with label unix shell. Show all posts

Wednesday, March 26, 2008

Cygwin: Unix filenames from Windows filenames

Here's a bash script that will help Cygwin reference Windows filenames. It could work under /bin/sh, but I wrote is as part of a bash .profile, so I've only tested it there.


#!/bin/bash
#
# sanify - turn a Windows path name into a Unix name
# - turns drive letters into /cygdrive/drive,
# - flips slashes, removes enclosing quotes,
# - replaces unusual characters with '?'

function usage() { cat <<"EOF"
Usage: $1 'Windows filename'
... where 'Windows filename' only has to be in quotes if
it has special characters, such as backslashes or spaces.
This is free.
EOF
}

function sanify() {
echo ${@} | sed \
-e 's,^[A-Za-z]:,/cygdrive/&,'\
-e 's,:,,g' \
-e 's,\\,/,g' \
-e 's,^\",,g' \
-e 's,\"$,,g' \
-e 's,[^A-Za-z0-9_\.-],\?,g'
}

if [ -t ] ; then
[ -z "$@" ] && { usage "$0" }
sanify "${@}" else
for name in `cat` ; do
sanify "${name}"
done
fi

Wednesday, October 24, 2007

Exceed, Cygwin, and Terminal Server

... or "How to waste an afternoon"

I've been having trouble getting the combination of MS Terminal Server 2003, Hummingbird Exceed 2006, and Cygwin to work together.

Cygwin's Xfree86 doesn't work well for Terminal Server, since Cygwin's X has one global X.log file that is owned by and read-only for only one user at a time. So we use Hummingbird Exceed on the Terminal Server.

But Exceed doesn't come with xterm, ssh, etc. They expect you to use rsh, rexec, or a program you configure with their proprietary goo to connect to your remote systems. Not my style.

Background

X programs running on a remote host can display on your computer through the use of a lot of complicated technology, much of which depends on a properly set environment variable named DISPLAY. It's format is

DISPLAY=your.hostname:N.m

where "your.hostname" is either the domain name your ISP gives you, an IP address, or the special name "localhost". All computers on the Internet believe that they themselves are "localhost".

Ssh programs (either the proprietary ones from SSh, Inc., or free versions such as openssh or putty) have a wonderful feature: they can hijack data to be sent to your local computer, encrypt it, send it over their secure connection, and deliver it to your local computer for display. They do this by setting the remote DISPLAY variable to (for example) "localhost:10.0". Remote programs you run send their output to remote display 10, screen 0. Ssh receives the data, encrypts, delivers, decrypts, and sends to whatever your local DISPLAY variable says.

But I've not been able to find a Windows-based Ssh program that is able to tunnel X11 connections with remote hosts to Exceed. In the past, I've just looked at the display number in the Exceed taskbar button and set DISPLAY manually, losing the benefits of tunneling.

A little digging turned up some documentation (pdf), which says:

While Exceed sessions are running, the display numbers are tracked through a dynamic file called Display Snapshot.HumTable. This is located in

C:\Documents and Settings\All Users\Application Data\Hummingbird\Connectivity\11.00\Global\Exceed\Display Snapshot.HumTable

As this is dynamic, it should not be edited manually.
Ok, now I know what to do. I can grab the DISPLAY number from that file, which by the grace of Hummingbird is a text file and not more proprietary goo. Unfortunately, it's a Windows file, with an ugly filename with spaces in it. So I need a script to turn that into a Cygwin name:

In /etc/profile on your Terminal Server, put the following:


HUMTABLE="C:\Documents and Settings\All Users\Application \
\Data\Hummingbird\Connectivity\11.00\Global\Exceed\Display Snapshot.HumTable"

#
# sanify - turn a Windows directory name into a Unix name
# - turns drive letters into /cygdrive/drive,
# - flips slashes, removes enclosing quotes,
# - replaces unusual characters with '?'
function sanify() {
echo ${@} | sed \
-e 's,^[A-Za-z]:,/cygdrive/&,'\
-e 's,:,,g' \
-e 's,\\,/,g' \
-e 's,^\",,g' \
-e 's,\"$,,g' \
-e 's,[^A-Za-z0-9_\.-],\?,g'
}
# disp() grabs the information from the Humtable file
# and puts it in the right format.

DOMAIN=your_windows_domain

function disp() {
EX_LF="`sanify ${HUMTABLE}`"
[ -r $EX_LF ] && {
cat $EX_LF | awk -v d=$DOMAIN u=${USERNAME} \
'BEGIN {FS=","}\
$3 ~ d "." u {print "localhost:" $4 ".0";}'
}
}
export DISPLAY=`disp`


[Updated 20071026 to touch the script a bit]

Tuesday, September 25, 2007

Script for OpenSSL Certificate Signing Request

[Updated for bugfix 20080722] If you're like me, you need a new SSL Certificate about once a year. You know what to do:
  1. Generate a "Certificate Signing Request" and a key
  2. Send the CSR to your Certificate Authority for signing
  3. Wait for the signed Certificate to come back from the CA
  4. Put the key and the Certificate where your web, email, or other server can find them

I always have to look up the right openssl(1) command line arguments.

This year, I decided to make a script. This script takes an optional argument, the host for which you're making the certificate. I suggest generating the Certificate on the target host, but if you feel bold you can make a CSR for any host you want.

#!/bin/sh
#
#############################
#
# Shell script to automate making
# Certificate Signing Requests (CSR)
# with openssl
#
# tested on v 0.9.8e
# Loren Heal
#
#############################

echodo() {
echo "${@}"
(${@})
}

yearmon() {
date '+%Y%m%d'
}

fqdn() {
(nslookup ${1} 2>&1 || echo Name ${1}) \
| tail -3 | grep Name| sed -e 's,.*e:[ \t]*,,'
}


C=Your_Country_Abbreviation
ST=Your_State_Spelled_Out
L=Your_City
O="Your Company or Whatever"
OU="Your Office or Department or Whatever"
HOST=${1:-`hostname`}
DATE=`yearmon`
CN=`fqdn $HOST`

csr="${HOST}-${DATE}-csr.pem"
key="${HOST}-${DATE}-key.pem"

openssl req -new -newkey rsa:1024 -keyout $key \
-nodes -out $csr <<EOF
${C}
${ST}
${L}
${O}
${OU}
${CN}
$USER@${CN}
.
.
EOF
echo ""

[ -f ${csr} ] && echodo openssl req -text -noout -in ${csr}
echo ""

Wednesday, August 22, 2007

Programs I Want to Write

A Shell script compiler

A To Do / Project manager

A better (robust, complete, elegant) compiler language

A March Madness tournament picker

A GUI for script writing

Monday, July 23, 2007

Troublesome Filenames

smith: In my public_html directory there are subdirectories called "~backup" and "~smith". "Backup" is the name we use for file archival of old work. When I cd to them I'm taken to some home directory. What's going on?

me: That looked funny at first, but I think it's ok.

A ~ (tilde) character is shell-ese for a home directory, either your own by itself or that of a given user with "~username". So when you entered "cd ~smith", it actually took you to your home directory. The /public_html/~smith thing is a real directory with a tilde as the first character of the name. You can create a directory with that name by typing

        mkdir public_html/~smith
The tilde is only interpreted as a home directory when it's the first character of a directory name, and only by csh/tcsh/zsh/ksh. Shell scripts are typically interpreted by the Bourne shell (/bin/sh), which doesn't know what "~smith" means, so sometimes shell scripts will create files named like that.

Entering

        cd ~smith/public_html/~smith
took me to a directory that didn't look like your home directory. I renamed public_html/~backup to public_html/backup and public_html/~smith to public_html/smith.

There are other misbehaving filenames. Usually they come about the same way the "public_html/~smith did: UNIX file systems allows filenames to contain characters that are special to some command interpreters. For example, a mistaken cut-and-paste operation can generate several spurious commands, perhaps creating files with random names. Misbehaved filenames may make it hard to work with files, even in the newer shell programs.

For instance, files beginning with a hyphen ("-") will confound some commands. If you have a file named "-h" and try to do anything to it, the usual commands such as mv, cp, or rm will interpret the name as a command line switch and tell you you're typing the command incorrectly:

~/temp me@server 8:48> ls -l
total 0
-rw-r--r-- 1 me mygroup 0 Feb 20 08:46 --help
-rw-r--r-- 1 me mygroup 0 Feb 20 08:46 -h

~/temp me@server 8:48> rm -h
rm: illegal option -- h
usage: rm [-fiRr] file ...
zsh: exit 2 rm -h

~/temp me@server 8:48> mv -h goodname

mv: illegal option -- h
mv: Insufficient arguments (1)
Usage: mv [-f] [-i] f1 f2
mv [-f] [-i] f1 ... fn d1
mv [-f] [-i] d1 d2
zsh: exit 2 mv -h goodname
The solution is to specify a path name for the file, either an absolute path as in /usr/local/bin/--badfile, or a relative path such as "./" (dot forward-slash, meaning the current directory).
~/temp me@server 8:48> rm ./-h    
~/temp me@server 8:48> mv ./--help goodname
~/temp me@server 8:48> ls -l
total 0
-rw-r--r-- 1 me mygroup 0 Feb 20 08:46 goodname

Other inconvenient filenames can require a "\" (backslash) to quote characters that are special to the shell, such as "-" (hyphen), "~" (tilde), " " (space). The newer shells offering command-line completion will automatically quote the characters for you.

Advanced users may wish to apply the stream editor sed to the problem.

For a list of names of punctuation marks, I recommend the Wikipedia entry.

Wednesday, June 20, 2007

More sed Tricks

Sometimes I think sed(1) is the reason I like Unix. Well, it's one of the quintessentially Unix tools, anyway.

One of my favorite uses for sed is to rename a whole bunch of files all at once. Whether the problem is a spaces or other special characters in filenames, capitalization problems, or whatever, as long as you can see a pattern sed can probably fix it for you.

For instance, I just had to make a whole bunch of symbolic links to some files

audit_user.dir
auto_data.pag
auto_master.dir
exec_attr.pag
....

so that the links had the names:

audit.user.dir
auto.data.pag
auto.master.dir
exec.attr.pag

and so on. Sed to the rescue:

for f in *_* ; do
ln -s $f `echo $f | sed -e 's,_,.,'`
done
(If you try something like that, put an "echo" before the "ln" to test it out)

That's a fairly simple example, and in fact the Unix C-shell has that kind of search-replace built in. I don't use C-shell, because the standard Bourne shell /bin/sh and derivatives (such as the Bourne Again SHell /bin/bash) are better for scripting.

But consider the problem of turning off some, but not all, of the "init scripts" under a particular runlevel in a typical SystemV-style system, such as Solaris or Linux. Red Hat Linux solves this with the chkconfig command, and Red Hat admins may like to use that handy facility.

But for those of us who have heterogenous collections of systems to worry about, and even on Red Hat systems when digging under the hood, it would be nice to have a way to turn off (or on) several services at once.

A "runlevel" is sort of like a system mode, and the levels are not standardized but generally follow a pattern of sorts. The chkconfig link above gives a nice description of runlevels for Linux, but note that while under Linux runlevel 5 means X Window operation, under Solaris it means shut down.

In a System V-style system, the init scripts themselves are stored in /etc/init.d, with some reasonable name like 'apache' for the Apache web server or 'autofs' for the file system automounter.

Each runlevel has its own directory, /etc/rcN.d, which contains symbolic links to the init scripts in /etc/init.d. To control how a particular runlevel uses a given init script, the symbolic link is prepended with an "S" for Start, "K" for Kill, or sometimes another letter, which means to ignore. After the S or K is a number, like 01 or 25, used to sort the names. The init(1) processing runs each S script in alphanumerical order, so that services should get higher numbers than the more basic services on which they depend.

Renaming the files is a bit of a hassle, either from the command line or with a GUI, because each one must be done. From the command line in particular, changing just the first letter requires typing the whole file name, with the numbers.

So what has all of this to do with sed?

This little script renames all the files matching a list of patterns you supply, either from S##name to K##name or the other way. It preserves the numbers, without you having to type the whole name.
#!/bin/sh
#------------------------------
# Script : s2k Copyright 2000,Loren Heal
# Author : lheal
# Created: 20010305
# Known Bugs:
# TODO: only operates on current directory.
#(------------------------------
FROM=S
TO=K
FORCE=""
TEST=""

usage()
{
echo "$1 [-on|-off|-force|-test] expression [...]"
echo ... where "expression" matches one or more of:
ls -F ${FROM}*
exit
}

[ -z ''"${@}" ] && usage "${0}"

while [ -n "$1" ] ; do
# echo "$1"
case ${1} in
"-on" ) FROM="K"; TO="S" ;;
"-off" ) FROM="S"; TO="K" ;;
"-force" ) FORCE="-f" ;;
"-test" ) TEST="echo" ;;
* ) for fname in `ls ${FROM}*${1}*` ; do
tname=`echo ${fname} | sed "s/^${FROM}/${TO}/"`
if [ -n "${tname}" -a -n "${fname}" -f ${fname} ] ; then
&& ${TEST} mv ${FORCE} ${fname} ${tname}
fi
done
;;
esac
shift
done

Monday, May 14, 2007

Fun with find, sed and xargs

[See below for update 20070807]
Common tasks for Unix system administrators often require working with all of the files in a directory tree and selectively doing something with some of them: copying, deleting, renaming, or moving them, or simply getting a list of files matching certain characteristics.

Sometimes we want to do something from the Unix command line with files that have spaces in their names. Let's see what we can do with our friends find(1), sed(1), and xargs(1).

Find looks for entries in some directory matching its arguments, typically sending a list of them to the standard output. Sed is the Stream EDitor, and applies a series of commands to transform its input into its output. Xargs supplies its input to the command line of any program.

First, let's set up our little foobox:
$ cd /tmp
$ mkdir foo
$ touch 'foo/file with spaces'
$ touch 'foo/bar'
$ touch 'foo/another file with spaces'
$ ls -1 foo
another file with spaces
bar
file with spaces

Now lets's do a simple find:

/tmp $ find foo -type f
foo/file with spaces
foo/bar
foo/another file with spaces

Now let's do something with those files. Let's just list them:

/tmp $ find foo -type f | xargs ls
foo/file: No such file or directory
spaces: No such file or directory
foo/another: No such file or directory
file: No such file or directory
with: No such file or directory
spaces: No such file or directory
foo/bar

What happened? Xargs delivered its input to the command line of ls(1), which interpreted the spaces in the filenames as new filenames. We need to escape the spaces inside the names for ls, but leave the spaces surrounding the filenames. That's just the sort of thing sed likes to do:

/tmp $ find foo -type f | sed 's, ,\\&,g'| xargs ls -ltr
-rw-r--r-- 1 user group 0 May 11 12:12 foo/file with spaces
-rw-r--r-- 1 user group 0 May 11 12:12 foo/bar
-rw-r--r-- 1 user group 0 May 11 12:12 foo/another file with spaces

In the dorky sed command between the single quotes, the "s" means to substitute for the text matched by the pattern between the first and second delimiter the text between the second and third delimiters. I like to use commas as delimiters instead of slashes, though any character will do. Slashes often appear in path names, and by habitually using commas I avoid errors when I fail to escape the slashes.

The pattern, called a regular expression, in this case says to look for a space, and replace it with a backslash followed by the text we just found. This is sed-ese for "prepend a backlash".

A slightly more general approach is to wrap each filename with single quotes. You still run into a problem with filenames which have single quotes in them, but you shouldn't put quotes in filenames:

$ find foo -type f | sed -e "s,[^.],\'&," -e "s,\$,\',"

'foo/file with spaces'
'foo/bar'
'foo/another file with spaces'

$ find foo -type f | \
sed -e "s,[^.],\'&," \
-e "s,\$,\'," | \
xargs ls

foo/another file with spaces
foo/file with spaces
foo/bar


Sharp reader Nic Ivy has noted a far simpler way to deal with spaces in filenames for find(1) and xargs(1), which also deals with other special characters like quotes and greater-than or less-than symbols:

$ find foo -type f -print0 | xargs -0 ls

foo/another file with spaces
foo/file with spaces
foo/bar

From the Unixhelp xargs(1) man page:

--null, -0
Input items are terminated by a null character instead of by
whitespace, and the quotes and backslash are not special (every
character is taken literally). Disables the end of file string,
which is treated like any other argument. Useful when input
items might contain white space, quote marks, or backslashes.
The GNU find -print0 option produces input suitable for this
mode.


Man pages courtesy UnixHelp.