Linux



Table of Contents

1. Links

1.1 General

1.2 Distros

1.3 Guides & References

1.3.1 Command Line

1.3.2 Ubuntu OS

1.3.3 Specific How-To's

1.3.4 News & Articles

1.4 Applications

1.5 Services

1.6 Misc Links




2. Technical Documentation

2.1 Quick Reference

2.1.1 Commands

Linux Commands
System Information
Command Description
cal -3 Display Calendar
ifconfig Display Network Information
date Display system Date and Time
netstat -tup List Active Internet Connections
who Current Users
w Current Users Different Format
top Display System Process Information
top -B -N 1 List Processes
arp Display Ethernet Info
last Display Last Logins
whoami Display Your Login Name
clear Clears Terminal Window
df Display Disk Space Usages
df -hT Displays Disk Space Usage
h = Human Readable. T = File Type.
man Display Linux User Manual
man command Display Command Info
sudo command Execute Command As Super User
history Display Command History
crontab -l Display Scheduler
printenv Display Environmental Variables
uname -a Display System Info - OS, Kernel Version, etc
finger Display Users & Processes
wall Send Message To All Users
(Use Ctrl-D at end of message)
visudo Editor for Sudoers
dmesg System Boot Log
runlevel Displays Current Run Level
lsb_release -a Display Ubuntu Release Info
lsusb List USB Devices
gparted Manage Partitions on Hard Drive & USB Drives
alias Define A Command
ps aux Display Process Information
sudo kill -0 processID Kill a Specific Process
uptime Display System Uptime
reset Reset Terminal Session Display
lsof +D /mnt/windows Display Process Using Drive
eject Eject CD/DVD Drive
cat /proc/cpuinfo Display CPU Information
time read Stopwatch Press Enter To Stop
Network Information
Command Description
ping ip address Check connectivity to IP Address
whois domain.com Display Domain Information
dig domain.com a Display Domain IP Information
arp -a Display Router IP
nslookup domain.com Display Domain Information
tcpdump Display IP traffic
iftop Display Bandwidth
findsmb Find Windows & SMB Computers On Network
smbclient -L x.x.x.x List Shares on SMB Computer
host gmail.com To check If DNS Is Working
shutdown -r now Shutdown and Restart
poweroff Shuts down and power off
sudo tcpdump not port 22 Monitor Non SSH Network Traffic
iwlist scan View WiFi Networks
User Information
Command Description
finger username Display Detailed User Info
passwd Changes Your Password
gpasswd administer the /etc/group file
cut -d: -f1 /etc/passwd | sort Display Linux User Accounts
skill -kill -u username Bump User w/o Notice
File Information
Command Description
ls -al List Files and Directories
ls | wc -l Count of Files
du -h directoryname Directory Size
pwd Present Working Directory
cd Change Directory
cp Copy File
mv Move File
rm Remove or Delete File
mkdir Make Directory
rmdir Remove or Delete Directory
rm -r directoryname Remove full directory
locate Search for File
chmod Change Permissions
chown Change Owner
rm -rf ~/.Trash/* Empty Trash
shred -u -z -v filename Shred File
gpg -c filename.doc Encrypt Filename
gpg filename.doc.gpg Unencrypt Filename
mount | column -t Display Mounted Filesystems
Executing Information
Command Description
sftp Secure FTP File Transfers
wget www.website.com Download website
ssh Secure Shell
rsync File Backup Between Computers

2.1.2 Files

Linux System Files
File Description
/etc/issue Ubuntu Version Number
/etc/fstab This file contains descriptive information about the various file systems and their mount points, like floppies, cdroms, and so on.
/etc/network/interface Ethernet Settings
/etc/passwd A file that contains various pieces of information for each user account. This is where the users are defined.
/etc/profile System Login Script
For All Users
/home/john/.profile User Login Script (For User john)
/etc/vsftpd.conf FTP Server Configuration File
/etc/ssh/sshd_config SSH Configuration File
/etc/issue.net Banner Displayed After Login and Before Password
/etc/sudoers List of who can run what
/etc/group Local groups file
/etc/netgroup List of network groups
/var/log/messages System Messages
~/dead.letter Email that is unable to send
/boot/grub/menu.lst Grub Boot Menu
/proc/cpuinfo CPU Information
/proc/acpi/battery/BAT0/info Battery Info (Sometimes BAT1)

2.1.3 Directories

Linux System Directories
Directory Usage
/bin important binary applications
/boot files that are required to boot the computer
/dev the device files
/etc configuration files, startup scripts, etc…
/etc/profile.d contains scripts that are run by /etc/profile upon login.
/etc/rc.d contains a number of shell scripts that are run on bootup at different run levels. There is also typically an rc.inet1 script to set up networking (in Slackwar), an rc.modules script to load modular device drivers, and an rc.local script that can be edited to run commands desired by the administrator, along the lines of autoexec.bat in DOS.
/etc/rc.d/init.d contains most of the initialization scripts themselves on an rpm-based system.
/etc/rc.d/rc*.d where “*� is a number corresponding to the default run level. Contains files for services to be started and stopped at that run level. On rpm-based systems, these files are symbolic links to the initialization scripts themselves, which are in /etc/rc.d/init.d.
/etc/skel directory containing several example or skeleton initialization shells. Often contains subdirectories and files used to populate a new user’s home directory.
/etc/X11 Configuration files for the X Window system
/home Local users' home directories
/lib System libraries
/lost+found Provides a lost+found system for files that exist under the root (/) directory
/media Mounted (loaded) removable media such as CDs, digital cameras, etc…
/mnt Mounted filesystems
/opt Provides a location for optional applications to be installed
/proc Special dynamic directory that maintains information about the state of the system, including currently running processes
/root Root user home directory, pronounced 'slash-root'
/sbin Important system binaries
/srv Provides a location for data used by servers
/sys Contains information about the system
/tmp Temporary files
/usr Applications and files that are mostly available for all users to access
/usr/local/bin The place to put your own programs. They will not be overwritten with upgrades.
/usr/share/doc Documentation.
/var Variable files such as logs and databases
/var/log Log files

2.2 System Commands

2.2.1 Bash Startup - Ubuntu

How Bash Executes Startup Files
For Login shells (subject to the -noprofile option):

On logging in:
If ‘/etc/profile’ exists, then source it.

If ‘~/.bash_profile’ exists, then source it,
else if ‘~/.bash_login’ exists, then source it,
else if ‘~/.profile’ exists, then source it.

On logging out:
If ‘~/.bash_logout’ exists, source it.

For non-login interactive shells (subject to the -norc and -rcfile options):
On starting up:
If ‘~/.bashrc’ exists, then source it.


2.2.2 Bash Startup - DSL

bootlocal.sh can be compared to DOS' autoexec.bat. You add (non X programs, for X apps, use .xinitrc) commands that you want to start at boot here.

Here is the default content (DSL 1.5).

#!/bin/bash
# put other system startup command here
/sbin/syslogd
loadkeys </path/to/your/selected/keymap>

For example, if I wanted to start the Monkey Web Server and sshd, I would add these two lines to the bottom.
/etc/init.d/sshd start
/opt/monkey/bin/banana start

Retrieved from "http://damnsmalllinux.org/wiki/index.php/Bootlocal.sh"

2.2.3 Crontab

Use Cron to schedule events in Linux.
Use Crontab -l to list the contents of Crontab.
Use Crontab -e to edit contents of Crontab.

* * * * * command to be executed
- - - - -
| | | | |
| | | | +----- day of week (0 - 6) (Sunday=0)
| | | +------- month (1 - 12)
| | +--------- day of month (1 - 31)
| +----------- hour (0 - 23)
+------------- min (0 - 59)
Commands are shell commands. Separate multiple commands with a semicolon ";" and end on the line ending.

Activation parameters:
@reboot = run at boot and reboot only
@yearly = run at midnight Jan 1 each year (equiv to 0 0 1 1 *)
@annually = run at midnight Jan 1 each year (equiv to 0 0 1 1 *)
@monthly = run at midnight on the first day of each month (equiv to 0 0 1 * *)
@weekly = run at midnight each Sunday (equiv to 0 0 * * 0)
@daily = run at midnight each day (equiv to 0 0 * * *)
@ midnight = run at midnight each day (equiv to 0 0 * * *)
@ hourly = run on the first second of every hour (equiv to 0 * * * *)
- or -
1 2 3 4 5 = specific time tags
- where -
1 = Minute (of hour) to activate [0-59]
2 = Hour (of day) to activate [0-23]
3 = Day (of month) to activate [1-31 ... 29,30,31 may not activate during all months]
4 = Month (of year) to activate [1-12 or 3-letter names "Jan,Feb,Mar"]
5 = Weekday to activate [0-7 or 3-letter names "Mon,Tue,Wed"]

If 3-letter names are used on Month/Weekday instead of numbers, they are case-insensitive.
"Mon" and "mON" are equally acceptable.
If numbers are used for the weekday, "0" and "7" are both Sunday and are interchangeable.

Time tags are separated by spaces. Do not use spaces within a tag, this will confuse cron.
All five tags must be present. They are a logical AND of each other.
There is another space between the last time tag and the first command.

A time tag can be a wildcard "*", which means "all". It can be one value, several values, a range, or a fractional range.

Examples for the Hour column:
8 = one value: execute in the 8 AM hour
5,6,9 = multiple values: execute in the 5, 6, and 9 AM hours
5-8 = range: execute in each hour between 5-8 AM (inclusive)
*/2 = fractional: execute in every other hour. 0 (midnight), 2AM, 4AM, 6AM, etc
3-12/3 = fractional range: execute in every third hour between 3AM and 12PM: 3AM, 6AM, 9AM, 12PM

By default cron jobs sends a email to the user account executing the cronjob. If this is not needed put the following command At the end of the cron job line .

>/dev/null 2>&1

Crontab Restrictions:
You can execute crontab if your name appears in the file /usr/lib/cron/cron.allow. If that file does not exist, you can use
crontab if your name does not appear in the file /usr/lib/cron/cron.deny.
If only cron.deny exists and is empty, all users can use crontab. If neither file exists, only the root user can use crontab. The allow/deny files consist of one user name per line.

2.2.4 VSFTPD - FTP Service

The following commands are for starting, stopping and restarting the FTP Server Service.

[root@bigboy tmp]# /etc/init.d/vsftpd start
[root@bigboy tmp]# /etc/init.d/vsftpd stop
[root@bigboy tmp]# /etc/init.d/vsftpd restart

The following file is the configuration file for the FTP service.
/etc/vsftpd.conf

2.2.5 Display Version Number

cat /etc/issue

2.2.6 Upgrading Ubuntu via Command Line

To upgrade from Ubuntu 8.04, press Alt+F2 and type in "update-manager -d" (without the quotes) into the command box. Update Manager should open up and tell you: New distribution release '8.10' is available. Click Upgrade and follow the on-screen instructions.


2.2.7 Upgrades

Upgrade the repositories.

sudo apt-get update

Upgrade the packages of the currently installed version.

sudo apt-get upgrade

If you wish to upgrade to the newest version.

sudo apt-get dist-upgrade

Note: Upgrading to a new version should be done with caution. Make sure you are not using a system that requires a specific version of Ubuntu to function. Some applications are not compatible with newer releases and may stop functioning when you do a distribution upgrade. This is especially true if you are using an "appliance" version of Ubuntu. These often should only have a distribution upgrade in co-ordination with a complete appliance upgrade.

2.2.8 Rename Computer

gksudo network-admin

Go to General Tab and change hostname.

2.2.9 Installing & Removing Packages

Install a package.

sudo apt-get install package

To install the music player Amarok, for example.

sudo apt-get install amarok

Remove a package.

sudo apt-get remove package

To remove the Exaile music player, for example.

sudo apt-get remove exaile

Search for a package-name in the cache.

sudo apt-cache search <package-name>

Example of searching for music player.
sudo apt-cache search music player

2.2.10 Add Extra Repositories

Add extra repositories.

sudo cp /etc/apt/sources.list /etc/apt/sources.list.backup
sudo gedit /etc/apt/sources.list

Add the following.
deb http://us.archive.ubuntu.com/ubuntu/ gutsy main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ gutsy main restricted universe multiverse

deb http://us.archive.ubuntu.com/ubuntu/ gutsy-updates main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ gutsy-updates main restricted universe multiverse

deb http://us.archive.ubuntu.com/ubuntu/ gutsy-backports main restricted universe multiverse
deb-src http://us.archive.ubuntu.com/ubuntu/ gutsy-backports main restricted universe multiverse

deb http://archive.canonical.com/ubuntu gutsy partner
deb-src http://archive.canonical.com/ubuntu gutsy partner

deb http://security.ubuntu.com/ubuntu gutsy-security main restricted universe multiverse
deb-src http://security.ubuntu.com/ubuntu gutsy-security main restricted universe multiverse

Run Update
sudo apt-get update

2.2.11 Install GUI Desktop on Ubuntu Server

sudo apt-get install ubuntu-desktop

2.2.12 Resetting Lost Ubuntu Password

Guide to resetting lost Ubuntu password. Reboot into single user mode to reset it. Here's how to do it on a typical Ubuntu machine with the GRUB bootloader:

Boot Linux into single-user mode

1. Reboot the machine.
2. Press the ESC key while GRUB is loading to enter the menu.
3. If there is a 'recovery mode' option, select it and press 'b' to boot into single user mode.
4. Otherwise, the default boot configuration should be selected. Press 'e' to edit it.
5. Highlight the line that begins with 'kernel'. Press 'e' again to edit this line.
6. At the end of the line, add an additional parameter: 'single'. Hit return to make the change and press 'b' to boot.

Change the admin password
The system should load into single user mode and you'll be left at the command line automatically logged in as root. Type 'passwd' to change the root password or 'passwd someuser' to change the password for your "someuser" admin account.

Reboot
Once your done, give the three finger salute, or enter 'reboot' to restart into your machine's normal configuration.


2.2.13 Samba

The Samba project was started in 1992 by Andrew Tridgell. Samba is a set of tools to share files and printers with computers running Microsoft Windows. It implements the SMB network protocol, which is the heart of Windows networking.

To find Samba servers or Windows computers on a Linux Network.

findsmb

or
smbclient -L 192.168.1.2 -U%

To connect to a Windows computer or samba server.

smbclient

To change users samba password.

sudo smbpasswd -a username

To edit the Samba configuration.

sudo nano -w /etc/samba/smb.conf

Restart Samba after making configuration change.

sudo /etc/init.d/samba reload

Setting up Samba documentation:
https://help.ubuntu.com/community/SettingUpSamba


2.2.14 Alias

Use Alias to define a command. In the example below alias defines 'dir' as 'ls -al'.

alias dir='ls -al'

2.3 User Commands

2.3.1 Adding Users

sudo useradd -d /home/<username> -m <username>

The -d is for creating the Home directory for the user

To Set the password for the new account use this;

sudo passwd <username>

Or if you want to have ubuntu run you through a wizard like process that asks for every piece of information use this:
sudo adduser <username>

Add user to a group.
useradd -G groupname username

2.3.2 Deleting Users

How to Delete users accounts

sudo userdel <username>

This will however not delete the Home directory. To delete the Home directory just use this:
sudo rm -r /home/<username>/

2.3.3 Recovering Passwords

sudo apt-get install john
sudo john /etc/shadow

2.3.4 Reseting Passwords

Restart Ubuntu in safe mode and type:

passwd

to change root password.

2.3.5 Adding Groups

groupadd developers

Check for existence of group named 'developers'.
grep developers /etc/group

2.4 File Commands

2.4.1 Empty Trash via Terminal

To empty trash via Terminal.

sudo rm -rf ~/.Trash/*
sudo rm -rf ~/.local/share/Trash/files/*

2.4.2 RM - Deleting FIles

Use the following when unable to delete files in a directory due to too many files.

find . -name 'something*' -print0 | xargs -0 rm -rf

2.4.3 Deleting Files Older Than x Days

The example below deletes files older than 5 days old.

find /path/to/files* -mtime +5 -exec rm {} \;

To Force, Add -f

find /path/to/files* -mtime +5 -exec rm -f {} \;

2.4.4 Chown

chown [-R] newowner filenames

-R Change the permission on files that are in the subdirectories of the directory that you are currently in.
newowner The alias/username of the new owner of the file.
filenames The file that you are changing the rights to.

Examples

chown john file.txt - Give permissions as owner to user john.


2.4.5 Chgrp

chgrp newgroup filenames [-f] [-h]

newgroup Specifies the new group that you wish to allow access to.
filenames Specifies the files that the newgroup has access to.
-f Force. Do not report errors.
-h If the file is a symbolic link, change the group of the symbolic link. Without this option, the group of the file referenced by the symbolic link is changed.
-R Recursive. chgrp descends through the directory, and any subdirectories, setting the specified group ID as it proceeds. When a symbolic link is encountered, the group of the target file is changed (unless the -h option is specified), but no recursion takes place.

Examples

chgrp mygroup1 file.txt - Would change the group to mygroup1 for the file file.txt if present and the group mygroup1 is valid.


2.4.6 Chmod

Examples of Chmod.

chmod 400 file - Read by owner
chmod 040 file - Read by group
chmod 004 file - Read by world
chmod 200 file - Write by owner
chmod 020 file - Write by group
chmod 002 file - Write by world
chmod 100 file - execute by owner
chmod 010 file - execute by group
chmod 001 file - execute by world

To combine these just add the numbers together:
chmod 444 file - Allow read permission to owner and group and world
chmod 777 file - Allow everyone to read, write, and execute file

PERMISSION COMMAND

U G O Command Usage
rwx (7) rwx (7) rwx (7) chmod 777 filename User: Read Write Execute Group: Read Write Execute Other: Read Write Execute
rwx (7) rwx (7) r-x (5) chmod 775 filename User: Read Write Execute Group: Read Write Execute Other: Read Execute
rwx (7) r-x (5) r-x (5) chmod 755 filename User: Read Write Execute Group: Read Execute Other: Read Execute
Legend
U User - Owner of File
G Group
O Other - Everyone Else
r Readable
w Writable
x Executable
- No Permission

2.4.7 MKISOFS - Make An .ISO File From A Directory

To make an .iso file from files in a directory, use mkisofs:

mkisofs -o file.iso directory_of_files

For additional options:
http://www.oreillynet.com/linux/cmd/cmd.csp?path=m/mkisofs


2.4.8 Rip CD or DVD

This will make an iso from the CD or DVD drive:

dd if=/dev/cdrom of=/cdrom_image.iso

2.4.9 ISOINFO - View Contents Of .ISO Files

To list files in an .iso file, use isoinfo:

isoinfo -l -i filename.iso |more

You can also find out more about the ISO image by using

isoinfo -d -i filename.iso |more

2.4.10 Mount An .ISO

Use the following to mount and use an .iso file (opposed to burning a CD):
Make a directory for it, then mount it.

mkdir /mnt/iso
mount NAME.iso /mnt/iso/ -t iso9660 -o loop

2.4.11 Create A Ram Disk / Ram Drive

Use the following to make a RAM Disk / Drive for fast read / write speeds:
The example below creates a 128MB Ram Drive. Enter a different value to create a different size.

mkdir/ ramdisk
mount none -t tmpfs -o size=128M /ramdisk

2.4.12 Unmount A Drive In Use

Use the following to display processes currently using a drive:

[[/code]]
lsof +D /mnt/windows
[[/code]]


2.4.13 Ubuntu 8.10 Encryption

Provide a default location for users to securely store sensitive data using filesystem encryption.
Encrypts ~/Private
To install:

sudo apt-get install ecryptfs-utils
ecryptfs-setup-private

To use the encrypted folder:

mount.ecryptfs_private

2.4.14 GPG File Encryption

Use GPG for public key encryption. Use FireGPG (install from browser plugins) for the Mozilla Firefox Browser and GMail. Use GPA (sudo apt-get install gpa) for a good GUI Interface for GPG.

To check encryption version:

gpg --version

To Encrypt a file:

gpg -c filename.doc

To Decrypt the file:

gpg filename.doc.gpg

2.5 Network Commands

2.5.1 Optaining External IP Address

Use the following code to assign the value of your external IP address to the $IP variable.
http://whatismyip.org/ also works.

john@Laptop01:~$ ip=$( wget -qO - http://cfaj.freeshell.org/ipaddr.cgi )
john@Laptop01:~$ echo $ip
68.178.187.109

2.5.2 Installing SSH

sudo apt-get install ssh

Restart SSH Daemon

/etc/init.d/sshd restart

2.5.3 Connecting via SSH

Connecting via SSH with X option for graphics and D option for forwarding port 1080:

ssh -X -D 1080 user@192.168.1.x

2.5.4 SCP - Secure Copy

To copy a file from your computer to another computer with ssh you will need to use secure copy, the scp command. The command would look like this.

scp <file> <username>@<IP address or hostname>:<DestinationDirectory>

Example of copying a file from the machine that you are on to a remote machine.

scp "New Document.odw" joe@laptop:"/home/joe/Summer 2005"

Example of copying files from remote computer to local directory.

scp hornbeck@192.168.1.103:/home/hornbeck/otherfile.txt .

2.5.5 RSYNC - Remote Sync Backup

Example below runs rsync to backup //laptop01/home/john/Desktop to //RemoteDomain.com/home/john/Laptop01-backup
sudo rsync -azvv -e ssh /home/john/Desktop moc.niamoDetomeR|resU#moc.niamoDetomeR|resU:./Laptop01-backup


2.5.6 Editing Via Remote Connection - DSL

sudo beaver filename

2.5.7 Editing Via Remote Connection - Ubuntu

sudo nano filename

2.5.8 Change SSH Loging Prompt - Message

To change the SSH login message at sign in. Uncomment the Banner /etc/issue.net line in /etc/ssh/sshd_config. Then put your message in /etc/issue.net and it'll be displayed before you put in your password.


2.5.9 WGET - Download From Web

Use wget (multi purpose download tool) to download content from the internet via HTTP, HTTPS & FTP sites. Also, use Wget to pull in updated jpgs every x minutes via crontab.

# Store local browsable version of a page to the current dir
(cd cli && wget -nd -pHEKk http://www.pixelbeat.org/cmdline.html)

# Continue downloading a partially downloaded file
wget -c http://www.example.com/large.file

# Download a set of files to the current directory
wget -r -nd -np -l1 -A '*.jpg' http://www.example.com/dir/

# FTP supports globbing directly
wget ftp://remote/file[1-9].iso/

# Process output directly
wget -q -O- http://www.pixelbeat.org/timeline.html | grep 'a href' | head

# Download url at 1AM to current dir
echo 'wget url' | at 01:00

# Do a low priority download (limit to 20KB/s in this case)
wget --limit-rate=20k url

# Check links in a file
wget -nv --spider --force-html -i bookmarks.html

# Efficiently update a local copy of a site (handy from cron)
wget --mirror http://www.example.com/

2.5.10 - Interfaces - Sample

Sample of /etc/networking/interfaces to force internal IP to 192.168.1.210.

auto lo
iface lo inet loopback

iface eth0 inet static
address 192.168.1.210
netmask 255.255.255.0
gateway 192.168.1.1

auto eth0

2.5.11 Restarting Network After Making Changes

/etc/init.d/networking restart

2.5.12 Filtering Websites

This can be used to block users from going to a site, or prevent info from a site to come in.
Edit /etc/hosts and add the following line:

127.0.0.1 website.com

ie:
127.0.0.1 http://www.doubleclick.net/

2.6 Scripts

2.6.1 Creating & Executing Shell Scripts

Create a file called test.sh via Nano editor if using Ubuntu or Beaver editor if using DSL. Include '#!/bin/bash' in the first line of the script file.

#!/bin/bash
ls -al
cal -3

After creating the file then make it executable.
sudo chmod +x test.sh

To view test.sh script file.

sudo cat ~/Desktop/test.sh

To Execute Script

sudo ~/Desktop/test.sh

2.6.2 Creating Bash Variables

Creating a varable.

tempname=$(date +%m%d%y)
echo $tempname
061108

2.6.3 Creating & Executing Shell Scripts With Variables

Script with variables.

#!/bin/sh
#
STARTED=`date`
NODE=`uname -n`
OS=`uname -o`
CPU=`uname -p`
FINISHED=`date`
#
echo "Nodename: $NODE"
echo "OS type: $OS"
echo "Processor: $CPU"
echo "Script start time: $STARTED"
echo "Script finish time: $FINISHED"

Results

ubuntu$ /tmp/1.sh
Nodename: ubuntu
OS type: GNU/Linux
Processor: unknown
Script start time: Wed May 7 05:05:31 CDT 2008
Script finish time: Wed May 7 05:05:31 CDT 2008

2.6.4 Creating File Name With Date

Obtain date and create 'now' variable.

john@Laptop01:~$ now=$(date +"%Y-%m%d-%H%M%S")
john@Laptop01:~$ echo $now
2008-0611-213811

Create filename with date in filename.
john@Laptop01:~$ testfile="$now File 01.log"
john@Laptop01:~$ echo $testfile
2008-0611-213811 File 01.log

Put data in file, list file, and view contents of file.
john@Laptop01:~$ echo "hello world" > "$testfile"
john@Laptop01:~$ ls "$testfile"
2008-0611-213811 File 01.log
john@Laptop01:~$ cat "2008-0611-213811 File 01.log"
hello world

2.6.5 Creating Directory Name With Date

Obtain date and create 'now' variable.

john@WarEagleServer:~$ now=$(date +"%Y-%m%d-%H%M%S")
john@WarEagleServer:~$ echo $now
2008-0612-075012

Create directory name with date in directory name.
john@WarEagleServer:~$ testdir="$now Test Directory 01"
john@WarEagleServer:~$ echo $testdir
2008-0612-075012 Test Directory 01

Make, list and change to directory using file name.
john@WarEagleServer:~$ mkdir "$testdir"
john@WarEagleServer:~$ ls -adl "2008-0612-075012 Test Directory 01"
drwxr-xr-x 2 john admin 4096 2008-06-12 07:52 2008-0612-075012 Test Directory 01

john@WarEagleServer:~$ cd "2008-0612-075012 Test Directory 01"
john@WarEagleServer:~/2008-0612-075012 Test Directory 01$ pwd
/home/john/2008-0612-075012 Test Directory 01

2.6.6 Rsync Backup Script To Backup Desktop

#!/bin/sh
#

  1. Application rsync's //laptop01/home/john/Desktop with //RemoteDomain.com/home/john/Laptop01-backup

sudo rsync -azvv -e ssh /home/john/Desktop moc.niamoDetomeR|resU#moc.niamoDetomeR|resU:./Laptop01-backup


2.6.7 Bash File Testing

Check for file existence.

#!/bin/bash
file="./file"
if [ -e $file ]; then
echo "File exists"
else
echo "File does not exists"
fi

Other Bash File Testing Options
-b filename Block special file
-c filename Special character file
-d directoryname Check for directory existence
-e filename Check for file existence
-f filename Check for regular file existence not a directory
-G filename Check if file exists and is owned by effective group ID.
-g filename true if file exists and is set-group-id.
-k filename Sticky bit
-L filename Symbolic link
-O filename True if file exists and is owned by the effective user id.
-r filename Check if file is a readable
-S filename Check if file is socket
-s filename Check if file is nonzero size
-u filename Check if file set-ser-id bit is set
-w filename Check if file is writable
-x filename Check if file is executable

2.6.8 Samba - Windows Access

Use Samba to allow file sharing with Windows computers.
The installation and usage command lines can be run remotely via SSH -X x.x.x.x.
To install Samba:

sudo apt-get install system-config-samba

To run the Samba Configuration program:

gksu system-config-samba

To list Samba Computers on Network:

findsmb

2.6.9 DNS Settings

Display DNS Setting.

Default setting for /etc/resolv.conf.
cat /etc/resolv.conf

# generated by NetworkManager, do not edit!

nameserver 192.168.1.1

If DNS does not appear to be working, make the following change. The additional two lines actually forces the server to use OpenDNS. OpenDNS Nameservers (208.67.222.222 & 208.67.220.220).
cat /etc/resolv.conf

# generated by NetworkManager, do not edit!

nameserver 208.67.222.222
nameserver 208.67.220.220
nameserver 192.168.1.1

2.6.10 Command Line Email

Setup Command Line Email To Send Via Gmail.

sudo apt-get install ssmtp
sudo apt-get install mailutils

Configure /etc/ssmtp/ssmtp.conf for Gmail.
$ cat /etc/ssmtp/ssmtp.conf

#
# Config file for sSMTP sendmail
#
# The person who gets all mail for userids < 1000
# Make this empty to disable rewriting.
root=gmail_account_name@gmail.com # Your email address

# The place where the mail goes. The actual machine name is required no
# MX records are consulted. Commonly mailhosts are named mail.domain.com
mailhub=smtp.gmail.com:587 # Address and port number to send mail to
hostname=smtp.gmail.com:587
UseSTARTTLS=YES # Send SSL/TLS messages to Gmail
AuthUser=gmail_account_name # Your Gmail Username
AuthPass=gmail_password # Your Gmail Password

# Where will the mail seem to come from?
#rewriteDomain=gmail.com # So the message appears to come from Gmail

# The full hostname
hostname=your_linux_hostname # Hostname: use hostname -f in a Terminal

# Are users allowed to set their own From: address?
# YES - Allow the user to specify their own From: address
# NO - Use the system generated From: address
#FromLineOverride=YES # So the message appears to come from Gmail

$ cat /etc/ssmtp/revaliases
root:youraccount@gmail.com:smtp.gmail.com:587
# mainuser:youraccount@gmail.com:smtp.gmail.com:587 # Not sure if this line is needed.

Test Email by sending word test

$ echo test | mail -s test destination_email_address@domain.com

If mail delivery fails ssmtp stores message in ~/dead.letter.
You can resend it later using the following command.

$ cat ~/dead.letter | sendmail user@domain.tld

2.6.11 Gmail Captcha Lock On Automated Emails

Once email is setup configured correctly and appears to be working properly, if it ever fails to work, and you have not made any changes to the system, check the Gmail account that is being used. The following address will allow you to unlock a locked Gmail account.

http://www.google.com/accounts/DisplayUnlockCaptcha

2.6.12 Redirecting Output To Different Terminal Sessions

Identify the terminal session, then direct output to the terminal session.

john@laptop01:~$ w
21:03:22 up 5:07, 3 users, load average: 0.66, 0.73, 0.64
USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
john tty7 :0 15:57 5:07 25:02m 0.26s x-session-manag
john pts/0 :0.0 21:02 24.00s 0.24s 0.24s bash
john pts/1 :0.0 21:03 0.00s 0.18s 0.00s w

Directing output to the 'pts/0' terminal session.
john@laptop01:~$ echo 'test' > /dev/pts/0
john@laptop01:~$ ls -al > /dev/pts/0

2.6.13 Running Scripts At Startup (Boot)

Write a script and put it in the /etc/init.d/ directory.
In this example the script is "Script.sh".
Next make the script an executable:

chmod +x Script.sh

Next add the script to the boot process.
% update-rc.d Script.sh defaults

update-rc.d is a Debian utility to install scripts. The option “defaults� puts a link to start FOO in run levels 2, 3, 4 and 5. (and puts a link to stop Script.sh into 0, 1 and 6.)

To identify your runlevel in, use the runlevel command.


2.7 Applications

2.7.1 TrueCrypt - Disk & Media Encryption

TrueCrypt – Used to create a virtual drive using an encrypted file.

http://www.truecrypt.org/downloads.php

To mount the cryptfile to mountpoint, a folder you have previously created, the -u option is needed to set the permissions to the user otherwise you can not write back to the Virtual Disk unless Root

truecrypt -u containerfile mountpoint

Example - Where an empty vd directory exists under ~/Safe

truecrypt -u ~/Safe/tc01092006.tc ~/Safe/vd

Unmount all Virtual Disks

truecrypt -d

To create a container the following command takes you through the steps interactively

truecrypt -c

Script Examples to mount drives manually

#!/bin/bash
sudo truecrypt /dev/sda1 /home/john/tcPassport2500

2.7.2 DYNDNS - Dynamic DNS

Go to http://dyndns.org and create a new free account.

To install dyndns client:

sudo apt-get install ddclient

Then edit /etc/ddclient:

Example of simple /etc/ddclient.conf

Example of more detailed /etc/ddclient.conf

Edit /etc/default/ddclient

run_deamon="true"

Restart ddclient:

sudo /etc/init.d/ddclient restart

2.7.3 No-IP.com - Dynamic DNS

http://ubuntulinuxhowto.blogspot.com/2006/06/dynamic-dns-no-ip.html


2.7.4 NVU - HTML Editor

Go to: http://backports.org/debian/pool/main/n/nvu/
Download: nvu_1.0final-0bpo1_i386.deb


2.7.5 P7ZIP - File Compression and Encryption

P7Zip is a quick port of 7z.exe and 7za.exe (command line version of 7zip, see www.7-zip.org) for Unix. 7-Zip is a file archiver with highest compression ratio. 7-Zip works with Linux, Windows and OS-X. Use P7Zip for compression and AES-256 file encryption.
To install P7Zip

sudo apt-get install p7zip

For the full verison of P7Zip you will need to install the following. (Recommended).

sudo apt-get install p7zip-full

To use the full version of 7-Zip, type 7z at the command line. Type '7z —help' for help.
Use the follow to archive a file.

7z a archive.7z file.txt

To extract files.
7z x archive.7z

To archive using 7z with AES-256 encryption.
7z a -psecret -mhe archive.7z file.txt

To archive using Zip with AES-256 encryption.
7z a -tzip -psecret -mem=AES256 archive.zip file.txt

To view an archive.
7z l -slt archive.7z

P7ZIP Online Manual: (http://www.bugaco.com/7zip)
P7Zip Support Page: (http://sourceforge.net/projects/p7zip)


2.7.6 Installing Frozen Bubble

sudo apt-get install frozen-bubble

2.7.7 KeePassX - Password Manager

KeePass is a crossplatform password manager. To install it simply run:

sudo apt-get install keepassx

or use Synaptic Package Manager under System > Administration menu, to locate and install the "keepassx" package.

2.7.8 Editors


2.7.9 IFTOP - Bandwidth Display

To install iftop

sudo apt-get install iftop

To run iftop.
iftop

2.7.10 Java Browser Plugin

If using an i386 computer install the sun-java5-plugin package from the “Multiverse� repository.


2.7.11 Bluetooth

The D-Link Bluetooth DBT-122 works very well with Ubuntu.

Two Steps for the D-LInk Bluetooth DBT-122:

sudo apt-get install bluez-utils
sudo apt-get install gnome-bluetooth

To View Content on Phone via Browser:

obex://[00:15:A8:2E:30:D3]/audio

2.7.12 Java

https://help.ubuntu.com/community/Java


++++ **2.7.13 Midnight Commander - File Manager*
Midnight Commander is a command line file manager.
To install.

sudo apt-get install mc

2.7.14 VLC Media Player

sudo apt-get install vlc vlc-plugin-* mozilla-plugin-vlc

2.7.15 Installing Flash Player Version 9

Command line install for Flash Player.

wget http://fpdownload.macromedia.com/get/flashplayer/current/install_flash_player_9_linux.tar.gz

tar xvfz install_flash_player_9_linux

cd install_flash_player_9_linux

./flashplayer-installer

Then type the following in the address bar of Firefox to confirm Flash Player is installed.
about:plugins

Installing Flash Player in Firefox on Ubuntu Gutsy via GUI.

http://www.howtogeek.com/howto/linux/installing-flash-player-in-firefox-on-ubuntu-gutsy/

2.7.16 Installing Latest Version Of Wine

http://winehq.org/site/download-deb

2.7.17 Thunar - File Manager (Includes Bulk File Renamer)

To install:
Go to Add/Remove Programs and select Bulk File Renamer

http://thunar.xfce.org


2.7.18 UFW - Uncomplicated Firewall

To install:

sudo apt-get install ufw

For the GUI for ufw
Go to: http://gufw.tuxfamily.org
Or From the command line:

sudo apt-get install gufw
gufw

2.7.19 Chkrootkit - Root Kit Checker

To install:

sudo apt-get install chkrootkit

To run:
chkrootkit

2.8 Bash Script Programs

2.8.1 Pull Photos From Camera To Computer

This program pulls photos from digital camera memory and stores to computer. It creates a directory and names it based on the current date & time. It also removes the files from the digital camera memory after copying it.


2.8.2 JPG Image Puller

Application pulls Gulf Shores photos from ABC33/40.com. Can be added to Crontab to pull at certain times.

2.8.3 Display System Stats

Display various system stats.
$ cat serverstatus.sh

Send report via email.
$ cat emailserverstatus.sh

/home/john/serverstatus.sh > /home/john/serverstatus.log 
mail -s "Your_Server Status" You@gmail.com < /home/john/serverstatus.log

2.9 Misc Technical Documentation

2.9.1 Firefox Browser

Type the following in the address line on the browser to access config options.

about:config

2.9.2 Anonymous Surfing Via SSH & Firefox

-If you are using your home computer as the SSH server, you need to find out the external IP address of your home router or use DynDNS to map your external router IP to a hostname. You can find out the external IP address of your router by going to WhatsMyIP.org from a computer in your house.

-Install the SSH server on your Ubuntu computer at home using the following command at the Terminal:

sudo apt-get install ssh

-Set up port-forwarding on your router to forward any external SSH traffic to your Ubuntu SSH server in your house. Consult your router manual for information on how to set this up.

-Make sure you leave your home SSH server running before you leave the house with your laptop.

-At the hotspot run the following command in the Terminal to establish the SSH tunnel:

ssh -ND 9999 username@home_router_ip_address

-Minimize the Terminal window.

-Configure Firefox to use the SSH tunnel as a proxy server by going to “Edit -> Preferences�, selecting the “Advanced� tab, selecting the “Network� tab and clicking on “Settings…� under the “Connection� section. Select “Manual Proxy Configuration� and set up a SOCKS Host for “localhost� and Port 9999. Also choose “SOCKS v5.�

-To also, encrypt DNS lookups in the tunnel go to “about:config� in your browser. Set the network.proxy.socks_remote_dns setting.

network.proxy.socks_remote_dns = true

2.9.3 Saving .swf Files from Dayport (CBS Sites)

To pull .swf videos from Dayport which is used by CBS stations check the following folder for a cache file the size of the viewed file. Folder name may vary.

~/.mozilla/firefox/zg37avl5.default/Cache$

Browser temp files (.tmp) in a Windows Vista environment are stored under \Users\loginname\appdata\local\temp. Windows temp files will be erased as soon as the browser leaves the page or closes preventing you from copying them.

2.9.4 Saving .flv Files from ABC Sites

To pull .flv videos from ABC stations check the 'Embed Video:' field under the video. An example of one below.

<object id='VideoPlayback' type='application/x-shockwave-flash' height='280' width='320'> <param value='http://cfc.abc3340.com/mediaplayer.swf' name='movie' /> <param value='always' name='allowScriptAcess' /> <param value='transparent' name='wmode' /> <param value='best' name='quality' /> <param value='#000000' name='bgcolor' /> <param value='noScale' name='scale' /> <param value='TL' name='salign' /> <param value='file=http://cfc.abc3340.com/xmls/abc3340_22733.xml' name='FlashVars' /></object>

Identify the .xml file in the field. In this case it's the following line.
http://cfc.abc3340.com/xmls/abc3340_22733.xml'

Next paste the above line with the .xml link in your browser displaying the following page.
This XML file does not appear to have any style information associated with it. The document tree is shown below.

−
<playlist version="1">
<title>ABC 33/40 News Video</title>

<info>http://www.abc3340.com</info>
−
<trackList>
−
<track>
<title>ABC 33/40 News</title>
−
<location>

http://oascentral.abc3340.com/RealMedia/ads/adstream_sx.ads/www.abc3340.com/video/hs-v/@x10
</location>
<info>http://www.abc3340.com</info>
<album>preroll</album>
</track>
−
<track>
<title>ABC 33/40 News</title>

<creator>ABC 33/40 News</creator>
−
<location>
http://www.acc-tv.com/sites/abc3340/news/stories/0908/video/0912-blitzgow.flv
</location>
−
<image>
http://www.acc-tv.com/images/abc3340/news/vidcap_0912-blitzgow.jpg
</image>
</track>

−
<track>
<title>ABC 33/40 News</title>
−
<location>
http://oascentral.abc3340.com/RealMedia/ads/adstream_sx.ads/www.abc3340.com/video/hs-v/@x11
</location>
<info>http://www.abc3340.com</info>

<album>postroll</album>
</track>
</trackList>
</playlist>
<!--node1-->

Identify the .flv video in the file above. In this example it would be the line below.
http://www.acc-tv.com/sites/abc3340/news/stories/0908/video/0912-blitzgow.flv

Using Linux -
You can use wget to pull the video to your computer.
john@Laptop01:~$ wget http://www.acc-tv.com/sites/abc3340/news/stories/0908/video/0912-blitzgow.flv
--19:12:51-- http://www.acc-tv.com/sites/abc3340/news/stories/0908/video/0912-blitzgow.flv
=> `0912-blitzgow.flv.1'
Resolving www.acc-tv.com... 216.147.203.200
Connecting to www.acc-tv.com|216.147.203.200|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 18,379,153 (18M) [video/x-flv]

100%[====================================>] 18,379,153 486.46K/s ETA 00:00

19:13:29 (474.64 KB/s) - `0912-blitzgow.flv.1' saved [18379153/18379153]

2.9.5 Watching Movies in ASCII

This works with .avi and .wmv and may work with over movie formats.

First make sure that mplayer is installed, from the command line:

sudo apt-get install mplayer

Then, to actually watch the movies from a terminal window, use the following syntax, replacing MovieName with the filename of your video.

mplayer -vo caca MovieName.avi

The "caca" command is actually the color text driver - you could also use " -vo aa " instead for black & white.


2.9.6 Boot To Command Line

Make the following changes to your Ubuntu Desktop to have your computer boot directly to the command line.

sudo update-rc.d -f gdm remove

To run the desktop:

sudo gdm

2.9.7 Send Email / Txt Msg After Booting

The following will setup your computer to call once it's booted. The call is made 2 minutes after booting. User does not have to login.
First create script that will email and call. Notice script also sends IP address.

sleep 120
/usr/bin/wget -qO /home/john/ip.txt http://whatismyip.org
echo "." >> /home/john/ip.txt
/usr/bin/mail -s $( cat /etc/hostname)" Booted - "$(date +%m/%d/%Y)" "$(date +%H:%M:%S) youremailaddress@gmail.com < /home/john/ip.txt
/usr/bin/mail -s $( cat /etc/hostname)" Booted - "$(date +%m/%d/%Y)" "$(date +%H:%M:%S) yourphonenumber@txt.att.net < /home/john/ip.txt

Save the file as Call.sh.
Next copy the file to the /etc/init.d folder.
Make the file executable.

sudo chmod +x Call.sh

Next add the script file "Call.sh" to run at system startup.
sudo update-rc.d Call.sh start 99 2 3 4 5 .

Remember to put the space and period at the end of the command.

To remove, delete the script and run the update with the remove parameter:

sudo rm /etc/init.d/Call.sh
sudo update-rc.d Call.sh remove

2.9.8 Error With High Number Of Files

To resolve the following error:

sudo: unable to execute /bin/chmod: Argument list too long

The example below is for issuing a 'chmod 0644' command on a very high number of files.

sudo find . -type f -exec chmod 0644 {} \; -print

2.9.9 ClamAV - Anti Virus

To install clamav:

sudo apt-get install clamav

To update ClamAV data files:

sudo freshclam

To run ClamAV:

clamscan -i -r /

The script below displays the ClamAV version number, updates the data files, runs a scan, and emails the results to you.

# ClamAV Script
# John 2009-0327
#
# Write Version Number To Log
clamscan -V > /home/john/clamav.log
#
# Update Data Files
freshclam >> /home/john/clamav.log
#
# Run Actual Scan
clamscan -r -i / >> /home/john/clamav.log
#
# Send Email of Scan Results
mail -s $( cat /etc/hostname)" ClamAV Report - "$(date +%m/%d/%Y)" "$(date +%H:%M:%S) youremailaddress@domain.com < /home/john/clamav.log

2.9.10 Recover From Lost User Name or Password

To recover from a lost user name or password:

1) Turn on your computer, and as soon as you the Press Esc to enter grub message.

2) Select the option that says (recovery mode).

3) Your PC will boot into a shell.
At the command prompt, type “passwd username� where the username is your username.
If you can’t remember your username, then you can type “ls /home� which should bring it up.

4) Enter a new password when prompted, and again when prompted again.
Type “shutdown -r now� to reboot your system.


2.9.11 Monitor System Temperature

For detailed instructions see:
http://ubuntuforums.org/showthread.php?t=2780

Install temperature sensor:

sudo apt-get install lm-sensors

Run the following script:
#!/bin/bash

# Here you can set several defaults.

# The number of devices to create (max: 256)
NUMBER=32

# The owner and group of the devices
OUSER=root
OGROUP=root
# The mode of the devices
MODE=600

# This script doesn't need to be run if devfs is used
if [ -r /proc/mounts ] ; then
if grep -q "/dev devfs" /proc/mounts ; then
echo "You do not need to run this script as your system uses devfs."
exit;
fi
fi

i=0;

while [ $i -lt $NUMBER ] ; do
echo /dev/i2c-$i
mknod -m $MODE /dev/i2c-$i c 89 $i || exit
chown "$OUSER:$OGROUP" /dev/i2c-$i || exit
i=$[$i + 1]
done

Detect sensors:

sensors-detect

Add the detected sensors results in reverse order to /etc/modules then run /etc/init.d/module-init-tools.

To monitor sensors:

sensors -f


2.9.12 Embedding Information in .jpg Files

Create document with information.
You can use an editor such a nano to create the .txt file or via command line.

echo "This is the information to be hidden" > test.txt

Next create a zip file from the test.txt file. In this example 7za is used from p7zip.
7za a test.zip test.txt

Next embed the zip file into an image.
cat image.jpg test.zip >> newimage.jpg

The new file 'newimage.jpg' can now be viewed using a standard viewer, and unziped with p7zip.
To unzip the file use 7za from p7zip.
7za e newimage.jpg

2.9.13 YouTube Movies - Buffering Too Much

For buffering issues with Normal YouTube Video:
Add the following tag "&fmt=18" (without the quotes) to the end of the URL and reload that page.

For buffering issues with HD YouTube Video:
Add the following tag "&fmt=22" (without the quotes) to the end of the URL and reload that page.

Source: http://techreport.com/forums/viewtopic.php?f=30&t=64937&start=0&st=0&sk=t&sd=a


2.9.14 Fresh Linux Install - App Checklist

Basic applications to install after initial Linux install.

Fresh Linux Install
App Checklist
Applications Installation
Truecrypt From Repository / Synaptic Package Manager (actually installed from web site)
KeePassX From Repository / Synaptic Package Manager
GParted From Repository / Synaptic Package Manager
ufw sudo apt-get ufw
ClamAV sudo apt-get clamav
Email sudo apt-get install ssmtp & sudo apt-get install mailutils (configure /etc/ssmtp/ssmtp/conf)
DynDNS sudo apt-get install ddclient (configure /etc/ddclient.conf)
VirtualBox From VirtualBox.org
Adobe Flash Loaded via get.adobe.com/flashplayer
Java sun-java5-plugin & sun-java5-bin (From Repository / Synaptic Package Manager)
VLC sudo apt-get install vlc
p7zip sudo apt-get install p7zip-full
Real Player http://www.real.com/offer/linux

Also check out JohnMcGough.com/office for more application options.



2.9.15 GPS Connectivity

GPS Connectivity.

Install gpsbabel to pull .gpx file from your GPS. sudo apt-get install gpsbabel sudo gpsbabel -i garmin -f usb: -o gpx -F waypoints.gpx GPSMap 60CSx Connectivity
  1. Install gpsd using the System > Administration > Synaptic Package Manager
  2. Perform a 'sudo modprobe garmin_gps'. This will create /dev/ttyUSB0 when the device is connected.
  3. Perform a 'sudo mount -t usbfs none /proc/bus/usb'. This is needed by gpsd.
  4. Set the 60CSx to "Text Out". (I set the baud rate for 9600 also. I haven't experimented to see if this is even required.)
  5. Connect the 60CSx to the USB port.
  6. Get gpsd running: 'sudo gpsd /dev/ttyUSB0'.
  7. Verify it is operating by running 'xgps'. You should see satellite information confirming incoming data is working. Web Sites: http://gpsvisualizer.com

2.9.16 Cisco VPN

Cisco VPN.

Cisco Anyconnect VPN Client For Linux
 
cd to the binaries folder
sudo ./vpnsetup.sh

During setup you can run index.html.

Use /opt/cisco/vpn/bin and run vpnui (./vpnui) or vpn (./vpn) if Cisco does not show in menu.   

Command line interface commands:

http://www.cisco.com/en/US/docs/security/vpn_client/anyconnect/anyconnect20/administrative/guide/admin7.html

File: anyconnect-linux-2.4.0202-k9.pkg
Download Site: http://www.asc.edu/downloads/CiscoVPN/

2.9.17 Using DD To Copy

To copy one drive to another using dd, simply use the following command, substituting sda and sdb for your source and destination device names.
dd if=/dev/sda of=/dev/sdb

To create an image file instead, substituting sda for your source drive name, and modifying the path to your external hard drive.
dd if=/dev/sda of=/media/EXTERNAL/backup.img bs=4096

Once you've created the image, you can swap out your hard drive, boot from the live CD again, and then reverse the command:
dd if=/media/EXTERNAL/backup.img of=/dev/sda bs=4096



>