Bash socket programming with /dev/tcp(大家能联想到怎么使用吗)

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:

CODE:
  1. exec 3<>/dev/tcp/www.google.com/80
  2. echo -e "GET / HTTP/1.1/n/n">&3
  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!

上一篇:Linux虚拟机NAT上网


下一篇:[DevEpxress]GridControl 显示Gif动画