javascriptjqueryshelljquery-terminal

How to send a command to the shell with jQuery Terminal?


I want to build a Web-based Terminal and I want to execute a shell command.

How can I use jQuery Terminal library to send command to shell and print the reply?


Solution

  • So to execute the shell commands you need to have a server code. The simplest way is to use, Apache and PHP. For this, you need to create a PHP script and use one of the functions that allow executing shell commands.

    shell.php

    <?php
    
    if (isset($_POST['command'])) {
       echo shell_exec($_POST['command']);
    }
    

    with this server-side script in place, you can write JavaScript code using jQuery Terminal that will send the request to that PHP script and display the results.

    $('body').terminal(function(command) {
       return fetch('shell.php').then(res => res.text());
    });
    

    What else you can do to improve the terminal is to use a unix_formatting.js file that will display any ANSI Escape code that may be generated by the shell in the browser:

    <script src="https://cdn.jsdelivr.net/npm/jquery.terminal/js/unix_formatting.js"></script>
    

    If you want to see an example of this that is more advanced, you can take a look at:

    jcubic/jsh.php that was created as a single file, PHP shell that looks like a real terminal. It uses few tricks to make it more user-friendly like using unbuffer (part of expect package on GNU/Linux) and other bash tricks to make it display ANSI escapes code for every command. By default ls don't return output in colors.

    If you want something even more advanced you can look at Leash Shell project that was created to give access to the shell on shared hosting.

    Alternatives are: