Skip to content

Instantly share code, notes, and snippets.

@minimedj
Forked from gerjantd/gist:9787489
Created March 8, 2016 11:00
Show Gist options
  • Save minimedj/cd85641cd7f7af1fd250 to your computer and use it in GitHub Desktop.
Save minimedj/cd85641cd7f7af1fd250 to your computer and use it in GitHub Desktop.
Bash/nc: netcat as a simple telnet server
CLIENT/SERVER MODEL
It is quite simple to build a very basic client/server model using nc. On one console, start nc listening on a specific port for a connection. For example:
$ nc -l 1234
nc is now listening on port 1234 for a connection. On a second console (or a second machine), connect to the machine and port being listened on:
$ nc 127.0.0.1 1234
There should now be a connection between the ports. Anything typed at the second console will be concatenated to the first, and vice-versa. After the connection has been set up, nc does not really care which side is being used as a ‘server’ and which
side is being used as a ‘client’. The connection may be terminated using an EOF (‘^D’).
There is no -c or -e option in this netcat, but you still can execute a command after connection being established by redirecting file descriptors. Be cautious here because opening a port and let anyone connected execute arbitrary command on your site is
DANGEROUS. If you really need to do this, here is an example:
On ‘server’ side:
$ rm -f /tmp/f; mkfifo /tmp/f
$ cat /tmp/f | /bin/sh -i 2>&1 | nc -l 127.0.0.1 1234 > /tmp/f
On ‘client’ side:
$ nc host.example.com 1234
$ (shell prompt from host.example.com)
By doing this, you create a fifo at /tmp/f and make nc listen at port 1234 of address 127.0.0.1 on ‘server’ side, when a ‘client’ establishes a connection successfully to that port, /bin/sh gets executed on ‘server’ side and the shell prompt is given to
‘client’ side.
When connection is terminated, nc quits as well. Use -k if you want it keep listening, but if the command quits this option won't restart it or keep nc running. Also don't forget to remove the file descriptor once you don't need it anymore:
$ rm -f /tmp/f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment