Thursday, May 14, 2009

BASH Shell change the color of my shell prompt under Linux or UNIX

Q. How do I change the color of my shell prompt under Linux ?

A. You can change the color of your shell prompt to impress your friend or to make your own life quite easy while working at command prompt.

In the Linux default shell is BASH.

Your current prompt setting is stored in PS1 shell variable. There are other variables too, like PS2, PS3 and PS4.

Bash displays the primary prompt PS1 when it is ready to read a command, and the secondary prompt PS2 when it needs more input to complete a command. Bash allows these prompt strings to be customized by inserting a number of backslash-escaped special characters.

Task: Display current BASH prompt (PS1)

Use echo command to display current BASH prompt:
$ echo $PS1Output:

[\\u@\h \\W]\\$

By default the command prompt is set to: [\u@\h \W]\$. Backslash-escaped special characters are decoded as follows:

  • \u: Display the current username
  • \h: Display the hostname
  • \W: Print the current working directory

Task: Modify current BASH prompt

Use export command to setup a new shell prompt:$ export PS1="[\\u@\\H \\W \\@]\\$"

Where,

  • \H: Display FQDN hostname
  • \@: Display current time in 12-hour am/pm format

Task: Add colors to the prompt

To add colors to the shell prompt use the following export command syntax:
'\e[x;ym $PS1 \e[m'

Where,

  • \e[ Start color scheme
  • x;y Color pair to use (x;y)
  • $PS1 is your shell prompt
  • \e[m Stop color scheme

To set a red color prompt, type the command:
$ export PS1="\e[0;31m[\u@\h \W]\$ \e[m "

List of Color code

ColorCode
Black0;30
Blue0;34
Green0;32
Cyan0;36
Red0;31
Purple0;35
Brown0;33
Blue0;34
Green0;32
Cyan0;36
Red0;31
Purple0;35
Brown0;33

Replace digit 0 with 1 to get light color version.

Task: How to make the prompt setting permanent

Your new shell prompt setting is temporary i.e. when you logout setting will be lost. To have it set everytime you login to your workstation add above export command to your .bash_profile file or .bashrc file.
$ cd
$ vi .bash_profile
OR
$ vi .bashrc
Append export line:
export PS1="\e[0;31m[\u@\h \W]\$ \e[m"

Save and close the file.

tput command

You can also use tput command. For example display RED prompt use tput as follows:
export PS1="\[$(tput setaf 1)\]\u@\h:\w $ \[$(tput sgr0)\]"

handy tput commands

  • tput bold - Bold effect
  • tput rev - Display inverse colors
  • tput sgr0 - Reset everything
  • tput setaf {CODE}- Set foreground color, see color {CODE} below
  • tput setab {CODE}- Set background color, see color {CODE} below

Colors {code} code for tput command

Color {code}Color
0Black
1Red
2Green
3Yellow
4Blue
5Magenta
6Cyan
7White

Read the man page of bash and tput command for more information.


//Lin u X u niL

Script to log shutdown/reboot or runlevel change by users

Creating a script that updates the rc.local file and the .bashrc file for log the shutdown/runlevel change or reboot activity done by any user (after giving "su" command)

-------------
#!/bin/bash

##- Updating the /etc/rc.local file
/bin/echo '/bin/echo `date +%Y-%m-%d\ %H:%M:%S\` System booted >> /var/log/reboot' >> /etc/rc.local

##- Updating .bashrc file for Log

/bin/echo "# Alias for logging the shutdown or runlevel change:" >> /root/.bashrc
/bin/echo 'alias shutdown="echo \`date +%Y-%m-%d\ %H:%M:%S\` System shutdown command by: \`who am i\` >> /var/log/reboot & shutdown" ' >> /root/.bashrc
/bin/echo 'alias reboot="echo \`date +%Y-%m-%d\ %H:%M:%S\` System rebooted by: \`who am i\` >> /var/log/reboot & reboot" ' >> /root/.bashrc
/bin/echo 'alias init="echo \`date +%Y-%m-%d\ %H:%M:%S\` System runlevel changed: by: \`who am i\` >> /var/log/reboot & init" ' >> /root/.bashrc
/bin/echo 'alias poweroff="echo \`date +%Y-%m-%d\ %H:%M:%S\` Poweroff command issued by: \`who am i\` >> /var/log/reboot & poweroff" ' >> /root/.bashrc
/bin/echo 'alias halt="echo \`date +%Y-%m-%d\ %H:%M:%S\` System Halted by: \`who am i\` >> /var/log/reboot & halt" ' >> /root/.bashrc
/bin/echo 'alias telinit="echo \`date +%Y-%m-%d\ %H:%M:%S\` System runlevel change: by: \`who am i\` >> /var/log/reboot & telinit" ' >> /root/.bashrc
-----------

//Lin u X u niL

Script to delete the users that starts with ex and wm

mkdir $HOME/userdel
grep -e wm -e ex /etc/passwd > $HOME/userdel/userdel.tmp
cut -f 1 -d: $HOME/userdel/userdel.tmp > $HOME/userdel/userde2.tmp
for i in `cat $HOME/userdel/userde2.tmp`
do
userdel -r $i
done
rm -rf $HOME/userdel


//Lin u X u niL

Wednesday, May 13, 2009

squid Transparent server configuration (Old using http_accel)

http_port 3128
hierarchy_stoplist cgi-bin ?
acl QUERY urlpath_regex cgi-bin \?
#--
no_cache deny QUERY
cache_mem 100 MB
#--------
acl apache rep_header Server ^Apache
broken_vary_encoding allow apache
access_log /var/log/squid/access.log squid
refresh_pattern ^ftp: 1440 20% 10080
refresh_pattern ^gopher: 1440 0% 1440
refresh_pattern . 0 20% 4320
#--
dns_nameservers 192.168.1.7 202.56.250.5 202.56.230.6
#---------
acl all src 0.0.0.0/0.0.0.0
acl manager proto cache_object
acl localhost src 127.0.0.1/255.255.255.255
acl to_localhost dst 127.0.0.0/8
acl SSL_ports port 443 563
acl Safe_ports port 80 # http
acl Safe_ports port 21 # ftp
acl Safe_ports port 443 563 # https, snews
acl Safe_ports port 70 # gopher
acl Safe_ports port 210 # wais
acl Safe_ports port 1025-65535 # unregistered ports
acl Safe_ports port 280 # http-mgmt
acl Safe_ports port 488 # gss-http
acl Safe_ports port 591 # filemaker
acl Safe_ports port 777 # multiling http
acl CONNECT method CONNECT
#---------- Full Acces Define--
acl admin src 192.168.1.99 192.168.1.12 192.168.1.75 192.168.1.76 192.168.1.124 192.168.1.129
http_access allow admin
acl murahari src 192.168.1.145
#------------------------------------------

acl download urlpath_regex "/etc/squid/blocks.files.acl"
acl local src 192.168.1.0/255.255.255.0
#acl local2 src 192.168.0.0/255.255.255.0

http_access deny download
deny_info ERR_BLOCKED_FILES download

#########--------------------- Blocking URLS ---------
acl valid_sites url_regex "/etc/squid/valid_sites.txt"
http_access allow valid_sites

acl music_domains url_regex "/etc/squid/block/music/domains"
acl music_urls url_regex "/etc/squid/block/music/urls"
acl movies_domains url_regex "/etc/squid/block/movies/domains"
acl movies_urls url_regex "/etc/squid/block/movies/urls"
acl gamble_domains url_regex "/etc/squid/block/gamble/domains"
acl gamble_urls url_regex "/etc/squid/block/gamble/urls"
acl chat_domains url_regex "/etc/squid/block/chat/domains"
acl chat_urls url_regex "/etc/squid/block/chat/urls"
#acl webmail_domains url_regex "/etc/squid/block/webmail/domains"
#acl webmail_urls url_regex "/etc/squid/block/webmail/urls"
acl dating_domains url_regex "/etc/squid/block/dating/domains"
acl dating_urls url_regex "/etc/squid/block/dating/urls"
acl webradio_domains url_regex "/etc/squid/block/webradio/domains"
acl webradio_urls url_regex "/etc/squid/block/webradio/urls"
#acl _domains url_regex "/etc/squid/block"
acl share url_regex "/etc/squid/block/share/urls"
acl virus url_regex majesty italy-fund exitexchange trafficholder tamotua
acl proxyservers url_regex orkut rapidshare
acl proxyservers url_regex orkut proxy proxi prox rapidshare
acl rapidshare url_regex rapid
acl ncbi url_regex ncbi

http_access allow ncbi
http_access allow rapidshare murahari

http_access deny share
http_access deny virus
http_access deny proxyservers
http_access deny music_domains
http_access deny music_urls
http_access deny movies_domains
http_access deny movies_urls
http_access deny gamble_domains
http_access deny gamble_urls
http_access deny chat_domains
http_access deny chat_urls
#http_access deny webmail_domains
#http_access deny webmail_urls
http_access deny dating_domains
http_access deny dating_urls
http_access deny webradio_domains
http_access deny webradio_urls


###########---------------------------------##################



http_access allow local
#http_access allow local2

http_access allow manager localhost
http_access deny manager
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access allow localhost
http_access deny all
http_reply_access allow all
icp_access allow all
visible_hostname firecone
coredump_dir /var/spool/squid
httpd_accel_host virtual
httpd_accel_port 80
httpd_accel_with_proxy on
httpd_accel_uses_host_header on

//Lin u X u niL

IPTables - Firewall Script

#------------------------------------------------------

#-------------------------------MODULES-------------------------------------
#Load Mdules
/sbin/modprobe ip_tables
/sbin/modprobe iptable_mangle
/sbin/modprobe iptable_filter
/sbin/modprobe iptable_nat
/sbin/modprobe ipt_limit
/sbin/modprobe ipt_LOG
/sbin/modprobe ipt_MASQUERADE
/sbin/modprobe ipt_state
/sbin/modprobe ip_conntrack
#Enable passive ftp
/sbin/modprobe ip_nat_ftp
/sbin/modprobe ip_nat_irc
/sbin/modprobe ip_conntrack_irc
#---------------------------------------------------------------------------

#----------------------------INTERFACES-------------------------------------
#Interface Definitions

int_nic="eth1"
ext_nic="eth0"
anywhere="0.0.0.0/0"
lan="192.168.1.0/24"
ext_ip="6x.x.x.4"
dns1="1x.x2.xx7.1xx"
dns2="2xx.5x.2x.5x"

#----------------------------FLUSH POLICIES AND RULES------------------------

#Clear out any existing firewall rules

/sbin/iptables -F
/sbin/iptables -F INPUT
/sbin/iptables -F OUTPUT
/sbin/iptables -F FORWARD
/sbin/iptables -F -t mangle
/sbin/iptables -F -t nat
/sbin/iptables -X -t nat
/sbin/iptables -X -t mangle
/sbin/iptables -X
#-------------------------------------------------------------------------------------------

#----------------------------BASIC SECURITY RESTRICTIONS------------------------------------

#Enable ip forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward

#Disabling IP Spoofing attacks
echo 2 > /proc/sys/net/ipv4/conf/all/rp_filter

#Don't respond to broadcast pings
echo "1" > /proc/sys/net/ipv4/icmp_echo_ignore_broadcasts

#Block source routing
echo 0 >/proc/sys/net/ipv4/conf/all/accept_source_route

#Kill timestamps. These have been the subject of a recent bugtraq
#thread
echo 0 > /proc/sys/net/ipv4/tcp_timestamps

#Enable SYN Cookies
echo 1 > /proc/sys/net/ipv4/tcp_syncookies

#Kill ICMP redirects
echo 0 >/proc/sys/net/ipv4/conf/all/accept_redirects

#Enable bad error message protection
echo 1 > /proc/sys/net/ipv4/icmp_ignore_bogus_error_responses

#Allow dynamic ip addresses
echo "1" > /proc/sys/net/ipv4/ip_dynaddr

#Log martians (packets with impossible addresses)
#RiVaL said that certain NICs don't like this. Comment out if necessary.
# echo 1 >/proc/sys/net/ipv4/conf/all/log_martians

#Set out local port range
echo "32768 61000" >/proc/sys/net/ipv4/ip_local_port_range

#PING OF DEATH
/sbin/iptables -A FORWARD -p icmp --icmp-type 8 -m limit --limit 3/second -j ACCEPT

#SYN-FLOOD PROTECTION
/sbin/iptables -A FORWARD -p tcp --syn -m limit --limit 1/s -j ACCEPT
#------------------------------------------------------------------------------

#---------------------------DENIAL OF SERVICE-----------------------------------

#Reduce DoS'ing ability by timeouts
echo 30 > /proc/sys/net/ipv4/tcp_fin_timeout
echo 1800 > /proc/sys/net/ipv4/tcp_keepalive_time
echo 1 > /proc/sys/net/ipv4/tcp_window_scaling
echo 0 > /proc/sys/net/ipv4/tcp_sack
echo 1280 > /proc/sys/net/ipv4/tcp_max_syn_backlog
#---------------------------------------------------------------------------------------------------

#---------------------------FIREWALL POLICIES AND TRAFFIC DETAILS-----------------------------------
#Default POLICIES
/sbin/iptables -P INPUT DROP
/sbin/iptables -P OUTPUT ACCEPT
/sbin/iptables -P FORWARD DROP

#LOOPBACK ALLOW TRAFFIC ON THE LOOPBACK INTERFACE
/sbin/iptables -A INPUT -i lo -j ACCEPT

#ALLOW ESTABLISHED AND RELATED TRAFFIC
/sbin/iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
/sbin/iptables -A FORWARD -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT


#Allow every traffic from local lan
/sbin/iptables -A INPUT -s $lan -p all -j ACCEPT
/sbin/iptables -A FORWARD -s $lan -p all -j ACCEPT

#Masquerade all internal traffic reaching external world
/sbin/iptables -t nat -A POSTROUTING -s $lan -d ! 192.168.1.0/24 -j MASQUERADE
#----------------------------------------------------------------------------------------------------
/sbin/iptables -t nat -A PREROUTING -i eth1 -p tcp --dport 80 -j REDIRECT --to-port 3128
#--------------------------ICMP CONNECTIONS----------------------------------------------------------

#Allow and Accept icmp traffic with restrictions

/sbin/iptables -A INPUT -p 1 -s $lan -j ACCEPT
/sbin/iptables -A INPUT -p 1 -d $ext_ip --icmp-type 8 -j DROP

#--------------------------TCP CONNECTIONS------------------------------------

#Allow access to SSH from outside when required
/sbin/iptables -A INPUT -p tcp -s $anywhere -d $ext_ip --dport 222 -m limit -j ACCEPT

#------------------------------UDP CONNECTIONS----------------------------------------------------------

/sbin/iptables -A INPUT -p tcp -s $dns1 -d $ext_ip --dport 53 -j ACCEPT
/sbin/iptables -A INPUT -p tcp -s $dns2 -d $ext_ip --dport 53 -j ACCEPT
/sbin/iptables -A INPUT -p udp -s $dns1 -d $ext_ip --dport 53 -j ACCEPT
/sbin/iptables -A INPUT -p udp -s $dns2 -d $ext_ip --dport 53 -j ACCEPT


#---------------------------------------------------------------------------------------------------------

#DNAT
# make internal mail server accessbile

$IPTABLES -t nat -A PREROUTING -i eth0 -d 99.90.80.70  -p tcp --dport 25 -j DNAT --to 10.0.0.3
$IPTABLES -t nat -A PREROUTING -i eth0 -d 99.90.80.70  -p tcp --dport 110 -j DNAT --to 10.0.0.3 
$IPTABLES -t nat -A PREROUTING -i eth0 -d 99.90.80.70  -p tcp --dport 80 -j DNAT --to 10.0.0.3
  
#SNAT
# Mask the internal IP address to appear as Public IP
$IPTABLES -t nat -A POSTROUTING -o eth0 -s 10.0.0.3 -p tcp --sport 25 -j SNAT --to 99.90.80.70 
$IPTABLES -t nat -A POSTROUTING -o eth0 -s 10.0.0.3 -p tcp --sport 80 -j SNAT --to 99.90.80.70
$IPTABLES -t nat -A POSTROUTING -o eth0 -s 10.0.0.3 -p tcp --sport 110 -j SNAT --to 99.90.80.70

# //Lin u x u niL

Backup full & incremental using TAR ; a complete backup solution for SMB

#!/bin/sh
#full and incremental backup script
# created 07 February 2000
# Based on a script by Daniel O'Callaghan

#Change the 5 variables below to fit your computer/backup

COMPUTER=server # name of this computer
DIRECTORIES="/home" # directoris to backup
BACKUPDIR=/backups # where to store the backups
TIMEDIR=/backups/last-full # where to store time of full backup
TAR=/bin/tar # name and locaction of tar

#You should not have to change anything below here

PATH=/usr/local/bin:/usr/bin:/bin
DOW=`date +%a` # Day of the week e.g. Mon
DOM=`date +%d` # Date of the Month e.g. 27
DM=`date +%d%b` # Date and Month e.g. 27Sep

# On the 1st of the month a permanet full backup is made
# Every Sunday a full backup is made - overwriting last Sundays backup
# The rest of the time an incremental backup is made. Each incremental
# backup overwrites last weeks incremental backup of the same name.
#
# if NEWER = "", then tar backs up all files in the directories
# otherwise it backs up files newer than the NEWER date. NEWER
# gets it date from the file written every Sunday.


# Monthly full backup
if [ $DOM = "01" ]; then
NEWER=""
$TAR $NEWER -cf $BACKUPDIR/$COMPUTER-$DM.tar $DIRECTORIES
fi

# Weekly full backup
if [ $DOW = "Sun" ]; then
NEWER=""
NOW=`date +%d-%b`

# Update full backup date
echo $NOW > $TIMEDIR/$COMPUTER-full-date
$TAR $NEWER -cf $BACKUPDIR/$COMPUTER-$DOW.tar $DIRECTORIES

# Make incremental backup - overwrite last weeks
else

# Get date of last full backup
NEWER="--newer `cat $TIMEDIR/$COMPUTER-full-date`"
$TAR $NEWER -cf $BACKUPDIR/$COMPUTER-$DOW.tar $DIRECTORIES
fi

//Lin u x u niL

Why do I get error message "Stale NFS file handle"

This type of error message is seen when a file or directory that was opened by an NFS client is removed, renamed, or replaced.
To fix this problem, the NFS file handles must be renegotiated. Try one of these on the client machine:

a) Unmount and remount the file system, may need to use the -O (overlay option) of mount.

From the man pages:
-O Overlay mount. Allow the file system to be
mounted over an existing mount point, making
the underlying file system inaccessible. If a
mount is attempted on a pre-existing mount point
without setting this flag, the mount will fail,
producing the error "device busy".

b) Kill or restart the process trying to use the nonexistent files.

c) Create another mount point and access the files from the new mount point.

d) Run: /etc/init.d/nfs.client stop; /etc/init.d/nfs.client start

e) Reboot the client having problems.

//Lin u x u niL

Accessing same vmware virtual hardisk from windows as well as Linux

Add the following line to vmware configuration file

mainMem.useNamedFile=FALSE

(scenario:
Dual boot: Linux/Windows
a common partition (NTFS) mounted on linux also
installed vmware on both OS
Without the parameter virtual machines created in WIndows wont boot in Linux)

//Lin u x u niL

Amazone Cloud computing : How to

Prerequisites:


Topics

This document assumes that the reader is comfortable working in a Linux/UNIX enviornment

An installation of a Java 5 compatible Java Runtime Environment (JRE) is required. Additionally, accessing Linux and UNIX instances requires access to an SSH client and accessing Windows instances requires access to a Remote Desktop client. For more information, refer to the two following sections.

As a convention, all command line text is prefixed with a generic PROMPT> command line prompt. The actual command line prompt on your machine is likely to be different. We also use $ to indicate a Linux/UNIX specific command and C:\> for a Windows specific command. While we don't currently provide explicit instructions, the tools also work correctly on Mac OS X (which resemble the Linux and UNIX commands). The example output resulting from the command is shown immediately thereafter without any prefix.

[Note]Note

If you are using Cygwin, EC2_HOME, EC2_PRIVATE_KEY, and EC2_CERT must use Linux/UNIX paths (e.g,, /usr/bin instead of C:\usr\bin). However, JAVA_HOME should have a Windows path. Additionally, the value of EC2_HOME cannot contain any spaces, even if the value is quoted or the spaces are escaped.

The Java Runtime Environment

The command line tools used in this guide require Java version 5 or later to run. Either a JRE or JDK installation is acceptable. To view and download JREs for a range of platforms, including Linux/UNIX and Windows, go to http://java.sun.com/j2se/1.5.0/.

The command line tools depend on an environment variable (JAVA_HOME) to locate the Java runtime. This environment variable should be set to the full path of the directory that contains a sub-directory named bin which in turn contains the java (on Linux and UNIX) or the java.exe (on Windows) executable. You might want to simplify things by adding this directory to your path before other versions of Java.

Following is an example of how to set this environment variable in Linux and UNIX.

$ export JAVA_HOME=

You can confirm this by running $JAVA_HOME/bin/java -version and checking the output.

$ $JAVA_HOME/bin/java -version
java version "1.5.0_09"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_09-b03)

Accessing Linux and UNIX Instances through SSH Clients

For some of the examples illustrated in this guide you'll need access to an SSH client. Most Linux and UNIX installations include an SSH client by default. If yours does not, the OpenSSH project provides a free implementation of the full suite of SSH tools. For more information, go to the OpenSSH home page.

Windows users can download and install PuTTY, a free SSH client. To download the client and installation instructions, go to the PuTTY home page. For information on how to use PuTTY with Amazon EC2, see Appendix: PuTTY.

Setting up an Account

To use Amazon EC2, you must sign up for an AWS Account, sign up for Amazon Simple Storage Service (Amazon S3), and sign up for Amazon EC2. These are three different actions that must be performed separately. For information on obtaining an AWS Account, go to the Amazon AWS Home Page. For information on signing up for Amazon S3, see Signing up for Amazon S3. For information on signing up for Amazon EC2, see Signing up for Amazon EC2.

Signing up for Amazon S3

Amazon EC2 AMIs are stored in and retrieved from Amazon S3. This means you need to sign up for Amazon S3. If you already have an Amazon S3 account, you can skip this step.

Amazon S3 Signup Process

1

Go to the Amazon S3 home page.

2

Click the Sign up for this service button.

If you don't already have an AWS account, you are prompted to create one as part of the sign up process.


After signing up for Amazon S3, point to the button labeled Your Web Services Account and select the AWS Access Key Identifiers link on the menu that appears. Be sure to note down your AWS account's Access Key ID and Secret Access Key. You need these to bundle your own image (see Making Your New Amazon Machine Image).

Signing up for Amazon EC2

After you sign up for Amazon S3, you'll need to sign up for Amazon EC2.

Amazon EC2 Signup Process

1

Log into your AWS account and follow the link to Amazon EC2 under the Browse Web Services section on the left.

2

Click Sign Up For Web Service in the top right of the screen and follow the on-screen instructions.


After you sign up for Amazon EC2, you'll want to get your Access Key identifiers.

Access Key Identifiers Process

1

Point to the button labeled Your Web Services Account and select the View Access Key Identifiers link on the menu that appears.

2

Click Create New in the Your X.509 Certificate section to create a new X.509 certificate.

3

Save the certificate and private key. You'll need this when you set up our command line tools (see Setting up the Tools).

4

Create a .ec2 directory in your home directory, and save these files to it with the filenames offered by your browser. You should end up with a PEM-encoded X509 certificate and a private key file named as shown in the following examples.

The following is an example of a PEM encoded signed X.509 certificate.

cert-HKZYKTAIG2ECMXYIBH3HXV4ZBZQ55CLO.pem

The following is an example of an unencrypted, PEM encoded RSA private key that corresponds to the preceding X.509 certificate.

pk-HKZYKTAIG2ECMXYIBH3HXV4ZBZQ55CLO.pem

This X.509 certificate is associated with your account until you generate or upload a new certificate. If you have an existing certificate that you prefer to use, you can return to the Access Key Identifiers upload it later.

5

Finally, you'll need to look up your AWS account ID. You should use this value whenever you need to provide an Amazon EC2 user ID. From the AWS portal page, point to Your Web Services Account and select the Account Activity link on the menu that appears. At the top of this page, locate your the Account Number which is a hyphenated number that looks similar to 4952-1993-3132. This number, with the hyphens removed, is your AWS account ID. In this example, it is 495219933132.


That's it. You're all set to start setting up your tools.


Setting up the Tools

One step remains before you'll be able to use Amazon EC2. You need to get our command line tools and set them up to use your AWS account.

Getting the Command Line Tools

The command line tools are available as a ZIP file in the Amazon EC2 Resource Center. These tools are written in Java and include shell scripts for both Windows 2000/XP and Linux/UNIX/Mac OSX. The ZIP file is self-contained; no installation is required. You just download it and unzip it.

Some additional setup is required in order for the tools to use your AWS account credentials. These are discussed next.

Telling the Tools Where They Live

The command line tools depend on an environment variable (EC2_HOME) to locate supporting libraries. You'll need to set this environment variable before you can use the tools. This should be set to the path of the directory into which the command line tools were unzipped. This directory is named ec2-api-tools-A.B-nnnn (A, B and n are version/release numbers), and contains sub-directories named bin and lib.

On Linux and UNIX, you can set this environment variable as follows.

$ export EC2_HOME=  

On Windows the syntax is slightly different.

C:\> set EC2_HOME=  

In addition, to make your life a little easier, you probably want to add the tools' bin directory to your system PATH. The rest of this guide assumes is done.

On Linux and UNIX, you can update your PATH as follows.

$ export PATH=$PATH:$EC2_HOME/bin 

On Windows the syntax is slightly different.

C:\> set PATH=%PATH%;%EC2_HOME%\bin 
[Note]Note

The Windows environment variables are reset when you close the command window. You might want to set them permanently.

Telling the Tools Who You Are

The command line tools need access to the private key and X.509 certificate you generated after signing up for the Amazon EC2 service (see Setting up an Account).

Since there's nothing stopping you from having more than one AWS account, you need to identify yourself to the command line API tools so they know which credentials to use for requests. It's possible, but tedious, to provide this information on the command line every time you invoke the tools. But it's far simpler to set up some environment variables and be done with it.

Two environment variables are supported to make this possible. They can be set to point at your private key and certificate. If these environment variables are set, the tools use their values to find the relevant credentials. The environment variable EC2_PRIVATE_KEY should reference your private key file, and EC2_CERT should reference your X509 certificate.

On Linux and UNIX, you can set these environment variables as follows.

$ export EC2_PRIVATE_KEY=~/.ec2/pk-HKZYKTAIG2ECMXYIBH3HXV4ZBZQ55CLO.pem 
$ export EC2_CERT=~/.ec2/cert-HKZYKTAIG2ECMXYIBH3HXV4ZBZQ55CLO.pem

On Windows the syntax is slightly different.

C:\> set EC2_PRIVATE_KEY=c:\ec2\pk-HKZYKTAIG2ECMXYIBH3HXV4ZBZQ55CLO.pem 
C:\> set EC2_CERT=c:\ec2\cert-HKZYKTAIG2ECMXYIBH3HXV4ZBZQ55CLO.pem

Changing the Region

By default, the Amazon EC2 tools use the Eastern United States region (us-east-1) with the us-east-1.ec2.amazonaws.com service endpoint. This section describes how to specify a different region.

To specify a different region

  1. View available regions by entering the following:

    PROMPT> ec2-describe-regions

    REGION us-east-1 us-east-1.ec2.amazonaws.com
    REGION eu-west-1 eu-west-1.ec2.amazonaws.com

  2. If you want to change the service endpoint on Linux and UNIX, set the EC2_URL environment variable as follows:

    $ export EC2_URL=https://  
  3. If you want to change the service endpoint on Windows, set the EC2_URL environment variable as follows:

    C:\> set EC2_URL=https://  

You're ready to start using Amazon EC2.

Running an Instance

This section describes how to run an instance that uses Linux or UNIX.

[Note]Note

For information about creating your own AMI, refer to the Amazon Elastic Compute Cloud Developer Guide.

Before We Begin

Before running an instance, verify the requirements in the following table.

Verification Steps

1

Ensure you have a version 1.5.0 compatible Java Runtime installation, and that the JAVA_HOME environment variable has been correctly set. If not, see The Java Runtime Environment.

2

Ensure you have an active Amazon Web Services Account, and that you've signed up for both Amazon S3 and Amazon EC2. If not, see Setting up an Account.

3

Ensure that you have created a directory called .ec2 in your home directory for Linux/UNIX or a directory without spaces in Windows (e.g., C:\EC2), that contains your X.509 certificate and private key, and that they're named correctly. If not, see Signing up for Amazon EC2.

4

Ensure that the EC2_HOME environment variable has been correctly set. If not, see Telling the Tools Where They Live.

5

Ensure that the EC2_CERT and EC2_PRIVATE_KEY environment variables have been correctly set. If not, see Telling the Tools Who You Are.


Once these are correct, you are ready to launch your first instance.

Finding a Suitable AMI

To find a suitable AMI

  1. Use the ec2-describe-images command.

    PROMPT> ec2-describe-images -o self -o amazon | grep machine

    IMAGE ami-2c5fba45 ec2-public-images/demo-paid-AMI-v1.07.manifest.xml amazon available public A79EC0DB i386 machine
    IMAGE ami-bd9d78d4 ec2-public-images/demo-paid-AMI.manifest.xml amazon available public A79EC0DB i386 machine
    IMAGE ami-2f5fba46 ec2-public-images/developer-image-i386-v1.07.manifest.xml amazon available public i386 machine
    IMAGE ami-26b6534f ec2-public-images/developer-image.manifest.xml amazon available public i386 machine
    IMAGE ami-f51aff9c ec2-public-images/fedora-8-i386-base-v1.06.manifest.xml amazon available public i386 machine aki-a71cf9ce ari-a51cf9cc
    IMAGE ami-2b5fba42 ec2-public-images/fedora-8-i386-base-v1.07.manifest.xml amazon available public i386 machine aki-a71cf9ce ari-a51cf9cc
    IMAGE ami-f21aff9b ec2-public-images/fedora-8-x86_64-base-v1.06.manifest.xml amazon available public x86_64 machine aki-b51cf9dcari-b31cf9da
    IMAGE ami-2a5fba43 ec2-public-images/fedora-8-x86_64-base-v1.07.manifest.xml amazon available public x86_64 machine aki-b51cf9dcari-b31cf9da
    IMAGE ami-a21affcb ec2-public-images/fedora-core-6-x86_64-base-v1.06.manifest.xml amazon available public x86_64 machine aki-a53adfccari-a23adfcb
    IMAGE ami-2d5fba44 ec2-public-images/fedora-core-6-x86_64-base-v1.07.manifest.xml amazon available public x86_64 machine aki-a53adfccari-a23adfcb
    IMAGE ami-225fba4b ec2-public-images/fedora-core4-apache-mysql-v1.07.manifest.xml amazon available public i386 machine
    IMAGE ami-25b6534c ec2-public-images/fedora-core4-apache-mysql.manifest.xml amazon available public i386 machine
    IMAGE ami-2e5fba47 ec2-public-images/fedora-core4-apache-v1.07.manifest.xml amazon available public i386 machine
    IMAGE ami-23b6534a ec2-public-images/fedora-core4-apache.manifest.xml amazon available public i386 machine
    IMAGE ami-215fba48 ec2-public-images/fedora-core4-base-v1.07.manifest.xml amazon available public i386 machine
    IMAGE ami-20b65349 ec2-public-images/fedora-core4-base.manifest.xml amazon available public i386 machine
    IMAGE ami-205fba49 ec2-public-images/fedora-core4-i386-base-v1.07.manifest.xml amazon available public i386 machine aki-9b00e5f2
    IMAGE ami-255fba4c ec2-public-images/fedora-core4-mysql-v1.07.manifest.xml amazon available public i386 machine
    IMAGE ami-22b6534b ec2-public-images/fedora-core4-mysql.manifest.xml amazon available public i386 machine
    IMAGE ami-36ff1a5f ec2-public-images/fedora-core6-base-x86_64.manifest.xml amazon available public x86_64 machine
    IMAGE ami-235fba4a ec2-public-images/getting-started-v1.07.manifest.xml amazon available public i386 machine
    IMAGE ami-2bb65342 ec2-public-images/getting-started.manifest.xml amazon available public i386 machine

    The command lists your AMIs and Amazon's public AMIs. The output might not exactly match the preceding example.

  2. Look for the line containing the public image identified by the ec2-public-images/getting-started.manifest.xml value in the third column and note the corresponding value in the second column.

    This is the AMI ID you need. In this example, it is ami-2bb65342.

Generating an SSH Key Pair

You will run an instance of a public AMI. Since it has no password, you need a public/private key pair to login to the instance. One half of this key pair is embedded in your instance, allowing you to login securely without a password using the other half of the key pair. After learning to create your own images, you can choose other mechanisms to allow you to securely login to your new instances. Every key pair you generate requires a name. Be sure to choose a name that is easy to remember.

[Note]Note

If you lose the key pair file, you will not be able to access the instances launched with that key pair. However, you can always generate a new key pair to launch new instances.

To generate a key pair using gsg-keypair

  1. Enter the following information.

    PROMPT>  ec2-add-keypair gsg-keypair 

    Amazon EC2 returns a key pair, similar to the key pair in the following example.

    KEYPAIR gsg-keypair  1f:51:ae:28:bf:89:e9:d8:1f:25:5d:37:2d:7d:b8:ca:9f:f5:f1:6f
    -----BEGIN RSA PRIVATE KEY-----
    MIIEoQIBAAKCAQBuLFg5ujHrtm1jnutSuoO8Xe56LlT+HM8v/xkaa39EstM3/aFxTHgElQiJLChp
    HungXQ29VTc8rc1bW0lkdi23OH5eqkMHGhvEwqa0HWASUMll4o3o/IX+0f2UcPoKCOVUR+jx71Sg
    5AU52EQfanIn3ZQ8lFW7Edp5a3q4DhjGlUKToHVbicL5E+g45zfB95wIyywWZfeW/UUF3LpGZyq/
    ebIUlq1qTbHkLbCC2r7RTn8vpQWp47BGVYGtGSBMpTRP5hnbzzuqj3itkiLHjU39S2sJCJ0TrJx5
    i8BygR4s3mHKBj8l+ePQxG1kGbF6R4yg6sECmXn17MRQVXODNHZbAgMBAAECggEAY1tsiUsIwDl5
    91CXirkYGuVfLyLflXenxfI50mDFms/mumTqloHO7tr0oriHDR5K7wMcY/YY5YkcXNo7mvUVD1pM
    ZNUJs7rw9gZRTrf7LylaJ58kOcyajw8TsC4e4LPbFaHwS1d6K8rXh64o6WgW4SrsB6ICmr1kGQI7
    3wcfgt5ecIu4TZf0OE9IHjn+2eRlsrjBdeORi7KiUNC/pAG23I6MdDOFEQRcCSigCj+4/mciFUSA
    SWS4dMbrpb9FNSIcf9dcLxVM7/6KxgJNfZc9XWzUw77Jg8x92Zd0fVhHOux5IZC+UvSKWB4dyfcI
    tE8C3p9bbU9VGyY5vLCAiIb4qQKBgQDLiO24GXrIkswF32YtBBMuVgLGCwU9h9HlO9mKAc2m8Cm1
    jUE5IpzRjTedc9I2qiIMUTwtgnw42auSCzbUeYMURPtDqyQ7p6AjMujp9EPemcSVOK9vXYL0Ptco
    xW9MC0dtV6iPkCN7gOqiZXPRKaFbWADp16p8UAIvS/a5XXk5jwKBgQCKkpHi2EISh1uRkhxljyWC
    iDCiK6JBRsMvpLbc0v5dKwP5alo1fmdR5PJaV2qvZSj5CYNpMAy1/EDNTY5OSIJU+0KFmQbyhsbm
    rdLNLDL4+TcnT7c62/aH01ohYaf/VCbRhtLlBfqGoQc7+sAc8vmKkesnF7CqCEKDyF/dhrxYdQKB
    gC0iZzzNAapayz1+JcVTwwEid6j9JqNXbBc+Z2YwMi+T0Fv/P/hwkX/ypeOXnIUcw0Ih/YtGBVAC
    DQbsz7LcY1HqXiHKYNWNvXgwwO+oiChjxvEkSdsTTIfnK4VSCvU9BxDbQHjdiNDJbL6oar92UN7V
    rBYvChJZF7LvUH4YmVpHAoGAbZ2X7XvoeEO+uZ58/BGKOIGHByHBDiXtzMhdJr15HTYjxK7OgTZm
    gK+8zp4L9IbvLGDMJO8vft32XPEWuvI8twCzFH+CsWLQADZMZKSsBasOZ/h1FwhdMgCMcY+Qlzd4
    JZKjTSu3i7vhvx6RzdSedXEMNTZWN4qlIx3kR5aHcukCgYA9T+Zrvm1F0seQPbLknn7EqhXIjBaT
    P8TTvW/6bdPi23ExzxZn7KOdrfclYRph1LHMpAONv/x2xALIf91UB+v5ohy1oDoasL0gij1houRe
    2ERKKdwz0ZL9SWq6VTdhr/5G994CK72fy5WhyERbDjUIdHaK3M849JJuf8cSrvSb4g==
    -----END RSA PRIVATE KEY-----

    The private key returned must be saved to a local file so that you can use it later.

  2. Create a file named id_rsa-gsg-keypair and paste the entire key generated in step 1, including the following lines.

    "-----BEGIN RSA PRIVATE KEY-----"
    "-----END RSA PRIVATE KEY-----"
  3. Confirm that the file contents looks similar to the following and save the file.

    You can save the file in any directory, but if you do not put it in your current directory, you should specify the full path when using commands that require the key pair.

     -----BEGIN RSA PRIVATE KEY-----
    MIIEoQIBAAKCAQBuLFg5ujHrtm1jnutSuoO8Xe56LlT+HM8v/xkaa39EstM3/aFxTHgElQiJLChp
    HungXQ29VTc8rc1bW0lkdi23OH5eqkMHGhvEwqa0HWASUMll4o3o/IX+0f2UcPoKCOVUR+jx71Sg
    5AU52EQfanIn3ZQ8lFW7Edp5a3q4DhjGlUKToHVbicL5E+g45zfB95wIyywWZfeW/UUF3LpGZyq/
    ebIUlq1qTbHkLbCC2r7RTn8vpQWp47BGVYGtGSBMpTRP5hnbzzuqj3itkiLHjU39S2sJCJ0TrJx5
    i8BygR4s3mHKBj8l+ePQxG1kGbF6R4yg6sECmXn17MRQVXODNHZbAgMBAAECggEAY1tsiUsIwDl5
    91CXirkYGuVfLyLflXenxfI50mDFms/mumTqloHO7tr0oriHDR5K7wMcY/YY5YkcXNo7mvUVD1pM
    ZNUJs7rw9gZRTrf7LylaJ58kOcyajw8TsC4e4LPbFaHwS1d6K8rXh64o6WgW4SrsB6ICmr1kGQI7
    3wcfgt5ecIu4TZf0OE9IHjn+2eRlsrjBdeORi7KiUNC/pAG23I6MdDOFEQRcCSigCj+4/mciFUSA
    SWS4dMbrpb9FNSIcf9dcLxVM7/6KxgJNfZc9XWzUw77Jg8x92Zd0fVhHOux5IZC+UvSKWB4dyfcI
    tE8C3p9bbU9VGyY5vLCAiIb4qQKBgQDLiO24GXrIkswF32YtBBMuVgLGCwU9h9HlO9mKAc2m8Cm1
    jUE5IpzRjTedc9I2qiIMUTwtgnw42auSCzbUeYMURPtDqyQ7p6AjMujp9EPemcSVOK9vXYL0Ptco
    xW9MC0dtV6iPkCN7gOqiZXPRKaFbWADp16p8UAIvS/a5XXk5jwKBgQCKkpHi2EISh1uRkhxljyWC
    iDCiK6JBRsMvpLbc0v5dKwP5alo1fmdR5PJaV2qvZSj5CYNpMAy1/EDNTY5OSIJU+0KFmQbyhsbm
    rdLNLDL4+TcnT7c62/aH01ohYaf/VCbRhtLlBfqGoQc7+sAc8vmKkesnF7CqCEKDyF/dhrxYdQKB
    gC0iZzzNAapayz1+JcVTwwEid6j9JqNXbBc+Z2YwMi+T0Fv/P/hwkX/ypeOXnIUcw0Ih/YtGBVAC
    DQbsz7LcY1HqXiHKYNWNvXgwwO+oiChjxvEkSdsTTIfnK4VSCvU9BxDbQHjdiNDJbL6oar92UN7V
    rBYvChJZF7LvUH4YmVpHAoGAbZ2X7XvoeEO+uZ58/BGKOIGHByHBDiXtzMhdJr15HTYjxK7OgTZm
    gK+8zp4L9IbvLGDMJO8vft32XPEWuvI8twCzFH+CsWLQADZMZKSsBasOZ/h1FwhdMgCMcY+Qlzd4
    JZKjTSu3i7vhvx6RzdSedXEMNTZWN4qlIx3kR5aHcukCgYA9T+Zrvm1F0seQPbLknn7EqhXIjBaT
    P8TTvW/6bdPi23ExzxZn7KOdrfclYRph1LHMpAONv/x2xALIf91UB+v5ohy1oDoasL0gij1houRe
    2ERKKdwz0ZL9SWq6VTdhr/5G994CK72fy5WhyERbDjUIdHaK3M849JJuf8cSrvSb4g==
    -----END RSA PRIVATE KEY-----
  4. If you're using OpenSSH (or any reasonably paranoid SSH client), you should set the permissions of this file so it is only readable by you.

    On Linux and UNIX, enter the information in the following example.

    $  chmod 700 id_rsa-gsg-keypair ; ls -l id_rsa-gsg-keypair  

    You receive output similar to the following example.

    -rw-------  1 fred flintstones 1701 Jun 19 17:57 id_rsa-gsg-keypair 
[Note]Note

If you are using PuTTY in Windows, convert the private key to PuTTY's format. For more information on using PuTTy with Amazon EC2, see Appendix: PuTTY .

Running an Instance

To launch an instance of your AMI

  1. Use the ec2-run-instances command.

    PROMPT>  ec2-run-instances ami-235fba4a -k gsg-keypair

    Amazon EC2 returns output similar to the following example.


    RESERVATION r-7430c31d 924417782495 default
    INSTANCE i-ae0bf0c7 ami-2bb65342 pending gsg-keypair 0 m1.small 2008-03-21T16:19:25+0000 us-east-1a
  2. Look for the instance ID in the second field and write it down.

    You use it to manipulate this instance (including terminating it when you are finished).

    It takes a few minutes for the instance to launch.

  3. The following command displays the launch status of the instance.

    PROMPT>  ec2-describe-instances i-ae0bf0c7 
    RESERVATION r-7430c31d 924417782495 default
    INSTANCE i-ae0bf0c7 ami-2bb65342 ec2-67-202-7-236.compute-1.amazonaws.com ip-10-251-31-162.ec2.internal running gsg-keypair 0 m1.small 2008-03-21T16:19:25+0000us-east-1a
[Important]Important

After launching an instance, you are billed hourly for running time. If you leave this tutorial at any time, make sure you terminate any instances you have started as described in Terminating Your Instances.

When the instance state in the field just before the key pair name reads "running" the instance started booting. There might be a short time before it is accessible over the network, however. The first DNS name is your instance's external DNS name, i.e. the one that can be used to contact it from the Internet. The second DNS name is your instance's local DNS name, and is only contactable by other instances within the Amazon EC2 network. The DNS names of your instances are different than those shown in the preceding example and you should use yours instead. The examples in this guide use the public DNS name.

Authorizing Network Access to Your Instances

To authorize access to your instance

  • Enter the ec2-authorize command.

    PROMPT>  ec2-authorize default -p 22
    PERMISSION default ALLOWS tcp 22 22 FROM CIDR 0.0.0.0/0
    PROMPT> ec2-authorize default -p 80
    PERMISSION default ALLOWS tcp 80 80 FROM CIDR 0.0.0.0/0

    Since we didn't specify otherwise, your instance was launched in your default group. The first command authorizes network access to instances in your default group on the standard SSH port (22). Similarly, the second command opens up the standard HTTP port (80). For more details on controlling network security groups, see the Amazon EC2 Developer Guide.

[Caution]Caution

In this example, you enable any IP address to access port 22 of the instance. Although this might be acceptable for testing purposes, it is extremely unsafe for production environments. For production systems, you must obtain your public IP address ranges and grant access to those ranges only. For example, if your IP address is 123.123.123.123, you specify 123.123.123.123/32.

Connecting to your Instance

To connect to your instance

  1. Open a web browser and go to http:///, where is your instance's public hostname as returned by ec2-describe-instances (ec2-67-202-51-223.compute-1.amazonaws.com in the example).

    A webpage welcoming you to your instance displays.

    [Note]Note

    If the website times out, your instance might not have finished starting up. Wait a couple of minutes and try again.

  2. Whenever you launch a public AMI that you have not rebundled, run the ec2-get-console-output command and locate the SSH HOST KEY FINGERPRINTS section.

    PROMPT>  ec2-get-console-output instance_id

    ...
    ec2: -----BEGIN SSH HOST KEY FINGERPRINTS-----
    ec2: 2048 bc:89:29:c6:45:4b:b3:e2:c1:41:81:22:cb:3c:77:54
    /etc/ssh/ssh_host_key.pub
    ec2: 2048 fc:8d:0c:eb:0e:a6:4a:6a:61:50:00:c4:d2:51:78:66
    /etc/ssh/ssh_host_rsa_key.pub
    ec2: 1024 b5:cd:88:6a:18:7f:83:9d:1f:3b:80:03:10:17:7b:f5
    /etc/ssh/ssh_host_dsa_key.pub
    ec2: -----END SSH HOST KEY FINGERPRINTS-----

    ...

    Note the fingerprints. You will compare them in the next step.

  3. Use the following command to login as root and exercise full control over this instance as you would any host.

    PROMPT>  ssh -i id_rsa-gsg-keypair root@ec2-67-202-51-223.compute-1.amazonaws.com 
    The authenticity of host 'ec2-67-202-51-223.compute-1.amazonaws.com (216.182.225.42)' can't be established.
    RSA key fingerprint is fc:8d:0c:eb:0e:a6:4a:6a:61:50:00:c4:d2:51:78:66.
    Are you sure you want to continue connecting (yes/no)? yes
    Warning: Permanently added 'ec2-67-202-51-223.compute-1.amazonaws.com' (RSA) to the list of known hosts.
    Last login: Wed Jun 21 08:02:08 2006
    root@ec2-67-202-51-223 #

    If you are launching a public AMI, verify the fingerprint matches one of the fingerprints from the output of the ec2-get-console-output command. If it doesn't, someone might be attempting a "man-in-the-middle" attack.

[Note]Note

Your machine might have a different name for the preceding ssh command or even use different command line options. Consult the documentation for your machine or download one of the clients described in Accessing Linux and UNIX Instances through SSH Clients if you are unsure whether you have such a client installed. For more information about using PuTTY on Windows, see Appendix: PuTTY.

Congratulations

You've set up the tools and used them to run an instance based on a public AMI. You have learned enough to successfully use to run as many standard Linux/UNIX instances as you wish. You can run instances based on any of the public AMIs by following this process.

The next section builds on this success by having you connect to the running instance and customize it to create your own image. If you wish to save this for a later date, be sure to terminate any instances you have started as described in the section called “Terminating Your Instances”.

Cleaning Up

Terminating Your Instances

As soon as your instance starts to boot, you are billed for the resources it consumes. Once you have decided that you no longer require its services, you can terminate an instance using the instance identifier you received in Running an Instance.

[Note]Note

You cannot recover a terminated instance. However, you can launch additional instances of an AMI.

To terminate an instance

  • Execute the following command:

    PROMPT>  ec2-terminate-instances i-10a64379 
    INSTANCE i-10a64379 running shutting-down

    It takes a few minutes for the instance to terminate because Amazon EC2 needs to clean-up your data. For information on checking the status of your instance, see Running an Instance

[Tip]Tip

For Linux and UNIX, you can also terminate your instances by logging onto the instances with your ssh tool and running the "shutdown -h" command. Don't forget the "-h", otherwise you put your instance into single user mode, which is quite useless.

# /sbin/shutdown -h now  

For Windows, you can also terminate your instances by selecting Shutdown from the Start menu or by entering the following from the command line:

C:\> shutdown /s /t 0  

Deregistering Your AMI

If you no longer need your AMI you should deregister it from Amazon EC2.

For this task you'll need your AWS Access Key ID () and AWS Secret Access Key (). For more information on how to find these keys, see Signing up for Amazon S3.

To deregister an AMI

  • Execute the following command:

    PROMPT>  ec2-deregister ami-2bb65342 
    IMAGE ami-2bb65342

Removing Your AMI from Amazon S3

You can delete your deregistered AMIs from Amazon S3. If you don't, Amazon S3 continues to charge you for the space you are using.

The AMI tools contain a command to delete your image. You can get these from the resource center or they are installed on the instance from which you created the image.

To delete your AMI

  • Execute the following command:

    PROMPT> ec2-delete-bundle -b  -p sampleimage -a  -s  
    Deleting AMI bundle parts from https://s3.amazonaws.com/...
    Deleted sampleimage.part.00.
    Deleted sampleimage.part.01.
    Deleted sampleimage.part.02.
    Deleted sampleimage.part.03.
    ...
    Deleted sampleimage.part.23.
    Deleted sampleimage.part.24.
    Delete Bundle complete.
[Note]Note

If you are unable to run the AMI tools, you can use any Amazon S3 utility to delete AMIs.


//Lin u x u niL

The Bash Script To Configure The Firewall Using IPTABLES

The Bash Script To Configure The Firewall Using IPTABLES

About the Script:

This script is about to build a firewall in Linux OS by using iptables, the user only needs to follow and answer the simple and easy steps and the script will generate the user specified iptables rule in its original form.

I HAVE TESTED THE SCRIPT ON PCLINUXOS, FEDORA-9, DREAM_LINUX, UBUNTU-8.

This is my iptables Version 1.0

About iptables:

Network security is a primary consideration in any decision to host a website as the threats are becoming more widespread and persistent every day. One means of providing additional protection is to invest in a firewall. Though prices are always falling, in some cases you may be able to create a comparable unit using the Linux iptables package on an existing server for little or no additional expenditure.

Originally, the most popular firewall/NAT package running on Linux was ipchains, but it had a number of shortcomings. To rectify this, the Netfilter organization decided to create a product called iptables.


:-) !!!The Script is Totally User Friendly!!! :-)

Starting of the Script

A Menu will appear like this:

*****Main Menu*****
1. Check Iptables Package
2. Iptables Services
3. Build Your Firewall with Iptables
4. Exit

1. Check Iptables Package

Now let the user select the option 1. Check iptable Package from the menu by pressing "1" from the keyboard.

Now the script confirms that the user must be Root, and we know that the UID of Root is zero ( 0 ). So first I have to compare the UID of the current user with zero ( 0 ), if the UID doesn't match with the UID of root then it will display the following message:

****You must be the root user to run this script!****

and if the UID matches with root's UID then it displays the following message and runs the script:

***Identity Verified_You are the Root***

We can check the UID of the current user by typing the following command in the terminal:

echo $UID

If the identity of the user is verified as root, then the script will check the iptables package in the Linux OS by using the following command.

rpm -q iptables

*****Main Menu*****
1. Check Iptables Package
2. Iptables Services
3. Build Your Firewall with Iptables
4. Exit

Now if the user selects the option 2. Iptables Services then the checkstatus function will be called. In this function there are some options for the user:

*****Note: Save your Iptables before stop/Restart the iptables Services*****
1. Save the iptables
2. Status of Iptables
3. Start iptables Services
4. Stop iptables Services
5. Restart iptable Services
6. Flush iptables (**Use Carefully_it will remove all the rules from iptables**)
7. Go back to Main Menu

If the user selects 1. Save the iptables the iptables rules will be saved in the Linux OS by using the following command:

/etc/init.d/iptables save

If the user selects 2. Status of iptables the current status of iptables will be displayed, using the following command:

/etc/init.d/iptables status

Chain INPUT (policy ACCEPT)
target prot opt source destination
REJECT tcp -- 192.168.1.45 172.16.4.8 reject-with icmp-port-unreachable
ACCEPT tcp -- 192.168.1.1 192.168.1.25
LOG icmp -- anywhere anywhere LOG level warning

Chain FORWARD (policy ACCEPT)
target prot opt source destination

Chain OUTPUT (policy ACCEPT)
target prot opt source destination
DROP udp -- 192.168.6.3 10.6.3.7

If the user selects 3. Start iptables Services then iptables will be started, using the following command:

/etc/init.d/iptables start

If the user selects 4. Stop iptables Services then iptables will be stopped, using the following command:

/etc/init.d/iptables stop

If the user selects 5. Restart iptable Services then iptables will be restarted, using the following command, it will load the saved iptables rules:

/etc/init.d/iptables restart

If the user selects 6. Flush iptables then iptables will be flushed, (**use Carefully_it will remove all the rules from iptables**), using the following command, it will flush the saved iptables rules:

iptables -F

To go back to the Main Menu the user must select option 7. Go back to Main Menu.

*****Main Menu*****
1. Check Iptables Package
2. Iptables Services
3. Build Your Firewall with Iptables
4. Exit

Option 3. Build your Firewall with Iptables is the heart of this script, by using this option users can create the firewall with iptables using simple steps, when a user selects the option 3. Build your Firewall with Iptables then the script will ask the user to create the firewall.

Using Which Chain of Filter Table?
1. INPUT
2. OUTPUT
3. Forward"

The above menu will ask the user to select the chain where he/she wants to put the rule.

Now the script will ask the user to get the IP information from the Source side...

1. Firewall using Single Source IP
2. Firewall using Source Subnet
3. Firewall using for All Source Networks

Then the above menu ask the user the above three question, if the user selects the option 1. Firewall using Single Source IP then the script will ask the user to enter the IP address.

If the user selects option 2. Firewall using Source Subnet then the script will ask the user to enter the subnet in the form of "192.168.1.0/24".

If the user selects option 3. Firewall using for All Source Networks then the script will put 0/0 in the variable named "ip_source" in the script.

Now the script will ask the user to get the IP information from the Destination side...

1. Firewall using Single Destination IP
2. Firewall using Destination Subnet
3. Firewall using for All Destination Networks

Then the above menu asks the user the above three questions, if the user selects option 1. Firewall using Single Destination IP then the script will ask the user to enter the IP address.

If the user selects option 2. Firewall using Destination Subnet then the script will ask the user to enter the subnet in the form of "192.168.1.0/24"

If the user selects option 3. Firewall using for All Destination Networks then the script will put 0/0 in the variable named "ip_dest" in the script.

Now the script asks the user to select the PROTOCOL:

1. Block All Traffic of TCP
2. Block Specific TCP Service
3. Block Specific Port
4. Using no Protocol

Now from the above displayed menu if the user selects 1. Block All Traffic of TCP then the script will block all the TCP Traffic.

If the user selects 2. Block Specific TCP Service, now the script will ask the user to enter the TCP Service of his/her choice (e.g ICMP).

Note: the TCP Service name should be in CAPITAL LETTERS!!!

If the user selects 3. Block Specific Port the script will ask the user to enter the PORT number.

Now the script prompts the user What to do with the Above Created Rule?

What to do with Rule?
1. Accept the Packet
2. Reject the Packet
3. Drop the Packet
4. Create Log

If the user selects 1. Accept the Packet then the packet will be accepted.

If the user selects 2. Reject the Packet then the packet will be rejected.

If the user selects 3. Drop the Packet then the packet will be dropped.

If the user selects 4. Create Log then only the log will be created.

Now the following message will be shown to the user:

Press Enter key to Generate the Complete Rule!!!

When the user presses the Enter key then the script generates the original rule with the correct syntax and displays it to the user, in my case:

The Generated Rule is
iptables -A INPUT -s 192.168.0.0/24 -d 172.16.0.0/16 -p TCP -j ACCEPT

Now the script shows the following message to the user:

Do you want to Enter the Above rule to the IPTABLES? Yes=1 , No=2

If the above rule is correct then the user presses 1 for Yes and adds the rule to iptables
otherwise 2 for No and the script will return to let the user edit the rule.


Here is the whole script:

#!/bin/bash
##############USMAN AKRAM "FA05-BTN-005" (~*Lucky*~) BTN-6########
######COMSATS INSTITUTE OF INFORMATION TECHNOLOGY - ABBOTTABAD####
echo -e "****************Welcome*************"
###############################IPTABLE SERVICES PROGRAM BEGINS HERE###############################
checkstatus()
{
opt_checkstatus=1
while [ $opt_checkstatus != 7 ]
do
clear
#echo -e "\nChoose the Option Bellow!!!\n
echo -e "\n\t*****Note: Save your Iptables before stop/Restart the iptables Services*****\n"
echo -e " 1. Save the iptables\n
2. Status of Iptables\n
3. Start iptables Services\n
4. Stop iptables Services\n
5. Restart iptable Services\n
6. Flush iptables (**Use Carefully_it will remove all the rules from iptables**)\n
7. Go back to Main Menu"
read opt_checkstatus
case $opt_checkstatus in
1) echo -e "*******************************************************\n"
/etc/init.d/iptables save
echo -e "\n*******************************************************\n"
echo -e "Press Enter key to Continue..."
read temp;;
2) echo -e "*******************************************************\n"
/etc/init.d/iptables status
echo -e "*******************************************************"
echo -e "Press Enter key to Continue..."
read temp;;
3) echo -e "*******************************************************\n"
/etc/init.d/iptables start
echo -e "*******************************************************\n"
echo -e "Press Enter key to Continue..."
read temp;;

4) echo -e "*******************************************************\n"
/etc/init.d/iptables stop
echo -e "*******************************************************\n"
echo -e "Press Enter key to Continue..."
read temp;;

5) echo -e "*******************************************************\n"
/etc/init.d/iptables restart
echo -e "*******************************************************\n"
echo -e "Press Enter key to Continue..."
read temp;;
6) iptables -F
echo -e "*******************************************************"
echo -e "All the Rules from the Iptables are Flushed!!!"
echo -e "*******************************************************\n"
echo -e "Press Enter key to Continue..."
read temp;;
7) main;;
*) echo -e "Wrong Option Selected!!!"
esac
done
}
###############################BUILD FIREWALL PROGRAM BEGINS FROM HERE###############################
buildfirewall()
{
###############Getting the Chain############
echo -e "Using Which Chain of Filter Table?\n
1. INPUT
2. OUTPUT
3. Forward"
read opt_ch
case $opt_ch in
1) chain="INPUT" ;;
2) chain="OUTPUT" ;;
3) chain="FORWARD" ;;
*) echo -e "Wrong Option Selected!!!"
esac

#########Getting Source IP Address##########
#Label

echo -e "
1. Firewall using Single Source IP\n
2. Firewall using Source Subnet\n
3. Firewall using for All Source Networks\n"
read opt_ip

case $opt_ip in
1) echo -e "\nPlease Enter the IP Address of the Source"
read ip_source ;;
2) echo -e "\nPlease Enter the Source Subnet (e.g 192.168.10.0/24)"
read ip_source ;;
3) ip_source="0/0" ;;
#4) ip_source = "NULL" ;;
*) echo -e "Wrong Option Selected"
esac
#########Getting Destination IP Address##########
echo -e "
1. Firewall using Single Destination IP\n
2. Firewall using Destination Subnet\n
3. Firewall using for All Destination Networks\n"

read opt_ip
case $opt_ip in
1) echo -e "\nPlease Enter the IP Address of the Destination"
read ip_dest ;;
2) echo -e "\nPlease Enter the Destination Subnet (e.g 192.168.10.0/24)"
read ip_dest ;;
3) ip_dest="0/0" ;;
#4) ip_dest = "NULL" ;;
*) echo -e "Wrong Option Selected"
esac
###############Getting the Protocol#############
echo -e "
1. Block All Traffic of TCP
2. Block Specific TCP Service
3. Block Specific Port
4. Using no Protocol"
read proto_ch
case $proto_ch in
1) proto=TCP ;;
2) echo -e "Enter the TCP Service Name: (CAPITAL LETTERS!!!)"
read proto ;;
3) echo -e "Enter the Port Name: (CAPITAL LETTERS!!!)"
read proto ;;
4) proto="NULL" ;;
*) echo -e "Wrong option Selected!!!"
esac

#############What to do With Rule#############
echo -e "What to do with Rule?
1. Accept the Packet
2. Reject the Packet
3. Drop the Packet
4. Create Log"
read rule_ch
case $rule_ch in
1) rule="ACCEPT" ;;
2) rule="REJECT" ;;
3) rule="DROP" ;;
4) rule="LOG" ;;
esac
###################Generating the Rule####################
echo -e "\n\tPress Enter key to Generate the Complete Rule!!!"
read temp
echo -e "The Generated Rule is \n"
if [ $proto == "NULL" ]; then
echo -e "\niptables -A $chain -s $ip_source -d $ip_dest -j $rule\n"
gen=1
else
echo -e "\niptables -A $chain -s $ip_source -d $ip_dest -p $proto -j $rule\n"
gen=2
fi
echo -e "\n\tDo you want to Enter the Above rule to the IPTABLES? Yes=1 , No=2"
read yesno
if [ $yesno == 1 ] && [ $gen == 1 ]; then
iptables -A $chain -s $ip_source -d $ip_dest -j $rule
else if [ $yesno == 1 ] && [ $gen == 2 ]; then
iptables -A $chain -s $ip_source -d $ip_dest -p $proto -j $rule

else if [ $yesno == 2 ]; then

main
fi
fi
fi
}

main()
{
ROOT_UID=0
if [ $UID == $ROOT_UID ];
then
clear
opt_main=1
while [ $opt_main != 4 ]
do
echo -e "/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n"
#############Check Whether the iptables installed or not############
echo -e "\t*****Main Menu*****\n
1. Check Iptables Package\n
2. Iptables Services\n
3. Build Your Firewall with Iptables\n
4. Exit"
read opt_main
case $opt_main in
1) echo -e "******************************"
rpm -q iptables
echo -e "******************************" ;;
2) checkstatus ;;
3) buildfirewall ;;
4) exit 0 ;;
*) echo -e "Wrong option Selected!!!"
esac
done
else
echo -e "You Must be the ROOT to Perfom this Task!!!"
fi
}
main
exit 0
-----------------------------
//(Lin u x u niL)