0

Could anyone give me directions as for how to write a shell script that constantly listens to a port and when someone/something sends an HTTP request to that port, it executes an action as sudo?

I need to restart nginx from another server and SSHing to this server isn't an option. So I'm looking for means to achieve that. My idea is to have Server A constantly listening to a port and when there's a request on that port sent from Server B, Server A restarts nginx.

Security shouldn't be a problem. I'll write the shell script on Ubuntu 14.0.4 LTS

Edward Leoni
  • 11
  • 1
  • 2

1 Answers1

2

It would be possible to use Netcat to listen to a specific port (12345 in the example provided) and then check its output for what was received such as:

while test 1 # infinite loop
do
    nc -l localhost 12345 > /tmp/12345.log

    # check for start
    grep start /tmp/12345.log > /dev/null

    if test $? -eq 0 
    then
        startJob&
    else
        # check for stop
        grep stop /tmp/12345.log > /dev/null

        if test $? -eq 0 
        then
            stopJob&
        fi
    fi
done

That said, it would be simpler and easier to expand a web based solution.

Julie Pelletier
  • 1,010
  • 7
  • 8
  • Hi, thanks for this answer, that's absolutely what I needed. However I'm uncertain as for what this piece of code does exactly: if test $? -eq 0 then startJob& else # check for stop grep stop /tmp/12345.log > /dev/null if test $? -eq 0 then stopJob& fi fi – Edward Leoni May 21 '16 at 04:31
  • `$?` is the return code from the last command. `grep` returns `0` on success (found) or `1` on error. – Julie Pelletier May 21 '16 at 05:01
  • I have changed the code to echo on the screen in several lines, on the first if, on the second if and on the else... It never echoes anything, that would probably mean it's not working, right? Cuz I access the port from my browser, my headers are loged on the log file, but the echoes don't show a thing – Edward Leoni May 21 '16 at 05:23
  • Well if all you want is to start a process when the port is accessed, you can remove most of the code. My logic allowed the front-end to send `start` and `stop` commands. I actually think it would probably work if you pass them as GET parms but don't have time to test it just now. – Julie Pelletier May 21 '16 at 05:34
  • @JuliePelletier, and what's the compatability of `nc`? What to do when there's no netcat? – Pacerier Apr 22 '23 at 03:42