We can turn any process into a server in an incredibly simple manner using the powerful networking utility netcat
. For example, we can make a shell a server:
(a computer with ip address 192.168.1.2) $ mkfifo fifo # create a named pipe $ cat fifo | sh -i 2>&1 | nc -l 1234 > fifo # server (on another window) $ nc localhost 1234 # client (or if you're on the same netwok from another computer) $ nc 192.168.1.2 1234 # client
Now let’s try to understand the above-highlighted line. Noting that a pipeline runs in parallel, cat fifo
therefore outputs the content of fifo
only when nc -l 1234
writes its output to the pipe fifo
.
We know that when the client connects to the server via netcat
, if the client types in anything, it will be output to the server; and vice versa. Hence, nc localhost 1234
‘s input becomes nc -l 1234
‘s output, and nc -l 1234
‘s input becomes nc localhost 1234
‘s output.
When the client types in something, say, the command ls
, it also appears in the output of the server, which then is redirected to the pipe fifo
, which in turn goes to cat fifo
(read end comes the data). Then the output of cat fifo
(“ls”) is redirected to as the input of sh -i 2>&1
, which executes the command ls
and sends the results to the server nc -l 1234
as its input, which finally as output appears in the client nc localhost 1234
.
Isn’t it beautiful? Just setting a few pipes and redirections we can turn a process into a server. Pipes are really one of the greatest UNIX inventions. They make many incredible things possible.
See also using netcat
as a proxy.