Tuesday, September 6, 2011

Virtual Memory in Linux- SWAP

Swap space in Linux is used when the amount of physical memory (RAM) is full. If the system needs more memory resources and the RAM is full, inactive pages in memory are moved to the swap space. While swap space can help machines with a small amount of RAM, it should not be considered a replacement for more RAM. Swap space is located on hard drives, which have a slower access time than physical memory.

Swap space can be a dedicated swap partition (recommended), a swap file, or a combination of swap partitions and swap files.

According to RedHat, the size of swap space can be calculated by using the following formulae.

M = Amount of RAM in GB, and S = Amount of swap in GB, then

If M < 2
S = M *2
Else
S = M + 2

Using this formula, a system with 2 GB of physical RAM would have 4 GB of swap, while one with 3 GB of physical RAM would have 5 GB of swap.

Basically you can create virtual memory by two ways...

1. Create a new partition
2. Use existing partition


Create a new partition

First of all create a new partition.It should be double of RAM in size
Change its ID to 82. 82 is the ID of swap
Now run the following command

[root@localhost ~]# mkswap /dev/sda7 <-------i m assuming the you have created sda7 partition

Note: mkswap format this partition into swap file system

[root@localhost ~]# swapon /dev/sda7

Note: swapon command will activate the swap file system >Now edit your fstab

[root@localhost ~]# vim /etc/fstab

/dev/sda7 swap swap defaults 0 0

save and exit the file and mount it

[root@localhost ~]# mount -a

you can check the status of your swap by the following command

[root@localhost ~]# swapon -s


Use existing partition


Suppose i have a ram of 256 mb and also have a partition /dev/sda6 which has free space space upto 512mb,then i will use this partition for create virtual memory

[root@localhost ~]# dd if = /dev/zero of = swapfile bs = 512 mb count=1


dd -->disk to disk copy,,
if --> input file,,
/dev/zero -->accumlate zero,,
of --> output file,,
swapfile --> it can be any name,,
bs --> block size,,
512 mb --> size of swap ,,
count=1 --number of times command runs,,


>Now run the following commands

[root@localhost ~]# mkswap swapfile

[root@localhost ~]# swapon swapfile

[root@localhost ~]# vim /etc/fstab

/swapfile swap swap defaults 0 0

save and exit the file and mount it

[root@localhost ~]# mount -a

If you wanna unactivate the swap, run following command

[root@localhost ~]# swapoff swapfile

Mount-Unmount in Linux

In Linux, we can not access a device directly. To access a device we need a certain point on our system, from where we can access that device, and that certain point is always a 'directory'. We can access any device by mounting it with a directory.

To mount a device or partition, the mount command is used. We can mount devices temporary or permanently.

Lets see how to mount device temporary:

you can mount a partition with any directory ,Temporary or Permenent.

Temporary mount

The mount command provides large number of options and the common pattern for mount command is shown below.

To mount a partition,run:

[root@localhost ~]# mount /dev/sda4 /abc

To mount cdrom, run:

[root@localhost ~]# mount /dev/cdrom /mnt


To check whether the partition has mounted or not, run following command

[root@localhost ~]# df -Th

if you wanna detach it, run the following command

[root@localhost ~]# umount /abc

Note: After reboot,the partition will detach automatically


Permanent mount

The /etc/fstab and edit it

[root@localhost ~]# vim /etc/fstab

/dev/sda4 /mnt defaults ext3 0 0

save and exit the file

Now run mount command

[root@localhost ~]# mount -a

Now if you wanna detach it again, then you have to remove the above lines from the fstab file and then you have to run the following command

[root@localhost ~]# umount /abc

Note: If you dont wanna detach the partition,then dont remove the entry from the file,,it will still work after reboot. Keep in mind,not to change any other entries of file,bcoz it can lead your system to unbootable condition.

Linux File System Table

The Linux /etc/fstab is a configuration file that contains information of all the partitions and storage devices in your computer. The Linux /etc/fstab contains information of where your partitions and storage devices should be mounted and how.

The following contents lists a sample Linux /etc/fstab file

LABEL=/ / ext3 defaults 1 1
LABEL=/boot /boot ext3 defaults 1 2
devpts /dev/pts devpts gid=5,mode=620 0 0
tmpfs /dev/shm tmpfs defaults 0 0
proc /proc proc defaults 0 0
sysfs /sys sysfs defaults 0 0
LABEL=SWAP-sda3 swap swap defaults 0 0

Additional entries are "devpts", "/proc", "tmpfs", "sysfs"

• The devpts file system provides an interface to pseudo-terminal (pty) devices. It is typically mounted at /dev/pts.

• The /proc filesystem is to provide an easy way to view kernel and information about currently running processes.

• The tmpfs is a temporary file storage facility.

• sysfs is a virtual file system which exports information about devices and drivers from the kernel device model to userspace, and is also used for configuration.

The following table describes the different fields of /etc/fstab file.

Field Name

Description

Device

Specifies the device to be mounted. You can specify the device file or Label in this field. If mounted, you can find the related information from /etc/mtab file.

Mount Point

The directory under the root filesystem, where this filesystem will be mounted.

Filesystem Format

Specifies the filesystem type (ext2, ext3, iso9660 etc).

Mount Options

Refer the next link to learn about different Linux mount options

Dump Value

Dump is a backup utility. The possible values can be either 0 or 1. Dump use this value to decide whether the filesystem should be backed up. If the value is "0", dump will ignore that filesystem.

Filesystem Check Order

"fsck" is a tool to check the file system consistency. This value determines the order that filesystems are checked by "fsck" program during the boot process. If the value is "0", fsck won't check the filesystem.



Linux Mount Options:

Mount Option

Description

auto and noauto

The Linux "auto" mount option allows the the device to be mounted automatically at bootup. The Linux "auto" mount option is the default option. You can use the "“noauto" mount option in /etc/fstab, if you don't want the device to be mounted automatically. With the Linux noauto mount option, the device can be mounted only explicitly and later you can use "mount -a" command to mount the devices listed in Linux /etc/fstab file.

user and nouser

The Linux "user" mount option allows normal users to mount the device, whereas the Linux "nouser" mount option allows only the super user (root) to mount the device. "nouser" is the default mount option.

exec and noexec

"exec" mount option allows you to execute binaries stored on that partition and "noexec" option will prevent it. "exec" is the default Linux mount option.

ro

The Linux "ro" (Read Only) mount option is used to mount the filesystem read-only.

rw

The Linux "rw" (Read Write) mount option is used to mount the filesystem read-write.

sync

The "sync" mount option specifies the input and output to the filesystem is done synchronously. When you copy a file to a removable media (like floppy drive) with "sync" option set, the changes are physically written to the floppy at the same time you issue the copy command.

async

The "async" mount option specifies the input and output to the filesystem is done asynchronously. When you copy a file to a removable media (like floppy drive) with "async" option set, the changes are physically written to the floppy some time after issuing the copy command. If "async" option is set and if you remove the media without using the "unmount" command, some changes you made may be lost.

defaults

Uses the default options that are rw, suid, dev, exec, auto, nouser, and async. Usually the Linux operating systems use this option in /etc/fstab file.

File System Journaling

Journaling allows the filesystem to repair itself after an improper shutdown or other type of damages. Journaling keep record transactions which are to be performed, or which have been performed.

Journaling filesystems have two main advantages.

1) Journaling filesystems are faster to check during the boot process.

2) If a crash happened, using the journal (file system log) the metadata can restored faster and more efficiently.

The ext3 file system is a journaling file system. Other major journaling filesystems are ReiserFS, JFS (IBM) and XFS (Silicon Graphics)

Linux File System Management Tools - "FSCK"

The Linux fsck command analyzes the specified filesystem and performs repairs as required. For example, if you have problems in your Linux machine with files in the /home1 directory, which is mounted on /dev/sdb1, then execute the following "fsck" command for a file system to check it and repair. Make sure to unmount the file system before running fsck.

[root@localhost ~]# df -h
Filesystem Size Used Avail Use% Mounted on
/dev/sda2 14G 2.3G 11G 18% /
/dev/sda1 99M 9.9M 84M 11% /boot
tmpfs 252M 0 252M 0% /dev/shm
/dev/sdb1 7.9G 147M 7.4G 2% /home1


[root@localhost ~]# umount /dev/sdb1


[root@localhost ~]# fsck -t ext3 /dev/sdb1
fsck 1.39 (29-May-2006)
e2fsck 1.39 (29-May-2006)
/dev/sdb1: clean, 11/1048576 files, 70321/2096474 blocks

Important options of Linux fsck command are

• -a option: Automatically repair the file system without any questions.

• -r option: Interactively repair the filesystem (ask for confirmations).

Other options of Linux fsck command are

• -A option: Walk through the /etc/fstab file and try to check all filesystems in one run. This option is typically used from the /etc/rc system initialization file, instead of multiple commands for checking a single file system.


• -R option: When checking all filesystems with the -A flag, skip the root file system (in case it’s already mounted read-write).


• -T option: Don’t show the title on startup.


• -N option: Don’t execute; just show what would be done.


• -s option: Serialize fsck operations.


• -V option: Produce verbose output, including all filesystem-specific commands that are executed.

Sunday, September 4, 2011

Linux Partitioning and Formation

Fdisk

The "fdisk" file system management tool is a text-based interface that lets you divide a hard disk into partitions, which are contiguous regions of disk space on which you can make file systems. The process of dividing a hard disk space is called disk partitioning.

To list out the current available hard disks and their layout, you can use "fdisk -l" as shown below.

[root@localhost ~]# fdisk -l

Disk /dev/sda: 17.1 GB, 17179869184 bytes
255 heads, 63 sectors/track, 2088 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/sda1 * 1 13 104391 83 Linux
/dev/sda2 14 1930 15398302+ 8e Linux LVM
/dev/sda3 1931 2088 1269135 82 Linux swap / Solaris

Disk /dev/sdb: 8589 MB, 8589934592 bytes
255 heads, 63 sectors/track, 1044 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/sdb1 * 1 1044 8385898+ 8e Linux LVM

Disk /dev/sdc: 8589 MB, 8589934592 bytes
255 heads, 63 sectors/track, 1044 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/sdc1 * 1 1044 8385898+ 8e Linux LVM

Disk /dev/sdd: 8589 MB, 8589934592 bytes
255 heads, 63 sectors/track, 1044 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/sdd1 * 1 1044 8385898+ 8e Linux LVM

Disk /dev/sde: 8589 MB, 8589934592 bytes
255 heads, 63 sectors/track, 1044 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/sde1 * 1 1044 8385898+ 8e Linux LVM

The "fdisk -l" command will list out the connected hard disks and their partitions as shown above. The output columns can be explained as below.

• The Device column indicates the Linux partition names.

• The Boot column contains an asterisk that indicates the active partition.

• The Start and End columns give the starting and ending cylinder numbers of the partition.

The Blocks column gives the size of the partition in 1024-byte blocks.

• The Id and System columns specify the type of the partition. The id is the hexa code and the System is its description.

To launch the fdisk tool to manage a hard disk, run the fdisk command and specify as an argument the hard disk you want to partition.

For example, the command "fdisk /dev/sdb" will be executed as shown below.

[root@RHEL01 ~]# fdisk /dev/sdb

The number of cylinders for this disk is set to 1044.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
(e.g., DOS FDISK, OS/2 FDISK)

Command (m for help):

Once fdisk has started, it presents an interactive prompt as shown above it’s prompt is ready to run fdisk commands.

Following are the important fdisk Commands

Command

Description

a

Toggles the active partition flag.

d

Deletes a partition.

l

Lists known partition types.

n

Adds a new partition.

o

Creates a new empty partition table.

p

Prints (displays) the partition table.

q

Quits without saving changes.

t

Sets the partition type.

u

Toggles display units from cylinders to sectors or the reverse.

v

Verifies the partition table.

w

Writes the partition table to disk and exits.


Mkfs

The Linux mkfs command can be used to format a Linux partition. The Linux "mkfs" command allows you to format a partition to a number of different filesystems. The Linux "mkfs" command also serves as a "front end," depending on the filesystem format. if you're formatting a standard ext3 filesystem, mkfs automatically calls the mkfs.ext3 command. The following commands show how create a partition using "fdisk" command and how to format the new partion using "mkfs" command.

[root@localhost ~]# fdisk /dev/sdb
Device contains neither a valid DOS partition table, nor Sun, SGI or OSF disklabel
Building a new DOS disklabel. Changes will remain in memory only,
until you decide to write them. After that, of course, the previous
content won't be recoverable.

The number of cylinders for this disk is set to 1044.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
(e.g., DOS FDISK, OS/2 FDISK)
Warning: invalid flag 0x0000 of partition table 4 will be corrected by w(rite)

Command (m for help): n
Command action
e extended
p primary partition (1-4)
p
Partition number (1-4): 1
First cylinder (1-1044, default 1):
Using default value 1
Last cylinder or +size or +sizeM or +sizeK (1-1044, default 1044):
Using default value 1044

Command (m for help): w
The partition table has been altered!

Calling ioctl() to re-read partition table.
Syncing disks.

The above set of fdisk commands create /dev/sdb1 partition. After creating the partition, we can overlay a filesystem (format) using mkfs command as shown below.

[root@localhost ~]# mkfs -t ext3 /dev/sdb1
mke2fs 1.39 (29-May-2006)
Filesystem label=
OS type: Linux
Block size=4096 (log=2)
Fragment size=4096 (log=2)
1048576 inodes, 2096474 blocks
104823 blocks (5.00%) reserved for the super user
First data block=0
Maximum filesystem blocks=2147483648
64 block groups
32768 blocks per group, 32768 fragments per group
16384 inodes per group
Superblock backups stored on blocks:
32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632

Writing inode tables: done
Creating journal (32768 blocks): done
Writing superblocks and filesystem accounting information: done

This filesystem will be automatically checked every 20 mounts or
180 days, whichever comes first. Use tune2fs -c or -i to override.

Other Linux tools to create filesystems

• mkfs.ext2 command can be used to format a partition with ext2 filesystem.


• mkfs.ext3 command can be used to format a partition with ext3 filesystem.


• mkfs.msdos (or mkfs.vfat or mkdosfs) formats a partition to the Microsoft-compatible VFAT filesystem (The inode numbers for all three files are the same; that means they are three different names for the same command).


• mkswap command can be used to format a partition with Linux swap filesystem.

Standard Linux Filesystem Formats

Filesystem Type

Description

ext

The first Linux filesystem used on early versions.

ext2

The most featureful of the native Linux filesystems, but with no journaling support.

ext3

The ext3 filesystem has all the features of the ext2 filesystem with journaling has been added.

swap

The Linux swap filesystem is associated with dedicated swap partitions.

reiserfs

A stable journaled filesystem.

Jfs

JFS is a journaled filesystem designed by IBM to to work in high performance environments

vfat

VFAT lets you read Windows 9x/NT/2000/XP/Vista partitions formatted to the FAT16 or FAT32 filesystems.

iso9660

The standard filesystem for CD-ROMs

ntfs

The Microsoft Windows NT/2000/XP/2003/2008 filesystem designed for username/password security.

/proc

A Linux virtual filesystem. Virtual means that it doesn't occupy real disk space. Instead, files are created as needed. Used to provide information on kernel configuration and device status.

/dev/pts

The Linux implementation of the Open Group's Unix98 PTY support.

nfs

The Network File System, the system most commonly used to share files and printers between Linux and Unix computers.

cifs

The Common Internet File System (CIFS) is used to to share files and printers with Microsoft Windows operating systems.


User & Group Database Files

The Linux user database (/etc/passwd)

Th Linux User account (except password related information) are stored in a configuration file, /etc/passwd.

A sample /etc/passwd configuration file is copied below.

[root@localhost ~]# cat /etc/passwd

root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
halt:x:7:0:halt:/sbin:/sbin/halt
mail:x:8:12:mail:/var/spool/mail:/sbin/nologin
news:x:9:13:news:/etc/news:
uucp:x:10:14:uucp:/var/spool/uucp:/sbin/nologin
operator:x:11:0:operator:/root:/sbin/nologin
games:x:12:100:games:/usr/games:/sbin/nologin
gopher:x:13:30:gopher:/var/gopher:/sbin/nologin
ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin
nobody:x:99:99:Nobody:/:/sbin/nologin
rpm:x:37:37::/var/lib/rpm:/sbin/nologin
dbus:x:81:81:System message bus:/:/sbin/nologin
avahi:x:70:70:Avahi daemon:/:/sbin/nologin
mailnull:x:47:47::/var/spool/mqueue:/sbin/nologin
smmsp:x:51:51::/var/spool/mqueue:/sbin/nologin
nscd:x:28:28:NSCD Daemon:/:/sbin/nologin
vcsa:x:69:69:virtual console memory owner:/dev:/sbin/nologin
haldaemon:x:68:68:HAL daemon:/:/sbin/nologin
rpc:x:32:32:Portmapper RPC user:/:/sbin/nologin
rpcuser:x:29:29:RPC Service User:/var/lib/nfs:/sbin/nologin
nfsnobody:x:65534:65534:Anonymous NFS User:/var/lib/nfs:/sbin/nologin
sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin
pcap:x:77:77::/var/arpwatch:/sbin/nologin
ntp:x:38:38::/etc/ntp:/sbin/nologin
gdm:x:42:42::/var/gdm:/sbin/nologin
xfs:x:43:43:X Font Server:/etc/X11/fs:/sbin/nologin
sabayon:x:86:86:Sabayon user:/home/sabayon:/sbin/nologin
tintin:x:500:500::/home/tintin:/bin/bash

Each column in /etc/passwd, delimited by a colon and it is explained in detail below.

Column

Field

Description

1

Username

User login id

2

Password

The password. You should see either an x, an asterisk (*), or an encrypted password. An x points to /etc/shadow for the actual password. An asterisk means the account is disabled.

3

User ID

The unique numeric user ID (UID) for that user. By default, Red Hat starts normal user IDs at 500.

4

Group ID

The numeric group ID (GID) associated with that user. By default, RHEL creates a new group for every new user, and the number matches the UID.

5

User info

You can enter any information of your choice in this field. Standard options include the user's full name, telephone number, e-mail address, or physical location. Also known as GECOS field.

6

Home Directory

Users home directory. RHEL places new home directories in /home/username.

7

Login Shell

Users login shell. Default Linux shell is bash shell.


The Linux password database (/etc/shadow)

Traditional Unix systems store user account information, including one-way encrypted passwords, in user database file "/etc/passwd". This file is world-readable and hence storing password in this file is not secure.

Another method of storing account information is the shadow password format. This method stores account information in the /etc/passwd file, but the password is stored as a single "x" character (ie. not actually stored in this file). A second file, called "/etc/shadow", contains encrypted password and other information related with password. The "/etc/shadow" file is readable only by the root account.

The following are the advantages shadow passwords over the traditional way of storing passwords on UNIX-based systems.

• Improves system security by moving encrypted password hashes from the world-readable /etc/passwd file to /etc/shadow, which is readable only by the root user.

• Stores information about password aging.

• Allows the use the /etc/login.defs file to enforce security policies.

A sample /etc/shadow configuration file is copied below.

[root@localhost ~]# cat /etc/shadow

root:$1$CQoPk7Zh$370xDLmeGD9m4aF/ciIlC.:14425:0:99999:7:::
bin:*:14425:0:99999:7:::
daemon:*:14425:0:99999:7:::
adm:*:14425:0:99999:7:::
lp:*:14425:0:99999:7:::
sync:*:14425:0:99999:7:::
shutdown:*:14425:0:99999:7:::
halt:*:14425:0:99999:7:::
mail:*:14425:0:99999:7:::
news:*:14425:0:99999:7:::
uucp:*:14425:0:99999:7:::
operator:*:14425:0:99999:7:::
games:*:14425:0:99999:7:::
gopher:*:14425:0:99999:7:::
ftp:*:14425:0:99999:7:::
nobody:*:14425:0:99999:7:::
rpm:!!:14425:0:99999:7:::
dbus:!!:14425:0:99999:7:::
avahi:!!:14425:0:99999:7:::
mailnull:!!:14425:0:99999:7:::
smmsp:!!:14425:0:99999:7:::
nscd:!!:14425:0:99999:7:::
vcsa:!!:14425:0:99999:7:::
haldaemon:!!:14425:0:99999:7:::
rpc:!!:14425:0:99999:7:::
rpcuser:!!:14425:0:99999:7:::
nfsnobody:!!:14425:0:99999:7:::
sshd:!!:14425:0:99999:7:::
pcap:!!:14425:0:99999:7:::
ntp:!!:14425:0:99999:7:::
gdm:!!:14425:0:99999:7:::
xfs:!!:14425:0:99999:7:::
sabayon:!!:14425:0:99999:7:::
tintin:$1$wKAP1RyH$JeCAcEGhSGVlD0J7.AMg.0:14396:2:5:7:30::

Column

Field

Description

1

Username

Username

2

Password

Encrypted password; requires an x in the second column of /etc/passwd

3

Password history

Date of the last password change, in number of days after January 1, 1970 (Unix epoch)

4

mindays

Minimum number of days that you must keep a password (-m)

5

maxdays

Maximum number of days after which a password must be changed (-M)

6

warndays

Number of days before password expiration when a warning is given (-W)

7

inactive

Number of days after password expiration when an account is made inactive (-I)

8

disabled

The number of days since January 1, 1970 (Unix epoch) that an account has been disabled (-E)

9

Reserved

Currently not in use


Linux Group Database (/etc/group) file

RedHat Enterprise Linux group database is /etc/group file. It stores group information or defines the user groups in the Linux machine. The Linux group configuration file /etc/group

defines the groups to which the Linux users belong. A sample /etc/group file is shown below.

[root@localhost ~]# cat /etc/group
root:x:0:root
bin:x:1:root,bin,daemon
daemon:x:2:root,bin,daemon
sys:x:3:root,bin,adm
adm:x:4:root,adm,daemon
tty:x:5:
disk:x:6:root
lp:x:7:daemon,lp
mem:x:8:
kmem:x:9:
wheel:x:10:root
mail:x:12:mail
news:x:13:news
uucp:x:14:uucp
man:x:15:
games:x:20:
gopher:x:30:
dip:x:40:
ftp:x:50:
lock:x:54:
nobody:x:99:
users:x:100:
rpm:x:37:
dbus:x:81:
utmp:x:22:
utempter:x:35:
avahi:x:70:
mailnull:x:47:
smmsp:x:51:
nscd:x:28:
floppy:x:19:
vcsa:x:69:
haldaemon:x:68:
rpc:x:32:
rpcuser:x:29:
nfsnobody:x:65534:
sshd:x:74:
pcap:x:77:
ntp:x:38:
slocate:x:21:
gdm:x:42:
xfs:x:43:
sabayon:x:86:
tintin:x:500:
engineering:x:501:tintin

The following table explains in detail, the different columns which are delimited by a ":" character in Linux group database file, /etc/group.

Column

Field

Description

1

Group name

It is the name of Linux group. If you run ls -l command, you will see this name printed in the group field.

2

Password

Generally password is not used; hence it is empty/blank. It can store encrypted password. An “x” in this field means the password is encrypted and kept in another file.

3

Group ID (GID)

The group id. By default, Red Hat Linux starts normal group IDs at 500.

4

Group List

Comma separated list of user names of users who are members of the Linux group.





User & Group Account Administration Commands

There are three basic types of Linux user accounts: administrative (root), regular, and service.

The Linux administrative root account is automatically created when you install Linux, and it has administrative privileges for all services on Linux Operating System. The root account is also known as super user

Regular users have the necessary privileges to perform standard tasks on a Linux computer such as running word processors, databases, and Web browsers. They can store files in their own home directories. Since regular users do not normally have administrative privileges, they cannot accidentally delete critical operating system configuration files.

Services such as Apache, Squid, mail, games, and printing have their own individual service accounts. These accounts exist to allow each of these services to interact with your computer.

Each user on a Red Hat Enterprise Linux system is assigned a unique user identification number, also known as a UID. UIDs below 500 are reserved for system users such as the root user and service users.

A user group is a group of one or more users. A user can be a member of more than one group. In Red Hat Enterprise Linux, when a user is added, a private user group (primary group) is created—meaning that a user group of the same name is created and that the new user is the sole user in that group.

To add a new user, use the useradd command. The basic syntax is



# useradd vinod

The username is the only information required to add a new user; however, for exam prospective you should know some additional command-line arguments for useradd. The useradd command creates the account, but the account is locked.

To unlock the account and create a password for the user, use the command passwd [username]. By default, the user's home directory is created and the files from /etc/skel/ are copied into it.

The two exceptions are if the –M option is used or if the home directory already exists.

We have already discussed about these two basic commands in our last article. If you haven't completed our last assignments we suggest you to review it before going with this article as it's the sequential of last assignments.

Create a user with additional command-line arguments.In this example you are going to assign home directory on other locations so first create it and same as create first desired user's secondary group.



#mkdir /test
#groupadd example
#useradd –u 700 –d /test/user1 –g example –c “testing user” –s /bin/sh –m user1
#passwd user1

useradd command



-c [fullname] Full name of the user (or a comment about the user).
If more than one word is needed, place quotation marks
around the value.
-d [directory] Home directory for the user. The default value is /home/[username]/.
-g [group] Default group for the user specified as a group name or group ID
number. The group name or GID must already exist. The default is
to create a private user group. If a private user group is not
created, the default is the users group.
-m Create a home directory for the user if it doesn't exist. Files from
/etc/skel/ are copied into the home directory.
-s [shell] Specify the user login shell for the user. The default shell if not
specified is /bin/bash.
-u [uid] Integer to use for the user ID. Must be unique unless -o is used.
Values less than 500 are reserved for system users.
-M Do not create a home directory for the user. By default, a home
directory is created unless this option is used or unless the
directory already exists.

Now login form this user. And check where did this user logged in and why its shell prompt is looking different.



$pwd
/test/user1

useradd command

By default user gets bash sell prompts. But we modified this by –s switch and given user to /bin/sh shell. Now change user shell again



#usermod –s /bin/bash user1

useradd command

Verify by login again from user1

useradd command


How to manage bulk users

Consider a situation where you need to create more then thousand user. It will be really tedious task if you will do it by simple useradd commands. Here you have to switch to Linux shell scripts.

loop for creating user



# for USER in _ _ _ _ _ _ _ _ _ _ _
> do
>useradd $USER
>echo _ _ _ _ |passwd --stdin $USER
>done

Example
(replace users vinita nikkita niddhi sumit shweta vickey kaushal manoj jai to your users)



# for USER in vinita nikkita niddhi sumit shewta vickey kaushal manoj jai
> do
>useradd $USER
>echo friends |passwd --stdin $USER
>done

This simple for loop will create 9 users and set their defaults passwords to friends.

useradd for loop

Loop for creating groups

Now create 3 groups named sales market productions using for loop



#for GROUP in sales market productions
> do
>groupadd $GROUP
>done
Verify by cat and grep commands

groupadd command linux

For loop for deleting bulk users

Now remove all the user which we created in pervious example.



#for USER in vinita nikkita niddhi sumit shweta vickey kaushal manoj jai
>do
>userdel -r $USER
>done

userdel linux command

For loop for deleting bulk users

Remove groups which we create in pervious example



#for GROUP in sales market productions
> do
>groupdel $GROUP
>done

groupdel linux command


In Red Hat Enterprise Linux, all files have file permissions that determine whether a user is allowed to read, write, or execute them. When you issue the command ls -l, the first column of information contains these file permissions.Within this first column are places for 10 letters or hyphens.

file permission

The first space is either a hyphen, the letter d, or the letter l.

  • A hyphen means it is a file.
  • If it is the letter d, the file is actually a directory.
  • If it is the letter l, it is a symbolic link to a directory somewhere else on the file system.

The next nine spaces are divided into three sets of three as shown in image.

linux file permission


Files and directories belong to both an owner and a group. A group usually consists of a collection of users, all belonging to the same group. The first set of three is the read, write, and execute permissions for the owner of the file.

A group can also consist of one user, normally the user who creates the file. Each user on the system, including the root user, is assigned his or her own group of which he or she is the only member, ensuring access only by that user. The second set of three is the read, write, and execute permissions for anyone who belongs to the user group for the file.

The last set of permissions is for anyone who has a login to the system.

Ownership

Create a directory /test we will use this for the practical demonstration of permission.



#mkdir /test
#ls –ld /test

linux command chown

The root user, the system administrator, owns most of the system files that also belong to the root group, of which only the root user is a member. Most administration files, like configuration files in the /etc directory, are owned by the root user and belong to the root group. Only the root user has permission to modify them, whereas normal users can read and, in the case of programs, also execute them.

In this example, the root user owns the fstab file in the /etc directory, which also belongs to the root user group.



-rw-r--r-- 1 root root 621 jan 22 11:03 fstab

Certain directories and files located in the system directories are owned by a service, rather than the root user, because the services need to change those files directly. This is particularly true for services that interact with remote users, such as Internet servers. Most of these files are located in the /var directory. Here you will find files and directories managed by services like the Squid proxy server and the Domain Name Server (named).

In this example, the Squid proxy server directory is owned by the squid user and belongs to the squid group:



drwxr-x--- 2 squid squid 4096 Jan 24 16:29 squid

Changing a File's Owner or Group

Although other users may be able to access a file, only the owner can change its permissions. If you want to give other user to control over one of your file's permissions, you can change the owner of the file from yourself to the other user. The chown command transfers control over a file to another user. This command takes as its first argument the name of the other user. Following the username, you list the files you are transferring. In our example, we gives control of the /test directory to user a:



# chown a /test
# ls -ld /test

chown

You can also change the group for a file and directories, using the chgrp command. chgrp takes as its first argument the name of the new group for a files or directories.



#chgrp example /test

chgrp linux commands







Wednesday, August 31, 2011

Linux Basic Commands


Linux operating system has a beautiful graphical interface which most of us will be using. It will be good to learn the basic commands in Linux to work interactively with the Linux operating system. Linux has a back end access know as shell. You can control and activate all the process in Linux from the shell. So it is very important to learn few basic commands to work with Linux operating system.

First we will learn how to login for shell access. There are 7 terminals for Linux. 6 terminals are non - GUI and 1 terminal for GUI access. You can login to each terminal using Alt + Ctrl + F1 , F2, .. F7. Each terminals will request your username and password for login. If you want to use the shell in the graphical interface (GUI), press Alt + F2 and type "konsole". As a user you will have permission to access only your /home/user directory and other directories in it.

Now lets check out some commands:

pwd
This command is used to find the current location or current working directory.

Eg:
[user@ws26 ~]$ pwd
/home/user

cd
This command id used to change the directory. You can move from one directory to another using this command. Few examples are given below.

Concider you have a directory structure /home/user/test/test1/ . test and test1 are directories in user home.

Example 1:
Consider you have a directory "test" in /home/user. Your current working directory is /home/user. You want to change your current working directory from /home/user to /home/user/test, use the following command
[user@ws26 ~]$ pwd
/home/user
[user@ws26 ~]$ cd test
[user@ws26 ~]$ pwd
/home/user/test

Example 2:
If you want to move back to /home/user, use the following command
[user@ws26 ~]$ cd ..
[user@ws26 ~]$ pwd
/home/user

Example 3:
To get back to the home directory of the user
[user@ws26 ~]$ cd ~
[user@ws26 ~]$ pwd
/home/user.

Listing contents in a directory - [ ls, ls -l, ll ]

ls
This command is used to list all the files and directory in the current directory.

Eg:
[user@ws26 ~]$ ls
1152696870.jpg book OperaDownloads snapshot52.png
image300.jpg Desktop test spiderman2.jpg

ls -l or ll
This command is also used to list all the files and directories. Here you will get more details about the files and directories present in the current directory. You will see the permission set, creation date, file / directory size etc.

Eg:
[user@ws26 ~]$ ls -l
total 5
-rw-rw-r-- 1 user user 33188 Dec 22 02:56 1152696870.jpg
-rw-rw-r-- 1 user user 17647 Aug 19 2006 534458.gif
-rw-rw-r-- 1 user user 26817 Aug 19 2006 534477.gif
drwxrwxr-x 2 user user 4096 Jan 13 04:20 book
drwx------ 3 user user 4096 Feb 4 02:34 Desktop

Reading files in Linux - [ cat, more, less ]

Cat
This command is used to display the contents of a file. You can read the file contents using the cat command.

Example:
[user@ws26 ~]$ cat testfile
this is a test file.. You can read me..


Less and More
Both the less and more commands serve similar function. They are used to display file one screen at a time. You can press spacebar to continue reading the file. These commands are mainly used while reading large files.

Example 1:
[user@ws26 ~]$ less testfile
this is a test file.. You can read me..

Example 2:
[user@ws26 ~]$ more testfile
this is a test file.. You can read me..



Manipulating files - [ cp, mv, rm, mkdir ]

cp
This command is used to copy files/directory.

Example:
[user@ws26 ~]$ cp file1 directory1
This will copy the file1 into the directory1

cp -R
This command is used to copy directories recursively (copy all the files and folders inside the directory).

Example:
[user@ws26 ~]$ cp directory2 directory1
This will copy the whole directory2 into directory1

mv
This command is used to move the file or directory.

Example:
[user@ws26 ~]$ mv directory2 directory1
This will move the whole directory2 into directory1

rm
This command is used to remove or delete files and directories.

Example:
[user@ws26 ~]$ rm directory2
This will delete the directory - directory2

mkdir
This command is used to create a new directory

Example:
[user@ws26 ~]$ mkdir directory3
This will create a new directory - directory3.

create new file in Linux - vi editor

The Vi editor is mainly used to create new files in Linux.

Example:
vi testfile
The command will open a new window and you can insert text to it. To begin press "i". After adding your contect press ":wq" to save the file.


Linux Run Levels & Init

Once kernel and drivers are loaded, Linux starts loading the rest of the system. This starts with the First Process, known as init and it has the process id of 1 (the kernel itself has the process id of 0, which cannot be displayed by using the "ps" command).

The init process takes control of the boot operation. The init process in turn runs /etc/rc.d/rc.sysinit, which performs a number of tasks, including network configuration, SELinux status, keyboard maps, system clock, partition mounts, and host names.

The runlevels are controlled by a configuration file which init process reads from the location /etc. The name of the init configuration file is "inittab".

The init process then determines the runlevel by looking at the initdefault directive in /etc/inittab configuration file. The following are the defined runlevels. The init process remains active as long as the system is running.

Runlevel value

Description

0

Halt

1

Single-user mode

2

Multiuser, with some network services

3

Multiuser, with networking

4

Unused

5

Full Multiuser mode with X Windows (GUI login screen)

6

Reboot


Inittab configuration file

After the kernel boots, it always executes a program called "init". The init program then reads its configuration file called /etc/inittab and commences the boot process. A sample inittab file is copied below. The lines which are commencing with a "#" are comments.

### Beginning of inittab ###


# inittab This file describes how the INIT process should set up
# the system in a certain run-level.
#
# Author: Miquel van Smoorenburg,
# Modified for RHS Linux by Marc Ewing and Donnie Barnes
#

# Default runlevel. The runlevels used by RHS are:
# 0 - halt (Do NOT set initdefault to this)
# 1 - Single user mode
# 2 - Multiuser, without NFS (The same as 3, if you do not have networking)
# 3 - Full multiuser mode
# 4 - unused
# 5 - X11
# 6 - reboot (Do NOT set initdefault to this)
#
id:5:initdefault:

# System initialization.
si::sysinit:/etc/rc.d/rc.sysinit

l0:0:wait:/etc/rc.d/rc 0
l1:1:wait:/etc/rc.d/rc 1
l2:2:wait:/etc/rc.d/rc 2
l3:3:wait:/etc/rc.d/rc 3
l4:4:wait:/etc/rc.d/rc 4
l5:5:wait:/etc/rc.d/rc 5
l6:6:wait:/etc/rc.d/rc 6

# Trap CTRL-ALT-DELETE
ca::ctrlaltdel:/sbin/shutdown -t3 -r now

# When our UPS tells us power has failed, assume we have a few minutes
# of power left. Schedule a shutdown for 2 minutes from now.
# This does, of course, assume you have powerd installed and your
# UPS connected and working correctly.
pf::powerfail:/sbin/shutdown -f -h +2 "Power Failure; System Shutting Down"

# If power was restored before the shutdown kicked in, cancel it.
pr:12345:powerokwait:/sbin/shutdown -c "Power Restored; Shutdown Cancelled"

# Run gettys in standard runlevels
1:2345:respawn:/sbin/mingetty tty1
2:2345:respawn:/sbin/mingetty tty2
3:2345:respawn:/sbin/mingetty tty3
4:2345:respawn:/sbin/mingetty tty4
5:2345:respawn:/sbin/mingetty tty5
6:2345:respawn:/sbin/mingetty tty6

# Run xdm in runlevel 5
x:5:respawn:/etc/X11/prefdm -nodaemon

### End of inittab ###


Format of Inittab

The format of each line in inittab file is as follows:

id:runlevels:action:process

• id: A unique sequence of one to four characters that identifies this entry in the /etc/inittab file.

• runlevels: The runlevels at which the process should be invoked. For example, the runlevels entry 123 specifies something that runs at runlevels 1, 2, or 3.

• action: Describes what action should be taken. Options for this field are explained in the next table.

• Process: Names the process (or program) to execute when the runlevel is entered.

The following table specifies some valid actions for the action field.

Action Field in inittab file

Description

respawn

The process will be restarted whenever it terminates.

wait

The process will be started once when the runlevel is entered, and init will wait for its completion.

once

The process will be started once when the runlevel is entered; however, init won’t wait for termination of the process before possibly executing additional programs to be run at that particular runlevel.

boot

The process will be executed at system boot. The runlevels field is ignored in this case.

bootwait

The process will be executed at system boot, and init will wait for completion of the boot before
advancing to the next process to be run.

ondemand

The process will be executed when a specific runlevel request occurs. (These runlevels are a, b,
and c.) No change in runlevel occurs.

initdefault

Specifies the default runlevel for init on startup. If no default is specified, the user is prompted for a runlevel on console.

sysinit

The process will be executed during system boot, before any of the boot or bootwait entries.

powerwait

If init receives a signal from another process that there are problems with the power, this process will be run. Before continuing, init will wait for this process to finish.

powerfail

Same as powerwait, except that init will not wait for the process to finish.

Powerokwait

This process will be executed as soon as init is informed that the power has been restored.

ctrlaltdel

The process is executed when init receives a signal indicating that the user has pressed the ctrl-alt-del key combination. Keep in mind that most X Window System servers capture this key combination, and thus init may not receive this signal if the X Window System is active.