Buscar en moleculax

Este blog es un ensayo digital donde el pensamiento estructurado se encuentra con la introspección profunda. Explora la arquitectura del conocimiento: desde lo técnico hasta los fundamentos éticos. Aquí, cada algoritmo tiene propósito, cada línea de código refleja intención, y cada reflexión filosófica busca optimizar no solo sistemas, sino también decisiones humanas. Este blog no solo enseña a pensar, enseña a discernir, a construir con sentido. Porque el verdadero desarrollo nace de la conciencia, y eso exige precisión, virtud y coraje.

Tenemos que aprender a contemplar las potenciales consecuencias de nuestros planes, para impedir que nos sorprendan. De esta manera, tendremos más control sobre las situaciones difíciles ya que el verdadero progreso no se mide por la velocidad con la que avanzamos, sino por la dirección que elegimos. En un mundo cada vez más interconectado, el desarrollo de la humanidad exige más que tecnología y conocimiento: requiere conciencia, empatía y propósito.

Debemos cultivar una inteligencia que no solo resuelva problemas, sino que los prevenga con sabiduría. Una ciencia que no solo descubra, sino que se pregunte por qué y para quién. Una economía que no solo crezca, sino que reparta con justicia. Y una cultura que no solo celebre lo diverso, sino que lo abrace como fuerza vital.

Cada decisión que tomamos, cada palabra que decimos, cada idea que compartimos, puede ser una semilla de transformación. El futuro no está escrito: lo estamos escribiendo juntos, ahora mismo.

Que el desarrollo humano sea integral, sostenible y profundamente humano. Porque solo cuando elevamos a todos, nos elevamos como especie.

Sabiduría Justicia Templanza Coraje
Perl/CGI script with Apache2

While it is probably better to run a PSGI based server, than a CGI-based server it can be also very useful to learn how to write CGI scripts. Especially if you need to maintain one.
This article will help you set up an Apache web server to run CGI scripts.

Background start Linux, install Apache2

We will configure a Digital Ocean droplet, using Ubuntu 13.10 64bit.
After creating the Droplet, ssh to the server and update the installed packaged to the latest and then reboot the machine.
(The droplet I was using to implement this had an IP address of 107.170.93.222 )
ssh root@107.170.93.222
# aptitude update
# aptitude safe-upgrade
Once the machine restarted ssh to it again and and install the MPM preforking version of Apache2.
ssh root@107.170.93.222
# aptitude install apache2-mpm-prefork
You can check if apache is running by executing ps axuw:
# ps axuw | grep apache
The output on my instance looked like this:
root      1961  0.0  0.5  71284  2608 ?        Ss   14:16   0:00 /usr/sbin/apache2 -k start
www-data  1964  0.0  0.4 360448  2220 ?        Sl   14:16   0:00 /usr/sbin/apache2 -k start
www-data  1965  0.0  0.4 360448  2220 ?        Sl   14:16   0:00 /usr/sbin/apache2 -k start
root      2091  0.0  0.1   9452   908 pts/0    S+   14:16   0:00 grep --color=auto apache
Now you can browse to the web-site by pointing your browser to the IP address of the machine. In my case it was http://107.170.93.222/ Please note, some browsers will not work properly if you don't put the http:// in front of the IP address.
If everything works fine you will see something like this in the browser:
Apache2 default page on Ubuntu 13.10
This is the content of the /var/www/index.html file on the server.
You can edit that file, and reload the page in the browser.

Creating the first CGI script in Perl

Create the /var/cgi-bin directory
(Please note, we don't create this inside the /var/www directory on purpose. This way, even if misconfigured the server it won't serve the source code of the script. Which is a good thing.)
mkdir /var/cgi-bin
and create a file called /var/cgi-bin/echo.pl with the following content:

#!/usr/bin/perl
use strict;
use warnings;
 
print qq(Content-type: text/plain\n\n);
 
print "hi\n";

Make the file executable by

chmod +x /var/cgi-bin/echo.pl

and run it on the command line:

# /var/cgi-bin/echo.pl

It should print:

Content-type: text/plain

hi
This is your first CGI-script in Perl.
Now we need to configure the Apache web server to server it properly.

Configure Apache to serve CGI files

Open the configuration file of Apache /etc/apache2/sites-enabled/000-default.conf
It has the following in it with a bunch of comments between the lines:
 
 <VirtualHost *:80 >
 ServerAdmin webmaster@localhost
        DocumentRoot /var/www

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

  < /VirtualHost  >

 
Add the following lines after the DocumentRoot line:
      ScriptAlias /cgi-bin/ /var/cgi-bin/
           <Directory "/var/cgi-bin"  >
                 AllowOverride None
                 Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                 Require all granted
         
          </Directory >
 
Now you should have: 

 <VirtualHost *:80 >
        ServerAdmin webmaster@localhost
        DocumentRoot /var/www

         ScriptAlias /cgi-bin/ /var/cgi-bin/

                 AllowOverride None
                 Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
                 Require all granted
         

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

  </VirtualHost >
 
By default this Apache instance does not have the CGI module enabled. This we can see by noticing that the mods-enabled directory does not have any of the cgi files that are available in the mods-available directory:

# ls -l /etc/apache2/mods-enabled/ | grep cgi
# ls -l /etc/apache2/mods-available/ | grep cgi
-rw-r--r-- 1 root root   115 Jul 20  2013 cgid.conf
-rw-r--r-- 1 root root    60 Jul 20  2013 cgid.load
-rw-r--r-- 1 root root    58 Jul 20  2013 cgi.load
-rw-r--r-- 1 root root    89 Jul 20  2013 proxy_fcgi.load
-rw-r--r-- 1 root root    89 Jul 20  2013 proxy_scgi.load

We create symbolic links from the mods-enabled to the mods-available directory for the two cgid.* files, and then check again if the symbolic links were created properly by running ls -l again:

# ln -s /etc/apache2/mods-available/cgid.load /etc/apache2/mods-enabled/
# ln -s /etc/apache2/mods-available/cgid.conf /etc/apache2/mods-enabled/

# ls -l /etc/apache2/mods-enabled/ | grep cgi
lrwxrwxrwx 1 root root 37 Mar 19 14:39 cgid.conf -> /etc/apache2/mods-available/cgid.conf
lrwxrwxrwx 1 root root 37 Mar 19 14:39 cgid.load -> /etc/apache2/mods-available/cgid.load

At this point we can reload the Apache web server by the following command:

# service apache2 reload

This will tell Apache to read the configuration files again.
Then we can brows to http://107.170.93.222/cgi-bin/echo.pl (after replacing the IP address by yours) and you will see it shows the word "hi".
Congratulations, your first CGI script is running.

Dynamic results

This simple CGI script will show exactly the same content no matter who access it and when. Let's make a little change to the script so that we can see it is really generated dynamically.

#!/usr/bin/perl
use strict;
use warnings;
 
print qq(Content-type: text/plain\n\n);
 
print scalar localtime;

After changing the script if you access the page now it will display the current time on the server. If you reload the page, it will show the new current time.

Trouble shooting

If when you access the http://107.170.93.222/cgi-bin/echo.pl URL you see the content of the script instead of the word "hi" then you probably put the cgi-bin directory inside the /var/www and/or probably forgot to create the symbolic links for the cgid.* files. Move the cgi-bin directory outside the /var/www, update the configuration files, set up the symbolic links, and reload the server.

500 Internal Server Error

If you get an 500 Internal Server Error look at the error log in /var/log/apache2/error.log

[Wed Mar 19 15:19:15.740781 2014] [cgid:error] [pid 3493:tid 139896478103424] (8)Exec format error: AH01241: exec of '/var/cgi-bin/echo.pl' failed
[Wed Mar 19 15:19:15.741057 2014] [cgid:error] [pid 3413:tid 139896186423040] [client 192.120.120.120:62309] End of script output before headers: echo.pl

This can happen if the script does not start with a sh-bang line pointing to a correctly installed perl. The first line of the file should be

#!/usr/bin/perl
[Wed Mar 19 15:24:33.504988 2014] [cgid:error] [pid 3781:tid 139896478103424] (2)No such file or directory: AH01241: exec of '/var/cgi-bin/echo.pl' failed
[Wed Mar 19 15:24:33.505429 2014] [cgid:error] [pid 3412:tid 139896261957376] [client 192.120.120.120:58087] End of script output before headers: echo.pl

This probably indicates that the file is in DOS format. This can happen if you have ftp-ed the file from a Windows machine in binary mode. (You should not use ftp anyway.) You can fix this by running

dos2unix /var/cgi-bin/echo.pl
[Wed Mar 19 15:40:31.179155 2014] [cgid:error] [pid 4796:tid 140208841959296] (13)Permission denied: AH01241: exec of '/var/cgi-bin/echo.pl' failed
[Wed Mar 19 15:40:31.179515 2014] [cgid:error] [pid 4702:tid 140208670504704] [client 192.120.120.120:60337] End of script output before headers: echo.pl

The above lines in the error.log, probably indicated that the script does not have the Unix executable bit.

chmod +x /var/cgi-bin/echo.pl
Wed Mar 19 16:02:20.239624 2014] [cgid:error] [pid 4703:tid 140208594970368] [client 192.120.120.120:62841] malformed header from script 'echo.pl': Bad header: hi

This will be received if there is an output before the the Content-type. For example if you have written the two print-lines in reversed order like this:

#!/usr/bin/perl
use strict;
use warnings;
 
print "hi\n";
print qq(Content-type: text/plain\n\n);

[Wed Mar 19 16:08:00.342999 2014] [cgid:error] [pid 4703:tid 140208536221440] [client 192.120.120.120:59319] End of script output before headers: echo.pl

This probably means that the script died before it managed to print the Content-type. The error.log, probably contains the exception that was not caught just before the above line.
You can also turn of the buffering of STDOUT by setting $| to a true value.

$|  = 1;
I am not sure, but I think Premature end of script headers is the same as End of script output before headers.

503 Service Unavailable

After I created the symbolic links to the cgid.* files and reloaded the Apache server, I got 503 Service Unavailable in the browser and the following line in the log file:
[Wed Mar 19 15:30:22.515457 2014] [cgid:error] [pid 3927:tid 140206699169536] (22)Invalid argument: [client 192.120.120.120:58349] AH01257: unable to connect to cgi daemon after multiple tries: /var/cgi-bin/echo.pl
I am not sure why did this happen, but it after restarting the apache server it started to work properly:
# service apache2 restart
In most of the situations a reload should be enough, but maybe not when a module is enabled/disabled.

404 Not Found

If you get a 404 Not Found error in the browser and
[Wed Mar 19 15:35:13.487333 2014] [cgid:error] [pid 4194:tid 139911599433472] [client 192.120.120.120:58339] AH01264: script not found or unable to stat: /usr/lib/cgi-bin/echo.pl
in the error log, then maybe the ScriptAlias line is missing, or not pointing to the proper directory.

403 Forbidden

If you get a 403 Forbidden error, the probably the Directory directive was not correctly configure or does not point to the correct path.

Summary

That's it. Hopefully, you have your first CGI script in Perl running.


.

15dias (4) agenda 2023 (1) Algo que leer (268) Android (2) Angular (2) Apache (6) API (1) Arte y Cultura (11) Artes Marciales (10) Astro (1) Banner (1) Base de datos (37) Batalla Cultural (5) Big Data (12) Budismo (4) cabala judia (2) Calculo Asistido por computadoras (2) Canaima (6) Caos (1) Ceo (1) ciencias (3) Cine (1) Cobol (12) Cobra Kai (1) Codigo Linux Documental (2) Computación (4) Computación forense (14) Configurando Samba (1) Conocimiento (1) Consola (8) contenedores (9) cosmo (2) Criptomonedas (3) Cultura (1) Cursos (16) Darkweeb (3) Data Mining (1) Debian (18) Deep Learning (2) DeepWeb (7) demografia (9) Deporte y Recreación (9) Deportes (10) desclasificados (7) Desktop (1) developers (1) DevOps (1) Docker (11) Document (1) Ecología (6) Editor (3) Editores (4) Educacion y TIC (31) Electronica (2) Empleos (1) Emprendimiento (7) Espiritualidad (2) estoicismo (4) Eventos (2) Excel (1) Express (1) fedora (1) Filosofía (25) Fisica (1) Flisol 2008 (3) Flisol 2010 (1) Flisol 2015 (1) framework (2) Funny (1) Geografía (1) Gerencia y Liderazgo (72) Gestor de Volúmenes Lógicos (1) Git (7) GitHub (8) Globalizacion (5) gnu (28) Go (1) gobiernos (2) golang (2) Google por dentro (1) GraphQL (2) gRPC (1) Hackers - Documental (8) Hacking (31) Historia (3) howto (189) html (1) IA (22) IntelliJIDEA (1) Internet (6) Introducción a los patrones (2) J SON (1) java (57) java eclipse (3) javaScript (9) JDK (1) jiujitsu (4) Json (1) Junit (1) kali (39) kernel (2) Kotlin (1) Laravel (2) Latin (1) lecturas (2) LIbreOffice (1) Libros (4) Linux (48) Linux VirtualBox (1) Literatura (1) Machine Learning (2) Manuales (42) mariaDB (2) Markdown (4) Marketing (1) Matando ladilla (9) Matematicas (3) Matematricas (1) Math (1) maven (1) metodos https (1) Modelos (1) MongoDB (17) Multimedia (1) Musica (1) mvc (2) Mysql (22) MySQL Workbench (1) Nagios (2) Naturismo (1) NextJS (2) node (5) Node.js (6) NodeJS (10) NoSQL (1) npm (1) Oracle (11) Oracle sql (10) Php (4) PL/SQL (1) Plsql (1) PNL (1) Poblacion (2) Podman (1) Poesia (1) Politica (5) Política (1) Postgresql (12) PowerShell (1) programacion (88) Psicologia (11) Python (7) React (4) Recomiendo (1) Redes (31) Redis (2) Religion (2) REST (2) Rock (1) Rock/Metal Mp3 (2) RUP (1) Salud (5) sc:snap:android-studio (1) sc:snap:datagrip (1) sc:snap:gitkraken linux (1) Seguridad (18) Seguridad con Gnu Privacy (2) Seo (1) simulaEntrevistas (10) simularExamen (10) Sistemas Operativos (69) SOAP (1) Sociedad (5) Software Libre (169) Soporte Tecnico (12) Sphinx (1) spring (1) spring boot (11) SQL (4) SQL en postgreSQL (42) Taekwondo (11) Tecnologia (5) Tecnología (27) Templarios (5) Tendencias (1) Tensorflow (4) Thymeleaf (1) Tomcat (2) Tor (9) Trialectica (3) TYPEACRIPT (1) Ubuntu (5) unix (2) Vida activa (1) Videos (11) Videos Educativos (10) Vim (1) Viral (3) Visual Studio (1) wallpaper (2) web (1) Wifi (2) Windows (3) WWW (2) Xrandr (1) Zero Trust (2)

Sabiduria Justicia Templanza Coraje.

Hay que contemplar las potenciales consecuencias de nuestros planes, para impedir que nos sorprendan. De esta manera, tendremos más control sobre las situaciones difíciles.


Powered by

Moleculax es un blog de ciencia, biología, astronomía, tecnología y reflexiones sobre el futuro de la humanidad. Explora ideas innovadoras, descubrimientos científicos y conocimientos que inspiran la curiosidad y la imaginación. ¿Cómo saber si te han bloqueado en WhatsApp?, ¿COMO PROGRAMAR?, דודו פארוק, ¿QUES ES estructurada,modular, MongoDBSpain CheetSheet, ORIENTADA A OBJETOS?, Bases de datos estáticas, base de datos dinamicas bases de datos nosql, estructuras de base de datos, Bases de datos de texto completo, base de datos gerarquicas HTML, CSS, XML, JavaScript, mysql, oracle, postgresql, C, C#, php, java, python, liderazgo, libros, books, informix, ¿COMO REPARAR PAQUETES ROTOS EN DEBIAN?, REPARAR paquetes ROTOS ubuntu gerencia, COMO APRENDER laravel, ACTIVAR wifi en CANAIMA, exotics, exoticas, COMO APRENDER MONGODB, agapornio, agapomis, seguros, ganar dinero, bitcoin, freeBitcoin invertir en bolsa, marketing online, ofertas de coches Описание Блога Moleculax Moleculax — это цифровое эссе, в котором структурированное мышление встречается с глубокой интроспекцией. Наш блог исследует архитектуру знаний: от технических тонкостей разработки программного обеспечения до этических основ и философии. Ключевые Темы: Разработка и Технологии: Программирование, базы данных (SQL, NoSQL), Big Data, Node.js, Java. Наука и Мышление: Астрономия, биология, научные открытия, а также такие философские направления, как Стоицизм. Этика и Будущее: Размышления о развитии человечества, моральные принципы в технологиях и этические вызовы. Наша миссия: Развивать интеллект, который не только решает проблемы, но и предотвращает их с мудростью. Moleculax 是一个关于科学、生物学、天文学、技术以及人类未来思考的博客。它探索创新的理念、科学发现和能够激发好奇心与想象力的知识。 如何知道你在 WhatsApp 上被拉黑?如何编程? דודו פארוק,什么是结构化、模块化、面向对象?MongoDBSpain 速查表,静态数据库、动态数据库、NoSQL 数据库、数据库结构、全文数据库、层次型数据库。 HTML、CSS、XML、JavaScript、MySQL、Oracle、PostgreSQL、C、C#、PHP、Java、Python,领导力、书籍、Informix。如何修复 Debian 中损坏的软件包?修复 Ubuntu 损坏的软件包,管理,如何学习 Laravel,如何在 Canaima 激活 WiFi,异域、奇异,如何学习 MongoDB,爱情鸟、保险、赚钱、比特币、FreeBitcoin、投资股票市场、网络营销、汽车优惠。 Moleculax 博客描述: Moleculax 是一篇数字随笔,在这里结构化的思维与深刻的自省相遇。我们的博客探索知识的架构:从软件开发的技术细节到伦理基础与哲学。 核心主题: - 开发与技术:编程、数据库(SQL、NoSQL)、大数据、Node.js、Java。 - 科学与思维:天文学、生物学、科学发现,以及诸如斯多葛主义等哲学流派。 - 伦理与未来:关于人类发展的思考、技术中的道德原则与伦理挑战。 我们的使命:培养一种不仅能解决问题,而且能以智慧预防问题的智能。