Saturday, June 9, 2012

Disks, partitions, and filesystems

Disks, partitions, and filesystems

Physical Disks
Hard disks in Linux are classified by type (IDE or SCSI). The device name of the first IDE disk is /dev/hda. The second IDE disk is /dev/hbd. The third IDE disk is /dev/hdc, and so on. SCSI disks follow a similar naming convention (i.e. /dev/sda, /dev/sdb...).
If your system uses any kind of RAID configuration you should configure that first. Most RAID controllers have a built in management utility that can be accessed shortly after the computer runs the POST. Keep in mind that regardless of how many disks are actually involved, a RAID array or mirror will appear as a single disk when you want to partition it.
Partition Types
The Master Boot Record (MBR) of a physical disk contains the partition table and has room for four records. Each record describes one partition on a disk. The most basic type of partition is called a primary partition. A single disk can contain up to four primary partitions. If you need more than four partitions, you can make one of your primary partitions an extended partition. An extended partition appears just like a regular primary partition in the MBR but in the first sector of its allocated disk space there is an additional partition table called the Extended MBR (EMBR). This allows you to create additional partitions within the extended partition. Partitions created within an extended partition are called logical partitions. The only partition types that can hold data are primary and logical. Extended partitions simply allow us to get around the four-partition limit of the MBR.
In Linux, partitions are identified by the name of the disk and a number. For example, the device /dev/hda1 represents the first primary partition on the first IDE disk. The third primary partition on the second SCSI disk would be identified as /dev/sdb3. For logical partitions, the numbering starts at five (i.e. /dev/hda5).
Logical Volume Management (LVM)
The concept of Logical Volume Management (LVM) is not particularly new, it has been utilized mainly in enterprise level servers, an area in which Linux only recently has begun to gain acceptance. The first step for setting up LVM is creating a Volume Group. This is a virtual storage container that consists of anywhere from a portion of a single physical disk to multiple physical disks. The volume group is given a descriptive name, such as “datavg”, and can be accessed by that name (i.e. /dev/datavg) rather than using the cumbersome naming convention of traditional IDE or SCSI devices. One of the main benefits of using a Volume Group is that physical disks can be added or removed as needed without reformatting anything.
Partitions are created within a volume group and are called Logical Volumes. The second main benefit of using LVM is that logical volumes can be resized as needed without having to backup and restore data. Logical Volumes introduce a completely different way of managing disks and partitions than have traditionally been used but in most Linux environments a compromise between the two models must be met. The /boot and root partitions are typically left as standard Primary partitions because most bootloaders are unable to recognize Logical Volumes. A Volume Group is often used to manage the remaining disk space.
Partitioning Tools
The most commonly used tool for creating and deleting partitions is fdisk. Fdisk is a command-line, menu-driven utility. You specify which disk to manipulate when invoking fdisk (ex. fdisk /dev/sda) and are presented with an interactive menu for editing the partition table on the disk. Some of the common commands used in this menu are:
d   delete a partition
l     list known partition types
m   print the help menu
n   add a new partition
p   print the partition table
q   quit without saving changes
v   verify the partition table
w   write table to disk and exit

Changes you make in fdisk do not take effect until you press ‘w’ to write the changes. If you make a mistake, simply type ‘q’ to quit and start over.
When you create a partition, you will be asked to specify the type of partition. Fdisk uses ID numbers to represent the type. Typing ‘l’ at the fdisk prompt will display a complete list of the different types of partitions, of which the most common are listed below:
82   Linux swap partition
83   Linux Primary partition (or a Logical partition if created within an Extended partition)
85   Linux Extended partition
8e   Linux LVM


Partition schemes in Linux should depend on the purpose of the system. The following partitions will exist on most systems and should be used as a basic template:
/
The root filesystem. Contains files needed for booting the system. The kernel image is stored here as well as critical system commands and configuration files. The /dev, /bin/, /lib, /mnt, and /etc directories are stored in the root filesystem
swap
While swap space can be contained in a file, like the Windows pagefile, it generally gets a separate partition for the sake of stability.
/var , /tmp, /usr
Each of these directories typically will contain dynamic data and have the greatest potential to completely fill up their allocated space. Therefore, it is generally a good idea to have each of these directories on its own partition. /usr generally contains additional software installed after the main operating system installation. /var is used for variable data files. It is commonly used to store log files and spooled print jobs. /tmp is of course for temporary files.
/home
The /home directory is used to contain each user’s personal files. If disk quotas are not being used, the home directory should also reside on a separate partition to prevent user data from filling up the system.
There are several other tools available for creating or modifying partitions. Some examples are sfdisk, parted, and Disk Druid. You do not need to know them in depth but you should be aware that they exist.
Filesystems
A filesystem is an organizational structure that determines how files and directories are stored and accessed on the physical disk. The main filesystems used by Windows are FAT and NTFS. The main filesystems used in Linux are ext2, ext3 and ReiserFS although others are available.
Ext2 is probably still the most commonly used although it is being phased out. Ext2 supports partitions up to 4 terabytes, files up to 2 gigabytes, 255 character filenames, multiple timestamps and standard UNIX permissions and ownership. Another nice feature is that ext2 reserves 5% of the available disk space for use by the root user. This allows the superuser access the filesystem to clean up or recover in the event the filesystem completely fills up.
Ext3 is essentially the same as ext2 with the addition of journaling. The ext3 filesystem keeps a log of all writes to disk and only updates the log after a write has been completed. What this means is that if the system crashes or is shut down improperly, ext3 requires far less time to check the disk for corruption.
ReiserFS is also a journaling filesystem and boasts better performance than ext2 or ext3. ReiserFS organizes files using a balanced tree algorithm resulting in faster access times. It also eliminates the concept of fixed block sizes meaning that disk space is used more efficiently.

Filesystem Tools
The mkfs command is used to create a filesystem on a partition. The general syntax is:
mkfs –t type device
For example: mkfs –t ext3 /dev/hda1
There are actually several commands for creating filesystems that are all linked to each other and have similar sets of options:
Filesystem Command
ext2 mkfs –t ext2
mke2fs
mkfs.ext2
ext3 mkfs –t ext3
mke2fs –j
mkfs.ext3
ReiserFS mkfs –t reiserfs
mkfs.reiserfs
swap mkswap
 
Remember that an ext3 filesystem is simply an ext2 filesystem with journaling, hence the mke2fs –j command.
Other tools that are used for managing filesystems are:
fsck – Used to check a filesystem for errors or inconsistencies. Fsck will run automatically on bootup when a system has not been shut down cleanly. It can also be run manually from the command line. Fsck should never be run on a mounted filesystem.
debugfs – Used for advanced debugging of ext2/3 filesystems. Most commonly used for recovering deleted files.
Accessing Filesystems
Once you have created a filesystem you need to mount it before you can write files to it. The mount command is used to mount a filesystem and has the following syntax:
mount device mount_point
For example: mount /dev/sda2 /home
The mount point must be an existing directory on the system. The filesystem type can be manually specified using the –t switch but is detected automatically in most cases. In order to mount a filesystem automatically when the system boots up, you need to add an entry in the /etc/fstab file.
The following shows an example of the contents of the /etc/fstab file:
/dev/hda1 / ext3 defaults 1 1
/dev/hda2 /boot ext3 defaults 1 2
/dev/hda3 /home ext3 defaults 1 2
none /proc proc defaults 0 0
/dev/hda5 /tmp ext3 defaults 1 2
/dev/hda6 /var ext3 defaults 1 2
The first column states the name of the device containing the filesystem. The second column defines the mount point for the filesystem. The third column shows the filesystem type. The fourth column is used to define filesystem options. This is where you would flag a filesystem as read-only or enable disk quotas. The fifth column is used to flag whether the filesystem should be dumped in the event of a system crash. The last field determines the order in which the filesystems should be checked by fsck. A value of 1 is the highest priority. A value of 0 indicates that the filesystem will not be checked.
The umount command is similarly used to unmount a mounted filesystem (ex. umount /home). A list of filesystems that are currently mounted is maintained in the /etc/mtab file. This file is updated by the kernel and should never be directly edited.
 
Current related exam topics for the Linux+ exam:

DOMAIN 2.0 Management
2.6 Modify file and directory permissions and ownership (e.g., chmod, chown, sticky bit, octal permissions, chgrp) using CLI commands
2.7 Identify and modify default permissions for files and directories (for example: umask) using CLI commands
2.20 Create, modify, and delete user and group accounts (e.g., useradd, groupadd, /etc/passwd, chgrp, quota, chown, chmod, grpmod) using CLI utilities
DOMAIN 4.0 Security
4.2 Delete accounts while maintaining data stored in that user's home directory
4.6 Set process and special permissions (e.g., SUID, GUID)
4.11 Given a set of security requirements, set password policies to match (complexity / aging / shadowed passwords) (for example: identify systems not shadow passwords)

Sunday, June 3, 2012

Linux Use as a Router

Steps To Make Linux Machine as Router : -
Assumptions: eth0 is internet interface (connected to router for example) and eth1 connected to your internal lan (connected to your HUB/Switch for example).

My Linux   eth0  --> Internet
box        eth1  --> Lan

Step1. Turn on ip forwarding in kernel
open the file  /etc/sysctl.conf  and add/modify following line:
net.ipv4.ip_forward = 1

Step2. Save this configuration using below command
# sysctl -p

Step3. Setup IP forwarding and Masquerading (to act as router), you need to use NAT option of iptables as follows (add following rules to your iptables shell script) :

#  iptables --table nat --append POSTROUTING --out-interface eth0 -j MASQUERADE
#  iptables    --append   FORWARD   –in-interface  eth1  -j   ACCEPT

Step4. We  are done with configuration part , Test it with ping or dig:

# ping   ISPdomain.com
# dig    yahoo.com

How To Set the static Route in Linux : -
 
Scenario :-  We have two lan cards and assigned below mentioned ips
eth0 LAN network 172.0.0.0/8 - gateway IP – 172.8.2.65
eth1 ISP assigned network 202.54.22.128/28 - gateway IP – 202.54.22.129

So we can only ping /access to public server but not the another servers inside LAN , for the solution of this problem we will set the route with route command and static-route file.
Set route using route command
Type the following command:
# route add -net 172.0.0.0 netmask 255.0.0.0 gw 172.8.2.65 eth0
# route -n

The problem with the above 'route' command is that, when linux machine  reboots it will forget static routes. So store them in configuration file: 
# echo '172.0.0.0/8 via 172.8.2.65' >> /etc/sysconfig/network-scripts/route-eth0
Restart the network service

# service network restart

Verify new changes:

# route -n

# ping 172.8.2.65

# ping 172.8.2.10

# ping google.com

# traceroute google.com

# traceroute 172.8.2.10
Understanding Routing Table

What is Routing Table ?

Almost all computers and network devices connected to Internet use routing tables to compute the next hop for a packet. It is electronic table that is stored in a router or a networked computer. The routing table stores the routes (and in some cases, metrics associated with those routes) to particular network destinations. This information contains the topology of the network immediately around it. The construction of routing table is the primary goal of routing protocols and static routes.
Each Linux / UNIX / Windows or any computer that uses TCP/IP need to make routing decision. Routing table is used to control these decisions. To display routing table type the following command at UNIX / Linux shell prompt:

# netstat -r -n
OR
#  route -n

Sample output:
Kernel IP routing table

Destination Gateway Genmask Flags Metric Ref Use Iface
192.168.2.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
192.168.1.0 0.0.0.0 255.255.255.0 U 0 0 0 ra0
169.254.0.0 0.0.0.0 255.255.255.0 U 1000 0 0 eth0
0.0.0.0 0.0.0.0 0.0.0.0 UG 100 0 0 ra0

Flag G indicates path to route packets via a gateway. If you would like to visit yahoo.com from your computer you need to go via 192.168.1.1 gateway. This usually means that you have to set up a static route to the gateway beforehand. If you specify the address of one of your local interfaces, it will be used to decide about the interface to which the packets should be routed to. metric field used by routing daemons. This is required on large LAN and wan setups. The output of the kernel routing table is organized in the following columns:


Monday, April 23, 2012

basic commands

RHEL Linux basic commands cat bzip gzip pwd cd mkdir

In our last assignment you perform some basic task related to system administration from normal user. In this assignment we will extend this further. To complete this assignment login form our normal user Vinita.
basic rhce commands

How to redirect the matter of files in a new file

Create two file and write some text in them.

$cat > one
This is first file
$cat > second
This is second file
Now we will combine these two files in a single file. In standard linux its call redirection of output.

$cat one second > new
$cat new
This is first file
This is second files
Linux system administration command
Then what exactly this command did? As you know cat command is used to display the matter of file so it will first display the matter of first file and then it will display the matter of second file. But as you put a > sign at the end of command so despite of showing this output on screen command will redirect this matter to a file.

How to execute multiple commands in a single row


$[command] ; [command] ; [command] ;[command]……..
To execute multiple commands from single row use a ; between them form example

$cat new ; mkdir xyz ; mkdir rat ; ls
This is first file
This is second files
new xyz rat
Linux system administration command
this command will first execute the first command which is cat new so it will display the matter of new file, further is mkdir xyz so it will create a xyz directory , further is mkdir rat so will create a rat directory and in the end we use ls command so it will list the contain of current directory.

How to create multiple sub directory form single command

To create multiple sub directory from a single command use –p switch with mkdir command for example

$mkdir –p a/b/c/d/f/g/h/i/j
In this example we created 9 subdirectories form a single mkdir command. Now verify it by listing.

$ls
new  xyz rat a
now change the directory to verify the depth of directories.

$cd a/b/c/d/f/g/h/i/j
$pwd
/home/vinita/a/b/c/d/f/g/h/i/j
Come back to home directory. Simple cd command without passing any argument will do this.

$cd
Linux system administration command

How to move multiple file in directory with a single commands?

Give all files name one by one with a single space between them and in the end give the destination directory name for example
$mv new first second xyz
Linux system administration command
This command will move three files new, one, second to the xyz directory.

$cd xyz
$ls
New one second
$cd ..

how to take back-up and restore files and directories.

tar command is used to take the back up with –cvf switches and the same tar command is used to restore the matter with –xvf switches. For example

$tar –cvf backup.tar xyz
$ls
$rm –rf xyz
Linux system administration command
In linux you cannot restore the data once deleted unless you have backup. Now restore these files and directory.

$tar –xvf backup.tar
$ls
$cd xyz
$ls
new first second
$cd ..

How to compress files to save disk space?

Create a large file and check how much disk space is consumed by this file

$man ls > manoj
$du –h manoj
12k manoj
File manoj is using 12k space on hard disk. For exam prospective you should familiar with two compress utilities.

$bzip2 [file name]                      {command syntax}
$bzip2 manoj
$ls
$du -h  manoj.bz2
4k manoj.bz2
Linux system administration command
To decompress file
$bzip2 –d manoj.bz2 $ls manoj as you can show file has been decompressed. Now use other utility to compress the file.

$gzip manoj
$ls
manoj.gz
$du –h manoj.gz
4k manoj.gz
$gzip –d manoj.gz
$ls
manoj
Linux system administration command

Basic RHCE commands using help for commands

In this article I will show some basic system administration related task which a normal user can perform. To complete this assignment login from normal user which we created in our first assignment.
basic rhce commands

How to count line word and character form a file


$wc [file name]
This command is used to count line words and character of file. Out will first show the line number word and in the end characters.

$wc test
2  4 23 test
basic rhce commands
In this example there are 2 lines 4 words and 23 character in test file.

how to display top and bottom line form files


$head –n [number] [file name]
head command is used to display specific number of line from top for given file.

$head –n 4 test
For example this command will show the 4 top most line of file test.
basic rhce commands

$tail –n  [number] [file name]
tail command will display the specific number of line form bottom for given file.

$tail –n 3 test
This command will display the 3 line from bottom of file test

how to find wrong spelling and correct them

$spell [file name]
spell command will display the wrong spelling of files.

$spell test 
This command will display the wrong spelling of test file. If there is no spelling mistake no out will show.
basic rhce commands

$aspell check [file]
This command is used to correct the spelling related mistake in any given files.

$aspell check test 
This command will show the all wrong spelling from test file and there possible corrections. To use correction just press the number shown in front of words.

how display logged in user information and terminal number


$who am i 
This command is use to display the username of currently logged.

$who  
This command will display all the user currently logged in all terminals.
basic rhce commands

$tty 
This command is used to display the terminal number of currently logged in terminals.

how to display date time and calendar


$cal   
This command will display the calendar of current month. You can see the calendar of any specific year also.

$cal 2010 |more 
basic rhce commands
This will display the calendar of year 2010. As output will be more than a page so use more switch with commands.

$date  
This will the current system times and date.

how to use calculator


$bc    
basic rhce commands
This command will launch the calculator at command prompt. Write down your calculations and press enter to get the answer. Use CTRL+D key combination to exit from calculator.

how to get help about commands


$info [command]
info command is used to get help about any commands.

$info cat 
This will display the help about cat commands. Generally output of info commands is more a then a page. You can quit form this out by just pressing q.

$command - - help
This help options is really very useful when do not want to be read full manual page for help. This will provide very basic help like which switch will work with this command.

$cat - - help
This will show the available switch cat command and a very brief descriptions about these switches.

$man [command]
If want to read the detail about any command use this command. This will give you the complete detail about commands.

$man cat
This command will give the complete details about the cat commands including switches and their usages. Use q to quit from the output of this commands.

$less [file]
When you have a file more than one pages use less command to read the output of file despite of using cat command with more switch. As with more switch you cannot scroll the text in both directions.

$cat [file] |more 
If you have a file more than one page than use |more switch with cat to read the output. Without this switch matter of file will scroll too fast that you will see only texts of last pages

how to use

how to use

Vi editor guide command reference

Critical to a Linux administrator is knowledge of one or more text editors to manage the many configuration files on a Linux system. The Linux file system hierarchy organizes hardware, drivers, directories, and of course, files. You need to master a number of basic commands to manage Linux. Printer configuration can be a complex topic. Shell scripts enable you to automate many everyday processes. Security is now a huge issue that Linux can handle better than other operating systems; locally, and on larger networks such as the Internet.

The VIsual Editor

Linux and Unix are managed through a series of text files. Linux administrators do not normally use graphical editors to manage these configuration files. Editors such as WordPerfect, starOffice, and yes, even Microsoft Word normally save files in a binary format that Linux can't read. Popular text editors for Linux configuration files include emacs, pico, joe, and vi.
While emacs may be the most popular text editor in the world of Linux, every administrator needs at least a basic knowledge of vi. While emacs may be more popular and flexible, vi may help you save a broken system. If you ever have to restore a critical configuration file using an emergency boot floppy, vi is probably the only editor that you’ll have available. You need to know how to restore your system from a rescue floppy, which does not have enough room to carry any editor other than vi.So should know how to use vi editor.
$ vi /tmp/test
If this is a new file, you should see something similar to the following:
~
~
~
~
~
“/tmp/test” [New File]
The box at the top represents where your cursor is. The bottom line keeps you informed about what is going on with your editing (here you just opened a new file). In between, there are tildes (~) as filler because there is no text in the file yet. Now here's the intimidating part: There are no hints, menus, or icons to tell you what to do. On top of that, you can't just start typing. If you do, the computer is likely to beep at you. And some people complain that Linux isn't friendly.
The first things you need to know are the different operating modes: command and input. The vi editor always starts in command mode. Before you can add or change text in the file, you have to type a command (one or two letters and an optional number) to tell vi what you want to do. Case is important, so use uppercase and lowercase exactly as shown in the examples! To get into input mode, type an input command. To start out, type either of the following:
  • a-The add command. After it, you can input text that starts to the right of the cursor.
  • i-The insert command. After it, you can input text that starts to the left of the cursor.
Type a few words and then press Enter. Repeat that a few times until you have a few lines of text. When you’re finished typing, press Esc to return to command mode. Now that you have a file with some text in it, try moving around in your text with the following keys or letters: Remember the Esc key! It always places you back into command mode.
Arrow keys-Move the cursor up, down, left, or right in the file one character at a time. To move left and right you can also use Backspace and the space bar, respectively. If you prefer to keep your fingers on the keyboard, move the cursor with h (left), l (right), j (down), or k (up).
  • w-Moves the cursor to the beginning of the next word.
  • b-Moves the cursor to the beginning of the previous word.
  • 0 (zero)-Moves the cursor to the beginning of the current line.
  • $-Moves the cursor to the end of the current line.
  • H-Moves the cursor to the upper-left corner of the screen (first line on the screen).
  • M-Moves the cursor to the first character of the middle line on the screen.
  • L-Moves the cursor to the lower-left corner of the screen (last line on the screen).
The only other editing you need to know is how to delete text. Here are few vi commands for deleting text:
  • x-Deletes the character under the cursor.
  • X-Deletes the character directly before the cursor.
  • dw-Deletes from the current character to the end of the current word.
  • d$-Deletes from the current character to the end of the current line.
  • d0-Deletes from the previous character to the beginning of the current line.
To wrap things up, use the following keystrokes for saving and quitting the file:
  • ZZ-Save the current changes to the file and exit from vi.
  • :w-Save the current file but continue editing.
  • :wq-Same as ZZ.
  • :q-Quit the current file. This works only if you don’t have any unsaved changes.
  • :q!-Quit the current file and don’t save the changes you just made to the file.
If you've really trashed the file by mistake, the :q! command is the best way to exit and abandon your changes.
The file reverts to the most recently changed version. So, if you just did a :w, you are stuck with the changes up to that point. If you just want to undo a few bad edits, press u to back out of changes.
You have learned a few vi editing commands. I describe more commands in the following sections. First, however,
here are a few tips to smooth out your first trials with vi:
  • Esc-Remember that Esc gets you back to command mode. (I’ve watched people press every key on the keyboard trying to get out of a file.) Esc followed by ZZ gets you out of command mode, saves the file, and exits.
  • u-Press u to undo the previous change you made. Continue to press u to undo the change before that, and the one before that.
  • Ctrl+R-If you decide you didn’t want to undo the previous command, use Ctrl+R for Redo. Essentially, this command undoes your undo.
  • Caps Lock-Beware of hitting Caps Lock by mistake. Everything you type in vi has a different meaning when the letters are capitalized. You don’t get a warning that you are typing capitals-things just start acting weird.
  • :! command-You can run a command while you are in vi using :! followed by a command name. For example,
  • type :!date to see the current date and time,
  • type :!pwd to see what your current directory is,
  • type :!jobs to see if you have any jobs running in the background.
  • INSERT-When you are in insert mode, the word INSERT appears at the bottom of the screen.
  • Ctrl+G-If you forget what you are editing, pressing these keys displays the name of the file that you are editing and the current line that you are on at the bottom of the screen. It also displays the total number of lines in the file, the percentage of how far you are through the file, and the column number the cursor is on.

Moving Around the File

Besides the few movement commands described earlier, there are other ways of moving around a vi file. To try these out, open a large file that you can’t do much damage to. (Try copying /var/log/ messages to /tmp and opening it in vi.) Here are some movement commands you can use:
  • Ctrl+F-Page ahead, one page at a time.
  • Ctrl+B-Page back, one page at a time.
  • Ctrl+D-Page ahead one-half page at a time.
  • Ctrl+U-Page back one-half page at a time.
  • G-Goto the last line of the file.
  • 1G-Go to the first line of the file. (Use any number to go to that line in the file.)

Searching for Text

To search for the next occurrence of text in the file, use either the slash (/) or the question mark (?) character. Follow the slash or question mark with a pattern (string of text) to search forward or backward, respectively, for that pattern. Within the search, you can also use metacharacters. Here are some examples:
  • /hello-Searches forward for the word hello.
  • ?goodbye-Searches backward for the word goodbye.
  • /The.*foot-Searches forward for a line that has the word The in it and also, after that at some point, the word foot.
  • ?[pP]rint-Searches backward for either print or Print. Remember that case matters in Linux, so make use of brackets to search for words that could have different capitalization.
The vi editor was originally based on the ex editor, which didn’t let you work in full-screen mode. However, it did enable you to run commands that let you find and change text on one or more lines at a time. When you type a colon and the cursor goes to the bottom of the screen, you are essentially in ex mode. Here is an example of some of those ex commands for searching for and changing text. (I chose the words Local and Remote to search for, but you can use any appropriate words.)
  • :g/Local-Searches for the word Local and prints every occurrence of that line from the file. (If there is more than a screenful, the output is piped to the more command.)
  • :s/Local/Remote-Substitutes Remote for the word Local on the current line.
  • :g/Local/s//Remote-Substitutes the first occurrence of the word Local on every line of the file with the word Remote.
  • :g/Local/s//Remote/g-Substitutes every occurrence of the word Local with the word Remote in the entire file.
  • :g/Local/s//Remote/gp-Substitutes every occurrence of the word Local with the word Remote in the entire file, and then prints each line so that you can see the changes (piping it through more if output fills more than one page).

Using Numbers with Commands

You can precede most vi commands with numbers to have the command repeated that number of times. This is a handy way to deal with several lines, words, or characters at a time. Here are some examples:
  • 3dw-Deletes the next three words.
  • 5cl-Changes the next five letters (that is, removes the letters and enters input mode).
  • 12j-Moves down 12 lines.
Putting a number in front of most commands just repeats those commands. At this point, you should be fairly proficient at using the vi command. Once you get used to using vi, you will probably find other text editors less efficient to use.

vi editor

RHCE vi editor switches options descriptions

In our last assignment your learnt about cat command. cat is a very basic command you cannot depend on cat command in exam to create files as cat is a very essential command. In cat you can neither see the matter of file nor modify the material. In this assignment we are going to use world's most powerful editor vi.
Before we go further just learn how to create a hidden file in linux and see it.

$cat > [.name of file]
 
A single dot in front of the file will make it hidden. For example to make a file named secret to hidden use this command

$cat > .secret
This is a secret file
 
Now normal ls command will not list this file. Do a ls form current directory

$ls
 
As you can see in output .secret file is not shown here. But can see hidden file with –a switch.

$ls –a
.secret
 
Now rename and make it unhidden. Use mv command to rename the file

$mv .secret  test
$ls
test
 
vi editior
If we want to change the matter of file cat will not do it for us. So we will use vi editor to change matter of file.

$vi test
 
This will open a window with bilking cursor. vi editor work in three different mode.

Esc         Command mode [press Esc key before giving any command]
Insert      Insert  mode [ to start editing use press Insert key ]
Exit        Exit mode [ Exit mode can be access via press Ecs key and :]
Beside it there are various command which can be used to control the behavior of vi editor, some of them most command are there to remember

Esc +:+w+q                    save and exit form file
Esc+:+q+!                     exit without saving
Esc+:+set nu                  to show hidden line
Esc+:+/test                   to find test word in forward directions
Esc+:+21                      to move cursor in line number 21
Esc+:+2+yy                    to copy 2 line form cursor
Esc+:+p                       to paste the copied line below the crusor
Esc+:+dd                      to remove the entire line
Esc+:+4+dd                    to remove 4 line below of cursor
Esc+:+x                       to remove single character
Esc+:+e                       to go to end of the word
Esc+:+h                       to go one character back
 
We have written a complete article about Vi editor. You can read it for more information about vi editor.

commands examples

RHCE Linux system administrations commands  examples

halt
This command shuts down the operating system, but can only be run by the root user.
#halt
reboot
This command shuts down and restarts the operating system. It also can only be run by root.
#reboot           [will perform simple reboot]
#reboot -f        [will perform fast reboot ]
init 0
This command also shuts down the operating system, and can only be run by your root user.
#init 0
init 6 This command also shuts down and restarts the operating system. It also can only be run by root
#init 6
man
This command opens the manual page for the command or utility specified. The man utility is a very useful tool. If you are unsure how to use any command, use man to access its manual page. For example, you could enter man ls at the shell prompt to learn how to use the ls utility.
#man ls
info
The info utility also displays a help page for the indicated command or utility. The information displayed with info command will be in-depth than that displayed in the man page for the same command.
info ls
su
This command switches the current user to a new user account. For example, if you’re logged in as vickey and need to change to user account to vinita, you can enter su vinita at the shell prompt. This command is most frequently used to switch to the superuser root account.
In fact, if you don’t supply a username, this utility assumes that you want to change to the root account. If you enter su -, then you will switch to the root user account and have all of root’s environment variables applied.
This command require password of the user you want switch.

Looking for Files

There are two basic commands used for file searches: find and locate

find

The find command searches through directories and subdirectories for a desired file. For example, if you wanted to find the directory with the grub.conf linux boot loader file, you could use the following command, which would start the search in the top-level root (/) directory:
# find / -name grub.conf
But this search took several minutes to get it task done. Alternatively, if you know that this file is located in the /etc subdirectory tree, or /boot/grub/grub.conf you could start in that directory with the following command:
# find /etc -name grub.conf

locate

If this is all too time-consuming, RHEL 5 includes a default database of all files and directories. Searches with the locate command are almost instantaneous. And locate searches don't require the full file name. The drawback is that the locate command database is normally updated only once each day, as documented in the /etc/cron.daily/mlocate.cron script.

Getting into the Files

Now that you see how to find and get around different files, it's time to start reading, copying, and moving the files around. Most Linux configuration files are text files. Linux editors are text editors. Linux commands are designed to read text files. If in doubt, you can check the file types in the current directory with the
file * command.

cat

The most basic command for reading files is cat. The cat filename command scrolls the text within the filename file. It also works with multiple file names; it concatenates the file names that you might list as one continuous output to your screen. You can redirect the output to the file name of your choice.

more and less

Larger files demand a command that can help you scroll through the file text at your leisure. Linux has two of these commands:
more and less.
With the more filename command, you can scroll through the text of a file, from start to finish, one screen at a time. With the less filename command, you can scroll in both directions through the same text with the PAGE UP and PAGE DOWN keys. Both commands support vi-style searches.

head and tail

The head and tail commands are separate commands that work in essentially the same way. By default, the head filename command looks at the first 10 lines of a file; the tail filename command looks at the last 10 lines of a file. You can specify the number of lines shown with the -nx switch. Just remember to avoid the space when specifying the number of lines; for example, the
# tail -n15 /etc/passwd
command lists the last 15 lines of the /etc/passwd file.

cp

The cp (copy) command allows you to take the contents of one file and place a copy with the same or different name in the directory of your choice. For example, the cp file1 file2 command takes the contents of file1 and saves the contents in file2. One of the dangers of cp is that it can easily overwrite files in different directories, without prompting you to make sure that's what you really wanted to do.

mv

While you can't rename a file in Linux, you can move it. The mv command essentially puts a different label on a file. For example, the mv file1 file2 command changes the name of file1 to file2. Unless you're moving the file to a different partition, everything about the file, including the inode number, remains the same.

ln

You can create a linked file.
linked files are common with device files such as /dev/dvdwriter and /dev/par0. They're also useful for making sure that multiple users have a copy of the same file in their directories. Hard links include a copy of the file. As long as the hard link is made within the same partition, the inode numbers are identical. You could delete a hard-linked file in one directory, and it would still exist in the other directory. For example, the following command creates a hard link from the actual Samba configuration file to smb.conf in the local directory:
# ln smb.conf /etc/samba/smb.conf
On the other hand, a soft link serves as a redirect; when you open up a file created with a soft link, you're directed to the original file. If you delete the original file, the file is lost. While the soft link is still there, it has nowhere to go. The following command is an example of how you can create a soft link:
# ln -s smb.conf /etc/samba/smb.conf

sort

You can sort the contents of a file in a number of ways. By default, the sort command sorts the contents in alphabetical order depending on the first letter in each line. For example, the sort /etc/passwd command would sort all users (including those associated with specific services and such) by username.

grep and egrep

The grep command uses a search term to look through a file. It returns the full line that contains the search term. For example, grep 'vickey' /etc/passwd looks for my name in the /etc/passwd file.
The egrep command is more forgiving; it allows you to use some unusual characters in your search, including +, ?, |, (, and). While it's possible to set up grep to search for these characters with the help of the backslash, the command can be awkward to use.

wc

The wc command, short for word count, can return the number of lines, words, and characters in a file. The wc options are straightforward: for example, wc -w filename returns the number of words in that file.

sed

The sed command, short for stream editor, allows you to search for and change specified words or even text streams in a file. For example, the following command changes the first instance of the word Windows to the word Linux in each line of the file data, and writes the result to the file newdata:
# sed 's/Windows/Linux/' data > newdata
However, this may not be enough. If a line contains more than one instance of Windows, the above sed command does not change the second instance of that word. But you can make it change every appearance of Windows by adding a "global" suffix:
# sed 's/Windows/Linux/g' data > newdata

awk

The awk command, named for its developers (Aho, Weinberger, and Kernighan), is more of a database manipulation utility. It can identify lines with a keyword and read out the text from a specified column in that line. Again, using the /etc/passwd file, for example, the following command will read out the username of every user with a vickey in the comment column:
# awk '/vickey/ {print $1}' /etc/passwd

ps

It's important to know what's running on your Linux computer. The ps command has a number of critical switches. When trying to diagnose a problem, it's common to get the fullest possible list of running processes, and then look for a specific program. For example, if the Firefox Web browser were to suddenly crash, you'd want to kill any associated processes. The ps aux | grep firefox command could then help you identify the process(es) that you need to kill.

who and w

If you want to know what users are currently logged into your system, use the who command or the w command. This can help you identify the usernames of those who are logged in, their terminal connections, their times of login, and the processes that they are running.

Wildcards

Sometimes you may not know the exact name of the file or the exact search term. This is when a wildcard is handy. The basic wildcards are shown
Wildcard Description
* Any number of alphanumeric characters (or no characters at all). For example, the ls ab* command would return the following file names, assuming they exist in the current directory: ab, abc, abcd.
? One single alphanumeric character. For example, the ls ab? command would return the following file names, assuming they exist in the current directory: abc, abd, abe
[ ] A range of options. For example, the ls ab[123] command would return the following file names, assuming they exist in the current directory: ab1, ab2, ab3. Alternatively, the ls ab[X-Z] command would return the following file names, assuming they exist in the current directory: abX, abY, abZ.

env

This command displays the environment variables for the currently logged-in user.

echo

This command is used to echo a line of text on the screen. It’s frequently used to display environment variables. For example, if you wanted to see the current value of the PATH variable, you could enter
echo $PATH

top

This command is a very useful command that displays a list of all applications and processes currently running on the system. You can sort them by CPU usage, memory usage, process ID number, and which user owns them

which

This command is used to display the full path to a shell command or utility. For example, if you wanted to know the full path to the ls command, you would enter
which ls

whoami

This command displays the username of the currently logged-in user.

netstat

This command displays the status of the network, including current connections, routing tables, etc

route

This command is used to view or manipulate the system’s routing table.

ifconfig

This command is used to manage network boards installed in the system. It can be used to display or modify your network board configuration parameters. This command can only be run by the root user.