[olug] Bash TCP scripting
Christopher Cashell
topher-olug at zyp.org
Sat Dec 29 02:44:14 UTC 2007
On Dec 28, 2007 3:32 PM, Travis Owens <openbook1441 at gmail.com> wrote:
> The information I've found so far on the net, show how to establish a
> connection, but not necessarily what to do with it after it's established...
I'd never try dealing with the low-level stuff from bash. Way too
much work, and not worth it. If you want to deal with connection
handling, I'd move up to something like Perl and Net::Server.
I've not used it, but I know there's a package out there (at least in
Debian), called tcputils, which is specifically intended to aid with
TCP programming in shell scripts. I don't know how low-level it gets,
though, or if it is more similar to some of the other options below.
My recommendation would be to let something else handle all of the
network bits, and just worry about the logic. The easiest way to do
it would be to run your script from inetd by adding the following line
(or translate for xinetd and other variants):
12345 stream tcp nowait nobody /usr/local/bin/yourscript.sh yourscript.sh
The biggest downside to this is the requirement for root access to set
it up and make changes to the network side. Another option would be
something like socat. Quick and dirty, you could do:
socat TCP4-LISTEN:8080,fork EXEC:/usr/local/bin/your-script-here
Or, if you really want to get fancy, and add additional security:
socat TCP4-LISTEN:12345,fork,tcpwrap=yourprogram
EXEC:/bin/yourprogram,chroot=/home/programuser,su-d=programuser,pty,stderr
Your script will fork on each connect, check against service
"yourprogram" in /ets/hosts.allow, chroot to /home/programuser and
execute /home/programuser/bin/yourprogram.
socat is one of the most uesful and nifty tools out there, kind of
like super-mega-netcat-on-steroids. The only downside is that it can
be a real pain to get the options all listed right. Googling for
examples can help immensely. Similar options would be socket,
netpipes, and even netcat. socat is my favorite of the bunch, though.
Any of these would work well enough for a short term or single shot
use.
If you're looking for something more reliable and long term, you can
also use some of the "designed" inetd replacements which are more
single-port, single-process tools. Examples include tcpserver,
superd, and ipsvd. Each of these is specifically designed to allow a
non-network aware program access to networks. Generally, you use
stdin and stdout to read and write to a socket established by the
supervising program.
> --
> Travis Owens
--
Christopher
More information about the OLUG
mailing list