Monday, April 30, 2012

HowTo: Restart SSH Service under Linux / UNIX

How do I restart SSH service under Linux or UNIX operating systems?

The command to restart ssh are as follows (you must login as root user):

CentOS / RHEL / Fedora / Redhat Linux Restart SSH

# /etc/init.d/sshd restart
OR
# service sshd restart

Debian / Ubuntu Linux Restart SSH

# /etc/init.d/ssh restart
OR
# service ssh restart

FreeBSD Restart SSH

# /etc/rc.d/sshd restart

UNIX Restart SSH

# kill -HUP `cat /var/run/sshd.pid`
Please note that the location of /var/run/sshd.pid may change. So just search a bit through /var/run/ directory.

KSH For Loop Array: Iterate Through Array Values

How do I use ksh for loop to iterate thought array values under UNIX / Linux / BSD operating systems?

You can define array as follows:
set -A arrayName value1 value2 value3
For example, create an array called characters with three values as follows:
set -A characters Mugen Jin Fuu
To print first value, enter:
echo ${characters[0]}
To print 3rd and last value, enter:
echo ${characters[2]}
To print all values, enter:
echo ${characters[@]}
To count number of items in an array called characters, enter:
echo ${#characters[@]}
You can use for loop as follows to iterate through all values:
for i in ${characters[@]}; do echo "Samurai Champloo character - $i"; done
Sample outputs:
Samurai Champloo character - Mugen
Samurai Champloo character - Jin
Samurai Champloo character - Fuu
You can add two more items as follows to exiting array:
characters[3]="Sunflower-Samurai"
characters[4]="Detective-Manzo"

Sample Shell Script

#!/bin/ksh
# set array called nameservers
set -A nameservers 192.168.1.1 192.168.1.5 202.54.1.5
 
# print all name servers
for i in ${nameservers[@]
do
echo $i
done

Linux: List / Display All Cron Jobs

How do I view currently setup or all running cron jobs under Linux operating systems?

The cron service searches its spool area (usually /var/spool/cron/crontabs) for crontab files (which are named after user accounts); crontabs found are loaded into memory. cron also reads /etc/crontab, which is in a slightly different format. Additionally, cron reads the files in /etc/cron.d: it treats the files in /etc/cron.d as in the same way as the /etc/crontab file. The intended purpose of /etc/cron.d/ directory feature is to allow packages that require finer control of their scheduling than the /etc/cron.{daily,weekly,monthly} directories to add a crontab file to /etc/cron.d.

View Users Cronjob

Use the following syntax to view vivek users cronjob:
crontab -u userName -l
crontab -u vivek -l

View Root User Cronjob

Just type the following command:
crontab -l

View /etc/crontab

A cronjob can be also run from /etc/crontab file. To view it, enter:
# less /etc/crontab

View Daily Cronjob

Type the following commands:
cd /etc/cron.daily/
ls -l
cat filename

View Hourly Cronjobs

Type the following commands:
cd /etc/cron.hourly/
ls -l
cat filename

View Weekly Cronjobs

Type the following commands:
cd /etc/cron.weekly/
ls -l
cat filename

View Monthly Cronjobs

Type the following commands:
cd /etc/cron.monthly/
ls -l
cat filename

View Software (Package) Specific Cronjobs

Type the following commands
cd /etc/cron.d/
ls -l
cat filename

Clear Shell History In Ubuntu Linux

How do I clear the shell history in Ubuntu Linux?

To clear the history, type the following command:
history -c
OR
rm ~/.bash_history
You can add the command to your ~/.bash_logout so that history will get cleared when you logout:
echo 'history -c' >> ~/.bash_history

Prevent A Bash History File From Ever Being Saved

Add the following commands to ~/.bashrc file:
echo 'unset HISTFILE' >> ~/.bashrc
echo 'export LESSHISTFILE="-"' >> ~/.bashrc

FreeBSD Install DJBDNS Server

djbdns's tinydns server is one of the second most popular DNS server with security in mind. How do I install DJBDNS server under FreeBSD operating systems?

DJBDNS is a collection of Domain Name System tools. It includes several components:
  1. The tinydns program is a fast, UDP-only DNS server.
  2. The axfrdns program is a fast, TCP-only DNS server. This is useful for transferring zones to secondary name server or bind server.
  3. The dnscache program is a local DNS cache. It accepts recursive DNS queries from local clients such as web browsers. It collects responses from remote DNS servers.

Sample Configuration Setup

ns1.nixcraft.in - 202.54.1.1
ns2.nixcraft.in - 203.51.2.1

Install DJBDNS on ns1.nixcraft.in

Type the following command:
# portsnap fetch update
# cd /usr/ports/dns/djbdns
# make install clean && rehash

Make sure you select IPv6 patch if you need to provide AAAA dns address for your domain.
Fig.01: FreeBSD Install djbdns Software via Ports
Fig.01: FreeBSD Install djbdns Software via Ports
This port will also install the following two required software:
  • daemontools: Service monitoring and logging utilities by djbdns (and qmail) server
  • ucspi-tcp2 : Command-line tools for building TCP client-server application

DJBDNS Files and Directories

  1. tinydns: a database-driven dns server - It will open UDP port 53
  2. axfrdns: a zone-transfer server - It will open TCP port 53
  3. /var/service: The directory containing the various service directories to be monitored. The author ( Daniel J. Bernstein) recommends /service, but the FreeBSD port has a default of /var/service instead, which is consistent with the FreeBSD filesystem hierarchy.
  4. /var/ns1.nixcraft.in : Your zone configuration directory. It will be symlinked to /var/service
  5. rsync or scp : Update your zone files on ns2.nixcraft.in server.
  6. tinydns-conf : sets up a DNS publication service (master name server)
  7. axfrdns-conf : sets up a DNS zone-transfer service
  8. /usr/local/etc/rc.d/svscan.sh : daemontools rc.d start / stop / restart script. Use this to start or stop djbdns server.

HowTo: Find Python Version

How do I find out python version under UNIX / Linux / OS X operating systems?

Simply type the following command to find out python version (open the terminal or shell prompt):
python -V
Sample outputs:
Python 2.4.3

Linux: Find Out BIOS Version Using a Command Line Option

How do I find out BIOS version using a Linux command line option?

To find out BIOS version under Linux operating systems use the dmidecode command which is a tool to analyse BIOS data. You must login as root to run dmidecode command:
dmidecode | less
Sample outputs:
dmidecode 2.10
SMBIOS 2.5 present.
45 structures occupying 1832 bytes.
Table at 0xCFF6A000.
Handle 0x0000, DMI type 0, 24 bytes
BIOS Information
Vendor: Phoenix Technologies LTD
Version: 2.1
Release Date: 06/23/2008
Address: 0xE4F00
Runtime Size: 110848 bytes
ROM Size: 1024 kB
Characteristics:
PCI is supported
PNP is supported
BIOS is upgradeable
BIOS shadowing is allowed
ESCD support is available
Boot from CD is supported
Selectable boot is supported
EDD is supported
3.5"/2.88 MB floppy services are supported (int 13h)
ACPI is supported
USB legacy is supported
LS-120 boot is supported
ATAPI Zip drive boot is supported
BIOS boot specification is supported
Targeted content distribution is supported
Another output from my laptop:
sudo dmidecode | less
Sample outputs:
BIOS Information
Vendor: Dell Inc.
Version: A02
Release Date: 02/03/2010
Address: 0xF0000
Runtime Size: 64 kB
ROM Size: 2112 kB
Characteristics:
ISA is supported
PCI is supported
PC Card (PCMCIA) is supported
PNP is supported
BIOS is upgradeable
BIOS shadowing is allowed
Boot from CD is supported
Selectable boot is supported
3.5"/720 KB floppy services are supported (int 13h)
Print screen service is supported (int 5h)
8042 keyboard services are supported (int 9h)
Serial services are supported (int 14h)
Printer services are supported (int 17h)
CGA/mono video services are supported (int 10h)
ACPI is supported
USB legacy is supported
AGP is supported
Smart battery is supported
BIOS boot specification is supported
Function key-initiated network boot is supported
Targeted content distribution is supported
BIOS Revision: 0.2
Firmware Revision: 0.2
Handle 0x0100, DMI type 1, 27 bytes
System Information
Manufacturer: Dell Inc.
Product Name: Precision M6500
Version: Not Specified
Serial Number: 55Lxxxx
UUID: 4a2yzzzeC-3500-xxx-yyy-Bzzzzyyy5y
Wake-up Type: Power Switch
SKU Number: Not Specified
Family:

Linux: Restart Nginx WebServer

How do I restart nginx web server under Linux?

To restart nginx web server use any one of the following command as a root user:
# /etc/init.d/nginx restart
However, recommed way is as follows which should work with any Linux distribution :
# nginx -s reload
OR
# /usr/local/nginx/sbin/nginx -s reload

HowTo: Ubuntu Linux Install Kernel Source Code And Headers

How do I install Linux kernel source with Ubuntu patches? How can I install Ubuntu Linux kernel source code tree for version 2.6.3x using command line options?

You need to use the apt-get command. Open the terminal and type the following commands to install Ubuntu Linux source code:
$ sudo apt-get update
$ sudp apt-get install linux-source

Sample outputs:
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
linux-source-2.6.32
Suggested packages:
libncurses-dev ncurses-dev kernel-package libqt3-dev
The following NEW packages will be installed:
linux-source linux-source-2.6.32
0 upgraded, 2 newly installed, 0 to remove and 0 not upgraded.
Need to get 65.9MB of archives.
After this operation, 66.0MB of additional disk space will be used.
Do you want to continue [Y/n]? y

Linux Remove All Partitions / Data And Create Empty Disk

How do I remove all partitions, data and create clean empty hard disk under Linux operating systems?

The simplest command to remove everything from Linux hard drive is as follows. Please note that this will remove all data so be careful:
dd if=/dev/zero of=/dev/hdX  bs=512  count=1
OR for sata disk, use the following syntax:
dd if=/dev/zero of=/dev/sdX  bs=512  count=1
In this example, empty sata disk /dev/sdb, enter (you must be login as the root user):
fdisk /dev/sdb
dd if=/dev/zero of=/dev/sdb bs=512 count=1
fdisk -l /dev/sdb

Securely Wipe Hard Disk

You can use the shred command to securely remove everything so that no one recover any data:
shred -n 5 -vz /dev/sda

RHEL / CentOS: yum Lists / Installs Only Security Updates

How do I only list or install only security updates under RHEL 5.x or CentOS Linux server? How do I find out security updates descriptions such as CVE, bugs, issued date and type for each patch?

You can easily find out security patches related information using yum-security plugin. This plugin adds the options --security, --cve, --bz and --advisory flags to yum and the list-security and info-security commands. The options make it possible to limit list/upgrade of packages to specific security relevant ones. The commands give you the security information.

Install Plugin

Type the following command:
# yum install yum-security

How Do I Display Available Security Updates?

Type the following command:
# yum list-security
Sample Outputs:
Loaded plugins: rhnplugin, security
RHSA-2009:1148-1 security httpd-2.2.3-22.el5_3.2.x86_64
RHSA-2009:1148-1 security httpd-devel-2.2.3-22.el5_3.2.i386
RHSA-2009:1148-1 security httpd-manual-2.2.3-22.el5_3.2.x86_64
RHSA-2009:1148-1 security mod_ssl-1:2.2.3-22.el5_3.2.x86_64
list-security done
To list all updates that are security relevant, and get a reutrn code on whether there are security updates use:
# yum --security check-update
To get a list of all BZs that are fixed for packages you have installed use:
# yum list-security bugzillas
To get the information on advisory RHSA-2009:1148-1 use:
# yum info-security RHSA-2009:1148-1
Sample Outputs:
Loaded plugins: rhnplugin, security
===============================================================================
RHSA-2009:1148
===============================================================================
Update ID : RHSA-2009:1148-1
Release :
Type : security
Status : final
Issued : 2009-07-08 23:00:00
Bugs : 509125 - None
: 509375 - None
CVEs : CVE-2009-1890
: CVE-2009-1891
Description : Important: httpd security update \The Apache HTTP Server is a
: popular Web server. A denial of service flaw was
: found in the Apache mod_proxy module when it was
: used as a reverse proxy. A remote attacker could
: use this flaw to force a proxy process to consume
: large amounts of CPU time. (CVE-2009-1890) A
: denial of service flaw was found in the Apache
: mod_deflate module. This module continued to
: compress large files until compression was
: complete, even if the network connection that
: requested the content was closed before
: compression completed. This would cause
: mod_deflate to consume large amounts of CPU if
: mod_deflate was enabled for a large file.
: (CVE-2009-1891) All httpd users should upgrade to
: these updated packages, which contain backported
: patches to correct these issues. After installing
: the updated packages, the httpd daemon must be
: restarted for the update to take effect.
Files : mod_ssl-2.2.3-22.el5_3.2.x86_64.rpm
: httpd-devel-2.2.3-22.el5_3.2.i386.rpm
: httpd-2.2.3-22.el5_3.2.x86_64.rpm
: httpd-devel-2.2.3-22.el5_3.2.x86_64.rpm
: httpd-manual-2.2.3-22.el5_3.2.x86_64.rpm
: mod_ssl-2.2.3-22.el5_3.2.i386.rpm
: httpd-2.2.3-22.el5_3.2.i386.rpm
: httpd-manual-2.2.3-22.el5_3.2.i386.rpm
info-security done
To get an info list of the latest packages which contain fixes for Bugzilla 3595; CVE # CVE-2009-1890 and advisories RHSA-2009:1148-1, use:
# yum --bz 3595 --cve CVE-2009-1890 --advisory RHSA-2009:1148-1 info updates

How Do I Install All The Security Updates Only?

Type the following command to download and install all the available security updates:
# yum update --security

Linux Disable Wireless Networking ( Wi-Fi )

We have over 20+ Dell Precision M6400 laptops pre installed with Red Hat Enterprise Linux version 5.x. I was asked to disable Wi-Fi on all laptops as it poses a serious security risk to our sensitive (classified) systems and networks. How do I disable wireless networking (802.11) under Linux?

You can easily disable Wi-Fi under Linux using the following techniques.

Remove Wireless Hardware

This is the best solution. Find out wireless hardware and if possible remove it. Refer to your laptops’s hardware manual which should contain information on its wireless capabilities. A mini-PCI card is typically accessible via a removable slot of the laptop. Some laptop comes with USB wireless device. Use the following commands to list installed devices (list PCI devices):
# lspci
List usb devices:
# lsusb

Disable Wireless in BIOS

Many laptops includes wireless support via BIOS. You can go to your BIOS setup and disable wireless. Again, read your laptops manual.

Disable Wireless Drivers

cd to /lib/modules/$(uname -r)/kernel/drivers/net/wireless and remove wireless driver. A simple solution as follows should work:
# mkdir -p /root/backup/
# mv /lib/modules/$(uname -r)/kernel/drivers/net/wireless /root/backup/
# reboot

Above will remove the kernel drivers that provide support for wireless devices and it will prevent users from easily activating the devices. Please note that you need to repeat above commands every time the kernel is upgraded.

Deactivate Wireless Interfaces ( Remove Config Files)

You can also deactive the wireless interfaces as normal user can not touch config file without root level access. Open terminal and type the following command to list the wireless interface:
# ifconfig -a
Usually, wireless interfaces may have names like wlan0, ath0, wifi0, or eth0:
Sample Outputs:
eth0      Link encap:Ethernet  HWaddr 00:19:d1:2a:ba:a8
BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
Memory:e3180000-e31a0000
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:2475 errors:0 dropped:0 overruns:0 frame:0
TX packets:2475 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:330752 (330.7 KB) TX bytes:330752 (330.7 KB)
ppp0 Link encap:Point-to-Point Protocol
inet addr:10.1.3.49 P-t-P:10.0.31.18 Mask:255.255.255.255
UP POINTOPOINT RUNNING NOARP MULTICAST MTU:1496 Metric:1
RX packets:230 errors:0 dropped:0 overruns:0 frame:0
TX packets:496 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:3
RX bytes:37976 (37.9 KB) TX bytes:47460 (47.4 KB)
wlan0 Link encap:Ethernet HWaddr 00:1e:2a:47:42:8d
inet addr:192.168.1.100 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::21e:2aff:fe47:428d/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:908222 errors:0 dropped:0 overruns:0 frame:0
TX packets:837085 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:787222721 (787.2 MB) TX bytes:322049568 (322.0 MB)
Interrupt:18 Memory:e3000000-e3010000
Turn of wireless interfaces after identifying the same with ifdown command:
# ifdown interface
# ifdown wlan0

Finally, remove wireless configuration file /etc/sysconfig/network-scripts/ifcfg-interfaceName. In above example you should use interface config file /etc/sysconfig/network-scripts/ifcfg-wlan0:
# mv /etc/sysconfig/network-scripts/ifcfg-wlan0 /root/backup
OR just remove config file, enter:
# rm /etc/sysconfig/network-scripts/ifcfg-wlan0
Above will make sure wlan0 will not return after the next reboot.

How Do I Restore Wi-Fi Again?

Just copy back all files and reboot the system:
# mv /root/backup/ifcfg-wlan0 /etc/sysconfig/network-scripts/ifcfg-wlan0
# mv /root/backup/wireless /lib/modules/$(uname -r)/kernel/drivers/net/wireless
# reboot

A Note About Debian / Ubuntu Systems

You need to edit /etc/network/interfaces file to remove wireless configuration.
You need to remove /lib/modules/$(uname -r)/kernel/drivers/net/wireless directory.

What Is The Meaning of 0.0.0.0 In Routing Table?

My home Linux laptop is connected to ADSL router and whenever I run route -n command at the prompt it says 0.0.0.0 is set to my routers IP 192.168.1.1. What is the meaning of 0.0.0.0?

Each network host has a default route for each network card. This will create a 0.0.0.0 route for such card. The address 0.0.0.0 generally means "any address". If a packet destination doesn't match an individual address in the table, it must match a 0.0.0.0 gateway address. In other words, default gateway is always pointed by 0.0.0.0:
route -n
Sample outputs:
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
10.0.31.18 0.0.0.0 255.255.255.255 UH 0 0 0 ppp0
38.96.196.94 192.168.1.2 255.255.255.255 UGH 0 0 0 wlan0
192.168.84.0 0.0.0.0 255.255.255.0 U 0 0 0 vmnet8
192.168.1.0 0.0.0.0 255.255.255.0 U 2 0 0 wlan0
192.168.110.0 0.0.0.0 255.255.255.0 U 0 0 0 vmnet1
192.168.122.0 0.0.0.0 255.255.255.0 U 0 0 0 virbr0
169.254.0.0 0.0.0.0 255.255.0.0 U 1000 0 0 wlan0
10.0.0.0 0.0.0.0 255.0.0.0 U 0 0 0 ppp0
0.0.0.0 192.168.1.2 0.0.0.0 UG 0 0 0 wlan0
192.168.1.2 is my ISP router i.e. default gateway indicated by 0.0.0.0. Other destination such as 10.0.0.0/8 network use ppp0 interface as gateway. If you are MS-Windows user use route print command.

FreeBSD DHCP Set Hostname ( Empty Hostname After Reboot )

I’m using FreeBSD 7.2 on HP laptop and getting IP info via WI-FI router. I’ve setup hostname in /etc/rc.conf buy after the boot process, I check host name with "hostname" command, but get empty line. Setting hostname with "hostname" works well, but after reboot host name is still empty. I suspect it has something to do with DHCP settings. How do I set hostname-using DHCP?

Dynamic Host Configuration Protocol (DHCP) is a network application protocol used by devices (DHCP clients) to obtain configuration information for operation in an Internet Protocol network. The dhclient utility provides a means for configuring network interfaces using DHCP, BOOTP, or if these protocols fail, by statically assigning an address.
This problem indicate that your DHCP server isn't sending the hostname back at all. To solve this problem configure your dhcp server to send back hostname or configure dhcp client to set hostname on your laptop itself.

Say Hello To dhclient-script

From the man page:
The DHCP client network configuration script is invoked from time to timeby dhclient. This script is used by the DHCP client to set each interface's initial configuration prior to requesting an address, to test the address once it has been offered, and to set the interface's final configuration once a lease has been acquired. If no lease is acquired, the script is used to test predefined leases, if any, and also called once if no valid lease can be identified.
Update your /etc/rc.conf as follows:
hostname=""
Create a file called /etc/dhclient-enter-hooks using a text editor:
# vi /etc/dhclient-enter-hooks
Append the following code:
#!/bin/sh
check_hostname(){
hostname laptop.nixcraft.in
}
Save and close the file. Set permission:
# chmod +x /etc/dhclient-enter-hooks
You can now reboot the laptop or just request dhcp lease:
# dhclient iface

Sample dhclient.conf

Here is sample /etc/dhclient.conf file for dhcp client:
timeout 60;
retry 60;
reboot 10;
select-timeout 5;
initial-interval 2;
interface "ep0" {
send host-name "laptop.nixcraft.in";
send dhcp-client-identifier 1:0:a0:24:ab:fb:9c;
send dhcp-lease-time 3600;
supersede domain-name "nixcraft.net.in r.nixcraft.com r.vsnl.nixcraft.net.in";
prepend domain-name-servers 127.0.0.1;
request subnet-mask, broadcast-address, time-offset, routers,
domain-name, domain-name-servers, host-name;
require subnet-mask, domain-name-servers;
script "/etc/dhclient-script";
media "media 10baseT/UTP", "media 10base2/BNC";
}
alias {
interface "ep0";
fixed-address 192.5.5.213;
option subnet-mask 255.255.255.255;
}
See dhclient, dhclient.conf and dhclient-script man page for more information.

Shell Script While Loop Examples

Can you provide me a while loop control flow statement shell script syntax and example that allows code to be executed repeatedly based on a given boolean condition?

Each while loop consists of a set of commands and a condition. The general syntax as follows for bash while loop:
while [ condition ]
do
command1
command2
commandN
done
  1. The condition is evaluated, and if the condition is true, the command1,2…N is executed.
  2. This repeats until the condition becomes false.
  3. The condition can be integer ($i < 5), file test ( -e /tmp/lock ) or string ( $ans != "" )
ksh while loop syntax:
while [[ condition ]] ; do
command1
command1
commandN
done
 
csh while loop syntax:
     while ( condition )
commands
end
 

BASH while Loop Example

#!/bin/bash
c=1
while [ $c -le 5 ]
do
echo "Welcone $c times"
(( c++ ))
done

KSH while loop Example

#!/bin/ksh
c=1
while [[ $c -le 5 ]]; do
echo "Welcome $c times"
(( c++ ))
done

CSH while loop Example

#!/bin/csh
c=1
while ( $c <= 5 )
echo "Welcome $c times"
@ c = $c + 1
end
Another example:
#!/bin/csh
set yname="foo"
while ( $yname != "" )
echo -n "Enter your name : "
set yname = $<
if ( $yname != "" ) then
echo "Hi, $yname"
endif
end

Mac OS X Start / Stop Apache Web Server

How do I start or stop Apache web server using shell prompt option under Apple OS X UNIX operating systems?

The apachectl command act as Apache HTTP Server control interface. Open the terminal and type the following command to stop Apache web server:
sudo apachectl stop
OR
sudo apachectl -k stop
To start Apache web server again, enter:
sudo apachectl start
OR
sudo apachectl -k start
The following will restart apache web server, enter:
sudo apachectl restart
OR
sudo apachectl -k restart
You can displays a brief status report by visiting the url http://localhost:80/server-status in the web browser of your choice.

Mac OS X: Restart / Stop / Start Apache2

How do I restart Apache 2 web server under Apple Mac OS X UNIX operating systems?

You need to use the apachectl command which nothing but a front end to the Apache 2 (HTTP) server. It is designed to help the administrator control the functioning of the Apache httpd daemon.
Open a terminal and use the following commands.

Task: Restart Apache2 Under Mac OS X

sudo apachectl -k restart
Sample session:
Fig.01: Restarting Apache 2 under Mac Os X Using command line
Fig.01: Restarting Apache 2 under Mac Os X Using command line options

The second command netstat -at | grep LISTEN verifies that port 80 (HTTP) is open and working fine.

Task: Stop Apache2 Under Mac OS X

sudo apachectl -k stop

Task: Start Apache2 Under Mac OS X

sudo apachectl -k start

Bash Substring Verification

How can I find out whether a variable called $vech contains a substring called 'car' under bash?
vech='car bus bike rail airplane'

Use the following syntax:
[[ $vech = *car* ]] && echo "Car found in \$vech" || echo "Sorry"
You can also use the following syntax:
 
case "$vech" in
*car*) echo "Car found, do something" ;;
*bus*) echo "call bus()";;
*) echo "Error..."
esac
 
You can use grep to display matching pattern only:
grep -o "car" <<<"$vech"
OR
echo "$vech" | grep -o "car"

Linux / UNIX Restrict at / cron Usage To Authorized Users

The cron and at services are used to allow commands to be executed at a later time. How do I restrict them to selected users such as root, opt1, opt2 and so on? How do I make sure user php can run php script but cannot modify or install a new job?

The cron service is required by almost all UNIX / Linux / BSD oses to perform necessary maintenance tasks. Both cron and anacron make use of a number of configuration files and directories. Regular users can modify and install their own cron configuration or jobs.
  1. /etc/cron.allow - Put users who are allowed to use cron.
  2. /etc/at.allow - Put users who are allowed to use at.
If these files exist and if the corresponding files /etc/cron.deny and /etc/at.deny do not exist, then only users listed in the relevant allow files can run the crontab and at commands to submit their jobs.

How Do I Restrict at And cron To Authorized Users Only?

First, delete both /etc/cron.deny and /etc/at.deny files.
# rm /etc/cron.deny /etc/at.deny
Now, open /etc/cron.allow, enter:
# vi /etc/cron.allow
Add one line for each user allowed to use the crontab command to create cron jobs. Finally, edit /etc/at.allow using a text editor such as vi, enter:
# vi /etc/at.allow
Add one line for each user allowed to use the at command to create at jobs:
vivek
shri
krish
tom
root
foo
bar
php
Note that even if a user called jerry is not listed in cron.allow, cron jobs, he can still be run as that user. The cron.allow file controls only administrative access to the crontab command for scheduling and modifying cron jobs. In other words you can set / modify cron jobs on behalf of jerry. Jerry can only run it but cannot set or modify jobs.

Linux Disable and Remove X Windows (X.org)

I revived my new Dell server pre installed with Red Hat Enterprise Linux server v5.2. However, my box boot with a GUI login system ( Gnome ). There is no reason to run X Windows on my dedicated mail and Apache web server. I only need ssh. How do I disable X login and windows without reinstalling the operating system to improve security and performance?

CentOS / RHEL 5.x / Fedora Linux comes with X Windows system called X.org. The X Window System implementation included with the system is called X.org. There is no need to run X on a dedicated server such as web server or mail server or file server. Root (admin) user can login via SSH or on the text console (or may be using KVM).

Disable X Windows at System Boot

The /etc/inittab file describes which processes are started at bootup and during normal operation. This file is used to start X windows system at boot by setting default run level to 5. Edit the file /etc/inittab using a text editor such as vi, enter:
# vi /etc/inittab
Find line:
id:5:initdefault:
Replace with:
id:3:initdefault:
Save and close the file. Restart the server. You can also drop to text mode by typing init command:
# init 3

Delete X Windows from the Server

To remove the X11 RPMs (all packages) from the server, enter:
# yum groupremove "X Window System"
Above will remove 100-150 packages from the server. This make sure no one can start X on server by typing startx at the shell prompt. This will result into more secure system. Since, your box is dedicated server for web or mail serving, it is safe to delete the X.org software from the system.

Linux: Find Out Apache User Name

How do I find out my apache username under Linux operating system or CentOS Linux server?

There are various methods to find out apache user name who is running httpd server

lsof command

Run the following command:
lsof -i
lsof -i | less
lsof -i | grep :http
Sample outputs:
httpd 17074     dc22    4u  IPv4 42496401       TCP 10.8.4.229:http (LISTEN)
httpd 17230 vivek 4u IPv4 42499206 TCP 10.8.4.230:http (LISTEN)
httpd 17336 jail2 5u IPv4 42499357 TCP 10.8.4.228:https (LISTEN)
httpd 31723 phpcgi1 4u IPv4 52573816 TCP 10.8.4.227:http (LISTEN)
Where,
  1. httpd (1st column) - Apache service / server name
  2. 17074 (2nd column) - Apache server PID
  3. dc22 (3rd column) - Apache server username for PID. This gives you apache username.

httpd.conf file

Another method is to go through config file httpd.conf and find out user and group name:
egrep -iw --color=auto 'user|group' /etc/httpd/conf/httpd.conf
egrep -iw --color=auto '^user|^group' /etc/httpd/conf/httpd.conf
Sample oututs:
User apache
Group apache

FreeBSD: IPv6 Configuration Set Prefixlen Value

How do I set the prefixlen for an IPv6 address under FreeBSD operating systems?

You can set the prefixlen for an IPv6 address by editing /etc/rc.conf file, enter:
# vi /etc/rc.conf
Assuming that your IPv6 is address is 2001:48c8:7::2 for em0, enter:
ipv6_ifconfig_em0="2001:48c8:7::2 prefix 64"
Save and close the file. Restart networking. You can also set it at the shell prompt using the ifconfig command as follows:
ifconfig interFace inet6 ipv6IpAddress prefixlen Value
ifconfig fxp0 inet6 2001:48c8:7::2 prefixlen 64
Where,
  • fxp0 or em0 - FreeBSD NIC interface name
  • 2001:48c8:7::2 - IPv6 public IP address
  • 64 - IPv6 Prefixlen Value

Ubuntu Linux: View Boot Log

How do I view detailed boot log of my Ubuntu system?

The dmesg command print or control the kernel ring buffer. You can also use files located in /var/log/ directory to see snapshot of boot messages. To see logs type the following command at shell prompt (open the terminal and type the commands):
$ dmesg | less
You can use the following two files as well:
  • /var/log/boot.log
  • /var/log/dmesg
To see them type:
less /var/log/boot.log
less /var/log/dmesg
grep error /var/log/dmesg
grep something /var/log/boot.log

Linux Configure Sendmail as SMTP Mail Client ( submission MTA )

I've central e-mail server. Other servers does not need to operate as a mail server. How do I configure Sendmail as submission-only e-mail server (mail client) under CentOS / Fedora / RHEL / Debian Linux / UNIX like operating systems?

Sendmail or any MTA can work in two different modes. It can accept incoming SMTP e-mail requests and send mail from the local machine / workstation or server (cluster node). This is called outbound MTA and it always runes in a queue-only mode.

Step # 1: Disable Sendmail Daemon In a Listing Mode

Edit the file /etc/sysconfig/sendmail using the text editor such as vi, enter:
# vi /etc/sysconfig/sendmail
Modify the line:
DAEMON=no
Save and close the file. Setting DAEMON=no tells Sendmail to execute only the queue runner on this machine, and never to receive SMTP mail requests on port # 25.

Step #2: Configure Mail Submission

You need to tell sedmail about a central MTA which will accept mail on port # 25 for all your domains. For e.g. mail.nixcraft.net act as a central MTA. Edit /etc/mail/submit.cf, enter:
# vi /etc/mail/submit.cf
Find the line beginning with D{MTAHost}, and update it to read as follows:
D{MTAHost}mail.nixcraft.net
Save and close the file. mail.nixcraft.net is the hostname of the server to which this machine should forward its all outgoing mail. Please note that mail.nixcraft.net must be configured to accept mail from your other workstations or server. Once done reload sendmail.

Shell Scripting: If Variable Is Not Defined, Set Default Variable

If var is defined AND NOT EMPTY, use var, otherwise set a default variable under Bash. For e.g. my script needs a parameter for output variable. It can be text or html. I set it as follows in my script
output=$1 # either text or html
However, sometime user forget to pass the parameter to my shell script and my enter logic fails. So how do I set default value to text, if no parameter passed?

BASH, POSIX shell, and Korn (all versions) support the parameter expansion and testing. For e.g. if $1 is defined AND NOT EMPTY, use $1; otherwise, set to "text", enter:
output=${1-text}
echo $output
OR (see my comment below):
output=${1:-text}
echo $output
Try another example at a shell prompt:
$ vech=Bus
$ echo ${vech-Car}
$ echo ${vech:-Car}
$ unset vech
$ echo ${vech-Car}
$ echo ${vech:-Car}

Finally, here is a sample script:
#!/bin/bash
output=${1-text}
echo "Setting output to $output..."
Now, run it as follows:
$ ./script.sh html
$ ./script.sh text
$ ./script.sh

You can also force to user to pass the parameter:
#!/bin/bash
output=${1-text}
[ $# -eq 0 ] && { echo "Usage: $0 format" ; exit 1; }
echo "Setting output to $output..."

How To: Find IP Address Owner

I'm getting lots of spam from few IPs. How do I find the owner of an IP address and report them to concern parties?

All public IP address on the Internet is registered to ISP or an owner or a larger organization. Each IP address is recorded in the whois database. You can query this database to get owner name, phone, email address and so on the Internet using whois command line client.

Find IP Address For A Host Name

For instance to find the IP address for a www.cyberciti.biz open a command line and type in:
host www.cyberciti.biz
or
nslookup www.cyberciti.biz
Sample Outputs:
www.cyberciti.biz has address 74.86.48.99
www.cyberciti.biz has IPv6 address 2607:f0d0:1002:11::4
74.86.48.99 is IPv4 address and 2607:f0d0:1002:11::4 is IPv6 address for www.cyberciti.biz hostname.

whois - Client For The Whois Directory Service

Type the following command to find out the owner of an IP address called 74.86.48.99:
$ whois 74.86.48.99
Sample Outputs:
OrgName:    SoftLayer Technologies Inc.
OrgID: SOFTL
Address: 1950 N Stemmons Freeway
City: Dallas
StateProv: TX
PostalCode: 75207
Country: US
ReferralServer: rwhois://rwhois.softlayer.com:4321
NetRange: 74.86.0.0 - 74.86.255.255
CIDR: 74.86.0.0/16
OriginAS: AS36351
NetName: SOFTLAYER-4-4
NetHandle: NET-74-86-0-0-1
Parent: NET-74-0-0-0-0
NetType: Direct Allocation
NameServer: NS1.SOFTLAYER.COM
NameServer: NS2.SOFTLAYER.COM
Comment: abuse@softlayer.com
RegDate: 2007-05-16
Updated: 2007-11-14
RAbuseHandle: ABUSE1025-ARIN
RAbuseName: Abuse
RAbusePhone: +1-214-442-0605
RAbuseEmail: abuse@softlayer.com
RNOCHandle: IPADM258-ARIN
RNOCName: IP Admin
RNOCPhone: +1-214-442-0600
RNOCEmail: ipadmin@softlayer.com
RTechHandle: IPADM258-ARIN
RTechName: IP Admin
RTechPhone: +1-214-442-0600
RTechEmail: ipadmin@softlayer.com
OrgAbuseHandle: ABUSE1025-ARIN
OrgAbuseName: Abuse
OrgAbusePhone: +1-214-442-0605
OrgAbuseEmail: abuse@softlayer.com
OrgTechHandle: IPADM258-ARIN
OrgTechName: IP Admin
OrgTechPhone: +1-214-442-0600
OrgTechEmail: ipadmin@softlayer.com
# ARIN WHOIS database, last updated 2009-07-23 20:00
# Enter ? for additional hints on searching ARIN's WHOIS database.
Found a referral to rwhois.softlayer.com:4321.
%rwhois V-1.5:003fff:00 rwhois.softlayer.com (by Network Solutions, Inc. V-1.5.9.5)
network:Class-Name:network
network:ID:NETBLK-SOFTLAYER.74.86.32.0/19
network:Auth-Area:74.86.32.0/19
network:Network-Name:SOFTLAYER-74.86.32.0
network:IP-Network:74.86.48.96/29
network:IP-Network-Block:74.86.48.96-74.86.48.103
network:Organization;I:SoftLayer Technologies, Inc.
network:Street-Address:1950 Stemmons Freeway Suite 2043
network:City:Dallas
network:State:TX
network:Postal-Code:75207
network:Country-Code:US
network:Tech-Contact;I:sysadmins@softlayer.com
network:Abuse-Contact;I:abuse@softlayer.com
network:Admin-Contact;I:IPADM258-ARIN
network:Created:20070708
network:Updated:20071205
network:Updated-By:ipadmin@softlayer.com
%referral rwhois://root.rwhois.net:4321/auth-area=.
%ok

HowTo: Mediawiki Reset a User Password

I forgot my mediawiki wiki software password, how do I reset my password?

You can easily reset mediawiki password as follows:

Using changePassword.php Script

You need to login to your server using ssh client where your mediawiki is installed. Next, you have to run the script from the command line. Once logged in go to the installation directory, then go to the maintenance subdirectory. In this example, mediawiki is installed at /home/httpd/wiki directory, enter:
$ cd /home/httpd/wiki/maintenance
Finally, run the following command:
 php changePassword.php --user=YOUR-USERNAME-HERE --password=YOUR-PASSWORD-HERE
# reset a password for Vivek user
php changePassword.php --user=Vivek --password=myPassowrd
Sample outputs:
Password set for Vivek
Now you user Vivek can login without any problem.

Centos Install and Configure MRTG

How do I install and configure MRTG under Fedora Linux or CentOS Linux v5.x server to monitor the traffic load on network-links including routers?

The Multi Router Traffic Grapher (MRTG) is a tool to monitor the traffic load on network-links.
MRTG generates HTML pages containing PNG images which provide a LIVE visual representation of this traffic. You need the following packages:
  • mrtg : Multi Router Traffic Grapher
  • net-snmp and net-snmp-utils : SNMP (Simple Network Management Protocol) is a protocol used for network management. The NET-SNMP project includes various SNMP tools. net-snmp package contains the snmpd and snmptrapd daemons, documentation, etc. You also want to install the net-snmp-utils package, which contains NET-SNMP utilities.
This FAQ works with RHEL / CentOS and Fedora Linux.

Step # 1: Install MRTG

Type the following command to install packages using yum command under CentOS / Fedora Linux:
# yum install mrtg net-snmp net-snmp-utils

Step # 2: Configure snmpd

If you need to monitor localhost including interface and other stuff such as CPU, memory etc, configure snmpd. Open /etc/snmp/snmpd.conf, enter:
# vi /etc/snmp/snmpd.conf
Update it as follows to only allow access from localhost:
com2sec local     localhost           public
group MyRWGroup v1 local
group MyRWGroup v2c local
group MyRWGroup usm local
view all included .1 80
access MyRWGroup "" any noauth exact all all none
syslocation VSNL, India
syscontact Root <vivek@nixcraft.tld>
Save and close the file. Restart snmpd:
# chkconfig snmpd on
# service snmpd restart

Make sure you see interface IP, by running the following command:
# snmpwalk -v 1 -c public localhost IP-MIB::ipAdEntIfIndex
Sample Outputs:
IP-MIB::ipAdEntIfIndex.123.xx.yy.zzz = INTEGER: 2
IP-MIB::ipAdEntIfIndex.127.0.0.1 = INTEGER: 1

Step # 3: Configure MRTG

Use cfgmaker command to creates /etc/mrtg/mrtg.cfg file, enter:
# cfgmaker --global 'WorkDir: /var/www/mrtg' --output /etc/mrtg/mrtg.cfg public@localhost
  • --global 'WorkDir: /var/www/mrtg' : add global config entries i.e. set workdir to store MRTG graphs.
  • --output /etc/mrtg/mrtg.cfg: configr output filename
  • public@localhost : public is the community name of the device you want to create a configuration for. If you are using the wrong community name you will get no response from the device. localhost is the DNS name or the IP number of an SNMP-managable device i.e. our local server.
Finally, run indexmaker to create web pages which display the status of an array of mrtg interface status pages:
# indexmaker --output=/var/www/mrtg/index.html /etc/mrtg/mrtg.cfg

Step # 4: Verify Cron Job

/etc/cron.d/mrtg runs mrtg command to monitor the traffic load on network links:
# cat /etc/cron.d/mrtg
Sample Output:
*/5 * * * * root LANG=C LC_ALL=C /usr/bin/mrtg /etc/mrtg/mrtg.cfg --lock-file /var/lock/mrtg/mrtg_l --confcache-file /var/lib/mrtg/mrtg.ok
Just make sure crond is running and you are done with configuration:
# chkconfig --list crond
If it is off in run level # 3, just run the following to turn on crond service:
# chkconfig crond on
# service crond on

How do I view mrtg graphs?

You need Apache web server to view graphs, simply type the following to install httpd:
# yum install httpd
# chkconfig httpd on
# service httpd on

Fire a webbrowser and type the url:
http://your-ip.add.ress/mrtg/
http://192.168.1.5/mrtg/
Fig.01:Sample MRTG Graph
Fig.01:Sample MRTG Graph

How Do I Create MRTG For My Router at 192.168.1.254?

Run cfgmaker as follows (there is no need to configure snmp for router, as most router and switches comes pre configured with their own SNMPD):
# cfgmaker --global 'WorkDir: /var/www/mrtg' --output /etc/mrtg/mrtg.cfg public@router
OR
# cfgmaker --global 'WorkDir: /var/www/mrtg' --output /etc/mrtg/mrtg.cfg public@192.168.1.254

Iptables Open VNC Port To Allow Incoming VNC Connections

How do I configure Linux system firewall to allow incoming VNC connections?

VNC server listens on the following TCP ports:
=> VNC server on display 0 will listen on TCP ports 5800, 5900 and 6000
=> VNC server on display 1 will listen on TCP ports 5801, 5901 and 6001
=> VNC server on display N will listen on TCP ports 580N, 590N and 600N
In other words a VNC server listens for a VNC client on TCP ports 5800+N, 5900+N, and 6000+N where N is the display which starts at zero. So,
  • 5800+N - Java-based vncviewer;
  • 5900+N - VNC Client Port;
  • 6000+N - X Server port.

Find Out VNC Port

Type the following command:
# netstat -tulp | grep vnc

Update /etc/sysconfig/iptables

Edit /etc/sysconfig/iptables file:
# vi /etc/sysconfig/iptables
Update it as follows:
# Open VNC for USER1
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 5800 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 5900 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 6000 -j ACCEPT
# Open VNC for USER2
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 5801 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 5901 -j ACCEPT
-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 6001 -j ACCEPT
Save and close the file. Restart iptables:
# service iptables restart

A Note About Other Linux Distributions

/etc/sysconfig/iptables works only on RHEL / CentOS / Fedora Linux. For other distros update your iptables shell script as follows:
$IPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 5801  -j ACCEPT
$IPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 5901 -j ACCEPT
$IPT -A INPUT -m state --state NEW -m tcp -p tcp --dport 6001 -j ACCEPT

Snmpd Listen to Specific IP Address ( BIND To Selected Interfaces )

How do I force SNMP (Simple Network Management Protocol) network management software to listen on public interfaces under RHEL / RedHat / Fedora / CentOS Linux server?

net-snmp comes with snmpd server which is an SNMP agent which binds to a port and awaits requests from SNMP management software. By default it binds to localhost (127.0.0.1) only.
snmpd can be configured to listens for incoming SNMP requests on UDP port 161 on all IPv4 interfaces or selected interface using the -x option. A listening address takes the form:
 [<transport-specifier>:]<transport-address>

Few Examples

       127.0.0.1:161           listen on UDP port 161, but only on the loopback interface.  This prevents snmpd being queried  remotely.   The
port specification ":161" is not strictly necessary since that is the default SNMP port.
TCP:1161 listen on TCP port 1161 on all IPv4 interfaces.
ipx:/40000 listen on IPX port 40000 on all IPX interfaces.
unix:/tmp/local-agent listen on the Unix domain socket /tmp/local-agent.
/tmp/local-agent is identical to the previous specification, since the Unix domain is assumed if the first character of the
is '/'.
PVC:161 listen on the AAL5 permanent virtual circuit with VPI=0 and VCI=161 (decimal) on the first ATM adapter in the
machine.
udp6:10161 listen on port 10161 on all IPv6 interfaces.

CentOS / RHEL / Fedora Linux Specific Configuration

Edit /etc/sysconfig/snmpd.options, enter:
# vi /etc/sysconfig/snmpd.options
Uncomment OPTIONS line. Add -x option as follows to listen on default port 161 and IP 127.0.0.1 and 192.168.1.254
OPTIONS="-Lsd -Lf /dev/null -p /var/run/snmpd.pid -a -x 127.0.0.1 192.168.1.254"
Save and close the file. Reload the changes:
# service snmpd reload
Update /etc/sysconfig/iptables firewall configuration to allow communication at udp port 161:
# vi /etc/sysconfig/iptables
Only accept connection only from 192.168.1.0/24 to UDP port 161, enter:
-A RH-Firewall-1-INPUT -p udp s 192.168.1.0/24 -m udp --dport 161 -j ACCEPT
Finally, restart iptables service:
# service iptables restart
You may also need to update your /etc/snmp/snmpd.conf to setup correct public community and other ACL settings. Refer snmpd.conf man page for more details.

How To Setup OpenVZ under RHEL / CentOS Linux

Ineed to run more than instance of Linux operating system and different Linux distributions under CentOS. How do I use OpenVZ virtualization to optimize the usage of my Dell servers, and create test Linux VPS running Debian, Ubuntu, and CentOS Linux? How do I deploy OpenVZ under CentOS / RHEL Linux?

OpenVZ virtualization uses the concept of containers to run Linux only instances on the same hadware. OpenVZ is an operating system-level virtualization technology. It allows a physical server to run multiple isolated different Linux distributions operating system instances, known as containers or Virtual Private Servers (VPSs), or Virtual Environments (VEs). It's similar to FreeBSD Jails and Solaris Zones.
OpenVZ doesn't have the overhead of a true hypervisor (e.g. XEN or VMware), so it is very fast and an efficient to run Linux only VPS. All virtual servers will use same Linux kernel version.

OpenVZ Virtualization and Isolation

It offers strong isolation. This is perfect for running named, mysqld, apache and other services in each container. Each VPS is a separate entity, and behaves just like a physical server. Each VPS has:
  1. System files (such as /bin, /sbin, /lib etc);
  2. Own root users, as well as other users and groups;
  3. Process tree;
  4. Network (private or public IP;
  5. Shared memory, semaphores, messages.

Our Sample Setup (HostNode)

Server: Dual Core CPU with Software RAID1 and 2GB RAM
eth0: Public IP 123.1.2.3
venet0: venet used by OpenVZ to talk with rest of the LAN or Internet.
Hostname: hostnode01.nixcraft.in.
vps.nixcraft.net: 123.1.2.5 - can run any supported Linux distribution.

Host node

The controlling system of container (VPS) environment. The host system has access to all the hardware resources available, and can control processes both outside of and inside a VPS environment. One of the important differences of the host system from a VPS is that the limitations which apply to superuser processes inside a VPS are not enforced for processes of the host system. Above server is host node.

CT0 or VE0

Another name for host node. In other words, CT0 or VE0 means the server itself. From CT0 / VE0, you can use vzctl and other tools to manage containers.

VPS or VE (Virtual Environment) or Virtual Machine

A process, user or other software, whose access to resources is restricted by OpenVZ software. VPS is nothing but an isolated program execution environment, which looks and feels like a separate physical server. Each VPS has file system, root user, other users, file system, firewall settings, routing tables and much more. You can setup multiple VPSs within a single physical server. Different VPSs can run different Linux distributions such as Gentoo, Debian, CentoS, Fedora Linux etc., but all VPSs operate under the same Linux kernel.

CTID

Each VPS has a unique number called CTID (a ConTainer's IDentifer). CTID is defined by server admin and it is used to create, start, stop, restart, delete VPS and other administrative jobs related to your VEs.

VPS Disk Quota

You can restrict VPS disk usage using standard Linux quota tools. For e.g. set vps.nixcraft.net disk usage to 10Gb only. You can also setup quota using number of inodes.

Fair CPU Scheduler

Each VPS gets the time slice from the kernel by taking into account the VPS's CPU priority and limit settings which can be set by server administrator on host node. This can not be modified by VPS users include vps root user. The standard Linux scheduler decides which process in the VPS to give the time slice to, using standard process priorities.

Beancounters - UBC Parameter Units

Each VPS follows set of user beancounters. It is nothing but set of limits and guarantees for each VPS. Beancounters make sure that no single VPS can abuse any resource which is limited for the whole host node and thus cause harm to other VPSs. The resources accounted and controlled are mainly memory and various in-kernel objects such as IPC shared memory segments, network buffers etc.
Beancounter valueUsage
lockedpagesThe memory not allowed to be swapped out (locked with the mlock() system call), in pages.
shmpagesThe total size of shared memory (including IPC, shared anonymous mappings and tmpfs objects) allocated by the processes of a particular VPS, in pages.
privvmpagesThe size of private (or potentially private) memory allocated by an application. The memory that is always shared among different applications is not included in this resource parameter.
numfileThe number of files opened by all VPS processes.
numflockThe number of file locks created by all VPS processes.
numptyThe number of pseudo-terminals, such as an ssh session, the screen or xterm applications, etc.
numsiginfoThe number of siginfo structures (essentially, this parameter limits the size of the signal delivery queue).
dcachesizeThe total size of dentry and inode structures locked in the memory.
physpagesThe total size of RAM used by the VPS processes. This is an accounting-only parameter currently. It shows the usage of RAM by the VPS. For the memory pages used by several different VPSs (mappings of shared libraries, for example), only the corresponding fraction of a page is charged to each VPS. The sum of the physpages usage for all VPSs corresponds to the total number of pages used in the system by all the accounted users.
numiptentThe number of IP packet filtering entries.
See this article which explains all UBC parameter unit.

VPS Templates

VPS templates are nothing but images which are used to create a new VPS. A template is a set of packages, and a template cache is an archive (tarball) of a chrooted
environment with those packages installed. Each Linux distribution comes as template.

Default Locations

  1. /vz - Main directory for OpenVZ.
  2. /vz/private - Each VPS is stored here i.e. container's private directories
  3. /vz/template/cache - You must download and store each Linux distribution template here.
  4. /etc/vz/ - OpenVZ configuration directory.
  5. /etc/vz/vz.conf - Main OpenVZ configuration file.
  6. /etc/vz/conf - Softlinked directory for each VPS configuration.
  7. Network port - No network ports are opened by OpenVZ kernel.

Virtualization With OpenVZ

Now, you are aware of basic terminology used by OpenVZ, it is time to get your hands dirty with OpenVZ. You can run OpenVZ on both CentOS / Red Hat and Debian Linux based server systems.

Is Open Source Software Legal To Use For My Business?

I can download and keep using free and open source software (FOSS) on multiple computers. Is this software legal to use for my business? Can you provide some legal information regarding usage of open source software for business which I can share with my boss?

Short answer - yes.
Free and open source software is legal for both personal and business use. FOSS comes with a free license such as GPL (e.g. Linux kernel). Other application software comes with a slightly different license. You will find license information on projects website itself.
There is one very simple rule that you should follow while using FOSS for business or personal use:
Do not take source code you did not write and try to sell it as your own software, period.
I'm not a lawyer but above is simple rule to follow. Please see the following resource for more information:
  • FSF Free Software Licensing and Compliance Lab
  • The Open Source Definition (Annotated)
  • Understanding Open Source Software - by Red Hat's Mark Webbink, Esq.
  • Understanding Open Source and Free Software Licensing - O'Reilly Media - Written by St. Laurent who is an experienced lawyer with a long-time interest in intellectual property, particularly software licensing. This book helps you make sense of the different options available to you. This concise guide focuses on annotated licenses, offering an in-depth explanation of how they compare and interoperate, and how license choices affect project possibilities. Written in clear language that you don't have to be a lawyer to understand, the book answers such questions as: What rights am I giving up? How will my use of OS/FS licensing affect future users or future developers? Does a particular use of this software--such as combining it with proprietary software--leave me vulnerable to lawsuits?

BSD PF Firewall Block FTP Bruteforce Attacks

I see lots of failed FTP login attempts in my log file. How do I stop FTP bruteforce attack? What should I do to solve this problem under FreeBSD 7.x server operating systems?

You can easily stop bruteforce attacks by limiting connections per IP using pf firewall under FreeBSD or OpenBSD.
Open /etc/pf.conf
# vi /etc/pf.conf
Update it as follows:
# the lists of known FTPD attackers
table <ftp-attacks> persist file "/etc/pf.ftp.block.list"
 
# block all incoming connections from attackers on FTPD
block in quick on $ext_if from <ftp-attacks>
 
# Let us allow FTP with bruteforce protection
pass in quick on $ext_if inet proto tcp from any to ($ext_if) port 21 keep state (max-src-conn-rate 5/40, overload <ftp-attacks> flush global)
Above will block FTP connections more than 5 times in 40 seconds. Also append the following line to /etc/rc.shutdown to keep changes after the reboot:
# echo '/sbin/pfctl -t ftp-attacks -T show > /etc/pf.ftp.block.list' >> /etc/rc.shutdown
Finally, reload pf firewall:
# /etc/rc.d/pf reload
To list currently blocked IP (attackers IP), enter:
# pfctl -t ftp-attacks -T show

UNIX Get An Alert When Disk Is Full

I want to get an alert when my disk is full under UNIX and Mac OS X? How do I set a a specified threshold and run the script via cron?

The df command report file system disk space usage including the amount of disk space available on the file system containing each file name argument. Disk space is shown in 1K blocks by default, unless the environment variable POSIXLY_CORRECT is set, in which case 512-byte blocks are used.
Use df command and pass the -P option which make df output POSIX compliant (i.e. 512-byte blocks rather than the default. Note that this overrides the BLOCKSIZE specification from the environment).
# df -P /
OR
# df -P /usr
Sample Outputs:
Filesystem    512-blocks     Used     Avail Capacity  Mounted on
/dev/aacd0s1e 162491344 21988048 127503992 15% /usr
You can now simply grep /usr file system and print out used capacity:
# df -P /usr | grep /usr | awk '{ print $5}' | sed 's/%//g'
15
Or assign value to a variable:
# output=$(df -P /usr | grep /usr | awk '{ print $5}' | sed 's/%//g')
# echo $output

Under BASH or KornShell you can use arrays indexed by a numerical expression to make code small:
# output=($(df -P /))
# echo "${output[11]}"

A Sample Shell Script

#!/bin/bash
# Tested Under FreeBSD and OS X
FS="/usr"
THRESHOLD=90
OUTPUT=($(LC_ALL=C df -P ${FS}))
CURRENT=$(echo ${OUTPUT[11]} | sed 's/%//')
[ $CURRENT -gt $THRESHOLD ] && echo "$FS file system usage $CURRENT" | mail -s "$FS file system" you@example.com
You need to modify syntax, if you are using KSH or TCSH / CSH instead of BASH. Save this script and run as a cron job:
@daily /path/to/your.df.script.sh

GUI Notification

Display warning dialog using /usr/bin/zenity
#!/bin/bash
# Tested Under FreeBSD and OS X
FS="/usr"
THRESHOLD=90
OUTPUT=($(LC_ALL=C df -P ${FS}))
CURRENT=$(echo ${OUTPUT[11]} | sed 's/%//')
[ $CURRENT -gt $THRESHOLD ] && /usr/bin/zenity --warning --text="The disk $FS ($CURRENT% used) is almost full. Delete some files or add a new disk." --title="df Warning"
DF GUI Warning Notification
DF GUI Warning Notification
Finally update your cronjob as follows (you need to use DISPLAY variable to display output window):
36 19 * * *  DISPLAY=:0.0 /path/to/script.sh

Adobe Photoshop Alternatives For Linux Desktop

I need Photoshop alternative under Ubuntu Linux for basic editing. I know Photoshop can be run using Wine but I'm not able to afford expensive software for just basic editing. Can you suggest a few free FOSS apps that works as alternatives to Photoshop under Ubuntu or Fedora Linux desktop operating systems?

The following is used for graphics purpose. If you are artist, illustrator, designer, business user, home user, photographer, or web designer you can use the following for image manipulation and they are similar to Adobe Photoshop, Corel Paint Shop Pro and Paint.NET software.

GIMP

GIMP (The GNU Image Manipulation Program) is a free software raster graphics editor. Primarily, GIMP is used as a tool for photo manipulations, such as resizing, editing, and cropping photos, combining multiple images, and converting between different image formats. GIMP can also be used to create basic animated images in the GIF format.
GIMP in Action Under Ubuntu Linux
GIMP in Action Under Ubuntu Linux

Install GIMP under Ubuntu

Simply type the following command:
# apt-get install gimp
Once installed you can open GIMP by visiting Application > Graphics > Gimp
=> Download GIMP

Krita

Krita is the bitmap graphics editor software included with the KDE based KOffice suite. Designed to be both a painting application and a photo editor, Krita is free software and distributed under GNU General Public License.
Krita in Action under KDE Destkop
Krita in Action under KDE Destkop

Install Krita under Ubuntu

Simply type the following command:
# apt-get install krita
Once installed you can open GIMP by visiting Application > Graphics > Krita
=> Download Krita

GIMPshop

GIMPshop is a modification of the free and open source graphics program GNU Image Manipulation Program (GIMP), intended to replicate the feel of Adobe Photoshop. Its primary purpose is to make users of Photoshop feel comfortable using GIMP.
GIMPshop In Action
GIMPshop In Action
=> Download Gimpshop