Tuesday, February 24, 2009

Create New Linux EXT3 File System In LVM



This is another 3-minutes Linux guide for newbie on How to create or add new Linux EXT3 file system in Logical Volume Manager (LVM) with a new disk partition, which involves creating new logical volume (LV)?




How to create new Linux EXT3 file system in LVM with new hard disk by creating new logical volume?

Assuming a new IDE hard disk hooked up to Secondary-Slave IDE bus for the new logical volume / file system. Hence, the Linux device code will be /dev/hdd for this IDE hard disk, according to LANANA Linux Device List or the offline copy in /usr/src/linux-2.x/Documentation/devices.txt
  1. Using the whole secondary-slave IDE hard disk for existing LVM volume group (called vg0 in my case) by creating the physical volume (PV):
    pvcreate /dev/hdd

    A similar message of this will be shown upon successful execution of pvcreate command:

    pvcreate — physical volume “/dev/hdd” successfully created
  2. Adding the new physical volume (PV) to volume group vg0, i.e. to extend the existing volume group size with new physical volume:
    vgextend vg0 /dev/hdd

    If no errors encounter while executing vgextend, a similar message of this will be seen:

    vgextend — INFO: maximum logical volume size is 1023.97 Gigabyte
    vgextend — doing automatic backup of volume group “vg0″
    vgextend — volume group “vg0″ successfully extended

  3. Create the new logical volume (LV) at 400MB (not fully utilize the whole IDE hard disk) to host the new EXT3 file system in question:
    lvcreate -L 400M -n lvol1 vg0

    Suppose lvcreate completed successfully, this similar message will be seen:

    lvcreate — doing automatic backup of “vg0″
    lvcreate — logical volume “/dev/vg0/lvol1″ successfully created

  4. Now, create the new EXT3 file system on the new logical volume (LV) with 1% file system reserved block count:
    mkfs -t ext3 -m 1 -v /dev/vg0/lvol1

    Once the new EXT3 file system creation completed, you can examine the file system by executing

    tune2fs -l /dev/vg0/lvol1
  5. Create a mount point directory for the new EXT3 file system:
    mkdir /mnt/newfs
  6. It’s now ready to mount the new EXT3 file system:
    mount -t ext3 /dev/vg0/lvol1 /mnt/newfs

    To confirm that the new EXT3 file system has been mounted successful, type df -h

Extend LVM Disk Space With New Hard Disk


This is a step-by-step guide used to extend logical volume group disk space, that’s configured under LVM version 1.x of Redhat Enterprise Linux AS 3. Although, this guide has also been used to extend LVM disk space with a new SCSI hard disk, that’s configured with LVM version 2.x in Debian Sarge 3.1.

So, it’s good enough to serve as a reference for Linux users, who plan to extend LVM disk space in Linux distributions other than Redhat and Debian Linux.


Although it’s not necessary, it’s advised to perform full file system backup before carry out this exercise!

The most risky step is to resize file system that resides in a LVM logical volume. Make sure the right file system resizer tool is used. If you’re using resize2fs to resize a Reiserfs file system, I guess you’ll know how bad will be the consequences.

Apparently, you’ll need resize_reiserfs to resize a Reiserfs file system, which is part of the reiserfsprogs package.

Steps to extend /home file system that mounts on logical volume /dev/vg0/lvol1 of volume group vg0, by using a new 36GB SCSI hard disk added to RAID 0 of HP Smart Array 5i Controller.

1) Log in as root user and type init 0 to shutdown Redhat Enterprise AS 3 Linux.

2) Add in the new 36GB SCSI hard disk. Since HP Smart Array 5i is configure for RAID 0, it’s fine to mix hard disks of different capacity, except that hard disk speed must be the same! A mix of 10K and 15K RPM hard disks might cause Redhat Enterprise Linux fails to boot up properly.

Normally, HP Smart Array 5i Controller will automatically configure new hard disk as a logical drive for RAID 0. If not, press F8 on boot up to get in HP Smart Array 5i Controller setup screen and manually create logical drive as part of RAID 0.

How to tell if new hard disk is not configured as logical drive for RAID 0?

Physically, the hard disk green light should be on or blinking to indicate that it’s online to RAID system.

From OS level, 3rd hard disk in RAID 0 of HP Smart Array 5i Controller is denoted as /dev/cciss/c0d2. So, type

fdisk /dev/cciss/c0d2

at root command prompt. If an error message Unable to open /dev/cciss/c0d2 or alike is returned, it means that new hard disk is not online to RAID system or Redhat Linux.

3) Boot up Redhat Enterprise Linux into multi-user mode and confirm it’s working properly. This step is not necessary, but it’s a good practice to prove that the server is working fine after each change has been made, be it a major or minor change.

4) Type init 1 at root command prompt to boot into single user mode. Whenever possible, boot into single user mode for system maintenance as to avoid inconsistency or corruption.

5) At the root command prompt, type

fdisk /dev/cciss/c0d2

to create partition for the 3rd SCSI hard disk added to RAID 0. Each hard disk needs at least one partition (maximum 4 primary partitions per hard disk) in order to use the new hard disk in a Linux system.

6) While at the fdisk command prompt, type m to view fdisk command options.

7) Type n to add a new partition, followed by p to go for primary partition type.

8) Type 1 to create the first partition. Press ENTER to accept first cylinder default as 1, and press ENTER again to accept the default value for last cylinder, which is essentially create single partition that use up all hard disk space.

9) Type t to change the partition system id, or partition type. As there is only one partition, partition 1 is automatically selected for action. Type L to list all supported partition type. As shown in partition type listing, type 8e to set partition 1 as Linux LVM partition type.

10) Type p to confirm partition /dev/cciss/c0d2p1 has been created in partition table. Type w to write the unsaved partition table of changes to hard disk and exit from fdisk command line.

11) Type df -hTa to confirm /home file system type, that’s mounts on logical volume /dev/vg0/lvol1. For this case, it’s an ext3 file system type.

12) Type umount /home to un-mount /home file system from Redhat Enterprise Linux.

13) Next, type LVM command

pvcreate /dev/cciss/c0d2p1

to create a new LVM physical volume on the new partition /dev/cciss/c0d2p1.

14) Now, type another LVM command

vgextend vg0 /dev/cciss/c0d2p1

to extend LVM volume group vg0, with that new LVM physical volume created on partition /dev/cciss/c0d2p1.

15) Type pvscan to display physical volumes created in Linux LVM system, which is useful to answer questions such as “How many physical volume created in volume group vg0?”, “How much of free disk space left on each physical volume?”, “How do I know which physical volume should be used for a logical volume?” “Which physical volume has free disk space for used with a logical volume?”, etc.

Sample output of pvscan command:

ACTIVE PV “/dev/cciss/c0d0p4″ of VG “vg0″ [274.27GB / 0 free]
ACTIVE PV “/dev/cciss/c0d1p1″ of VG “vg0″ [33.89GB / 0 free]
ACTIVE PV “/dev/cciss/c0d2p1″ of VG “vg0″ [33.89 GB / 33.89 GB free]
total: 3 [342.05 GB] / in use: 3 [342.05 GB] / in no VG: 0 [0]

Alternative, type vgdisplay vg0 | grep PE to confirm that new physical volume has been added to volume group vg0. Take note of Free PE / Size, 35GB in this case, that’s free disk space added by new physical volume in volume group vg0.

16) Execute LVM command

lvextend -L +33G /dev/vg0/lvol1 /dev/cciss/c0d2p1

to extend the size of logical volume /dev/vg0/lvol1 of volume group vg0 by 33GB on physical volume /dev/cciss/c0d2p1.

17) Now, the most risky steps to start. Type this command

e2fsck -f /dev/vg0/lvol1

to force ext3 file system check on /dev/vg0/lvol1. It’s a must to confirm file system is in good state, before implement any changes on it.

CAUTION - Utility e2fsck is only used to check EXT file system such as ext2 and ext3, and not other file system such Reiserfs file system!

Once the ext file system check completes without errors or warnings, type command

resize2fs /dev/vg0/lvol1

to resize EXT3 file system of /home, that mounts on logical volume /dev/vg0/lvol1, until it takes up all free disk space added to /dev/vg0/lvol1.

CAUTION - Utility resize2fs is only used to resize EXT file system such as ext2 and ext3, and not other file systems such as Reiserfs file system!

Both e2fsck and resize2fs utilities are part of e2fsprogs package. And both utilities takes some minutes to complete, depends on the size of target file system.

If everything alright, type mount /home to re-mount /home file system. Next, type df -h to confirm that /home file system has been extended successfully.


How To Create Linux LVM In 3 Minutes



What’s LVM? Why using Linux Logical Volume Manager or LVM?

These questions are not the scope here. But in brief, the most attractive feature of Logical Volume Manager is to make disk management easier in Linux! Basically, LVM allows users to dynamically extend or shrink Linux “partition” or file system in online mode! The LVM can resize volume groups (VG) online by adding new physical volumes (PV) or rejecting those existing PVs attached to VG.

A visualized concept diagram of the Linux Logical Volume Manager or LVM.

In this 3-minutes Linux LVM guide, let’s assume that
  • The LVM is not currently configured or in used. Having say that, this is the LVM tutorial if you’re going to setup LVM from the ground up on a production Linux server with a new SATA / SCSI hard disk.
  • Without a luxury server hardware, I tested this LVM tutorial on PC with the secondary hard disk dedicated for LVM setup. So, the Linux dev file of secondary IDE hard disk will be /dev/hdb (or /dev/sdb for SCSI hard disk).
  • This guide is fully tested in Red Hat Enterprise Linux 4 with Logical Volume Manager 2 (LVM2) run-time environment (LVM version 2.00.31 2004-12-12, Library version 1.00.19-ioctl 2004-07-03, Driver version 4.1.0)!

How to setup Linux LVM in 3 minutes at command line?
  1. Login with root user ID and try to avoid using sudo command for simplicity reason.
  2. Using the whole secondary hard disk for LVM partition:
    fdisk /dev/hdb

    At the Linux fdisk command prompt,
    1. press n to create a new disk partition,
    2. press p to create a primary disk partition,
    3. press 1 to denote it as 1st disk partition,
    4. press ENTER twice to accept the default of 1st and last cylinder - to convert the whole secondary hard disk to a single disk partition,
    5. press t (will automatically select the only partition - partition 1) to change the default Linux partition type (0×83) to LVM partition type (0×8e),
    6. press L to list all the currently supported partition type,
    7. press 8e (as per the L listing) to change partition 1 to 8e, i.e. Linux LVM partition type,
    8. press p to display the secondary hard disk partition setup. Please take note that the first partition is denoted as /dev/hdb1 in Linux,
    9. press w to write the partition table and exit fdisk upon completion.

  3. Next, this LVM command will create a LVM physical volume (PV) on a regular hard disk or partition:
    pvcreate /dev/hdb1
  4. Now, another LVM command to create a LVM volume group (VG) called vg0 with a physical extent size (PE size) of 16MB:
    vgcreate -s 16M vg0 /dev/hdb1

    Be properly planning ahead of PE size before creating a volume group with vgcreate -s option!
  5. Create a 400MB logical volume (LV) called lvol0 on volume group vg0:
    lvcreate -L 400M -n lvol0 vg0

    This lvcreate command will create a softlink /dev/vg0/lvol0 point to a correspondence block device file called /dev/mapper/vg0-lvol0.
  6. The Linux LVM setup is almost done. Now is the time to format logical volume lvol0 to create a Red Hat Linux supported file system, i.e. EXT3 file system, with 1% reserved block count:
    mkfs -t ext3 -m 1 -v /dev/vg0/lvol0
  7. Create a mount point before mounting the new EXT3 file system:
    mkdir /mnt/vfs
  8. The last step of this LVM tutorial - mount the new EXT3 file system created on logical volume lvol0 of LVM to /mnt/vfs mount point:
    mount -t ext3 /dev/vg0/lvol0 /mnt/vfs

To confirm the LVM setup has been completed successfully, the df -h command should display these similar message:

/dev/mapper/vg0-lvol0 388M 11M 374M 3% /mnt/vfs

vgdisplay vg0
To check or display volume group setting, such as physical size (PE Size), volume group name (VG name), maximum logical volumes (Max LV), maximum physical volume (Max PV), etc.
pvscan
To check or list all physical volumes (PV) created for volume group (VG) in the current system.
vgextend
To dynamically adding more physical volume (PV), i.e. through new hard disk or disk partition, to an existing volume group (VG) in online mode. You’ll have to manually execute vgextend after pvcreate command that create LVM physical volume (PV).

Maximum Size Of A Logical Volume In LVM



What is the maximum size of a single logical volume (LV) in Linux Logical Volume Manager or LVM? How to resize or change LVM PE size of an existing volume group or VG dynamically?

Most probably you’re here because you’re googling these similar LVM FAQ. Hopefully these are the answers!

The physical extent size (PE size) of a LVM volume group (VG) is fixed upon the creation of VG. In Linux command line, the -s option switch of vgcreate command is to explicitly set the physical extent size (PE size) on physical volumes (PV) of the volume group (VG). PE size is defaulted to 4MB if it’s not set explicitly. However, once this value has been set, it’s not possible to change a PE size without recreating the volume group which would involve backing up and restoring data on any logical volumes!

As far as LVM2 is concerned - LVM version 2.02.06 (2006-05-12), Library version 1.02.07 (2006-05-11), Driver version 4.5.0 - there is no LVM commands or utilities, not even the vgmodify in HPUX, to resize or change the LVM PE size of an existing VG dynamically or in online mode!

So, it’s recommended to properly plan ahead before creating a LVM volume group. For example, if the logical volume will store database tables where the database size will likely grow up to more than 300G in near future, you should have not created a volume group with the default PE size of 4MB!

A visualized concept diagram of the Linux Logical Volume Manager or LVM.

What’s the maximum size of a logical volume in Linux LVM?
Why there is a limitation on maximum size of logical volume?

In order to limit the Linux kernel memory usage, there is a limit of 65,536 physical extents (PE) per logical volume (LV). Hence, the LVM PE size will directly determine the maximum size of a logical volume (LV)! For example, 4MB PE size (the default PE size) will limit single logical volume (LV) to 256GB, 16MB PE size will limit single LV to grow beyond 1TB, etc.

Beside the PE size, the maximum size of single LV is also limited by CPU architecture and Linux kernel version:
  • Linux kernel version 2.4.x limit the maximum LV size to 2TB.
  • Some older Linux kernel prior to 2.4.x, the maximum LV size is limited to 1TB (caused by the integer signedness problems in the block layer).
  • The combination of 32-bit CPU and Linux kernel version 2.6.x, the limit of logical volume size is maximized at 16TB.
  • For Linux kernel 2.6.x running on 64-bit CPU, the maximum LV size is 8EB (extremely terrible big storage for this time being!)

Wednesday, February 18, 2009

Enable Audio CD writing in K3B

if you prefer then just open a terminal and
perform a

#yum install k3b k3b-extras-nonfree

and job done.



In Ubuntu you may only need to Run the following code in a terminal:


sudo apt-get install k3b libk3b2-mp3

- unsure as to whether you need the
other stuff (or similar), above?

Now when you run K3B, your system configuration should get the all clear and you can burn your MP3’s using your chosen method.

Tuesday, February 10, 2009

7 Cool Things to Do With Linux


So you’ve taken the plunge and installed Linux. You’ve followed all the HOWTOs all over the net. You’ve got your wireless card working flawlessly. You’ve got your video card working (and you’ve begun to loathe that spinning cube). You’ve installed all the “restricted” software like Adobe Flash, Sun Java and Google Earth. You’ve got all the patent restricted codecs and even DVD playback working just like you want. Now what? You want to know what you can do with Linux outside of the surfing, emailing, chatting and media consumption you normally do? Well, here are a few things to keep you busy.

  1. Use Your computer as a Home Theater PC. I personally use XBMC for this, but there are many other options including MythTV, Elisa, Entertainer, Freevo, GeeXboX and LinuxMCE.
  2. Set up a media server. There are many, many ways to go about doing this. There is the old tried and true file server approach, using either NFS or Samba.

    However, if it’s only music you’re sharing, you probably want something more like Firefly or Tangerine, which can share all of your music with the other computers and devices on your network with DAAP (this is the same music sharing technology iTunes uses). Most Linux music players provide this capability as well. If you want to access your music from anywhere in the world, you could set up Jinzora, which is a web based music server.

    If you have an Xbox 360 or PS3 that you’re using to consume music and videos, you’ll want to use a UPnP/DLNA server like uShare (which is based on GMediaServer) or MediaTomb. Many of the aforementioned HTPC programs (XBMC, MythTV) provide this functionality as well.

  3. Set up a download server. Centralize all your downloads to one Linux powered server. Get your Usenet downloads with HellaNZB or SABnzbd+. Get your torrents with Transmission, Vuze (formerly Azureus), TorrentFlux, Deluge or MonoTorrent. All of the software mentioned in this section has a web interface of some kind.
  4. Have an enterprise class VoIP phone system in your house. Asterisk gives you the ability to have all kinds of crazy phone system features, probably surpassing whatever you have at work, for free (not counting the hardware, obviously). If you want a smaller project, you could always just play with Ekiga.
  5. Set up your own surveillance system. Both ZoneMinder and Gspy will monitor your video cameras and optionally perform some action (playing a sound, emailing you, text messaging you, etc) when they detect motion. You could also use something like Motion to roll your own.
  6. Be really, really paranoid (Act like a spy!). With Linux, you have so many security and privacy options it’s not even funny.

    Encryption capabilities are already integrated into most desktop oriented distributions that allow you to encrypt certain files. You can encrypt your home directory or your entire hard drive with dm-crypt.

    You can use GnuPG to encrypt and sign email messages (most email clients support this). You can also encrypt your Pidgin chats with Pidgin-Encryption or Off-The-Record Messaging.

    Lock down your network (especially wireless) with FreeRADIUS and IPCop.

    When you’re not at home, you can use Tor for secure web browsing or SSH tunneling to encrypt just about any type of traffic.

    Steghide can conceal secret messages within images or audio, using a technique called Steganography.

    When you’re done with all that, don’t forget to clean up after yourself using either shred or dd.

  7. Poke into other people’s business (Act like a spy some more!). Wireshark will let you look at all the network traffic happening around your computer. This is especially cool because most instant messages and emails are unencrypted, meaning you can read them as they go by. You can also see what web pages people are visiting.

    This is even more fun if you get on someone else’s wireless network to spy on them. Find a wireless network with Kismet, then use the Aircrack-ng suite to gain access.

    You could also use Ophcrack to get into a physical computer for which you don’t have the password…

Monday, February 9, 2009

From the archives: the best distros of 2000


Distros

Back in May 2000 the first issue of Linux Format magazine hit the newsstands. One of its features was a group test of Linux distributions, reflecting the state of play in Linux flavours at the time. If you fancy a trip down memory lane or just a quick look at how beautiful Linux wasn't all those years ago, we've dug out the original article complete with screenshots - read on!

Historical note

Remember that nine years is a long time in the computing world -- and even more so for Linux. In 2000 the OS was still regarded as a niche player, a fantastic showcase of technology for geeks but not yet ready for prime time. Today we see Linux on netbooks, Linux on Dell boxes, Linux everywhere; it's serious business.

Corel Linux is long dead, despite a high-profile entrance into the distro scene, while Caldera Linux occupied a healthy position (before the SCO shenanigans busted it up). SUSE, Mandrake, Red Hat and Mandriva are still alive in various flavours, while the British Definite distro bought the farm and WinLinux only made it to a 2003 release...........................more..






Sunday, February 8, 2009

Linux PDF editor for manipulating PDF documents


by Vivek Gite

Adobe Acrobat is a commercial tool for manipulating PDF files. Earlier I was using CUPs - printing system, to export PDF files. I've also tried out gv for the same purpose. However, I needed complete editing of pdf documents. My search ended with PDFedit software, which is free and open source editor for manipulating PDF documents. The software available in both GUI and CLI (commandline) interface.

This software also supports scripting and almost anything can be scripted. PDFedit is a low-level tool for users. You can use this software:
=> To write / create / edit PDF files.
=> Print PDF files.
=> Save PDF files.
=> Export PDF files to XML etc.

Install PDFEdit

If you are using Debian or Ubuntu Linux, enter:
$ sudo apt-get install pdfedit

Start Editing PDF Files with PDFEdit editor

To start PDFEdit, type:
$ pdfedit /path/to/pdf.file &
$ pdfedit &

PDFEdit Linux freeware pdf writer software
( Fig 01: PDFedit ~ Linux PDF maker in action [click to enlarge the image] )

Other Linux pdf maker / writer software

During my research I came across other apps to edit PDFs. I hope you will find following tools useful:

=> scribus - Open Source Desktop Page Layout / desktop publishing (DTP) application software. It works under Linux, Mac and Windows computer. This software is another good alternative to PDFEdit. Just open file using open option and you can edit PDF file. You can install scribus using apt-get command:
$ sudo apt-get install scribus

To use scribus to edit PDF files:
Start scribus > New File > Insert > Image > Double click > Select PDF file

=> flpsed - a WYSIWYG pseudo PostScript editor. This software is very fast and light weight. To install flpsed, enter:
$ sudo apt-get install flpsed
To edit file, enter:
$ flpsed /path/to/pdf-file.pdf &

=> Gimp - I've also used gimp for editing pdf files. However, you need basic knowledge of gimp itself for editing pdf files. GIMP is almost installed on all Linux distribution. Please note that GIMP is not elegant solution for editing pdf files.

Online PDF manipulation tool

Finally, you can always use the Internet to modify PDF files using a web browser. [pdfescape.com]

Conclusion

PDFEdit is the best free open source software for for Linux / Unix-like operating systems. However, it does not support editing protected or encrypted PDF files.

Further readings:

Thursday, February 5, 2009

10 mistakes new Linux administrators make

For many, migrating to Linux is a rite of passage that equates to a thing of joy. For others, it’s a nightmare waiting to happen. It’s wonderful when it’s the former; it’s a real show stopper when it’s the latter. But that nightmare doesn’t have to happen, especially when you know, first hand, the most common mistakes new Linux administrators make. This article will help you avoid those mistakes by laying out the most typical Linux missteps.

Note: This information is also available as a PDF download.

#1: Installing applications from various types

This might not seem like such a bad idea at first. You are running Ubuntu so you know the package management system uses .deb packages. But there are a number of applications that you find only in source form. No big deal right? They install, they work. Why shouldn’t you? Simple, your package management system can’t keep track of what you have installed if it’s installed from source. So what happens when package A (that you installed from source) depends upon package B (that was installed from a .deb binary) and package B is upgraded from the update manager? Package A might still work or it might not. But if both package A and B are installed from .debs, the chances of them both working are far higher. Also, updating packages is much easier when all packages are from the same binary type.

#2: Neglecting updates

Okay, this one doesn’t point out Linux as much as it does poor administration skills. But many admins get Linux up and running and think they have to do nothing more. It’s solid, it’s secure, it works. Well, new updates can patch new exploits. Keeping up with your updates can make the difference between a compromised system and a secure one. And just because you can rest on the security of Linux doesn’t mean you should. For security, for new features, for stability — the same reasons we have all grown accustomed to updating with Windows — you should always keep up with your Linux updates.

#3: Poor root password choice

Okay, repeat after me: “The root password is the key to the kingdom.” So why would you make the key to the kingdom simple to crack? Sure, make your standard user password something you can easily remember and/or type. But that root password — you know, the one that’s protecting your enterprise database server — give that a much higher difficulty level. Make that password one you might have to store, encrypted, on a USB key, requiring you to slide that USB key into the machine, mount it, decrypt the password, and use it.

#4: Avoiding the command line

No one wants to have to memorize a bunch of commands. And for the most part, the GUI takes care of a vast majority of them. But there are times when the command line is easier, faster, more secure, and more reliable. Avoiding the command line should be considered a cardinal sin of Linux administration. You should at least have a solid understanding of how the command line works and a small arsenal of commands you can use without having to RTFM. With a small selection of command-line tools on top of the GUI tools, you should be ready for just about anything.

#5: Not keeping a working kernel installed

Let’s face it, you don’t need 12 kernels installed on one machine. But you do need to update your kernel, and the update process doesn’t delete previous kernels. What do you do? You keep at least the most recently working kernel at all times. Let’s say you have 2.6.22 as your current working kernel and 2.6.20 as your backup. If you update to 2.6.26 and all is working well, you can remove 2.6.20. If you use an rpm-based system, you can use this method to remove the old kernels: rpm -qa | grep -i kernel followed by rpm-e kernel-{VERSION}.

#6: Not backing up critical configuration files

How many times have you upgraded X11 only to find the new version fubar’d your xorg.conf file to the point where you can no longer use X? It used to happen to me a lot when I was new to Linux. But now, anytime X is going to be updated I always back up /etc/X11/xorg.conf in case the upgrade goes bad. Sure, an X update tries to back up xorg.conf, but it does so within the /etc/X11 directory. And even though this often works seamlessly, you are better off keeping that backup under your own control. I always back up xorg.conf to the /root directory so I know only the root user can even access it. Better safe than sorry. This applies to other critical backups, such as Samba, Apache, and MySQL, too.

#7: Booting a server to X

When a machine is a dedicated server, you might want to have X installed so some administration tasks are easier. But this doesn’t mean you should have that server boot to X. This will waste precious memory and CPU cycles. Instead, stop the boot process at runlevel 3 so you are left at the command line. Not only will this leave all of your resources to the servers, it will also keep prying eyes out of your machine (unless they know the command line and passwords to log in). To log into X, you will simply have to log in and run the command startx to bring up your desktop.

#8: Not understanding permissions

Permissions can make your life really easy, but if done poorly, can make life really easy for hackers. The simplest way to handle permissions is using the rwx method. Here’s what they mean: r=read, w=write, x=execute. Say you want a user to be able to read a file but not write to a file. To do this, you would issue chmod u+r,u-wx filename. What often happens is that a new user sees an error saying they do not have permission to use a file, so they hit the file with something akin to chmod 777 filename to avoid the problem. But this can actually cause more problems because it gives the file executable privileges. Remember this: 777 gives a file rwx permissions to all users (root, group, and other), 666 gives the file rw privileges to all users, 555 gives the file rx permissions to all users, 444 gives r privileges to all users, 333 gives wx privileges to all users, 222 gives w privileges to all users, 111 gives x privileges to all users, and 000 gives no privileges to all users.

#9: Logging in as root user

I can’t stress this enough. Do NOT log in as root. If you need root privileges to execute or configure an application, su to root in a standard user account. Why is logging in as root bad? Well, when you log on as a standard user, all running X applications still have access only to the system limited to that user. If you log in as root, X has all root permissions. This can cause two problems: 1) if you make a big mistake via a GUI, that mistake can be catastrophic to the system and 2) with X running as root that makes your system more vulnerable.

#10: Ignoring log files

There is a reason /var/log exists. It is a single location for all log files. This makes it simple to remember where you first need to look when there is a problem. Possible security issue? Check /var/log/secure. One of the very first places I look is /var/log/messages. This log file is the common log file where all generic errors and such are logged to. In this file you will get messages about networking, media changes, etc. When administering a machine you can always use a third-party application such as logwatch that can create various reports for you based on your /var/log files.

Sidestep the problems

These 10 mistakes are pretty common among new Linux administrators. Avoiding the pitfalls will take you through the Linux migration rite of passage faster, and you will come out on the other side a much better administrator.

Wednesday, February 4, 2009

11 reasons to switch to Linux


, posted: 4-FEB-2009 08:24
People like to publish top-10 lists of all sorts. And "reasons to switch to Linux" is no exception. Many of those have been published, and the latest entry is here. However, I think the author completely forgot a very important point. Also, some of the points he makes should be examined a bit more closely and critically. The comments on the original article reflect some valid and some unfounded criticism. Let me just run through those points (italics are quotes from the original 10-point list, my comments are directly below each point) and provide my own take on those:
  1. Free: Linux is an open source project. As they say, it is free as in free beer. All you need to install Linux is an Internet connection to download the iso files and a CD where you can burn the iso. Compare this with Windows which costs a lot!

    That is of course true. It doesn't cost anything to download a GNU/Linux distro, besides whatever charges you have for bandwidth. Note also that in the case of Ubuntu you don't even need to burn your own CD. They will send you one for free if you request it. On the other hand, most users are not aware of the cost of Windows, since it comes pre-loaded with their PC and is 'just there'. Consequently, for many this is not really a reason to 'switch'. The cost advantage is only relevant if you are installing a new computer from scratch. Also, the author forgot to mention a very aspect of 'free'. See point 11 below.
  2. Linux distributions are COMPLETE: All the decent Linux distributions are complete: they include almost all the applications like office applications, pdf reader, web servers, compilers, etc. You don’t have to pay anything to download and install these applications. Ubuntu comes with OpenOffice, which is a perfect substitute for MS Office.

    Well, they may not all include them right off the bat, but you can usually install easily whatever is missing through the repository of that distro. This easy and efficient means of installing software is really one of the biggest advantages for the end-user when dealing with modern GNU/Linux distributions. While most of the high-profile FOSS software, such as OpenOffice, Thunderbird and Firefox are also available for Windows, you have this huge selection of FOSS software in the repos, with a very easy management and installation interface. I think the incredible ease of use should have been emphasised more.
  3. Virus, Spyware, Adware? None of these can affect a Linux based system. In fact, you don’t even have to install an anti-virus software which bogs down system performance in Windows.

    That is an overly optimistic statement. Of course one can write software that takes advantage of vulnerabilities even under Linux, or any other OS, really. But the commenters that complain about this assertion are also missing the point: They talk about how Linux security is based on the fact that there is less of an effort made by the malware authors to exploit Linux, due to its smaller market share. The 'less effort' part might be true, but it is not the complete picture. The Linux OS architecture is more secure and desktops apps are not normally run in admin mode. Exploiting Linux by clickable, executable email attachments is possible, but more complex and requires more steps for the user to go through. If Linux would gain significant market share, we would certainly see an increase in exploit attempts. How effective they would be, however, is another story. For the time being, though, GNU/Linux systems clearly have much less of a risk of being infected by anything than Windows machines.
  4. Low system requirements: I have a tough time running Windows XP on my system and Vista needs 1-2 GB RAM to work properly. On the other hand, Ubuntu boots and runs perfectly fast on this low configuration PC.

    Ok, let's not get carried away here. A full blown Gnome or KDE desktop will chew up a pretty astonishing amount of memory. The good thing is, however, that there are smaller, compact desktops (xfce, and others) available, which result in significantly smaller system requirements. Also, it is possible to produce distros with incredibly small footprint for embedded systems or small servers, especially if you forgo the graphical desktop. So, the correct thing to say would be that 'it is possible' to create very small footprint Linux systems. The flexibility to do so is a huge plus for Linux. But we should also admit that modern, full-blown GNU/Linux desktop distros will very happily use up gigabytes of memory as well.
  5. Much Stable: Linux is much more stable when compared with Windows. This is the reason most of the web servers are run using Linux. Forget about the blue screen of death [BSOD]!

    GNU/Linux can be very stable, especially in a server environment. I have had lockups in the graphical desktop, though. That desktop is a complex piece of software, apparently, and I find it disturbing that applications can screw it up in such a way that it locks me out. That doesn't happen often, but it has happened. The legendary reputation for stability of GNU/Linux was build in server environments. In general, the core of the OS is very stable. But while the desktop is quite good, it is not perfect. Maybe a bit more comparable to the typical Windows user experience? Your mileage may vary, though. If you don't try experimental 3D features in the desktop, or use a well-supported graphic card, or have your standard set of apps that you use every day, you may experience very good stability from the Linux desktop as well.
  6. Programming tools: If you want to learn programming, Linux is the best for you. Linux distributions come with many compilers and other tools to write and execute code. For example, I use gcc to compile C files which I write using the vi editor. I also have python IDLE installed which I use to learn programming in python.

    I can only agree here. The amount of available software development tools and languages, all for no cost at all, makes a Linux system a dream for any student of programming languages and software development. Combine that with a huge number of ready-made server packages, libraries, etc., and you can see how putting together complex, working software systems is quite a joy.
  7. Faster release cycles: Linux distributions are upgraded very fast. New versions of most Linux distributions are released once in every 6 months.

    True. It's important to point out that the improvements and updates are incremental and thus aide in the stability of the overall distro. See also what I wrote about that yesterday.
  8. Helpful community: Linux has a large fan-following. There are many forums and blogs which can help you if you have any problem. Millions of people cannot be wrong!

    Well, even millions of people can be wrong as history has shown over and over again. However, the point about the helpful community is of course a valid one. While this same community also has a problem with prick-ish elitists and fanboys, there is indeed a very large community of helpful and very nice individuals out there. And with popular distros a solution to a problem is often just a quick search away. It should also be pointed out that for those who want commercial support it is available as well through support contracts with the large Linux vendors (RedHat, Novell, Oracle, Canonical, etc.).
  9. You can run Linux along with Windows: You can run Linux along with Windows on a different partition. You can boot to Windows wherever you want. It is also possible to run Linux in Windows using emulator software like VMWare or MS Virtual PC. Likewise, it is also possible to run Windows applications in Linux using emulators like Wine (This Wine is different!).

    That's all true. Even though your mileage may vary when trying to run Windows software under Wine.
  10. A new learning experience: Install Linux on your computer and you will learn many new things. Linux does have a point and click interface, but you can use the command line or “Terminal” as it is called to completely unleash the power of Linux. This way you will learn many cool and new things.

    Yes, learning a bit about the command line and looking under the hood is a rewarding experience. GNU/Linux (and BSD and most other *nix OSs) wear their hearts on their sleeves. You can see and experience what's going on. A wonderful way to learn. But one more point: 'Linux' doesn't have a point and click interface, it's the graphical desktops you have in many distros with the point and click interface. Contrary to Windows, the desktop and the underlying OS are well separated. Linux as a server doesn't have a point and click interface. Ok, maybe I'm picky, but I think that is an important strength that shouldn't be left unmentioned: No unnecessary weight if you don't want to.
  11. Linux is truly free, as in freedom: As promised, there is at least one more point. The original article completely forgot to mention this one, which I personally think is the most important one of them all: GNU/Linux is free, as in freedom! The first point alluded to free as in beer (price) only. But I think the freedom aspect is much more important. Computers run our lives, they store our data and our most intimate secrets and communications. How can we give up control over this data to proprietary, closed software that was developed by corporations with the single, overriding motive of increasing their profits? Nothing wrong with making a profit, but the goals of those corporations are often directly opposite to our goals as consumers and users. How can we not demand complete transparency in the software that runs and manages our lives? How can we allow software that puts artificial restrictions on us to have any control over our lives and data? To put it in the words of the Free Software Foundation: Free software is the answer to a world built in code.
So, this is my comment on that most recent "10 reasons to switch to Linux" post. A bit too much enthusiasm and the most important point was forgotten. But I think the points provide a good basis at least for a more differentiated discussion.

Vi Search and Replace

Vi Search and Replace

Search and Replace

To begin a search and replace in Vi or Vim, start by hitting the colon <:>. This will allow you to enter a Vi command. Then, enter a search and replace command like so:

%s/old/new/g

This will search every line for 'old' and replace all occurrences in the line with 'new'. You start by mentioning which lines to affect. In my example, I use '%s'. This translates to all lines. Then, I trail the command with 'g' (for global) to affect all occurrences in the lines defined by '%s'. Note that global does not mean the entire file!

Limiting the Replace

You can declare the search and replace for only the current line by removing the percent sign:

s/old/new/g

It is also possible to limit the affected line numbers. The next example only affects lines 40 through 42:

40,42 s/old/new/g

Eliminating the 'g' from the end will only replace the first occurrence per line defined in the search. For example, the following replaces the first instance of 'hello' on every line in the file:

Regular Expressions

The search string can be the form of a regular expression. In the next example, I replace all numbers with the word 'number'.

%s/[0-9]/number/g

Escaping Characters

You will have to escape out the slash if it is part of your search string:

%s/http:\/\//https:\/\//g

Use Any Delimiter

Alternatively, change your delimiter. It can be anything!

%s!http://!https://!g

Get Confirmation Before Changing

You can get confirmation for each replace by adding a 'c' to the end of your command:

For more information, see the online Vi documentation.

Flash Plugin on Fedora 10


The Adobe Flash Plugin, with sound support, is available on Fedora. These instructions guide you through the installation of Adobe's Flash Plugin on Fedora 10.

Install Audio Libraries

First, install the audio libraries needed for sound support by the Flash Plugin.

su -c "yum -y install pulseaudio-libs alsa-lib alsa-plugins-pulseaudio"

Using 64-bit Firefox?

Adobe Labs has been offering a 64-bit Flash plugin since Dec 12, 2008. Be sure to first uninstall any other versions of Flash you have installed on the system. Then, download and unpack the 64-bit Flash Plugin for Linux into your Mozilla Plugins folder. For updates and details, visit the Adobe Labs Download page for Flash: http://labs.adobe.com/downloads/flashplayer10.html

cd $HOME/.mozilla/plugins
wget http://download.macromedia.com/pub/labs/flashplayer10/libflashplayer-10....
tar -xzvf libflashplayer-10.0.d21.1.linux-x86_64.so.tar.gz

Don't forget to restart your browser!

32-bit Users Only

Visit http://www.adobe.com/products/flashplayer/ and click Download Now. Then select YUM for Linux and download the provided RPM (adobe-release-i386-1.0-1.noarch.rpm).

Install the downloaded RPM which installs /etc/yum.repos.d/adobe-linux-i386.repo.

su -c "rpm -ivh adobe-release-i386-1.0-1.noarch.rpm"

Check that you can access the Adobe Yum repository.

su -c "yum --disablerepo=* --enablerepo=adobe* list"

Now, install the Adobe Flash Plugin

su -c "yum install flash-plugin"

Then, add the Flash Plugin is in your $HOME/.mozilla/plugins folder.

mkdir -p $HOME/.mozilla/plugins
cd $HOME/.mozilla/plugins
ln -s /usr/lib/flash-plugin/libflashplayer.so .

Don't forget to restart your browser!

Compile PHP on Fedora

Below is an outline on how to compile a feature rich, PHP Apache module on Fedora 9. First, compile Apache on the system using these instructions. This document assumes that Apache and the APache eXtenSion Tool are installed in the PREFIX: /opt/apache2.

Once you have Apache prepared, download the PHP source from php.net. As of August, 2008 the latest version is PHP 5.2.6. So, the following examples will use the php-5.2.6.tar.gz source tarball. Use your browser to download the latest and greatest. Then, untar the source.

tar -xzvf php-5.2.6.tar.gz
cd php-5.2.6

Next, configure the source for compile. Use the configure command. You can provide --help to see the large list of options.

./configure --help

For every option you enable, make sure you have the necessary RPMs installed to build PHP. For example, if you run configure with --with-snmp, you will need the net-snmp-devel RPM installed to complete the build. To ensure that you can build PHP with a full suite of options, install the following RPMs. Trim the list to suit your needs.

yum install aspell-devel curl-devel cyrus-sasl-devel e2fsprogs-devel freetype-devel glibc-devel keyutils-libs-devel krb5-devel libgcc libidn-devel libjpeg-devel libpng-devel libselinux-devel libsepol-devel libstdc++-devel libX11-devel libXau-devel libXdmcp-devel libxml2-devel libXpm-devel mysql-devel net-snmp-devel openldap-devel openssl-devel tcp_wrappers zlib-devel

Then, configure with the following settings. Change the configure --prefix to adjust your install PREFIX. Again, trim the list to suit your needs.

./configure --prefix=/opt/php5 --with-apxs2=/opt/apache2/apxs --with-mysql=/usr/bin/mysql_config --with-mysqli=/usr/bin/mysql_config --with-png-dir=/usr --with-gd --enable-gd-native-ttf --with-ttf --enable-safe-mode --enable-magic-quotes --with-pspell --with-gettext --with-jpeg-dir=/usr --with-zlib --with-curl --enable-soap --with-ldap=/usr --enable-sockets --with-openssl --with-snmp --enable-mbstring --with-freetype-dir=/usr --with-xpm-dir=/usr --with-libdir=lib64

Please note that if you are on a 32bit system, remove:

--with-libdir=lib64

Finally, build PHP and test it.

make
make test

If you are comfortable with the results (a few errors are OK in make test), then install PHP.

sudo make install

The install will place the PHP module in /opt/apache2/modules and prepare /opt/apache2/conf/httpd.conf with these settings:

LoadModule php5_module modules/libphp5.so

Then, place a php.ini in /opt/php5/lib (or your PREFIX/lib).

cp -a php.init-recommended /opt/php5/lib/php.ini

Finally, prepare your Apache Virtual Host to support index.php with the following code:

AddType application/x-httpd-php .php .inc .class
AddType application/x-httpd-php-source .phps
DirectoryIndex index.html index.php

The SysAdmin Ten Commandments


I. Thou shalt respect thy user

It is paramount that you respect the user and their data. Don't steal their MP3s, don't look at their porn. When working with email, look without reading. Respect them and they will respect you.

II. Thou shalt empower the user

The user is the customer. The system is not yours, it is theirs. Provide users the tools they need to be successful and they will be happy. Give them space to experiment, learn and create. Do not hold users back.

III. Thou shalt keep it simple

Keep It Simple, Stupid. The KISS principle will keep you from building barrels to keep a bottle's worth of wine. Do not mistake over-engineering for quality. Quality work is concise and scalable.

IV. Thou shalt expect catastrophe

Expect the worst surprises. Make your resources redundant, backup your data, test your backups, and then backup the backups. The shit will hit the fan someday. Be prepared.

V. Thou shalt plan

Great work follows great plans. Stay on target by first identifying it. Plan your work carefully and surprises will be easier to handle.

VI. Thou shalt stay informed

Gather all the news, information, logs and statistics you can. Without the raw data to analyze, you cannot be secure, you cannot debug problems and you cannot forecast. Without new information, you cannot learn.

VII. Thou shalt share

No one is alone in this world. Pass your knowledge on to others. Give to others, contribute to the community and you will reap many rewards. It is not wise to horde knowledge. Don't be an asshole.

VIII. Thou shalt automate

Do more, faster by automating tasks. You are the puppet master, do not waste your time with menial work. Work smarter, not harder.

IX. Thou shalt document

Always document your work, your code and your plans. Then document their execution and maintenance. Document for others and document for yourself. Documentation should be an extension of your mind and a resource for others.

X. Thou shalt respect thy organization

Without organization, there is no system, there is no user and there is no job. Understand the organization and it's business. Respect it and help it thrive.

Multimedia support in fedora

yum -y install libdvdcss libdvdread libdvdplay libdvdnav lsdvd libdvbpsi totem-xine xine-lib-extras-nonfree xine-lib-ex
tras gstreamer gstreamer-plugins-good gstreamer-plugins-bad gstreamer-plugins-ugly compat-libstdc++-33

Fedora 10 Codecs with MPlayer

If you just need MP3 support, you might want to start here. Otherwise, I recommend using RPMFusion.org's MPLayer package with the codecs found at http://www.mplayerhq.hu.

First, install RPM Fusion's free and nonfree YUM repositories. For detailed information about installing RPM Fusion, see: http://rpmfusion.org/Configuration

su -c "rpm -Uvh http://download1.rpmfusion.org/free/fedora/rpmfusion-free-release-stable.noarch.rpm"

su -c "rpm -Uvh http://download1.rpmfusion.org/nonfree/fedora/rpmfusion-nonfree-release-stable.noarch.rpm"

Next, install MPlayer from RPMFusion.org.

su -c "yum install mplayer gnome-mplayer gnome-mplayer-common mencoder"

Now, visit the MPlayer Codecs Directory and download the latest 'All' tarball.

wget http://www.mplayerhq.hu/MPlayer/releases/codecs/all-20071007.tar.bz2

Next, prepare the codecs folder. MPlayer from RPMFusion.org will use /usr/lib/codecs.

su -c "mkdir -p /usr/lib/codecs"

Other media players like Xine and avifile might use /usr/lib/win32, so create a symlink.

su -c "ln -s /usr/lib/codecs /usr/lib/win32"
ls -l /usr/lib/win32
lrwxrwxrwx 1 root root 15 2008-05-24 08:02 /usr/lib/win32 -> /usr/lib/codecs

Finally, extract the contents of the tarball and copy all files to /usr/lib/codecs.

tar -xjvf all-20071007.tar.bz2
su -c "cp -a all-20071007/* /usr/lib/codecs/"

See the MPlayer(1) man page for /usr/bin/mplayer usage.

man 1 mplayer

Compile Apache on Fedora


Below is a walk-through for compiling Apache 2.2 on Fedora 9. First, download and unpack the source tarball from Apache.org. As of August 2008, the latest version of Apache is 2.2.9 (httpd-2.2.9.tar.gz)

tar -xzvf httpd-2.2.9.tar.gz
cd httpd-2.2.9

Next, configure the source for build. You can provide configure with --help to see the large list of options. The example below enables mod_rewrite, mod_cache, mod_mem_cache and mod_ssl as shared modules in /opt/apache2/modules. Change --prefix to adjust your install PREFIX and adjust the configure options to suit your needs.

./configure --prefix=/opt/apache2 --enable-rewrite=shared --enable-cache=shared --enable-mem-cache=shared --enable-module=so

Now, build and install Apache.

make
sudo make install

Your Apache configuration will be in /opt/apache2/conf and you can control Apache with /opt/apache2/bin/apachectl. Refer to the Apache documentation for more details.

Tuesday, February 3, 2009

How to Connect to a VNC Server Using SSH

Need to connect to a VNC server behind a firewall that only allows SSH traffic? With SSH access to the VNC server, you can tunnel the VNC traffic through an SSH connection. This will encrypt your VNC traffic through an SSH tunnel.

To begin, SSH to the VNC server and forward the local client's 5904 TCP port to the VNC server's port 5901.

client$ ssh user@vncserver.mydomain.com -L 5904:*:5901

Next, In a new window, direct vncviewer to your localhost 5904 port and the traffic will be forwarded to your VNC server's port 5901.

client$ vncviewer localhost:5904

If you get any errors, be sure that your client's firewall is not blocking localhost's port 5904.

client$ su -c "iptables -L"

10 Tips for Writing Efficient Bash Scripts

Bash is the default command line interface for many Linux distributions and a powerful scripting language. Here are some suggestions that will keep your Bash scripts efficient and lean. Feel free to comment with your own suggestions.

  1. Avoid Full Paths to Bash Builtins

    Bash has many builtins that can be used instead of calling external commands. You should leverage the builtin commands whenever possible since it avoids calling a subcommand from the system.

    Since Bash has builtins for some commands found in /bin and /usr/bin (such as echo), avoid using the full path for these commands and the builtin will be used.

    # avoid this
    /bin/echo "hello"

    Use the Bash builtin instead:

    echo "hello"

    Other bash builtins include: test, read, declare, eval, let pushd and popd. See the Bash man page for a full listing of builtins.

  2. Avoid External Commands for Integer Math

    Bash also provides builtins that can be used for integer arithmetic. Only use /usr/bin/bc if you need to do floating point arithmetic. Integer calculations can be made with these Bash builtins:

    four=$(( 2 + 2 ))
    four=$[ 2 + 2 ]
    let four="2 + 2"

  3. Avoid using Cat

    Tools like Grep, Awk and Sed will take files as arguments. There is rarely a need to use /bin/cat. For instance, the following is unnecessary:

    # avoid this
    cat /etc/hosts | grep localhost

    Instead, use Grep's native ability to read files:

    grep localhost /etc/hosts

  4. Avoid Piping Grep to Awk

    If using Awk, you can often eliminate the need for grep. Try not to pipe Grep to Awk:

    # avoid this
    grep error /var/log/messages | awk '{ print $4 }'

    Use Awk's native ability to parse text and save yourself a command.

    awk '/error/ { print $4 }' /var/log/messages

  5. Avoid Piping Sed to Sed

    Sed can take more than one command in a single execution. Avoid piping sed to sed.

    # avoid this
    sed 's/hello/goodbye/g' filename | sed 's/monday/friday/g'

    Instead, use sed -e or delimit the sed expressions with a semicolon (;)

    sed -e 's/hello/goodbye/g' -e 's/monday/friday/g' filename
    sed -e 's/hello/goodbye/g; s/monday/friday/g' filename

  6. Use Double Brackets for Compound and Regex Tests

    The [ or test builtins can be used to test expressions, but the [[ builtin operator additionally provides compound commands and regular expression matching.

    if [[ expression1 || expression2 ]]; then do_something; fi
    if [[ string =~ regex ]]; then do_something; fi

  7. Use Functions for Repetitive Tasks

    Break your script up into pieces and use functions to conduct repetitive tasks. Functions can be declared like so:

    function_name() {
    do_something
    return $?
    }

    Make your functions usable by more than one shell script by sourcing a functions file from the various scripts. You can source another file in Bash using the . builtin.

    #!/bin/bash
    . /path/to/shared_functions

    See the Bash man page, or my article on Bash functions for more information.

  8. Use Arrays Instead of Multiple Variables

    Bash arrays are very powerful. Avoid using unnecessary variables:

    # avoid this
    color1='Blue'
    color2='Red'
    echo $color1
    echo $color2

    Instead, use Bash arrays.

    colors=('Blue' 'Red')
    echo ${colors[0]}
    echo ${colors[1]}

    Check out my article on Bash arrays for more details.

  9. Use /bin/mktemp to Create Temp Files

    Need a temporary file? Use /bin/mktemp to create temporary files or folders.

    tempfile=$(/bin/mktemp)
    tempdir=$(/bin/mktemp -d)

  10. Use /bin/egrep or /bin/sed for Regex Pattern Matching

    Think you need Perl? Check out Sed or Egrep (grep -e) for regex pattern matching.

    # grep for localhost or 127.0.0.1 in /etc/hosts
    egrep 'localhost|127\.0\.0\.1' /etc/hosts

    # print pattern localhost.* in /etc/hosts
    sed -n 's/localhost.*/&/p' /etc/hosts