Category Archives: Linux

Shell backup script

Script to backup the web dorectory and mysql databases. Tested on ubuntu with cronjob every week.

#!/bin/bash
#=======================================================================================================================
# VPS Backup Script by Ivan Denkov
#=======================================================================================================================
DATE=$(date +"%Y-%m-%d")
MYSQLDUMP="$(which mysqldump)"
TAR="$(which tar)"
PASS="MySQLPSWD"
DIR="/home/backups"
DBS=`mysql -u root -h localhost -p$PASS -e"show databases"`
UPTIME=`uptime`
FREEHD=`df -h`

#This will remove files older than 35 days
find $DIR/* -mtime +35 -exec rm -rf {} \;

$TAR -cvf $DIR/Backup-$DATE.tar /var/www
for DATABASE in $DBS
do
if [ $DATABASE != "Database" ]; then
FILENAME=$DATABASE
$MYSQLDUMP -u root -h localhost -p$PASS $DATABASE > $DIR/$FILENAME.sql
$TAR -rvf $DIR/Backup-$DATE.tar $DIR/$FILENAME.sql
fi
done

#Remove dumped .sql in the folder
rm -rf $DIR/*.sql

sleep 40

#send me e-mail when done
echo "Email Body - Back Up completed at date $DATE, or maybe not!? Let see the statistic \n\n $UPTIME \n\n  $FREEHD" | mail -s "Email Subject - Back UP $DATE" your@email.com

Kill and Logout users in pts/* Linux

As a  Linux administrator you may need to force logout and kill a specific user, or an active user in pts/0 pts/1 pts/3 etc. Also this tutorial will work in most linux distros.
First of all display the out put of “w” command.

[root@server ~#]w
18:08:30 up 3:54, 3 users, load average: 0.05, 0.02, 0.00
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
root pts/0 192.168.10.100 14:15 0.00s 0.05s 0.01s w
james pts/1 192.168.10.100 18:07 50.00s 0.02s 0.02s -bash
james pts/2 10.10.20.23 18:07 39.00s 0.02s 0.02s -bash

Here the user “james” is logged in from two different machines. And you need to force logout and kill the user “james” logged in from ip: 192.168.10.100 (pts/1)

use the below command

[root@server ~#]skill -KILL -v pts/1

This command will force logout and kill the user in pts/1. and the same user logged in pts/2 will not be logged out.

If need to kill a users all the connected sessions at once

[root@server ~#]skill -KILL -u james

(this will kill both pts/1 and pts/2 cessions)

To STOP/PAUSE a user’s activities

[root@server ~#]skill -STOP -u james

To RESUME a stopped user

[root@server ~#]skill -CONT -u james

Edit

There is some bug in recent Debian(7) and distros based on them like Ubuntu, which will make the command

skill -KILL -v pts/1

do nothing

What you can do in such case is to get the PID of the terminal you want to kill with

 skill -i -t pts/1

it will return something like

pts/1    root     27933 bash               ?

Just kill it –

kill 27933

ALFA AWUS036H Set to max power

Vivek’s video is here.

This video discusses the Alfa card in some detail. The frequency range the card operates on depends on your country. This limits which channels can be used, and the transmission power. Vivek shows us how to change the current country so as to increase the number of channels available and transmit power.

0. Start backtrack, leave the alfa card disconnected.

1. Monitor kernel messages in one terminal:

tail -f /var/log/messages

2. Plug in you alfa card.

3. You should see lines in your kernel messages that read:

cfg80211: Calling CRDA to update world regulatory domain
cfg80211: World regulatory domain updated:
cfg80211:      (start_freq - end_freq @ bandwidth), (max_antenna_gain, max eirp)
cfg80211:      (2402000 KHz - 2472000 KHx @ 40000 KHz), (300 mBi, 2000 mBm)
...

You can check these frequency ranges against the Wifi frequency table (wikipedia).

Transmit power is measured in dBm. 30dBm = 1W.

https://www.rapidtables.com/convert/power/dBm_to_mW.htm

The table in kernel messages show EIRP (effecive isotropic radiated power). It’s a measure of the effective transmit power of a device calculated as:

EIRP = Transmit Power (in dBm) + Antenna Gain (in dBi) – Cable loss (in dBm)

4. Bring up the alfa card, and select channel 1.

Open another terminal and enter the following:

	
ifconfig wlan0 up
iwconfig wlan0 channel 1
iwconfig

In the iwconfig output you should see that the frequency is listed as 2.412GHz and it’s transmiting at 20 dBm.

5. Change the transmit power of the card:

iwconfig wlan0 txpower 30

You’ll notice if you try this you get an error as follows:

	
Error for wireless request "Set Tx Power" (8B26) :
    SET failed on device wlan0 ; Invalid argument.

However, we can switch our card between regulatory domains:

	
ifconfig wlan0 down
iw reg set US
ifconfig wlan0 up

Look at your kernel message terminal. You should see that the regulatory domain has change to the US. And that the eirp has change to 2700 mBm for channel 1.

Try changing the power again:

	
iwconfig wlan0 txpower 27

However if you setting the power beyond 27 you’ll still receive and error. Setting a channel of 12 or above will also cause the following error:

	
Error for wireless request "Set Frequency" (8B04)
    SET failed on device wlan0 ; Invalid argument.

The least restrictive countries are BO and BZ. You can set these are before as:

	
ifconfig wlan0 down
iw reg set BO
ifconfig wlan0 up
iwconfig wlan0 channel 13
iwconfig wlan0 txpower 30

You should receive no errors. However you should be aware that using the card in this manner may be illegal in your country.

Update: You will have to perform these steps each time you power on your VM or physical device. You can toss the below script in your init.d dir so you wont need to remember. Again, not my work, just placing here for quick reference.

    #!/bin/bash
    ##iw reg set <your-country-code>
    iw reg set <insert-your-country-code-here-in-CAPITAL-LETERS>All country codes are in ‘CAPITAL LETTERS’

save & close text edoter

then put it in the /etc/init.d/ directory.

So in a terminal enter

    sudo cp ~/Desktop/setwirelesscountrycode.sh /etc/init.d/
    Then make the file you created executable.e.g.
    sudo chmod +x /etc/init.d/setwirelesscountrycode.sh To set it to run on startup
    sudo update-rc.d /etc/init.d/setwirelesscountrycode.sh defaults note ‘defaults’ puts a link to start ‘/etc/init.d/setwirelesscountrycode.sh’ in run levels 2, 3, 4 and 5. and puts a link to stop ‘/etc/init.d/setwirelesscountrycode.sh’ into run levels 0, 1 and 6.

Speed up PHP with APC on Ubuntu 10.04LTS

Ubuntu 10.04 LTS makes it quite simple to set up a basic LAMP server using tasksel; however, the default PHP set up does not include APC, the Alternative PHP Cache, which speeds up many PHP applications like Drupal. In the past, setting up APC involved using PECL or installing from source, but with Ubuntu Lucid, the process has been simplified using apt-get.

First, let me identify my demo system. It is running Ubuntu 10.04 LTS Lucid and has been patched to the latest version:

$ uname -a
Linux demo 2.6.32-24-generic #43-Ubuntu SMP Thu Sep 16 14:17:33 UTC 2010 i686 GNU/Linux
$ lsb_release -a
No LSB modules are available.
Distributor ID:	Ubuntu
Description:	Ubuntu 10.04.2 LTS
Release:	10.04
Codename:	lucid
$ sudo apache2ctl status | grep "Server Version"
Server Version: Apache/2.2.14 (Ubuntu) PHP/5.3.2-1ubuntu4.7 with Suhosin-Patch
$ apt-cache show php-apc | grep Version
Version: 3.1.3p1-2

Ubuntu has added a Debian package into universe that allows APC to be added to any system quite easily:

$ sudo apt-get install php-apc
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Suggested packages:
  php5-gd
The following NEW packages will be installed:
  php-apc
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
Need to get 0B/77.2kB of archives.
After this operation, 217kB of additional disk space will be used.
Selecting previously deselected package php-apc.
(Reading database ... 28911 files and directories currently installed.)
Unpacking php-apc (from .../php-apc_3.1.3p1-2_i386.deb) ...
Processing triggers for libapache2-mod-php5 ...
 * Reloading web server config apache2
   ...done.
Setting up php-apc (3.1.3p1-2) ...

Note: You must restart the web server to begin using APC

$ sudo apache2ctl graceful

Out of the box (er…package), APC has some sane defaults. If you are “a serious user,” you will want to change your configuration yourself. Seriously, that is what the documentation says:

    …serious users should consider tuning the following parameters…

To tweak your very serious APC installation, you can change the settings manually (using vim):

$ sudo vim /etc/php5/conf.d/apc.ini

The APC configuration file is seriously barren; it is little more than an extension include directive. You can add extra keys after reading the APC’s online documentation related to settings.

Finally, there is a small php script that provides more information on the operation of the APC module. Copy it to your web root and decompress it. You should change the default username and password used to protect the script by changing the username and password variables directly in the PHP code:

$ sudo cp /usr/share/doc/php-apc/apc.php.gz /var/www
$ sudo gzip -d /var/www/apc.php.gz
$ sudo vim /var/www/apc.php

Change credentials near line 41:

defaults('ADMIN_USERNAME','apc'); // Admin Username
defaults('ADMIN_PASSWORD','password'); // Admin Password - CHANGE THIS TO ENABLE!!!

Now, view your APC page (assuming your web server is at 192.168.0.6):

https://192.168.0.6/apc.php

fail2ban on centos 6.x

I just had to install fail2ban on a centOS server with plesk, and thought I write it down as I am going to need it in the future.

Fail2Ban is excellent software as it helps to deter those would brute force attacks on a server.

So first we need to enable the repo called epel, so as the root user:

wget https://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
yum install epel-release-6-8.noarch.rpm

Then in the text editor (I use nano) of your choice edit the repo to disable it (we only want to enable it to download any packages from it, this adds security):

nano /etc/yum.repos.d/epel.repo

and change

enabled=1

to

enabled=0

Now we are going to install fail2ban, we will also need the whois program so fail2ban can query ip whois database:

yum --enablerepo=epel install fail2ban jwhois

now we have our packages installed, we want to copy the config file and use the copy so we have a backup if we mess things up:

cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

OK we are ready to edit our config file so:

nano /etc/fail2ban/jail.local

I normally leave the the defaults in place. So find the place where ‘[ssh-iptables]‘ is located in the file.
This is already turned on but you will need to alter a few options. A quick review of the basic options are:

enabled : Whether to turn the filter on or off.
filter : Which filter to use located in ‘/etc/fail2ban/filter.d’.
action : The action to take located in ‘/etc/fail2ban/action.d’.
logpath : Where the log to scan is located.
maxretry : the number of times a login attempt can be made before a ban.
bantime : How long the ban will last in seconds.
findtime : The ban is reset if no match is found within “findtime” seconds.

So with that in mind here are some rules for ssh, postfix, courier-imap and proftpd. Change ‘yourdomain.com’ to your actual server domain and ‘user@yourdomain.com’ to your email address you want the whois data sent to.

[ssh-iptables]

enabled = true
filter = sshd
action = iptables[name=SSH, port=ssh, protocol=tcp]
sendmail-whois[name=SSH, dest=user@yourdomain.com, sender=fail2ban@yourdomain.com]
logpath = /var/log/secure
maxretry = 3
bantime = 43200
findtime = 43200

[postfix-iptables]

enabled = true
filter = postfix
action = iptables[name=Postfix, port=smtp, protocol=tcp]
sendmail-whois[name=Postfix, dest=user@yourdomain.com, sender=fail2ban@yourdomain.com]
logpath = /usr/local/psa/var/log/maillog
maxretry = 6

[courierimap-iptables]

enabled = true
filter = courierlogin
action = iptables-multiport[name=IMAP, port="110,995,143,993"]
sendmail-whois[name=IMAP, dest=user@yourdomain.com, sender=fail2ban@yourdomain.com]
logpath = /usr/local/psa/var/log/maillog
maxretry = 6

[proftpd-iptables]

enabled = true
filter = proftpd
action = iptables[name=ProFTPD, port=ftp, protocol=tcp]
sendmail-whois[name=ProFTPD, dest=user@yourdomain.com]
logpath = /var/log/proftpd/auth.log
maxretry = 6

Now edit the following filters:
/etc/fail2ban/filter.d/courierlogin.conf

Change:
LOGIN FAILED, .*, ip=\[\]$

To:
LOGIN FAILED, ip=\[\]$

/etc/fail2ban/filter.d/proftpd.conf. Repalce the failregex with:

failregex = \[\]\s+530$

Because Plesk doesn’t log failed auth attempts in proftpd, we have to make it do so.

/etc/proftpd.conf add:

ExtendedLog /var/log/proftpd/auth.log AUTH auth
LogFormat auth "%v %t \"%r\" [%h] %s"

create ‘proftpd’ directory in ‘/var/log’

mkdir /var/log/proftpd

Create a file in ‘/etc/logrotate.d’

mkdir /etc/logrotate.d/proftpd

and put this in it:

/var/log/proftpd/auth.log
{
weekly
missingok
rotate 7
compress
delaycompress
notifempty
create 640 root adm
sharedscripts
postrotate
# reload could be not sufficient for all logs, a restart is safer
/usr/bin/kill -HUP `cat /var/run/proftpd.pid 2>/dev/null` 2>/dev/null || true
endscript
}

Now restart fail2ban and proftpd:

service fail2ban restart
/etc/init.d/xinetd restart

Now you should have a more secure server. Enjoy!

Apachebench Tutorial ab testing Tool Example in Ubuntu/Linux

Official Apache Page

Is there a time when you are thinking how to do a server load testing to evaluate your PHP web application performance? This is where you will be using the Apachebench or “ab” testing tool. This is a very useful open source tool not only to PHP developers but to the entire users of the Apache server. This tool is used to evaluate the execution times of your PHP web application or the response time of your website under “stressing” conditions. This condition means how your PHP web application will perform under conditions similar to what exactly will be happening on a real web server not just on your local host environment (such as XAMPP). For example in actual website deployment in a production server; it will be subjected to two stressing conditions:

a.) Number of connections to that application – these are the number of visitors to your website which are connected to that application. The higher the number of visitors to that application, the higher also the number of connections. This is a stressing condition because sometimes if your PHP web application in your website is poorly written, it will result to a very poor performance in actual deployment which can slowed down if there are a lot of users in your website.

b.) Number of concurrent users – these are the actual number of users that are using the application at exactly the same time. Of course in a very low traffic website, the concurrent users is almost zero because the probability that two users will exactly hit the application and do the same request is very small. This can be an issue with high traffic websites; it is because the number of concurrent users can slowed down the application and put a signficant load on the web server. Some web host even limits the number of concurrent users (typically those that are originating from a free web hosting scheme).

The good thing with Apachebench is that you measure the performance of a certain web application or website given a stress conditions. The stressing conditions required by Apache bench are two above. What is expected to happen is that a poorly written PHP web application will perform poorly under stressing conditions. This is why performance benchmarks of CMS, PHP frameworks, etc are using ab testing to evaluate the quality of the application.

How to Get Started with AB testing tool in Linux/Ubuntu:

Below are the steps :

1.) In Ubuntu, Apachebench can be installed using the Apache 2 utils. Go to Applications – Accessories – Terminal, at the command prompt type:

sudo apt-get install apache2-utils

2.) After installation, you are now ready to use Apachebench. Lets have an example. Supposing you will need to know how wordpress.org performs when there are 300 connections and 3 concurrent users. First, this is the syntax of ab:

ab -n [number of connections] -c [number of concurrent users] [url]

3.) Using the syntax above for ab test, below is the final command to type in the shell prompt:

ab -n 300 -c 3 https://wordpress.org/

4.) Below are the results, you should see in your terminal:

This is ApacheBench, Version 2.3 <$Revision: 655654 $>
Copyright 1996 Adam Twiss, Zeus Technology Ltd, https://www.zeustech.net/
Licensed to The Apache Software Foundation, https://www.apache.org/

Benchmarking wordpress.org (be patient)
Completed 100 requests
Completed 200 requests
Completed 300 requests
Finished 300 requests


Server Software:        nginx
Server Hostname:        wordpress.org
Server Port:            80

Document Path:          /
Document Length:        9172 bytes

Concurrency Level:      3
Time taken for tests:   72.917 seconds
Complete requests:      300
Failed requests:        296
   (Connect: 0, Receive: 0, Length: 296, Exceptions: 0)
Write errors:           0
Total transferred:      2789682 bytes
HTML transferred:       2743782 bytes
Requests per second:    4.11 [#/sec] (mean)
Time per request:       729.172 [ms] (mean)
Time per request:       243.057 [ms] (mean, across all concurrent requests)
Transfer rate:          37.36 [Kbytes/sec] received

Connection Times (ms)
              min  mean[+/-sd] median   max
Connect:      214  225   6.8    224     253
Processing:   448  502 177.6    486    3481
Waiting:      221  252 175.9    237    3232
Total:        670  728 179.0    710    3722

Percentage of the requests served within a certain time (ms)
  50%    710
  66%    721
  75%    728
  80%    735
  90%    751
  95%    771
  98%    818
  99%    931
 100%   3722 (longest request)

Very important interpretation of results:

1.) It means it takes 3722ms for wordpress.org to serve longest request under a stressing conditions of 300 connections and 3 concurrent users. This is the longest response time.

2.) But on the “average” it will only take wordpress.org to respond within 728ms +- tolerance of 179 ms.

A more powerful and faster website can respond to faster times even with more stressing conditions. If you are using Windows, you can read this Apachebench tutorial using Windows OS.

Warning: Do not use Apachebench excessively to make enormous request to a web server that you do not own. This is a form of denial of service attack and can put you to jail: https://www.pcworld.com/businesscenter/article/181127/ex_ceo_charged_in_denial_of_service_attack.html

Defragment ext4

ext4 filesystems are not actually fragment-proof, however they fragment the drives a lot less than ntfs for example, you can use

e4defrag

Option c will check if defragment is need, and then you can run it with v
Example:

 sudo e4defrag -v <filename or mount point of ext4 drive> 

Manual page

Apache Landing Page

This code list the directories and files in a table.

<!DOCTYPE html>
<html>
<head>
   <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
   <title>Ze Master Server of The Universe</title>
   <style>
     *{
         padding:0;
         margin:0;
     }
     html,body {
         color:#333;
         font-family: "Lucida Console", Courier, monospace;
         font-size:14px;
         text-shadow:1px 1px 1px #cacaca;
         -webkit-text-shadow:1px 1px 1px #cacaca;
         -moz-text-shadow:1px 1px 1px #cacaca;
     }
     a{
         padding: 2px 0 0 24px;
         color:#FE4902;
         text-decoration:none;
     }
     a:hover{
         color:#000;
         cursor:url(hand.gif), progress;
     }
     #container{
         margin:0 auto;
         width:700px;
         margin-top:20px;
         padding-top:10px;
         border:1px solid #EEE;
         border-radius:10px;
         -moz-border-radius:10px;
     }
     .head{
         background-color:#38AF64;
         color:#FFF;
         font-weight:bold;
         padding:7px 0 5px 10px;
         font-size:14px;
         letter-spacing:1px;
         font-family: Verdana, Arial, Helvetica, sans-serif;
     }
     .head:hover{background-color:#FE4902;}
     .head span{font-size:9px; letter-spacing:0;}
     td{
         background-color:#F3F3F3;
         padding:6px;
     }
     td:hover{background-color:#EFEFEF;}
     h1{
         font-size:18px;
         font-weight:bold;
         padding:0 0 10px 10px;
     }

     /*icons for file types (add more to suit your needs - icons by famfamfam.)*/

     /*images*/
     a[href$=".jpg"] {background: url(image.gif) no-repeat left 50%;}
     a[href$=".gif"] {background: url(image.gif) no-repeat left 50%;}
     a[href$=".png"] {background: url(image.gif) no-repeat left 0%;}

     /*pdfs*/
     a[href$=".pdf"] {background: url(pdf.gif) no-repeat left 50%;}

     /*psds*/
     a[href$=".psd"] {background: url(psd.gif) no-repeat left 50%;}

     /*docs*/
     a[href$=".doc"] {background: url(doc.gif) no-repeat left 50%;}
     a[href$=".txt"] {background: url(doc.gif) no-repeat left 50%;}

     /*videos*/
     a[href$=".avi"] {background: url(video.gif) no-repeat left 50%;}
     a[href$=".m4a"] {background: url(video.gif) no-repeat left 50%;}
     a[href$=".mov"] {background: url(video.gif) no-repeat left 50%;}
     a[href$=".mp4"] {background: url(video.gif) no-repeat left 50%;}
     a[href$=".wmv"] {background: url(video.gif) no-repeat left 50%;}

     /*audio*/
     a[href$=".mp3"] {background: url(audio.gif) no-repeat left 50%;}
     a[href$=".wma"] {background: url(audio.gif) no-repeat left 50%;}
     a[href$=".aac"] {background: url(audio.gif) no-repeat left 50%;}

     /*web pages*/
     a[href$=".html"] {background: url(html.gif) no-repeat left 50%;}
     a[href$=".php"] {background: url(html.gif) no-repeat left 50%;}

   </style>

</head>
<body>
   <div id="container">
       <?php
         // opens this directory
         $myDirectory = opendir(".");

         // gets each entry
         while($entryName = readdir($myDirectory)) {
           $dirArray[] = $entryName;
         }

         // finds extention of file
         function findexts ($filename)
         {
           $filename = strtolower($filename) ;
           $exts = split("[/\\.]", $filename) ;
           $n = count($exts)-1;
           $exts = $exts[$n];
           return $exts;
         }

         // closes directory
         closedir($myDirectory);

         //  counts elements in array
         $indexCount   = count($dirArray);

         // sorts files
         sort($dirArray);

         // print 'em
         print("<h1>Directory Contents</h1>");
         print("<table width='100%' cellspacing='10'>
                 <tr>
                   <td class='head'>Directory/File</td>
                   <td class='head'>Type</td>
                   <td class='head'>Size <span>(bytes)</span></td></tr>\n");

         // loops through the array of files and print them all
         for($index=0; $index < $indexCount; $index++) {
               if (substr("$dirArray[$index]", 0, 1) != "."){ // don't list hidden files
               print("<tr><td><a href='$dirArray[$index]'>$dirArray[$index]</a></td>");
               print("<td>");
               print(findexts($dirArray[$index]));
               print("</td>");
               print("<td>");
               print(filesize($dirArray[$index]));
               print("</td>");
               print("</tr>\n");
           }
         }
         print("</table>\n");
       ?>
   </div>

</body>
</html>

LAMP on Ubuntu 11.10

Install LAMP and phpMyAdmin on Ubuntu 11.10

The Ubuntu development team has made it very easy to install and set up a web server. Open a terminal window and enter the following command.
sudo apt-get install lamp-server^

Please enter the command exactly as it’s shown above. The carat (^) is not a typo and the command will not work without it.

Command to install LAMP

If prompted, enter your password.

The package manager will now display a list of packages to be installed. Hit to confirm that you want to go ahead with the install.

Installing LAMP packages

Apt will now start downloading and installing the packages on your computer.

After a short wait, you will be prompted to set a password for MySQL’s administrative user. Enter a password at the prompt and make sure it’s something you will remember or make a note of it.

MySQL password

You will then be prompted to confirm your password.

Confirm MySQL password

Type in the same password and hit . The package manager will now continue downloading and installing packages. After a short wait the installation will complete.
Testing Apache

Now we’ll run a quick test to make sure that the Apache web server is working. Open a web browser and enter the address https://localhost/. You should see a page that says “It Works!”

Testing Apache installation
Testing php

Now that we’ve verified that Apache works, we need to verify that php is working properly. We’re going to create a file in the /var/www directory called testing.php. Enter the following command in the terminal to create the file.
echo “” | sudo tee /var/www/testing.php

Enter your password if prompted.

Now you’ll need to restart the Apache web server. Enter into the terminal:
sudo service apache2 restart

Now open your web browser and enter the following address: https://localhost/testing.php

You should see a web page that displays a bunch of information about your php and Apache environment.

Testing php
Configure MySQL

Since this is for a local development environment, the MySQL database needs to be bound to the localhost IP address. This should be 127.0.0.1 by default. You can verify your localhost address with the following terminal command.
cat /etc/hosts | grep localhost

You should see output something like this:

127.0.0.1 localhost
::1 ip6-localhost ip6-loopback

Now you need to verify that this address is the bind address MySQL’s my.cnf file. Use the following terminal command.
cat /etc/mysql/my.cnf | grep bind-address

You should see output like this.

bind-address = 127.0.0.1

If it’s not correct you’ll need to edit /etc/mysql/my.cnf as root to fix it.
Install phpMyAdmin

You now have a functioning LAMP installation. You don’t need to install phpMyAdmin, but it provides a much easier way to administer your MySQL databases if you’re not familiar with MySQL’s commands. You can install phpMyAdmin with:
sudo apt-get install libapache2-mod-auth-mysql phpmyadmin

Enter your password if prompted.

Installing phpMyAdmin

Again the package manger will show you the packages it’s about to install. Hit to move forward with the installation.

The package manager will now begin downloading and installing packages. After a short wait you will be prompted to choose the web server to configure for phpMyAdmin. Hit to mark apache2 with an asterisk (*) as it’s shown in the following picture (click on the image to see it in full size). Then hit .

Select apache2

The next screen will ask about some automatic database configuration with dbconfig-common. Hit to accept the default and move on.

Configure phpMyAdmin with dbconfig-common

Next you’ll be prompted for the MySQL administrator password. Enter the password that your created earlier.

Enter MySQL administrator password

Now you’ll be prompted for a MySQL application password. You can allow the system to generate a random password or choose your own.

Enter MySQL application password

If you choose your own password, you will be prompted to verify it at the next screen.

Verify MySQL application password

Your phpMyAdmin installation and configuration is now complete.
Testing phpMyAdmin

Open your web browser and enter the address https://localhost/phpmyadmin/.

You should see a page like this.

phpMyAdmin login screen

Now log in with the user name root and the password that you created earlier in the tutorial.

phpMyAdmin Home screen

Congratulations, you now have a working web development environment set up on Ubuntu 11.10. You can place the files for your website under /var/www. Note that this location is owned by the root user, so you’ll need to copy your files over as root for it to work. Otherwise, you can do some further Apache configuration so you can place the files for your website in a directory somewhere under your home directory.
Fixing some common problems
Fixing phpMyAdmin

One common error that some people make is that they forget to mark apache2 during the phpMyAdmin configuration. When this happens you’ll get a 404 Not Found error when trying to navigate to https://localhost/phpmyadmin/.

phpMyAdmin Not Found

If this happens, enter the following terminal command.
sudo dpkg-reconfigure phpmyadmin

You will be prompted about reinstalling the database. Accept the default of “No” and hit .

Don’t reinstall phpMyAdmin database

Make sure to then mark apache2 by having the cursor next to apache2 and then hitting to mark it with a *, then hit .

Reconfigure phpMyAdmin for Apache

You will then need to reload Apache.
sudo service apache2 reload

You should now be able to load https://localhost/phpmyadmin/. If you’re still seeing the 404 Not Found error, then you will need to clear your web browser cache and try again.

phpMyAdmin login screen
Fixing the Apache fully qualified domain name

During the above steps you may have seen an error message like this when reloading Apache.

apache2: Could not reliably determine the server’s fully qualified domain name,
using 127.0.1.1 for ServerName

This doesn’t seem to cause any problems for me, but if you don’t like seeing that error, you can fix it with this command.
echo “ServerName localhost” | sudo tee /etc/apache2/conf.d/fqdn

Then reload Apache with
sudo service apache2 reload

Enjoy your new web development environment!