Linux

Server Administration

Execute Logrotate Command Manually

Overview

One day while perusing around one of my Debian Linux servers I noticed that the disk was extremely full. It isn’t a server I access all the time so the disk space being filled up had gone unnoticed. After taking a look at what could be using up all the disk space, I realised that my log files had grown to be absolutely massive with some log files being a few GB’s in size.

logrotate.d Wasn’t Running

The cause of the issue was that logrotate had not been running for quite some time. I fixed logrotate but I couldn’t afford to wait for the logrotate to automatically run on it’s next schedule. I began to panic and needed to quickly rotate the logs to regain precious space before the server and websites came crashing down.

Execute Logrotate Command Manually

Since most of my disk space was consumed by apache, I decided to execute logrotate command manually in linux and pass it the config of the logrotate apache . To do so, I used the following command:

logrotate -vf /etc/logrotate.d/apache2.conf

The flags ‘-vf’ passed to the command are as follows:

  • -v verbose shows more information. useful to try detect any errors there may be with logrotate
  • -f force the rotation to occur even if it is not necessarily needed

And /etc/logrotate.d/apache2.conf is the location of my config file of for the apache2 logrotate. The content of my config file are as follows

/var/log/apache2/*_log {
	weekly
	missingok
	rotate 52
	compress
	delaycompress
	notifempty
	create 640 root adm
	sharedscripts
	postrotate
		if [ -f /var/run/apache2.pid ]; then
			/etc/init.d/apache2 restart > /dev/null
		fi
	endscript
}

Once I ran logrotate in linux manually, all my apache2 log files got rotated, compressed with gzip and recycled leaving me with heaps more free disk space.

How To Setup IP Address in Linux

Overview

In this guide, you will be shown how to setup the IP address of a computer or server running Linux. Before we know which way to configure your network card, you need to know if you want to use a static or dynamic IP address.

Setup IP Address

Setup IP Address

Static IP vs DCHP IP

Whats the difference? Static is an IP address that yet manually chose and set for your computer. It won’t change until you decide to update it. DHCP is an IP address that is given to your computer by a DHCP server (usually a router or another server). The DHCP assigned IP address is given to you from a pool (or range) of IP addresses and can change depending on which ones are available.

How To Setup IP Address in Linux

Depending on your network configuration, you will need to either use a static IP address which is commonly used on servers on corporate networks. A static IP address is manually entered in and doesn’t change.
You could also use a dynamic IP address which can be assigned to your computer via a DHCP service. DHCP is more common in home networks as it can be setup automatically and doesn’t require the user to know how to change an IP address. DHCP is a service that runs on your network that will automatically setup your network IP address. Before DHCP can assign your computer a IP address, you need to setup your network interface to use DHCP

Editing the Network Interface

All your IP address information be it dynamic or static is stored under your network interface file which can be found under the path /etc/network/interface. To edit this file you may need root or sudo access. To edit the file enter the following:

sudo vi /etc/network/interfaces

Inside this file you will notice a loop back device. Ignore this part as we want to focus on the eth0 interface – or interface 0. If you have multiple network interfaces, you may see eth0, eth1, etc.

Setup DHCP for Network Interface

Find the section that has iface eth0 (or whichever interface you need – eth1, eth2, etc). and change it to match below. That’s the only configuration you. Now you need to restart your network interface to bring in the changes (shown below).

allow-hotplug eth0
iface eth0 inet dhcp

Setup Static IP for Network Interface

If you need a static ip address, then edit your interface file to be similar to below. Note that your ip, netmask and other items will need to match your own network range.

# The primary network interface
allow-hotplug eth0
iface eth0 inet static
address 192.168.0.20
netmask 255.255.255.0
network 192.168.0.1
broadcast 192.168.0.255
gateway 192.168.0.1
dns-nameservers 192.168.0.2

Note that network and broadcast are optional entries and if omitted will be automatically detected.

Restart Networking Interfaces

In order for the above changes to come into effect, you need to restart your network interface. You can do this by running the following command:

/etc/init.d/networking restart

Sometimes you will find your interface doesn’t come online when restarting so entering in `ifup` will bring it back up where eth0 is the network interface you configured.

ifup eth0

And inversely, if you wanted to bring the network interface down, you would type in:

ifdown eth0

Caution! Typing in ifdown will take the network interface offline and drop your network connection so don’t running this command remotely!

Add New Zone To Bind DNS Server

Overview

Welcome to the second of my DNS articles. It is more of a prequel to my first article in which I explained the steps in Creating A DNS Entry For A SubDomain.

This article assumes you have already installed bind and it is all running. If not, then you will need to setup bind first.

What is a DNS Zone?

My previously article explained what a zone is so I won’t go into to much detail here, but essentially a zone is the term used to describe a config file which contains a specific domain/subdomain collection in your DNS server. Bear in mind that a DNS server has multiple zones (and thus domains) associated to it. Each domain generally has its own zone file however in some situations, you can have multiple domains per zone file. For example, mydomain.com and mydomain.net and mydomain.org could all be in the same zone file as long as they all need to point to the same ip address.

Create the DNS zone file

The zone file we will create for this example will be for the domain example.com. The zone file will tell the DNS server which IP the domain should point to as well as configuring expiry and refresh times for the domain. Generally, the naming format for a zone file is db.example.com.conf where the domain in this case is example.com. Now to create the zone file and add the contents shown in the Sample DNS Domain Zone File

sudo vi /etc/bind/db.example.com.conf

Sample DNS Domain Zone File

In this sample DNS domain zone file, there are a couple changes you need to make to ensure it works in your situation. Firstly, change ns1.exampledns.com and ns2.exampledns.com with your own ns1 and ns2 dns servers. Secondly you can change example.com to the domain you are adding.

Optionally leave out $ORIGIN if you are adding multiple domains to a single zone file. The @ symbol simply means the current zone which is great for when you have multiple domains to a single zone file.

; Zone file for example.com
$TTL    3600
$ORIGIN example.com
@       IN      SOA     ns1.exampledns.com.    root.example.com. (
                     2012033101         ; Serial
                           3600         ; Refresh
                           1800         ; Retry
                         604800         ; Expire
                          43200 )       ; Negative Cache TTL

        IN      NS      ns1.exampledns.com.
        IN      NS      ns2.exampledns.com.

@       IN      A       192.168.0.2
www     IN      A       192.168.0.2

Add New Zone To Bind DNS Server

Above we created the zone config file. Now we need to add the zone file to our dns config file which tells our DNS server that it should control and serve requests for this new domain zone.

Open your DNS config file and add a zone in for your domain. I will be using example.com in my example. Here the file is located under /etc/bind/named.conf.local however depending on the way your DNS server was configured, it may be under /etc/bind/named.conf.options or rarely even /etc/bind/named.conf

sudo vi /etc/bind/named.conf.local

Add a zone to your DNS config file

At the end of the file add an entry similar to the following

zone "example.com" {
	type master;
	file "/etc/bind/db.example.com.conf";
};

As you will see, the type of zone is a master zone. This means that it is the primary holder for dns information regarding this domain.

Restarting Bind DNS Server

Once you have added your new zone to your bind dns server, you need to restart the bind daemon in order to reload the new config file. You can do so by issuing the following command.

Debian / Ubuntu Linux

Restart bind dns server on Debian and Ubuntu Linux.

service bind9 start

Alternate method to restart bind dns server on Debian and Ubuntu Linux.

/etc/init.d/bind9 restart

Redhat / Fedora Linux

Restart bind dns server on Redhat and Fedora Linux.

service named restart

Alternate method to restart bind dns server on Redhat and Fedora Linux.

/etc/init.d/named restart

Note: you may need to use sudo to run these commands if your account doesn’t have enough privileges.

Create DNS Record For Subdomain – Add DNS Entry Into Bind

Overview

Welcome to the first of a number of DNS related articles I will write to help explain the different tasks needed to configure and manage your own DNS server using bind under Linux.

The article assumes you have already installed bind and it is all running. If not, then you will need to setup bind first. Once you have setup bind, you are now ready to create DNS record for subdomain. You can also checkout my next article (which is more of a prequel) about adding Adding New Zone To Bind DNS Server.

What is a DNS Zone?

Essentially a zone in DNS terms is a domain along with all it’s subdomains. Typically you will have one zone config file per domain (which includes its subdomains and any mail records, alias’ and other entries associated with that domain) however you can also have multiple domains using a single zone file. If you have multiple domains to a zone file, each of those domains will be configured identically which includes the IP addresses and subdomains each of the entries point to. The zone file tells the DNS server what IP addresses are associated to each of the domains and subdomains. Each record in the zone file can also be configured to be any type of DNS record such as A record, MX record, TXT record, etc.

Editing a zone file

The zone files are located under /etc/bind/ and the zone files generally (but not always) are in the format of db.domain.com.conf. For example, my zone file for darian-brown.com is under:

/etc/bind/db.darian-brown.com.conf

So now we simply edit the zone file using vi or your preferred editor

sudo vi /etc/bind/db.darian-brown.com.conf

Create DNS Record For Subdomain

In your zone file you will see a couple existing DNS records. You should see a section similar to this where 192.168.0.2 is the IP address on our internal network where these domains point to. The @ symbol simply means the current domain which in our case is darian-brown.com

@	IN	A	192.168.0.2
www	IN	A	192.168.0.2

Now we are going to add a subdomain called blog and point it to a different server. So we add the line after those two entries (or even at the bottom of the file) like so.

@	IN	A	192.168.0.2
www	IN	A	192.168.0.2
blog	IN	A	192.168.0.10

Update Config File Serial

You need to update the serial in the zone config file. Change it so the serial number is higher than it used to be. This will allow bind to see that the config file has been updated and that it need to load in the new config file.

$ORIGIN example.com
@       IN      SOA     ns1.exampledns.com.    root.example.com. (
                     2014082301         ; Serial
                           3600         ; Refresh
                           1800         ; Retry
                         604800         ; Expire
                          43200 )       ; Negative Cache TTL

I like to use the current date for the serial and a two digit to show the number of times it edited the file that day. This ensures the serial is unique, always higher and has the added benefit of showing when I last updated the config file. So use the format of YYYYMMDDXX where xx is the edit that day. Starting at 01 for the first edit, 02 for the second edit, etc.

Save And Restart Bind DNS Server

Once you have added your new subdomain and updated the serial in your DNS config file, you need to restart the bind daemon in order to reload the new config file. You can do so by issuing the following command.

Debian / Ubuntu Linux

Restart bind dns server on Debian and Ubuntu Linux.

service bind9 start

Alternate method to restart bind dns server on Debian and Ubuntu Linux.

/etc/init.d/bind9 restart

Redhat / Fedora Linux

Restart bind dns server on Redhat and Fedora Linux.

service named restart

Alternate method to restart bind dns server on Redhat and Fedora Linux.

/etc/init.d/named restart

Note: you may need to use sudo to run these commands if your account doesn’t have enough privileges.

Testing new subdomain

In order to test your new entry is working, you can dig the new address. See my article on What is Dig and When Should I use it for more information. Dig is a lot more informative and can be extremely useful as you can directly query your DNS server rather than waiting for the DNS to refresh.
An example of how to do would be

dig @ns1.mynameserver.com -t A blog.darian-brown.com

and if the DNS entry was added successfully, you should see a section in the response that is something like

;; ANSWER SECTION:
blog.darian-brown.com.	3600	IN	A	192.168.0.2

Alternately you can ping the subdomain using

ping blog.darian-brown.com

Final Note!

Once you have create DNS record for subdomain, it may take a while before it comes into effect. The reason is that your DNS server must send the new information to other DNS servers around the world, so that other DNS server all over know your new subdomain details and are able to find it on the internet. This process is commonly called DNS propagation.

DNS Propagation

This process may take up to 48 hours however a few hours usually does the trick. Updating a subdomain usually takes longer than creating a new domain or subdomain. This is because the other DNS servers will wait for their cache to expire before refetching your updated DNS zone file.

Disable SSH Login For FTP User

Overview

The below guide will show you have to create an FTP account for vsftpd and also block ssh access making a ssh account a ftp only account. This will also disable telnet access to the ssh account.

Disable SSH Login For FTP User

Secure Lock

Create The Ftp User

The ssh login account will be used as the ftp login account. So first step is to create the ssh user. Since this will be the FTP username choose name you wish to use are your ftp username. someusername is the username I am using as an example for this tutorial. We will disable ssh access later on.

Enable FTP Login Using SSH Account

In order to allow local ssh users to be able to ftp in, you need to set local_enable=YES in your vsftpd.conf file. That will allows any users on the system, to gain access to the server through FTP.

adduser someusername

Disable SSH Login For FTP User

Open up your passwd file which is usually located under /etc/passwd. Now change the default shell which would be similar to /bin/bash to your ftp only shell which I will create as /etc/ftponly. I created the file under /etc/ftponly however you can place the file anywhere you see fit.

someusername:x:1017:1017:,,,:/home/someusername:/etc/ftponly

Create the ftponly shell file

Now create the ftponly file of /etc/ftponly and type in a scary message to deter trespassers. Save the file in the location you specified in the passwd file located at /etc/passwd.

#!/bin/sh
echo "Welcome to my FTP Webserver. Please note that all activity is tracked for security purposes!"
exit

Ensure the file can be executed

chmod a+x /etc/ftponly

Step 5 – Add ftponly as a valid shell

Add our file /etc/ftponly to the list of valid shells. Simply add the following line to the end of your shells file which is located at /etc/shells. Your shells file will look something like this:

# /etc/shells: valid login shells
/bin/csh
/bin/sh
/usr/bin/es
/usr/bin/ksh
/bin/ksh
/usr/bin/rc
/usr/bin/tcsh
/bin/tcsh
/usr/bin/esh
/bin/bash
/bin/rbash
/usr/bin/screen
/etc/ftponly

All Done!

Now when people try to ssh or telnet into the server, they will see the message “Welcome to my FTP Webserver. Please note that all activity is tracked for security purposes!” and they won’t be able to gain any further access however they will still be able to login using FTP.

Warning Note!

If the shells file /etc/shells file doesn’t exist, you will need to add in the other shells similar to above since you will be overriding the default shells. If you fail to do so, you could prevent any further ssh access.

Real World Unix Timestamp Examples

Overview

Unix timestamps are extremely useful and can be used across my different programming languages and platforms. I will outline a couple programming languages that support timestamps.

  • PHPconvert timestamps to date in php
  • MysQLview example on how you can query timestamps from a MySQL Database
  • Javascriptthe Date() function in Javascript can use timestamps
  • Perlthe time() function in Perl can handle unix timestamps
  • Linuxreturn current timestamp in linux

Real World Unix Timestamp Examples

PHP

In PHP, you can convert a unix timestamp to a real time by using the php date() function. date() allows you to convert a timestamp that is supplied as the second parameter or if the second parameter is left out, it will convert the current timestamp to date.

<?php

/* this would display a time of 23 May 2011 17:12:pm */
echo date('d F Y H:i:a',1306134726);
/* and this would display the current time in the same format as above */
echo date('d F Y H:i:a');

?>

The way the date is displayed is controlled by the flags passed to the function. Here we used the flags ‘d’, ‘F’, ‘Y’, ‘H’, ‘i’ and ‘A’. For a complete list of flags and to see a complete description of this function, visit http://php.net/manual/en/function.date.php.
The PHP function time(), strtotime() and mktime() all return the current unix timestamp. If you wanted to, you can also get a time stamp 24 hours from now by using the following code.

<?php

/* get tomorrows timestamp */
$tomorrow = time() + (24 * 60 * 60);

/* or you can use strtotime to convert a natural string into a timestamp */
$tomorrow = strtotime('+24 hours');

/* and this will create a timestamp based on the date and time variables */
$timestamp = mktime($hour,$min,$sec,$month,$day,$year);

?>

MySQL

If you have a table that contains a column with a unix timestamp in it, you can convert it using the query below. It will return a column that contains rows of easy to read date and times.

SELECT FROM_UNIXTIME(column_name) AS real_time FROM `table_name`;

Javascript

Javascript has a function called ‘Date()’ which allows you to use timestamps in javascript. Remember that since javascript is client side code (i.e. runs on the persons browser), the date shown is their own computer time, not the server time. To get the current timestamp in javascript, simple use

<script type="text/javascript">

/* get the current timestamp */
var timestamp = +new Date();

</script>

You can also convert a timestamp to a date by using the following javascript date functions.

<script type="text/javascript">

/* create a new date as of the current date */
var date = new Date();
/* you can also create a new date and pass a timestamp to create the date as of the timestamp */
var another_date = new Date(1306482441);

var day  = date.getDate(); // get the day that date relates to
day = day < 10 ? '0' + day : day; // add a 0 if less that 10
var month = date.getMonth() + 1; // returns month as 0 - 11
var year = date.getFullYear(); // 4 digit year (eg. 2011)
var hour = date.getHours(); // get hours
hour = hour<10?'0'+hour:hour; // pad with a 0
var minute = date.getMinutes(); // and minutes
minute = minute<10?'0'+minute:minute; // pad with 0
var second = date.getSeconds(); // get seconds
second = second<10?'0'+second:second; // pad with 0

</script>

Perl

In order to retrieve the current timestamp in Perl, you can make use of the time() function which is the same as PHP.

my $timestamp = time();

Linux

Using the ‘date’ command in linux will print out the date specified by the parameters passed to it. We will use the %s flag to tell it to print the seconds passed since ‘1970-01-01 00:00:00 UTC’ (i.e. it will print out the current timestamp).

date +%s

Interesting Facts About Unix Timestamps

Here are a couple of facts surrounding unix timestamps you may find interesting. A couple of these are tips I discovered and a couple found browsing the internet. If you are not sure what a timestamp is, then read this article on What Is A Unix Timestamp And Why Is It Useful

  • On January 19, 2038, the Unix Time Stamp will cease to work due to a 32-bit overflow. This will result in websites crashing if they are still using 32-bit cpu’s. Before this moment millions of applications will need to either adopt a new convention for time stamps or be migrated to 64-bit systems which will buy the time stamp a “bit” more time.
  • At 03:33:20 UTC on May 18, 2033, the Unix time reaches 2,000,000,000 seconds, the second billennium.
  • At 23:31:30 UTC on February 13, 2009, the Unix time number reached 1,234,567,890 seconds.
  • At 01:58:31 UTC on March 18, 2005, the Unix time number reached 1,111,111,111.
  • At 01:46:40 UTC on September 9, 2001, the Unix billennium (Unix time number 1,000,000,000) was celebrated.
  • At 00:37:33 UTC on July 21, 2069, the Unix time will represent the first 10 digits of pi, 3141592653. (This coincides with the 100th anniversary of the first manned Moon landing, occurring between the times of touchdown and the first moon walk.)
  • At 09:06:49 UTC on Jun 16, 2034, the Unix time reaches 2,034,061,609 seconds and thus matches the current time to the hour (2034061609) when displayed as YYYYMMDDHH.

Check If Linux OS Is 64 Bit or 32 Bit

Overview – How To Check If Linux OS Is 64 Bit or 32 Bit

If you have ever needed to know if you have 32 bit or 64 bit linux installed, there are a number of simple ways to find this out of which I will show you two ways.

Note that if your cpu architecture is a 64 bit cpu, then you are able to install either 32 bit or 64 bit versions of Linux (or any operating system for that matter). However if your cpu architecture is 32 bit, then you are only able to use the 32 bit version of linux. It should also be noted that you are will not be able to install 64 bit applications on a computer with a 64 bit cpu if the linux operating system is running a 32 bit version of linux.

First Method to check if linux os is 64 bit or 32 bit

In your linux shell, type the following:

getconf LONG_BIT

It will return either 32 if you have the 32 bit installated or 64 for 64 bit versions.

Second Method to check if linux os is 64 bit or 32 bit

In your linux shell, type the following:

uname -m

If it returns x86_64 then you have the 64 bit variation and if you see i686 (or even i586, i386, etc.).

64 bit Hardware Support

If you need to see if your cpu architecture supports 64 bit

cat /proc/cpuinfo

What is eAccelerator for PHP

Overview

Before we can understand how eAccelerator (http://eaccelerator.net/) will help speed up your websites loading speed, it is important to realise how php scripts are executed and run to power your websites.

Executing PHP Scripts

When you create a php script to do amazing things like pulling information out of a MySQL database or connecting to a web service to perform complex authentication or other wondrous things, the php script must be compiled into byte-code before it can be run by the web server. The result of this is that each time a user accesses that specific php script, usually through your website, that script is then compiled and then executed. When multiple people access the same script, it is being recompiled over and over which can slow down your website and essentially puts an extra bit of strain on the web server it is being run on.

What is eAccelerator for PHP

Now this is where eAccelerator comes into play. eAccelerator is a php extension that you install onto a web server. After it is installed, each php script will then automatically be precompiled the first time they are executed and also stored for later. Now each time the script is accessed, the pre-compiled script is executed without the need of having to compile the script first.

Interested in installing eAccelerator? I have created a quick tutorial on how to install eAccelerator on Debian here.

Install eAccelerator On Debian Linux

After trying eAccelerator and finding out how great and simple it is, I decided to write a quick guide to show you how to install eAccelerator for PHP. If you are unsure on what eAccelerator is, you can view my post describing what it does and how it can drastically improve your website page generation speed.

Step 1 – Pre-requisites

Now to begin installing eAccelerator for php, make sure you have php4 or php5 installed along with autoconf, automake, libtool and m4. Running the below command appeared to installs these programs for me without any issues but ymmv.

apt-get install libtool m4 php5-dev make

If you get the error phpize command not found then make sure you installed php5-dev. It will also install automake and autoconf which are all required to install eAccelerator.

Step 2 – Get the latest version of eAccelerator

Download the latest version from the offical eAccelerator website and extract the contents to a folder such as your home directory and then CD to the extracted folder.

Step 3 – Building and install eAccelerator

Next step is to Install eAccelerator On Debian Linux. In order to do so, run the following commands commands. If you get any errors such as command not found, then ensure you have followed step 1

phpize
./configure
make

Pay attention to any output to make sure there are no errors before running the command:

make install

Step 4 – Edit your php.ini

Add the following lines to your php.ini file. Your php.ini is usually under /etc/php5/apache2/php.ini. You can run the php command “” to see where your php.ini file is located.

extension="eaccelerator.so"
eaccelerator.shm_size="16"
eaccelerator.cache_dir="/tmp/eaccelerator"
eaccelerator.enable="1"
eaccelerator.optimizer="1"
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="0"
eaccelerator.shm_prune_period="0"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"

Step 5 – Create the cache directory and restart apache2

Create the cache directories. This is were your compiled scripts will be held. My apache user is www-data so replace www-data with the user your apache is run under.

mkdir /tmp/eaccelerator
chown www-data.www-data /tmp/eaccelerator
chmod 0744 /tmp/eaccelerator
apache2ctl graceful

Step 6 – Check the installation

Check to make sure eAccelerator is installed and running by executing the php function “” and scroll down to the modules section and look for eAccelerator.