Feb 032011
 

tux-apacheQualche volta può essere utile mostrare con un semplice CGI il contenuto di una directory, o eseguire un comando con qualche parametro.
Se sieet dei programmatori avrete sicuramente in mente soluzioni eleganti e pratiche in Java, Ruby o PHP; ma per un amministratore di sistema può essere comodo fare un semplice programma bash, linguaggio che utilizza tutti i giorni.

Vediamo come utilizzare la bash che usiamo di solito sul terminale in un programma CGI.




Tutti questi esempi devono essere messi in un file con il permesso di esecuzione (eseguibile dal webserver) e messo nella directory CGI, in Apache questa è la directory indicare con la direttiva ScriptAlias .

Cgi Base

Una cosa importante da ricordare è che bisogna identificare il MIME type della pagina, ovvero il tipo di dati che vogliamo trasmettere ad esempio potrebbero essere text/plain text/html o application/xml.

Altrimenti avremo un errore del webserver con un messaggio del tipo “Malformed header”

#!/bin/bash
echo "Content-Type: text/plain"
echo
echo "Today is:"
date

Il MIME è identificato con i primi due echo, il primo imposta il content-type ed il secondo manda una linea vuota, necessaria per far interpretare correttamente il content-type.

Stesso esempio ma in html:

#!/bin/bash
        echo "Content-Type: text/html"
        echo
        echo "<HTML><BODY>"
        echo "<CENTER>Today is:</CENTER>"
        echo "<CENTER><B>"
        date
        echo "</B></CENTER>"
        echo "</BODY></HTML>"

Ottenere dei parametri dai metodi GET e POST

Il modo più semplice per ottenere dei parametri per il vostro semplice CGI è quello di utilizzare i metodi GET o POST, e di analizzarli con bashlib

bashlib è uno script shell che rende la programmazione CGI con la bash shell più facile, o almeno più tollerabile. Esso contiene alcune funzioni che vengono chiamate automaticamente e configurano gli elementi dei form (dalle POST e GET) e cookie nel proprio ambiente. Contiene anche una documentazione completa su come usare queste variabili e su come impostare i cookie manualmente.

Con bashlib per ottenere uno specifico parametro scrivete:

...
YourVariable=`param username`
...

Quindi se il vostro CGI è chiamato con la url:: http://yourserver.com/bash.cgi?name=joe&surname=smith potete usare il seguente codice per ottenere i due parametri.

#!/bin/bash

# this sources bashlib into your current environment
. /usr/local/lib/bashlib
echo "Content-type: text/plain"
echo ""
name=`param name` # name = joe
surname=`param surname` # surname = smith
echo "Hello $name $surname"

Esempio con le bashlib

#!/bin/bash

# this sources bashlib into your current environment
. /usr/local/lib/bashlib

echo "Content-type: text/html"
echo ""

# OK, so we've sent the header... now send some content
echo "<html><title>Crack This Server</title><body>"

# print a "hello" if the username is filled out
username=`param username`
if [ -n "x$username" != "x" ] ; then
    echo "<h1>Hello, $username</h1>
fi

echo "<h2>Users on `/bin/hostname`</h2>"
echo "<ul>"

# for each user in the passwd file, print their login and full name
# bold them if they are the current user
for user in $(cat /etc/passwd | awk -F: '{print $1 "\t" $5}') ; do
    echo "<li>"
    if [ "$username" = "$user" ] ; then
        echo "<strong>$user</strong>"
    else
        echo "$user"
    fi
    echo "</li>"
done
echo "</ul>"
echo "</body></html>"

E se pensate che con la bash si possano fare solo piccole cose, guardate questo progetto: http://nanoblogger.sourceforge.net/

Riferimenti:

Apache: CGI scritti in Bash

Bash Libraries
http://bashlib.sourceforge.net/

Bash CGI Reference Material
http://www.yolinux.com/TUTORIALS/LinuxTutorialCgiShellScript.html
http://www.ffnn.nl/pages/articles/linux/cgi-scripting-tips-for-bash-or-sh.php
http://www.acmesystems.it/?id=165
http://wiki.flexion.org/BashCGI.html

Popular Posts:

Flattr this!

  6 Responses to “Bash come CGI”

  1. Very cool, though I’ll need to do some more test for security sake (doesn’t seem to allow pipes, semicolons or characters to be executed even when used in grep and cat, so it look *pretty* secure.

    I did notice 2 errors though
    1) The semicolon on line 15 (echo Hello user) should be a quotation mark
    2) If you want the browser to INTERPRET the html (instead of just displaying it), replace < with .

  2. gah, comment thing ate my characters:

    Very cool, though I’ll need to do some more test for security sake (doesn’t seem to allow pipes, semicolons or <, > characters to be executed even when used in grep and cat, so it look *pretty* secure.

    I did notice 2 errors though
    1) The semicolon on line 15 (echo Hello user) should be a quotation mark
    2) If you want the browser to INTERPRET the html (instead of just displaying it), replace &lt; with < and &gt; with >

  3. Excellent intro!

    Thank you,
    Ricky

  4. The article might have been comprehensible to me if, someplace (near the beginning??), the author had spelled out or explained what CGI means.

  5. Funny! This churns up many memories.

    More than 15 years ago I was writing bash CGI scripts, storing data in little chunks in the filesystem. Didn’t have PHP and MySQL back then.

    Long before bashlib, there was uncgi, a C program that turned GET/POST into environment variables that were handed to bash:

    http://www.midwinter.com/~koreth/uncgi.html

    Actually, since I was doing this on a Sun SPARC-20, I suspect it was ancient /bin/sh Bourne Shell, not bash. Or ksh or csh. Whatever was on the machine. It didn’t even have Perl.

    I wrote a “caption contest” and, long before anybody used the word “blog,” a web log tool for Minneapolis weatherman Paul Douglas to update his online weather column for startribune.com.

    For a contest, Garrison Keillor wrote a short story with gaping holes that I turned into a madlibs-like Web form.

    Keillor faxed in his story about three hours before the deadline, but I was able get it online in time. If I ever meet Steven Grimm (author of uncgi) I owe him a beer.

  6. Linux Scanner Server is based on a shell script and CGI:
    http://scannerserver.online02.com

    When I discovered that it used shell scripting I fixed several bugs and released a patch for it:
    http://jhansonxi.blogspot.com/2010/10/patch-for-li nux-scanner-server-v12.html

    Shell scripting has its uses but using it for text handling is annoying.

    LSS is using sh (Dash on Ubuntu).

Leave a Reply to Rickyx Cancel reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

*