Search code examples
ubuntucgiportpidlsof

No Output Displayed when i run and echo lsof in cgi - Ubuntu


I have recently started using cgi. As I have to display port usage information about certain ports, I had written the following code:

#!/bin/bash

echo "Content-type: text/html"
echo ""
echo "<html><head><title>PortInfo</title></head><body><center>"
echo "<h1>Port 80 Usage Info</h1>"

#method1
echo "<pre> $(lsof -i :80) </pre>"

#method2
echo "$(lsof -i :80 > /home/shine/Desktop/tmp.txt)"
echo "<pre> $(cat /home/shine/Desktop/tmp.txt) </pre>" 

echo "<center>Information generated on $(date)</center>"
echo "</center></body></html>"

Method 1: The problem over here is that the echo "<pre> $(lsof -i :80) </pre>" does not give any output.

Method 2: In this method echo "$(lsof -i :80 > /home/shine/Desktop/tmp.txt)" never creates a file named tmp.txt on the desktop, as it is supposed to do.

Important Note: Both the methods specified above run perfectly once they are executed in the terminal.


Solution

  • So I kind of found the answer I was searching for, more like an alternative.

    Somebody mentioned somewhere, something about cron scripts so, I did the following.

    Step I:

    sudo crontab -e
    

    Enter 2 for nano editor

    Add the following lines:

    * * * * * lsof -i :80 > /home/shine/port80.txt
    * * * * * lsof -i :3000 > /home/shine/port3000.txt
    

    Note:The above lines of code will generate two text files containing port 80 & 3000 info in the current users' home directory every minute.

    ctrl+o, enter, ctrl+x to save and exit.

    Step II:

    In apache's www directory Create a php file with the following code.

    <?php
    
    $output80 = shell_exec("cat '/home/shine/reports/port80.txt'");
    echo "<pre>$output80</pre>";
    $output3000 = shell_exec('cat "/home/shine/reports/port3000.txt"');
    echo "<pre>$output3000</pre>";
    
    ?>
    

    This is the only way I can think of at this moment to make lsof work on a web page.