Friday, April 20, 2012

GRUB Image Files

GRUB consists of several images: a variety of bootstrap images for starting GRUB in various ways, a kernel image, and a set of modules which are combined with the kernel image to form a core image. Here is a short overview of them:

On PC BIOS systems, this image is the first part of GRUB to start. It is written to a master boot record (MBR) or to the boot sector of a partition. Because a PC boot sector is 512 bytes, the size of this image is exactly 512 bytes.
The sole function of boot.img is to read the first sector of the core image from a local disk and jump to it. Because of the size restriction, boot.img cannot understand any file system structure, so grub-setuphardcodes the location of the first sector of the core image into boot.img when installing GRUB. 
This image is used as the first sector of the core image when booting from a hard disk. It reads the rest of the core image into memory and starts the kernel. Since file system handling is not yet available, it encodes the location of the core image using a block list format. 
This image is used as the first sector of the core image when booting from a CD-ROM drive. It performs a similar function to diskboot.img
This image is used as the start of the core image when booting from the network using PXE. See Network
This image may be placed at the start of the core image in order to make GRUB look enough like a Linux kernel that it can be booted by LILO using an ‘image=’ section. 
This image contains GRUB's basic run-time facilities: frameworks for device and file handling, environment variables, the rescue mode command-line parser, and so on. It is rarely used directly, but is built into all core images. 
This is the core image of GRUB. It is built dynamically from the kernel image and an arbitrary list of modules by the grub-mkimage program. Usually, it contains enough modules to access /boot/grub, and loads everything else (including menu handling, the ability to load target operating systems, and so on) from the file system at run-time. The modular design allows the core image to be kept small, since the areas of disk where it must be installed are often as small as 32KB.
initrd (initial ramdisk) is a scheme for loading a temporary file system into memory in the boot process of the Linux kernel. initrd and initramfs refer to slightly different methods of achieving this. Both are commonly used to make preparations before the real root file system can be mounted.

How to password protect GRUB?

There are only 3 steps to password protect users to edit grub properties while system booting:

1) Run following command to generate MD5 encrypted password:

root@localhost# grub-md5-crypt
Retype password:

2) Copy MD5 encrypted password of above command

3) Paste copied MD5 encrypted password in menu.list/grub.conf file :

default = 0
password --md5 $1$yAr5c0$ZYlcLULaS2rwOvry1B4gX/

Thats it!!!

Now whenever user's try to run GRUB commands or try to change booting parameters at the time of BOOT, above entered text password will be required!!

Wednesday, April 4, 2012

Linux : How To Recover From Bad SuperBlock Corrupted Ext3 File System??

I was getting following error:

/dev/cciss/c0d0p1: Input/output error
mount: /dev/cciss/c0d0p1: can't read superblock

In case you are also facing the same error with superblocks, you can follow below given steps to recover superblock:

#### dumpe2fs  /dev/cciss/c0d0p1|grep -i superblock

dumpe2fs 1.39 (29-May-2006)
Filesystem features:      has_journal ext_attr resize_inode dir_index filetype needs_recovery sparse_super
  Primary superblock at 1, Group descriptors at 2-2
  Backup superblock at 8193, Group descriptors at 8194-8194
  Backup superblock at 24577, Group descriptors at 24578-24578
  Backup superblock at 40961, Group descriptors at 40962-40962
  Backup superblock at 57345, Group descriptors at 57346-57346
  Backup superblock at 73729, Group descriptors at 73730-73730

Above command output showing back'd up superblock. Now we need to restore from these superblocks

#### fsck -b 8193 /dev/cciss/c0d0p1

If still showing any error continue to restore with next Backup superblock i.e;  24577, 40961 etc....

After successful completion of above command i.e; output will be like this

Free blocks count wrong for group #362 (32254, counted=32248).
Fix? yes
Free blocks count wrong for group #368 (32254, counted=27774).
Fix? yes

/dev/cciss/c0d0p1: ***** FILE SYSTEM WAS MODIFIED *****

 /dev/cciss/c0d0p1: 59586/30539776 files (0.6% non-contiguous), 3604682/61059048 blocks

Now mount your file system

##### mount  /dev/cciss/c0d0p1 /mnt

Thats it!!!

Tuesday, April 3, 2012

How To Access GNU Screen Session Over SSH??

We can attach a GNU SCREEN session remotely over SSH; in this example we'll open a GNU screen session on host1, and connect to it from host2.

First open and then detach a screen session on host1, named testscreen:
host1 ~ $ screen -S testscreen
Then detach from your screen session with the keyboard combination Ctrl+a+d:
[detached from 3829.testscreen]
Do not "exit" from shell only use Ctrl+a+d to detach from that session. One of the main feature I like about screen is that we can trace whatever user was doing last time (in case of script command a typescript file is created which show the complete working of user)

You can verify that it's still there with this command:
host1 ~ $ screen -ls

There is a screen on:
        3941.testscreen (03/18/2012 12:43:42 PM) (Detached)
1 Socket in /var/run/screen/S-host1.
Then re-attach to your screen session from host2 (because we just detached our session last time not exited, so this will start from the last point were we were detached from session):
host2 ~ $ ssh -t user@host1 screen -r testscreen

You don't have to name the screen session if there is only one :)

Thursday, March 29, 2012

Redhat/CentOS/Fedora Linux: How to Setup Chroot SSH/SFTP

Find below given steps to setup chrooted SSH:

1) Create a group : groupadd sftpgroup

2) Create a user : useradd -g sftpgroup -d /home/mysftpuser -s /sbin/nologin mysftpuser

3) Open /etc/ssh/sshd_config file and comment following line

   #Subsystem      sftp    /usr/libexec/openssh/sftp-server

4) Add following lines to /etc/ssh/sshd_config

    Subsystem      sftp    internal-sftp
    ChrootDirectory /home/%u

5) Save and exit from /etc/ssh/sshd_config file

6) Restart sshd service

7) Try to login from server/client machine

[nginx_test:main.LINUX5 ~]# sftp mysftp@
Connecting to
mysftp@'s password:

sftp> pwd
Remote working directory: /

Thats it!!!

Friday, February 10, 2012

Script/Command To Authenticate Linux With Windows Active Directory Or Linux OpenLDAP

For Authenticating with Windows AD:

In this lets assume windows domain name is win-pfb09prf78l.scvmm.local


/usr/bin/authconfig --disablecache --enablewinbind --enablewinbindauth --smbsecurity=ADS --smbworkgroup=scvmm --smbrealm=scvmm.local --smbservers=win-pfb09prf78l.scvmm.local --enablewinbindusedefaultdomain --winbindtemplatehomedir=/home/%U --winbindtemplateshell=/bin/bash --enablekrb5 --krb5realm=SCVMM.LOCAL --krb5adminserver=win-pfb09prf78l.scvmm.local --krb5kdc=win-pfb09prf78l.scvmm.local --enablekrb5kdcdns --enablekrb5realmdns --enablelocauthorize --enablemkhomedir --enablepamaccess --update

echo "Comnet@12" | kinit administrator@SCVMM.LOCAL

net ads join -UAdministrator%Comnet@12 -S win-pfb09prf78l.scvmm.local

/bin/sed -i 's/idmap gid/#idmap gid/g' /etc/samba/smb.conf

/bin/sed -i 's/idmap uid/#idmap uid/g' /etc/samba/smb.conf

/bin/sed -i "/#idmap uid/i idmap config scvmm:backend = rid" /etc/samba/smb.conf

/bin/sed -i "/#idmap uid/i idmap config scvmm:base_rid = 500" /etc/samba/smb.conf

/bin/sed -i "/#idmap uid/i idmap config scvmm:range = 500-10000000" /etc/samba/smb.conf

For Authenticating with OpenLDAP:

/usr/bin/authconfig --enableldap --enableldapauth --ldapserver= --ldapbasedn=dc=domain,dc=myldap,dc=com --update --enablemkhomedir

Please correct if something missing or wrong :-)

What Are Unix/Linux Processes And Their Types.......

A process is a running instance of a program. In this article we used two terms ‘program’ and ‘running instance’. Suppose we run a program simultaneously 5 times, then corresponding to each instance there will be a process running in the system. So we say that a process is a “running instance” of a program.

As you already know, you can use ps command to view the processes running on your system. For effective use of the ps command, refer to 7 Practical PS Command Examples for Process Monitoring.

1. Peeping Inside a Process

Now, since we are clear with what exactly a process is, lets dig a bit deeper to see what a process consists of. A Unix process can be thought of as a container which contains:

Program Instructions

Program instructions are kept in text segments which are executed by CPU. Usually for programs like text editors which are executed frequently the text segment is shared. This segment has read only privileges which means that a program cannot modify its text segment.


Mostly the data is kept in data segment. Data segment can be classified into initialized data segment and uninitialized data segment. As the name suggest, initialized data segment contains those global variables which are initialized before hand while uninitialized data segment (also known as ‘BSS’ segment) contains uninitialized global variables. Also, static variables are stored in data segment.
Local variables which are local to functions are stored on stack. Stack is particular to a function and besides containing the information about local variables it also contains information about the address where the flow will return once the execution of function is done. Stack also contains information about the callers environment, like some of the machine registers are also stored on stack. A function which is called allocates memory for its local variables and temporary variables on stack itself. In case of recursive function an independent stack for each function call exists.
Then there is data which is stored on heap. This memory for this data is allocated on runtime on heap segment. Heap segment is not local to a process but shared across processes. This is the reason why C programmers worry a lot about memory leaks which are caused on heap segment and may affect other processes on the system.

Command line arguments and environment variables

A process also contains room for storing environment variables and the command line arguments that we pass to the program. Usually the vector containing the command line information is stored here and then the address of this vector of information and number of elements in vector is copied to ‘argv’ and ‘argc’ (the two arguments to ‘main()’ function).
Besides the above information, a process also contains information like
  • State of its I/O
  • Its priority and other control information
One of the most important control information for a process is the privileges. A process directly inherits all the privileges of the user who has triggered this process. For example a process triggered by user who does not have superuser privileges cannot do stuff that require root privileges while a process triggered by root can do any thing that it is programmed to do. An exception to the above rule is where a process can acquire greater privileges than the user who triggered it if the setuid or setgid bit is set for that particular process. But we will not go into much detail about it here(refer to the man pages of setuid and setgid for more information on this).

2. Background and foreground processes

As we already discussed that we can start a process by its name in Unix. Like some standard programs ‘ls’, ‘ps’ etc can be started by just typing their name on the shell prompt. There are two ways in which we can start a process
  • Starting in foreground
  • Starting in background
Suppose there is a utility that consumes some time and does a count. Lets say the the name of the utility is ‘count’ Now to trigger and run the program in foreground, I run the following command (where ‘count’ is the name of the binary from the code above) :
$ ./count
Counting done
So we see that, after running the binary ‘./count’, it took almost 10 seconds before the output was displayed on stdout and until then the shell was occupied by this process only. ie You could not perform any other operation on the same shell. Now, to trigger a process in background, add ‘&’ at the end of the command:
$ ./count &
[1] 4120

$ # Do some work on shell while the above program is working in the background

$ Counting done
The ampersand ‘&’ sign indicates that this process needs to be run as a background process. By running a background process, we can have access to the shell for doing any further operations. Like, in the output above, after running the binary ‘count’ in background, I used a couple of more commands on the same shell and when the binary ‘count’ was done with its processing, the output was thrown back on the same shell(the last line). So we can conclude that by default every process runs in foreground, receives input(if any) from keyboard and returns output to the user. While a background process is one which gets disconnected from the keyboard and user can use the same shell to do more operations.
For more information on foreground and background processes refer to: How to Manage UNIX Background Jobs

3. Types of process

So we see that process is a concept that is fundamental to an operating system. Almost every activity on an OS takes form of a process to do some stuff. There are different types of processes running on a system, some of them are :

Child processes

A process that is created by some other process during run-time. Usually child processes are created to execute some binary from within an existing process. Child processes are created using fork() system call. Normally process are made to run through shell/terminal. In that case the shell becomes the parent and the executed process becomes the child process. On Unix/Linux each process has a parent except the init process(we will learn about this later).

Daemon Processes

These are special processes that run in background. They are system related process that have no associated terminal. These processes run will root permissions and usually provide services to processes. As we already know that a daemon process does not have an attached terminal, well to achieve this the process has to be detached from the terminal. The ideal way on Linux/Unix to do this is to run a process through terminal and from within this process create another process and then terminate the parent process. Since the parent is terminated so now the child will become independent of the terminal and would be taken over by init process and hence would become a daemon process. A typical example would be a mail daemon that waits for the arrival of e-mails and notify when a mail is received.

Orphan processes

Usually a process creates a child process (as described above) and when the child process terminates, a signal is issued to the parent so that parent can do all the stuff that it is required to do when one of the child gets terminated. But there are situations when parent gets killed. In that case the child processes become orphan and then taken under by the init process. Though the init process takes the ownership of the orphan process but still these process are called as orphan as their original parents no longer exists.

Zombie process

When a child process gets terminated or completes its execution, then its entry in the process table remains until the parent process fetches the status information of the terminated child. So, until then the terminated process enters zombie state and is known as zombie process.  When a process is terminated then all the memory and resources associated with the process are released but the entry of the process in process table exists. A signal SIGCHILD is send to the parent of the process (that just terminated). Typically, the handler of this signal in the parent executes a ‘wait’ call that fetches the exit status of the terminated process and then the entry of this zombie process from the process table is also removed.

4. The init process

As we discussed earlier, init process is the 5th stage in the 6 Stage of Linux Boot Process.
You would be cognizant of the famous ‘chicken and egg’ theory regarding who came first. In terms of processes, as each process has a parent process, the same question can be asked about parent or child process. Well, fortunately there is an answer here. The answer is the init process that is started as a first process during boot sequence. That means there is no parent of init process. Lets verify it, since PID of init is ’1′, we use the ps command :
So we see from the output that PPID is 0, which means that there is no parent for this process.
$ ps -l 1
4 S     0     1     0  0  80   0 -  5952 poll_s ?          0:00 /sbin/init
Reference :

Thursday, February 9, 2012

Shell Script To Add User, Password And Add User To Sudo

Here's the Shell Script which required 2 parameters 1) UserName 2) Password.....

After setting up user name and password, script will ask you if you want to add user to Super User / Sudo or not....


if [ "$#" != "2" ]
        echo -e "\033[33m Required 2 Parameters : User Name and Password..."
        $UCOM $1
        ( echo $2; echo $2 ) | $PCOM $1

        if [ "$?" != "0" ]
                $DCOM -r $1
                echo -e "\033[35m User $1 Successfully Added To System"
                echo -e "\033[0m"

echo -e "\033[33m Do You Want To Add User to Sudoers/Super User List (y/n)"
read choice
echo -e "\033[0m"

if [ "$choice" == "y" -o "$choice" == "Y" ]
        $GCOM $1 /etc/sudoers

        if [ "$?" == "0" ]
                echo -e "\033[31m User $1 Already Added To Sudoers File"
                echo -e "\033[0m"
                echo "$1   ALL=(ALL)       ALL" | cat >> /etc/sudoers
                echo -e "\033[35m User $1 Successfully Added To Sudoers!!!"
                echo -e "\033[0m"

elif [ "$choice" == "n" -o "$choice" == "N" ]
        echo -e "\033[35m $1 User Not Added To Sudoers!!!"
        echo -e "\033[0m"
        echo -e "\033[37m Invalid Choice....User Not Added To Sudoers :-("
        echo -e "\033[0m"

That's it!!!

Please use and update your responses......waiting for your responses :)

Wednesday, January 25, 2012