How to View Configuration Files Without Comments in Linux

‘,
enableHover: false,
enableTracking: true,
buttons: { twitter: {via: ‘tecmint’}},
click: function(api, options){
api.simulateClick();
api.openPopup(‘twitter’);
}
});
jQuery(‘#facebook’).sharrre({
share: {
facebook: true
},
template: ‘{total}’,
enableHover: false,
enableTracking: true,
click: function(api, options){
api.simulateClick();
api.openPopup(‘facebook’);
}
});
jQuery(‘#googleplus’).sharrre({
share: {
googlePlus: true
},
template: ‘{total}’,
enableHover: false,
enableTracking: true,
urlCurl: ‘https://www.tecmint.com/wp-content/themes/tecmint/js/sharrre.php’,
click: function(api, options){
api.simulateClick();
api.openPopup(‘googlePlus’);
}
});
jQuery(‘#linkedin’).sharrre({
share: {
linkedin: true
},
template: ‘{total}’,
enableHover: false,
enableTracking: true,
buttons: {
linkedin: {
description: ‘How to View Configuration Files Without Comments in Linux’,media: ‘https://www.tecmint.com/wp-content/uploads/2017/12/View-Files-Without-Comments-in-Linux.png’ }
},
click: function(api, options){
api.simulateClick();
api.openPopup(‘linkedin’);
}
});
// Scrollable sharrre bar, contributed by Erik Frye. Awesome!
var shareContainer = jQuery(“.sharrre-container”),
header = jQuery(‘#header’),
postEntry = jQuery(‘.entry’),
$window = jQuery(window),
distanceFromTop = 20,
startSharePosition = shareContainer.offset(),
contentBottom = postEntry.offset().top + postEntry.outerHeight(),
topOfTemplate = header.offset().top;
getTopSpacing();
shareScroll = function(){
if($window.width() > 719){ var scrollTop = $window.scrollTop() + topOfTemplate,
stopLocation = contentBottom – (shareContainer.outerHeight() + topSpacing);
if(scrollTop > stopLocation){
shareContainer.offset({top: contentBottom – shareContainer.outerHeight(),left: startSharePosition.left});
}
else if(scrollTop >= postEntry.offset().top-topSpacing){
shareContainer.offset({top: scrollTop + topSpacing, left: startSharePosition.left});
}else if(scrollTop 1024)
topSpacing = distanceFromTop + jQuery(‘.nav-wrap’).outerHeight();
else
topSpacing = distanceFromTop;
}
});
]]>

How to Send a Message to Logged Users in Linux Terminal

‘,
enableHover: false,
enableTracking: true,
buttons: { twitter: {via: ‘tecmint’}},
click: function(api, options){
api.simulateClick();
api.openPopup(‘twitter’);
}
});
jQuery(‘#facebook’).sharrre({
share: {
facebook: true
},
template: ‘{total}’,
enableHover: false,
enableTracking: true,
click: function(api, options){
api.simulateClick();
api.openPopup(‘facebook’);
}
});
jQuery(‘#googleplus’).sharrre({
share: {
googlePlus: true
},
template: ‘{total}’,
enableHover: false,
enableTracking: true,
urlCurl: ‘https://www.tecmint.com/wp-content/themes/tecmint/js/sharrre.php’,
click: function(api, options){
api.simulateClick();
api.openPopup(‘googlePlus’);
}
});
jQuery(‘#linkedin’).sharrre({
share: {
linkedin: true
},
template: ‘{total}’,
enableHover: false,
enableTracking: true,
buttons: {
linkedin: {
description: ‘How to Send a Message to Logged Users in Linux Terminal’,media: ‘https://www.tecmint.com/wp-content/uploads/2017/12/Send-Message-to-Linux-Users.png’ }
},
click: function(api, options){
api.simulateClick();
api.openPopup(‘linkedin’);
}
});
// Scrollable sharrre bar, contributed by Erik Frye. Awesome!
var shareContainer = jQuery(“.sharrre-container”),
header = jQuery(‘#header’),
postEntry = jQuery(‘.entry’),
$window = jQuery(window),
distanceFromTop = 20,
startSharePosition = shareContainer.offset(),
contentBottom = postEntry.offset().top + postEntry.outerHeight(),
topOfTemplate = header.offset().top;
getTopSpacing();
shareScroll = function(){
if($window.width() > 719){ var scrollTop = $window.scrollTop() + topOfTemplate,
stopLocation = contentBottom – (shareContainer.outerHeight() + topSpacing);
if(scrollTop > stopLocation){
shareContainer.offset({top: contentBottom – shareContainer.outerHeight(),left: startSharePosition.left});
}
else if(scrollTop >= postEntry.offset().top-topSpacing){
shareContainer.offset({top: scrollTop + topSpacing, left: startSharePosition.left});
}else if(scrollTop 1024)
topSpacing = distanceFromTop + jQuery(‘.nav-wrap’).outerHeight();
else
topSpacing = distanceFromTop;
}
});
]]>

How to Find All Failed SSH login Attempts in Linux

Each attempt to login to SSH server is tracked and recorded into a log file by the rsyslog daemon in Linux. The most basic mechanism to list all failed SSH logins attempts in Linux is a combination of displaying and filtering the log files with the help of cat command or grep command.

In order to display a list of the failed SSH logins in Linux, issue some of the commands presented in this guide. Make sure that these commands are executed with root privileges.

The most simple command to list all failed SSH logins is the one shown below.

# grep "Failed password" /var/log/auth.log
List All Failed SSH Login Attempts

List All Failed SSH Login Attempts

The same result can also be achieved by issuing the cat command.

# cat /var/log/auth.log | grep "Failed password"


In order to display extra information about the failed SSH logins, issue the command as shown in the below example.

# egrep "Failed|Failure" /var/log/auth.log
Find Failed SSH Logins

Find Failed SSH Logins

In CentOS or RHEL, the failed SSH sessions are recorded in /var/log/secure file. Issue the above command against this log file to identify failed SSH logins.

# egrep "Failed|Failure" /var/log/secure
Find Failed SSH Logins in CentOS

Find Failed SSH Logins in CentOS

A slightly modified version of the above command to display failed SSH logins in CentOS or RHEL is as follows.

# grep "Failed" /var/log/secure
# grep "authentication failure" /var/log/secure
Find SSH Authentication Failure Logins

Find SSH Authentication Failure Logins

To display a list of all IP addresses that tried and failed to log in to the SSH server alongside the number of failed attempts of each IP address, issue the below command.

# grep "Failed password" /var/log/auth.log | awk ‘{print $11}’ | uniq -c | sort -nr
Find IP Addresses of SSH Failed Logins

Find IP Addresses of SSH Failed Logins

On newer Linux distributions you can query the runtime log file maintained by Systemd daemon via journalctl command. In order to display all failed SSH login attempts you should pipe the result via grep filter, as illustrated in the below command examples.

# journalctl _SYSTEMD_UNIT=ssh.service | egrep "Failed|Failure"
# journalctl _SYSTEMD_UNIT=sshd.service | egrep "Failed|Failure" #In RHEL, CentOS 
Find Real Time Failed SSH Logins

Find Real Time Failed SSH Logins

In CentOS or RHEL, replace the SSH daemon unit with sshd.service, as shown in the below command examples.

# journalctl _SYSTEMD_UNIT=sshd.service | grep "failure"
# journalctl _SYSTEMD_UNIT=sshd.service | grep "Failed"

After you’ve identified the IP addresses that frequently hit your SSH server in order to log in to the system with suspicious user accounts or invalid user accounts, you should update your system firewall rules to block the failed SSH attempts IP addresses or use a specialized software, such as fail2ban to manage these attacks.

How to Clear BASH Command Line History in Linux

The bash history keeps a record of all commands executed by a user on the Linux command line. This allows you to easily run previously executed commands by using the “up arrow” or “down arrow” keys to scroll through the command history file.

In this article, we will show you two simple ways to clear your command-line history on a Linux system.

The major reason for removing command-line history from the Linux terminal is to prevent another user, who could be using the same account.

For instance if you have typed a command that contained a password in plain-text and you don’t want another system user or an attacker to see this password, you need to delete or clear the history file.


Take a look at the command below, here the user aaronkilik has typed the database server password on the command line.

$ sudo mysql -u root [email protected]!#@%$lab

If you look into th bash history file towards the end, you will see the password typed above in there.

$ history
Check Last Executed Commands

Check Last Executed Commands

The bash_history file is normally located in a user’s home directory /home/username/.bash_history.

$ ls -l /home/aaronkilik/.bash_history

To remove a single line from the history file, use the -d option. For example, if you want to clear a command where you entered clear-text password as in the scenario above, find the line number in the history file and run this command.

$ history -d 2038

To delete or clear all the entries from bash history, use the history command below with the -c option.

$ history -c

Alternatively, you can use the command below to delete history of all last executed commands permanently in the file.

$ cat /dev/null > ~/.bash_history 

Note: A normal user can only view his/her own command history, but the root user can view the command history of all other users on the system.

You can learn more about the bash history file and useful history commands here: The Power of Linux “History Command” in Bash Shell.

Always remember that all commands you run are recorded in a history file, so do not type plain-text passwords on the command line. If you have questions or thoughts to share with us, make use of the feedback form below.

How to Disable SSH Root Login in Linux

‘,
enableHover: false,
enableTracking: true,
buttons: { twitter: {via: ‘tecmint’}},
click: function(api, options){
api.simulateClick();
api.openPopup(‘twitter’);
}
});
jQuery(‘#facebook’).sharrre({
share: {
facebook: true
},
template: ‘{total}’,
enableHover: false,
enableTracking: true,
click: function(api, options){
api.simulateClick();
api.openPopup(‘facebook’);
}
});
jQuery(‘#googleplus’).sharrre({
share: {
googlePlus: true
},
template: ‘{total}’,
enableHover: false,
enableTracking: true,
urlCurl: ‘https://www.tecmint.com/wp-content/themes/tecmint/js/sharrre.php’,
click: function(api, options){
api.simulateClick();
api.openPopup(‘googlePlus’);
}
});
jQuery(‘#linkedin’).sharrre({
share: {
linkedin: true
},
template: ‘{total}’,
enableHover: false,
enableTracking: true,
buttons: {
linkedin: {
description: ‘How to Disable SSH Root Login in Linux’,media: ‘https://www.tecmint.com/wp-content/uploads/2017/12/Disable-SSH-Root-Login-in-Linux.png’ }
},
click: function(api, options){
api.simulateClick();
api.openPopup(‘linkedin’);
}
});
// Scrollable sharrre bar, contributed by Erik Frye. Awesome!
var shareContainer = jQuery(“.sharrre-container”),
header = jQuery(‘#header’),
postEntry = jQuery(‘.entry’),
$window = jQuery(window),
distanceFromTop = 20,
startSharePosition = shareContainer.offset(),
contentBottom = postEntry.offset().top + postEntry.outerHeight(),
topOfTemplate = header.offset().top;
getTopSpacing();
shareScroll = function(){
if($window.width() > 719){ var scrollTop = $window.scrollTop() + topOfTemplate,
stopLocation = contentBottom – (shareContainer.outerHeight() + topSpacing);
if(scrollTop > stopLocation){
shareContainer.offset({top: contentBottom – shareContainer.outerHeight(),left: startSharePosition.left});
}
else if(scrollTop >= postEntry.offset().top-topSpacing){
shareContainer.offset({top: scrollTop + topSpacing, left: startSharePosition.left});
}else if(scrollTop 1024)
topSpacing = distanceFromTop + jQuery(‘.nav-wrap’).outerHeight();
else
topSpacing = distanceFromTop;
}
});
]]>

How to Create a Password Protected ZIP File in Linux

‘,
enableHover: false,
enableTracking: true,
buttons: { twitter: {via: ‘tecmint’}},
click: function(api, options){
api.simulateClick();
api.openPopup(‘twitter’);
}
});
jQuery(‘#facebook’).sharrre({
share: {
facebook: true
},
template: ‘{total}’,
enableHover: false,
enableTracking: true,
click: function(api, options){
api.simulateClick();
api.openPopup(‘facebook’);
}
});
jQuery(‘#googleplus’).sharrre({
share: {
googlePlus: true
},
template: ‘{total}’,
enableHover: false,
enableTracking: true,
urlCurl: ‘https://www.tecmint.com/wp-content/themes/tecmint/js/sharrre.php’,
click: function(api, options){
api.simulateClick();
api.openPopup(‘googlePlus’);
}
});
jQuery(‘#linkedin’).sharrre({
share: {
linkedin: true
},
template: ‘{total}’,
enableHover: false,
enableTracking: true,
buttons: {
linkedin: {
description: ‘How to Create a Password Protected ZIP File in Linux’,media: ‘https://www.tecmint.com/wp-content/uploads/2017/12/Create-Password-Zip-File-in-Linux.png’ }
},
click: function(api, options){
api.simulateClick();
api.openPopup(‘linkedin’);
}
});
// Scrollable sharrre bar, contributed by Erik Frye. Awesome!
var shareContainer = jQuery(“.sharrre-container”),
header = jQuery(‘#header’),
postEntry = jQuery(‘.entry’),
$window = jQuery(window),
distanceFromTop = 20,
startSharePosition = shareContainer.offset(),
contentBottom = postEntry.offset().top + postEntry.outerHeight(),
topOfTemplate = header.offset().top;
getTopSpacing();
shareScroll = function(){
if($window.width() > 719){ var scrollTop = $window.scrollTop() + topOfTemplate,
stopLocation = contentBottom – (shareContainer.outerHeight() + topSpacing);
if(scrollTop > stopLocation){
shareContainer.offset({top: contentBottom – shareContainer.outerHeight(),left: startSharePosition.left});
}
else if(scrollTop >= postEntry.offset().top-topSpacing){
shareContainer.offset({top: scrollTop + topSpacing, left: startSharePosition.left});
}else if(scrollTop 1024)
topSpacing = distanceFromTop + jQuery(‘.nav-wrap’).outerHeight();
else
topSpacing = distanceFromTop;
}
});
]]>

How to Change Default MySQL/MariaDB Port in Linux

In this guide we’ll learn how to change the default port that MySQL/MariaDB database binds in CentOS 7 and Debian-based Linux distributions. The default port that MySQL database server is running under Linux and Unix is 3306/TCP.

In order to change the default MySQL/MariaDB database port in Linux, open MySQL server configuration file for editing by issuing the below command.

# vi /etc/my.cnf.d/server.cnf [On CentOS/RHEL]
# vi /etc/mysql/mariadb.conf.d/50-server.cnf [On Debian/Ubuntu] 

Search for the line stat starts with [mysqld] and place the following port directive under [mysqld] statement, as shown in the below file excerpts. Replace the port variable accordingly.

[mysqld] port = 12345
Change MySQL Port on CentOS and Ubuntu

Change MySQL Port on CentOS and Ubuntu

After you’ve added the new MySQL/MariaDB port, save and close the configuration file and install the following package under CentOS 7 in order to apply the required SELinux rules to allow the database to bind on the new port.

# yum install policycoreutils-python


Next, add the below SELinux rule to bind MySQL socket on the new port and restart the database daemon to apply changes, by issuing the following commands. Again, replace MySQL port variable to match your own port number.

--------------- On CentOS/RHEL --------------- # semanage port -a -t mysqld_port_t -p tcp 12345
# systemctl restart mariadb
--------------- On Debian/Ubuntu ---------------
# systemctl restart mysql [On Debian/Ubuntu] 

In order to verify if the port configuration for MySQL/MariaDB database server has been successfully applied, issue netstat or ss command and filter the results via grep command in order to easily identify the new MySQL port.

# ss -tlpn | grep mysql
# netstat -tlpn | grep mysql
Verify MySQL Port

Verify MySQL Port

You can also display the new MySQL port by logging in to MySQL database with root account and issue the below command. However, be aware that all connections to MySQL on localhost are made via MySQL unix domain socket, not via the TCP socket. But the TCP port number must be explicitly specified in case of command line remote connections to MySQL database using the -P flag.

# mysql -h localhost -u root -p -P 12345
MariaDB [(none)]> show variables like 'port';
Check MySQL Port Variable

Check MySQL Port Variable

In case of remote connection to MySQL database, the root user must be explicitly configured to allow incoming connections form all networks or just an IP address, by issuing the below command in MySQL console:

# mysql -u root -p
MariaDB [(none)]> grant all privileges on *.* to 'root'@'192.168.1.159' identified by 'strongpass';
MariaDB [(none)]> flush privileges;
MariaDB [(none)]> exit

Remotely log in to MySQL server via a command line client on the new port by issuing the below command.

# mysql -h 192.168.1.159 -P 12345 -u root -p 
Remote Login to MySQL on Port

Remote Login to MySQL on Port

Finally, once you’ve changed MySQL/MariaDB database server port, you need to update your distribution Firewall rules to allow incoming connections to the new TCP port so that remote clients can successfully connect to the database.

How to Permanently Disable Swap in Linux

Swapping or swap space represents a physical memory page that lives on top of disk partition or a special disk file used for extending the RAM memory of a system when the physical memory fills up.

Using this method of extending RAM resources, inactive memory pages are frequently dumped into the swap area when no RAM is available. However, do to the spinning speed of classical hard disks, swap space is way lower in transfer speeds and access time compared to RAM.

On newer machines with fast SSD hard disks, reserving a small partition for swapping can greatly improve access time and speed transfer compared to classical HDD, but the speed is still more magnitudes lower than RAM memory. Some suggest that the swap space should be set as twice the amount of machine RAM. However, on systems with more than 4 GB or RAM, swap space should be set between 2 or 4 GB.

In case your server has sufficient RAM memory or does not require the use of swap space or the swapping greatly decreases your system performance, you should consider disabling the swap area.


Before actually disabling swap space, first you need to visualize your memory load degree and then identify the partition that holds the swap area, by issuing the below commands.

# free -h 

Look for Swap space used size. If the used size is 0B or close to 0 bytes, it can be assumed that swap space is not used intensively and can be safety disabled.

Check Swap Space

Check Swap Space

Next, issue following blkid command, look for TYPE=”swap” line in order to identify the swap partition, as shown in the below screenshot.

# blkid 
Check Swap Partition Type

Check Swap Partition Type

Again, issue the following lsblk command to search and identify the [SWAP] partition as shown in the below screenshot.

# lsblk
Search Confirm Swap Partition

Search Confirm Swap Partition

After you’ve identified the swap partition or file, execute the below command to deactivate the swap area.

# swapoff /dev/mapper/centos-swap 

Or disable all swaps from /proc/swaps

# swapoff -a 

Run free command in order to check if the swap area has been disabled.

# free -h
Disable Swap Partition

Disable Swap Partition

In order to permanently disable swap space in Linux, open /etc/fstab file, search for the swap line and comment the entire line by adding a # (hashtag) sign in front of the line, as shown in the below screenshot.

# vi /etc/fstab
Disable Swap Partition Permanently

Disable Swap Partition Permanently

Afterwards, reboot the system in order to apply the new swap setting or issuing mount -a command in some cases might do the trick.

# mount -a

After system reboot, issuing the commands presented in the beginning of this tutorial should reflect that the swap area has been completely and permanently disabled in your system.

# free -h
# blkid # lsblk 

How to Search DuckDuckGo from the Linux Terminal

Like Googler (Google Site Search from the command-line), ddgr is a command line utility that can be used to search for key terms words via DuckDuckGo search engine and a command line browser on your terminal prompt.

Before installing ddgr command line search engine in Linux, first assure that the Python 3.4 and Python requests library needed to handle HTTPS requests are installed on your system, by issuing the following commands.

------------------ On CentOS, RHEL & Fedora ------------------ # yum install epel-release
# yum install python34 python34-requests
------------------ On Debian & Ubuntu ------------------
# apt install python3 python3-requests

In order to open ddgr searches you need to install a command line browser, such as elinks, links, lynx, w3m or www-browser, in your system.

Read Also: 8 Command Line Tools for Browsing Websites


In this guide we’ll configure ddgr search engine to open links via lynx text based browser.

# yum insall lynx [On CentOS, RHEL & Fedora]
# apt-get install lynx [On Debian & Ubuntu]

Next, set the BROWSER environment variable system-wide to point to lynx browser, by issuing the following commands with root privileges.

# export BROWSER=lynx
# echo “export BROWSER=lynx” >> /etc/profile

In order to install DuckDuckGo search engine command line utility via official ddgr github binary package releases, issue the following commands specific to your own Linux distribution.

------------------ On CentOS, RHEL & Fedora ------------------
# yum install https://github.com/jarun/ddgr/releases/download/v1.1/ddgr-1.1-1.el7.3.centos.x86_64.rpm ------------------ On Ubuntu 16.04 ------------------
# wget https://github.com/jarun/ddgr/releases/download/v1.1/ddgr_1.1-1_ubuntu16.04.amd64.deb
# dpkg -i ddgr_1.1-1_ubuntu16.04.amd64.deb
------------------ On Ubuntu 17.10 ------------------
# wget https://github.com/jarun/ddgr/releases/download/v1.1/ddgr_1.1-1_ubuntu17.10.amd64.deb # dpkg -i ddgr_1.1-1_ubuntu17.10.amd64.deb
------------------ On Debian 9 ------------------
# wget https://github.com/jarun/ddgr/releases/download/v1.1/ddgr_1.1-1_debian9.amd64.deb # dpkg -i ddgr_1.1-1_debian9.amd64.deb

You can also install ddgr on Ubuntu using a PPA repository, which is maintained by the developer of ddgr project.

$ sudo add-apt-repository ppa:twodopeshaggy/jarun
$ sudo apt-get update
$ sudo apt-get install ddgr

How to Search DuckDuckGo from Terminal Using ddgr

Finally, in order to search a specific keyword in ddgr serach engine, issue the command as shown in the below example.

# ddgr tecmint
Search DuckDuckGo from Commandline

Search DuckDuckGo from Commandline

To automatically open a specific displayed search result in lynx text-based browser, hit the corresponding number key and wait for the webpage to load. Sometimes you need to type “a” in lynx browser in order to always accept website cookies and load the website.

That’s all! For other information regarding DuckDuckGo command line search engine utility, visit ddgr official github page.

How to generate webpages using CGI scripts

Back in the stone age of the Internet when I first created my first business website, life was good.

I installed Apache and created a few simple HTML pages that stated a few important things about my business and gave important information like an overview of my product and how to contact me. It was a static website because the content seldom changed. Maintenance was simple because of the unchanging nature of my site.

Static content

Static content is easy and still common. Let’s take a quick look at a couple sample static web pages. You don’t need a working website to perform these little experiments. Just place the files in your home directory and open them with your browser. You will see exactly what you would if the file were served to your browser via a web server.

The first thing you need on a static website is the index.html file which is usually located in the /var/www/html directory. This file can be as simple as a text phrase such as “Hello world” without any HTML markup at all. This would simply display the text string. Create index.html in your home directory and add “Hello world” (without the quotes) as it’s only content. Open the index.html in your browser with the following URL.

file:///home/<yourhomedirectory>/index.html

So HTML is not required, but if you had a large amount of text that needed formatting, the results of a web page with no HTML coding would be incomprehensible with everything running together.

So the next step is to make the content more readable by using a bit of HTML coding to provide some formatting. The following command creates a page with the absolute minimum markup required for a static web page with HTML. You could also use your favorite editor to create the content.

echo "<h1>Hello World</h1>" > test1.html

Now view index.html and see the difference.

Of course you can put a lot of additional HTML around the actual content line to make a more complete and standard web page. That more complete version as shown below will still display the same results in the browser, but it also forms the basis for more standardized web site. Go ahead and use this content for your index.html file and display it in your browser.


I built a couple static websites using these techniques, but my life was about to change.

Dynamic web pages for a new job

I took a new job in which my primary task was to create and maintain the CGI (Common Gateway Interface) code for a very dynamic website. In this context, dynamic means that the HTML needed to produce the web page on a browser was generated from data that could be different every time the page was accessed. This includes input from the user on a web form that is used to look up data in a database. The resulting data is surrounded by appropriate HTML and displayed on the requesting browser. But it does not need to be that complex.

Using CGI scripts for a website allows you to create simple or complex interactive programs that can be run to provide a dynamic web page that can change based on input, calculations, current conditions in the server, and so on. There are many languages that can be used for CGI scripts. We will look at two of them, Perl and Bash. Other popular CGI languages include PHP and Python.

This article does not cover installation and setup of Apache or any other web server. If you have access to a web server that you can experiment with, you can directly view the results as they would appear in a browser. Otherwise, you can still run the programs from the command line and view the HTML that would be created. You can also redirect that HTML output to a file and then display the resulting file in your browser.

Using Perl

Perl is a very popular language for CGI scripts. Its strength is that it is a very powerful language for the manipulation of text.

To get CGI scripts to execute, you need the following line in the in httpd.conf for the website you are using. This tells the web server where your executable CGI files are located. For this experiment, let’s not worry about that.

ScriptAlias /cgi-bin/ "/var/www/cgi-bin/"

Add the following Perl code to the file index.cgi, which should be located in your home directory for your experimentation. Set the ownership of the file to apache.apache when you use a web server, and set the permissions to 755 because it must be executable no matter where it is located.


#!/usr/bin/perl
print “Content-type: text/html\n\n;
print “<html><body>\n;
print “<h1>Hello World</h1>\n;
print “Using Perl<p>\n;
print “</body></html>\n;

Run this program from the command line and view the results. It should display the HTML code it will generate.

Now view the index.cgi in your browser. Well, all you get is the contents of the file. Browsers really need to have this delivered as CGI content. Apache does not really know that it needs to run the file as a CGI program unless the Apache configuration for the web site includes the “ScriptAlias” definition as shown above. Without that bit of configuration Apache simply send the data in the file to the browser. If you have access to a web server, you could try this out with your executable index files in the /var/www/cgi-bin directory.

To see what this would look like in your browser, run the program again and redirect the output to a new file. Name it whatever you want. Then use your browser to view the file that contains the generated content.

The above CGI program is still generating static content because it always displays the same output. Add the following line to your CGI program immediately after the “Hello World” line. The Perl “system” command executes the commands following it in a system shell, and returns the result to the program. In this case, we simply grep the current RAM usage out of the results from the free command.

system "free | grep Mem\n";

Now run the program again and redirect the output to the results file. Reload the file in the browser. You should see an additional line so that displays the system memory statistics. Run the program and refresh the browser a couple more times and notice that the memory usage should change occasionally.

Using Bash

Bash is probably the simplest language of all for use in CGI scripts. Its primary strength for CGI programming is that it has direct access to all of the standard GNU utilities and system programs.

Rename the existing index.cgi to Perl.index.cgi and create a new index.cgi with the following content. Remember to set the permissions correctly to executable.


#!/bin/bash
echo “Content-type: text/html”
echo “”
echo ‘<html>’
echo ‘<head>’
echo ‘<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8″>’
echo ‘<title>Hello World</title>’
echo ‘</head>’
echo ‘<body>’
echo ‘<h1>Hello World</h1><p>’
echo ‘Using Bash<p>’
free | grep Mem
echo ‘</body>’
echo ‘</html>’
exit 0

Execute this program from the command line and view the output, then run it and redirect the output to the temporary results file you created before. Then refresh the browser to view what it looks like displayed as a web page.

Conclusion

It is actually very simple to create CGI programs that can be used to generate a wide range of dynamic web pages. This is a trivial example but you should now see some of the possibilities.