Webserver in bash - execute bash command

Webserver in bash - execute bash command

Do you want a quick, dirty, and unsafe way to execute commands to your Linux box over HTTP? You can use the following hack! I don't recommend using this for a production system or something more important than a hobby project.

Save the following file as webserver.sh

#!/bin/bash

while true; do echo -e "HTTP/1.1 200 OK\n\n$($1)" | nc -l -k -p 8080 -q 1; done

Make it executable:

chmod 755 ./webserver.sh

Time for testing! We will execute ps aux in every HTTP request towards port 8080 of our computer

~] $ ./webserver.sh "ps aux"

Use wget to get output from bash script:

~] wget -q -O - 127.0.0.1:8080 
USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root           1  0.0  0.1 164948 10256 ?        Ss   Oct20   0:25 /sbin/init
root           2  0.0  0.0      0     0 ?        S    Oct20   0:01 [kthreadd]
root           3  0.0  0.0      0     0 ?        I<   Oct20   0:00 [rcu_gp]
root           4  0.0  0.0      0     0 ?        I<   Oct20   0:00 [rcu_par_gp]
root           6  0.0  0.0      0     0 ?        I<   Oct20   0:00 [kworker/0:0H-events_highpri]
root           8  0.0  0.0      0     0 ?        I<   Oct20   1:33 [kworker/0:1H-kblockd]
root           9  0.0  0.0      0     0 ?        I<   Oct20   0:00 [mm_percpu_wq]
root          10  0.0  0.0      0     0 ?        S    Oct20   0:00 [rcu_tasks_rude_]
root          11  0.0  0.0      0     0 ?        S    Oct20   0:00 [rcu_tasks_trace]
root          12  0.0  0.0      0     0 ?        S    Oct20   0:21 [ksoftirqd/0]
...
  • -q turns off the output of log, including error information
  • -O -, equivlalent to -O /dev/stdout, means dump the web page to a file named /dev/stdout.

Also, we can see some output of the HTTP request to the console.

~] ./webserver.sh "ps aux"
GET / HTTP/1.1
User-Agent: Wget/1.21
Accept: */*
Accept-Encoding: identity
Host: 127.0.0.1:8080
Connection: Keep-Alive

How this works

while true; do echo -e "HTTP/1.1 200 OK\n\n$($1)" | nc -l -k -p 8080 -q 1; done
  • There is an always-executing loop using while true
  • nc command opens a listener on port 8080
  • On every click, the text passed as a parameter to the webserver.sh is executed, and its result, along with some HTTP headers is passed to nc which in turn sends to our browser.

SUBSCRIBE FOR NEW ARTICLES

@
comments powered by Disqus