Easy Code Share > More > Linux > Trigger Remote Shell Script on Linux via Http Browser

Trigger Remote Shell Script on Linux via Http Browser


We present a way to achieve: (1) http browser clients can trigger a remote script to run, (2) Windows browsers auto refresh status for remote system on Linux. Obviously, that give us an alternative view about what common HTML layout can do.

All codes here are not complicated, so you can easily understand even though you are still students in school. To benefit your learning, we will provide you download link to a zip file thus you can get all source codes for future usage.

Estimated reading time: 7 minutes

 

 

BONUS
Source Code Download

We have released it under the MIT license, so feel free to use it in your own project or your school homework.

 

Download Guideline

  • Prepare HTTP server such as XAMPP or WAMP in your windows environment.
  • Download and unzip into a folder that http server can access.
  • Prepare HTTP server such as Apache on Linux. For someone without Linux, it still works to build Linux virtual machine on Windows by freeware like Oracle VM VirtualBox.
  • Download and unzip into a folder that HTTP server can access.
 DOWNLOAD SOURCE

 

SECTION 1
The Basics

Let us show you our idea for the design that people can manage real-time remote scripts from HTML. Also, Browsers on Windows play an uncommon role just like the control panel.

 

HTTP Trigger Remote Script

In general, browsers take responsibility of displaying contents for users. Moreover, http browser clients can trigger a shell script on remote Linux servers. Thus people refer to browsers as not only a monitor, but also the control panel.

For example, a lot of Apache child processes are waiting for tasks to do. When Apache assigns a job to the red one, the red child process seems to obey a remote command to run an external shell script on Linux. That execution will invoke a running process or daemon like the green oval.

Windows Browser Run Remote Shell Script on Linux

Operationally, you can trigger stop action to stop script on remote sites. For demo, that process created by loopawhile.sh simply performs dummy looping. But you can replace it with meaningful or even any non-script executable programs in your projects.

loopawhile.sh
 #!/bin/bash
START=`date +%s` # seconds since 1970
while [ $(( $(date +%s) - 3600 )) -lt $START ]; do
    sleep 1
done

 

Simple Control Panel

Suppose that we are controlling each remote script by this panel. When you switch on a daemon upon HTML layout, the status turns green along with its process id shown. Otherwise for switching off, the status becomes idle.

Browser Control Panel Monitor 2 Processes

 

SECTION 2
Browser Control Panel

There are links between HTML and jQuery codes for monitoring and control. Especially for monitoring, when change occurs in server sites, browser clients will not know unless an iterated polling trigger automatic reporting from http.

 

Trigger to Start & Stop

The following HTML and CSS codes consitute the screen layout for control panel. Inside that, you can find that some HTML attributes id in <tr> and <input> are defined to link to jQuery codes.

browser-ctrl.html
.....
<table>
    <tr>
        <th width="20%">Switch</td>
        <th width="60%">Process</td>
        <th width="20%">Status</td>
    </tr>
    <tr id="p1">
        <td><input type="checkbox" id="1"></td>
        <td id="text">process 1 (stopped)</td>
        <td id="status">&ofcir;</td>
    </tr>
    <tr id="p2">
        <td><input type="checkbox" id="2"></td>
        <td id="text">process 2 (stopped)</td>
        <td id="status">&ofcir;</td>
    </tr>
</table>
.....
browser-ctrl.css
body {background:#FAD0A0; font-family:Arial; font-size:1em}
table {width:600px; border-collapse:collapse; margin:5%;}
table tr th, table tr td {border:2px none gray; padding:15px;}
table tr th {background:lightblue;}
table tr td {background:navy; color:white; text-align:center;}
@media only screen and (max-width: 720px){
    table {margin:0%; width:100%}
}

See jQuery codes below. When people switch a checkbox to start a remote script, sendout("start", id) sends an AJAX request to servers, where id could be 1 or 2. Similarly, if trying to stop a remote script, sendout("stop", id) does.

browser-ctrl.html
.....
$(document).ready(function() {
    $('input').on("change", function() {
        id = $(this).attr("id");
        ele = "tr#p" + id + " td input";
        if($(ele).is(":checked")) sendout("start", id); else sendout("stop", id);
    });
    executeQuery();
});
.....

For start/stop actions, AJAX response can be ignored. However, for getting status, it is essential to parse response in order to refresh control panel.

 

Trigger to Get Status

We embed a timer in HTML layout. Periodically, the timer executeQuery() checks status of each daemon through an AJAX query sendout("status").

browser-ctrl.html
.....
function executeQuery() {
    try {
        sendout("status");
        setTimeout(executeQuery, 3000); // milliseconds
    } catch (e) {
        console.log(e);
    }
}
.....

Once status is replied, the callback function parses response data as to turn to right colors for each daemon. In addition, the process column attaches pid (process id) information at the tail end. It helps operators see details inside remote Linux servers.

browser-ctrl.html
.....
var status_check = {"start":true, "stop":false};
var status_color = {"start":"lightgreen", "stop":"white"};
function sendout(req, tag = null) {
    postdata = { req: req, tag: tag };
    console.log(postdata);
    $.post("controller.php", postdata, function(data) {
        if (req != "status") return;
        console.log("recv:"+data);
        info = JSON.parse(data);
        for(key in info) {
            id = parseInt(key)+1;
            pid = info[key][0];
            status = info[key][1];
            $('tr#p'+id+' td input').prop("checked", status_check[status]);
            $('tr#p'+id+' td#text').html("process (pid="+pid+")");
            $('tr#p'+id+' td#status').css("color",status_color[status]);
        }
    });
}

 

SECTION 3
Execute Remote Script

Let us see what the AJAX server does for browser’s commands. Using Linux shell commands can produce running features of processes. The AJAX server filters them to get valuable items.

 

Start Remote Script

Usually on Linux, people issue shell commands to run a program as daemon process in background with directing stdout to the null device. Like the following.


controller.php
<?php
$proc = dirname(__FILE__) . '/loopawhile.sh';
switch ($_POST['req']) {
    default: echo "INVALID REQUEST"; break;
    case "start": start($proc, $_POST['tag']); break;
    case "stop": stop($proc, $_POST['tag']); break;
    case "status": status($proc); break;
}
function start($proc, $tag) {
    $cmd="sh $proc $tag > /dev/null &";
    exec($cmd);
}
function stop($proc, $tag) {
    $getpid="ps aux | grep '$proc $tag' | grep -v grep | awk '{ print $2 }' | head -1";
    exec($getpid, $out);
    if(isset($out[0])) exec("kill -9 $out[0] > /dev/null &");
}
function status($proc) {
    /* ps aux e.g,
       www-data 24184 0.0 0.5 226324 21776 ? S 16:11 0:00 sh loopawhile.sh 1
    */
    $cmd="ps aux | grep '$proc' | grep -v grep | awk '{ print $2\" \"$13 }'";
    exec($cmd, $out);
    $result = [[0,"stop"],[0,"stop"]];
    foreach($out as $p) {
        $q = explode(" ", $p);
        $result[intval($q[1])-1] = [$q[0], "start"] ;
    }
    echo json_encode($result);
}
?>

 

Stop Remote Script

To stop the process already running by a remote script, you have to search for its pid in advance, and then kill it. Command lines below tell you how the result of shell commands is parsed to retrieve pid as stop($proc, $tag) does.

www-data 24184 0.0 0.5 226324 21776 ? S 16:11 0:00 sh loopawhile.sh 1
$ ps aux | grep 'loopawhile.sh 1' | grep -v grep | awk '{ print $2 }' | head -1
24184

 

Get Status

To get status of processes already running by each remote script, you have to find both pid and argument tag from shell commands output. Where tag is the 13th part of the output.

www-data 24184 0.0 0.5 226324 21776 ? S 16:11 0:00 sh loopawhile.sh 1
$ ps aux | grep 'loopawhile.sh 1' | grep -v grep | awk '{ print $2\" \"$13 }' | head -1
24184 1

For each daemon process not found in status($proc), we refer it as stopped.

 

How to Debug

F12 Inspect shows console log messages step by step. You can see what command you issue and what response control panel receives in each period. That helps you realize how real-time control system operates.

Browser Control Panel Debugging

 

FINAL
Conclusion

When a system is built, senior engineers can write the remote script for each action you want operators to follow up. That allows operators not to sign in Linux for some tasks. Usually, operating staff are not familiar with Linux at all.

Thank you for reading, and we have suggested more helpful articles here. If you want to share anything, please feel free to comment below. Good luck and happy coding!

 

Learning Tips

Let’s suggest a excellent way to learn HTML scripts here. Using Google Chrome F12 Inspect or Inspect Element will help you study the codes.

In Google Chrome, there are two ways to inspect a web page using the browser’s built-in Chrome DevTools:

  • Right-click an element on the page or in a blank area, then select Inspect.
  • Go to the Chrome menu, then select More Tools > Developer Tools.

 

Suggested Reading

2 thoughts on “Trigger Remote Shell Script on Linux via Http Browser”

  1. you’re in point of fact a just right webmaster. The website loading
    speed is incredible. It seems that you are doing any unique trick.
    Furthermore, The contents are masterwork. you’ve done a excellent job on this subject!

    My blog Buy CBD

    Reply

Leave a Comment