http://pangty.ta139.com/bash-guide/abs3.7cnhtm/devproc.html
Today I discovered a nifty way to do socket programming in bash without the need for netcat (nc) or telnet: /dev/tcp. Say you want to connect to Google and fetch their front page. Just do this:
-
exec 3<>/dev/tcp/www. google. com/ 80
-
echo -e "GET / HTTP/1.1/n/n">& 3
-
cat <& 3
I found this very handy when trying to connect to a host and read some info from a socket, but I wanted to do it all in a few lines of bash. This is great, because you don't have to worry about what version of Python or Perl your users will have. If they've got bash, you're set. There is one caveat: some systems (Debian included) don't enable /dev/tcp. I don't know why, but they don't. So make sure your target system has it before coding this up. Oh, and you can use /dev/udp too if you really want to spice things up!
Where does this come from? It turns out it's a pure bashism, which has to be enabled when you compile bash. Bash actually intercepts "/dev/tcp" and provides special behavior, so you're not actually opening a device node called /dev/tcp. Pretty cool, eh?!
Happy bashing!