Bash sockets

Here's a neat trick with the Bash shell that I learned today: Bash can open and read sockets natively.

When I say "natively" I mean, having been compiled with the `--enable-net-redirections` flag. But if that part is true (and it's at least true in Xubuntu 10.10) then you can read and write to sockets this way:
exec 3<>/dev/tcp/host/port

# Write to the socket as with any file descriptor
echo "Write this to the socket" >&3

# Read from the socket as with any file descriptor
cat <&3
So you could do something like pull down Google's home page like so:
exec 3<>/dev/tcp/www.google.com/80
echo -e "GET / HTTP/1.1\n\n" >&3
cat <&3
For my team's project, we have some scripts that need to pull down logging and monitoring data and then push it to the monitoring server's daemon. We set up each script to output its data in the right format, then call the whole thing from a wrapper script that redirects the output to the monitoring daemon. Here's what it looks like:
# Takes a command and pipes the output to graphite server
# running on the local machine
# Usage: ./graphite-push.sh 


exec 3>$OUTFILE
$CMD >&3
And it's called like so:
graphite-push.sh php ./collect-stats.php --flag --arg value
The neat part is that `collect-stats.php` can be run on its own and will output to stdout. The `graphite-push.sh` script just runs whatever command it is given and redirects stdout to the monitoring daemon.

Many thanks to Dave Smith for this useful bit of shell magic.

No comments:

Post a Comment