Showing posts with label RHCE. Show all posts
Showing posts with label RHCE. Show all posts

Monday, July 22, 2013

Configure NTP Server in Linux

According to the Red Hat Exam Prep Guide, you need to be able to synchronize clients with a higher stratum server. The term stratum is used to define different levels, from 1 to 15, of time servers that are available to sync with. A stratum 1 time server is the most accurate. For load balancing and redundancy, you would probably want to configure a primary NTP server and a secondary NTP server to sync with a stratum 1 time server. Now let’s look more closely at both the server and client side of NTP.

Configure NTP server
Step 1. Verify that the package has been installed:
# rpm -qa | grep ntp

To configure the primary NTP server, let’s look at part of the config file that comes with the system:
#vim /etc/ntp.conf
...
server 0.rhel.pool.ntp.org
server 1.rhel.pool.ntp.org
server 2.rhel.pool.ntp.org
...
#server 127.127.1.0
#fudge 127.127.1.0 stratum 10

The first three lines shown here are the Internet (public) NTP servers that you sync with for the correct time. The fourth server option, which is usually based on the BIOS click if used.

Step 2. Start the NTP service:
# service ntpd start

Client configuration:
With the server configured, you can turn your attention over to one of the client systems. For this example, use the Client01 system to sync with the server1 (192.168.1.100) primary NTP server.

Define server1 as the primary time server and make sure the driftfile line is uncommented:
#vim /etc/ntp.conf
...
Server 192.168.1.100
driftfile /var/lib/ntp/drift


Step 1. Use iptables to create the required firewall rules:
# iptables -I INPUT  -p udp -m udp --dport 123 -j ACCEPT
# iptables -I INPUT  -p tcp -m tcp --dport 123 -j ACCEPT


Step 2. Save the firewall rules you just created:
# service iptables save

Step 3. Then restart the iptables service:
# service iptables restart
#service ntpd restart


Step 4. Specify the upstream server that you want to sync against:
# ntpdate 0.rhel.pool.ntp.org

Step 5. Start the service again:
# service ntpd start

Step 6. Verify that the time is accurate with the date command:
# date

The next troubleshooting command is ntpq, which enables you to query for other NTP servers. Here, the only concern is the -p option, which polls for other NTP servers:
# ntpq -p

Process Management in Linux


Every time a program or command is run, a process is created for it. These processes are all unique and identified by the process identification (PID).

Here are some of the process management commands you can use:
ps Displays information about running processes

kill Terminates a process 

pgrep Finds a process based on its PID

pidof Displays all processes related to a service or command

top Monitors system resources (similar to Task Manager in Windows)

renice Adjusts the priority of a particular process

1-To view processes with more detailed information, you can use the following command:
# ps u
Or you could also use following command for more detail.
# ps aux

2-What happens if any process running on your system becomes out of control? you can use the kill command to terminate the process, even if it isn’t responding.
Syntax: kill PID

To find the PID(s) belonging to the SSH service, use the following:
# pidof sshd
4286
To achieve the same information you can also use the pgrep command:
# pgrep sshd
4286
Where 4286 is pid of sshd service
To kill the process forcefully the SSH service, you can use the following:
# kill 4286

top This command gives you an overview of processes on the system, including memory usage, CPU utilization, and more. Look the output as shown in figure (top 1.0).
#top                            
                                                                              top 1.0

You can use the renice command to change priority on the CPU.
Syntax: renice <priority> [options]
Options:
-p PID Changes process priority for a particular PID
-u user Changes process priority for a particular user(s)

The priority values range from –20 (very high priority) to 20 (very low priority).
For example following command will change the priority as -2 for pid 3874.
# renice -2 3874

Using the free Command The free command allows you to display the amount of free and used memory on the system. To do so, type the following at a shell prompt:
#free
 
Using the System Monitor Tool
The Resources tab of the System Monitor tool allows you to view the current CPU usage on the system.
To start the System Monitor tool, either select Applications > System Tools >? System Monitor from the panel, or type gnome-system-monitor at a shell prompt. Then click the Resources tab to view the system's CPU usage and Memory usage, (look figure System Monitor 1.0 ).

dixitmicroit.blogspot.com
System Monitor 1.0

Job scheduling Using Crontab

Ther are two utilities that you can use to schedule a job in Linux 1- AT, 2- CRONTAB.
A-at
At utility is used to schedule a one-time task at a specific time. Before configuring at make sure that service is running and set start to boot by using following commands.
#service atd start
#chkconfig atd on


If you have any problem regarding service management click here to know more.
To schedule a one-time job for a specific time with the At utility, do the following:
Step 1. On the command line, type the command at TIME, where TIME is the time when the command is to be executed.

The TIME argument can be defined in any of the following formats:
HH:MM specifies the exact hour and minute; For example, 04:00 specifies 4:00 a.m.
midnight specifies 12:00 a.m.
noon specifies 12:00 p.m.
MONTHDAYYEAR format; For example, august 15 2013 specifies the 15th day of august in the year 2013.

Step 2. In the displayed at> prompt, define the job commands:
Type the command the job should execute and press Enter, repeat the step to provide multiple commands.
Once done, press Ctrl+D on an empty line to save task.

Exercise: Following example this will create a kamal directory on root's Desktop at 12:03 p.m.
Step 1.#at 1203
a1>mkdir /root/Desktop/kamal
at>ctl+d (to save)


To view the list of pending jobs, use the atq command.
Step 2. #atq
You can restrict the access to the at commands using the /etc/at.allow and /etc/at.deny files.
If the file at.allow exists, only users listed in the file are allowed to use at and the at.deny file is ignored.

B-Crontab.
In any operating system, it is possible to create jobs that you want to reoccur. This process, known as job
scheduling, is usually done based on user-defined jobs. For Red Hat, this process is handled by the cron service, which can be used to schedule tasks (also called jobs).

To start working with cron, you first need to look at the two config files that control access to the cron service. These two files are:
1-The /etc/cron.allow file:
 If it exists, only these users are allowed.
 If it doesn’t exist, all users except cron.deny are permitted.
2-The /etc/cron.deny file:
 If it exists and is empty, all users are allowed

You can use the crontab command to create, edit, and delete jobs.
Syntax: crontab [-u user] [option]
Options:
-e Edits the user’s crontab
-l Lists the user’s crontab
-r Deletes the user’s crontab

/etc/crontab file represent scheduled jobs and have the following format:
minute hour day month day of week username command

The following define the time when the job is to be run:
minute any integer from 0 to 59

hour  any value from 0 to 23

day  any value from 1 to 31 (must be a valid day if a month is specified)

month  any value from 1 to 12 (you can also use as jan, feb)

day of week  any value from 0 to 7, (0 or 7 Sunday) (or sun, mon)

username specifies the user under which the jobs are run

command command to be executed

Exercise1:
Step 1. Verify that the cron service is currently running:
# service crond status

Step 2. Also verify that the service is set to start when the system boots:
# chkconfig --list crond

Step 3. #vim /sample_script
#!/bin/bash
# Send a msg to all users on the console
wall “Hello World”

Save the file and set the following permissions:
# chmod 775 /sample_script

Step 4. Set up user1’s crontab:
# crontab -u user1 -e

Step 5. Add the following line:
* * * * * /sample_script
*/2 * * * * /sample_script

 Save the file and quit the editor.

Because we are using * in every field ofter 60 seconds you will see the message ”Hello World” on
your screen. In second line */2 means this will execute ofter every 2 minute.

List the current cron jobs of user01:
# crontab -u user

To remove a user’s crontab jobs, use the following command:
# crontab -u user1 -r1 -l

Configure ACL in RHEL6

ACL is extended set of permissions on files and directories that give advanced security when needed. For example you can set different permission for different user on a single file or directory. Two commands control ACLs: getfacl and setfacl. When you use the ls -l or ll command, a plus sign (+) on the side of the permission indicates ACL permission.

Step 1.  Before you can even use ACLs, however, you need to make sure that the file system has been mounted with the ACL parameter:
# mount | grep acl

If nothing is returned, it means that all currently mounted file systems do not have ACLs set up to be used. To mount the file system with the ACL option use the following command:
# mount –t ext4 -o acl,remount /dev/sda5 /data

Step 2. To verify, you can use the previous command:
# mount | grep acl
/dev/sda5 on /data type ext4 (rw,acl)

Step 3. Add the following line in your /etc/fstab file:
/dev/sda5 /data ext4 defaults,acl 1 2
Save and close the file.

Step 4. To make the changes take effect, you need to remount the file system:
# mount -o remount /data

Step 6. You can now verify that your file system has the ACL option:
# mount | grep -i acl
/dev/sda5 on /data type ext3 (rw,acl)

Exercise: To understand ACL let's look an example.
Step 1. Create a sample file (file1) on which you can test an ACL in the /data/backup directory:
#mkdir /data/backup
# cd /data/backup
#touch file1

Check default permission by using following command.
# getfacl /data/backup

Step 2. Set the test file so that user1 also has access to this file:
# setfacl -m u:user1:rwx /data/backup/file1
Where -m means modify, u means ACL for user, rwx means i want to set read, write and execute permission on user1 for file /data/backup/file1

Step 3. Now check the ACL permissions:
# getfacl /data/backup/file1

# file: file1
# owner: root
# group: root
user::rw-
user:user1:rwx
group::r--
mask::rwx
other::r--
Now login as user1 and try to modify file1 it should be modify.

Step 4. Use the setfacl command again to remove the ACL for user01:
# setfacl -x u:user1 /data/backup/file1
Notice -x is used to remove ACL.

Step 5. Verify that the ACL has been removed:
# getfacl file1
# file: file1
# owner: root
# group: root
user::rwgroup::
r--
mask:r--
other:r--

Step 6. If you have multiple ACLs set up on a single file, you can remove them all with the -b option
# setfacl -b filename

Saturday, July 20, 2013

Configure NAT in Linux


NAT stand for Network address translation that allows you to use private ip address to access public network , because NAT translate private ip address in to public ip address. This also ensure your network security from hackers by hiding your actual IP information..
dixitmicro.blogspot.com
Simple NAT LAN Setup

Use the following rule to implement NAT for the internal network to update iptable.
# iptables -t nat -I POSTROUTING -o eth0 -s 10.8.8.0/24 -j MASQUERADE
(-t means table, -o means output interface, -s means source address. I am using classless ip).
Then restart iptable servcie by using following commands.
# service iptables restart
# service iptables save

Make the following change to the kernel: to forward LAN routing.
# echo 1 > /proc/sys/net/ipv4/ip_forward
OR use persistent
#vi /etc/sysctl.conf
net.ipv4.ip_forward = 1
Where 0 means LAN routing is disabled.
Now go to Private client end and configure ip address and try to open any public site it should be open.

Configure ACL in Linux

ACL is extended set of permissions on files and directories that give advanced security when needed. For example you can set different permission for different user on a single file or directory. Two commands control ACLs: getfacl and setfacl. When you use the ls -l or ll command, a plus sign (+) on the side of the permission indicates ACL permission.

Step 1.  Before you can even use ACLs, however, you need to make sure that the file system has been mounted with the ACL parameter:
# mount | grep acl
Because nothing is returned, you know that all currently mounted file systems do not have ACLs set up to be used. To mount the file system with the ACL option use the following command:
# mount –t ext4 -o acl,remount /dev/sda5 /data

Step 2. If your file system isn’t already mounted, you could also use the following:
# mount –t ext4 -o acl /dev/sda5 /data

Step 3. To verify, you can use the previous command:
# mount | grep acl
/dev/sda5 on /data type ext4 (rw,acl)

Step 4. Add the following line in your /etc/fstab file:
#vim /etc/fstab
/dev/sda5 /data ext4 defaults,acl 1 2
Save and close the file.

Step 5. To make the changes take effect, you need to remount the file system:
# mount -o remount /data

Step 6. You can now verify that your file system has the ACL option:
# mount | grep -i acl
/dev/sda5 on /data type ext3 (rw,acl)

Exercise: Create a file and apply ACL for it
Step 1. Create a sample file on which you can test an ACL in the /data/backup directory:
# cd /data/backup
#touch file1
To Show default permission type following command.
# getfacl /data/backup/file1

Step 2. Set the ACL on that file so user1 also has access to this file: For example i want to assign full permission on /data/backup/file1 to user1
# setfacl -m u:user1:rwx /data/backup/file1

Step 3.
Now check the ACL permissions:
# getfacl /data/backup/file1
# file: file1
# owner: root
# group: root
user: rw-
user:user1:rwx
group :r--
mask: rwx
other: r--
Now login as user1 and it should be able to modify file1.
Step 4. Use the setfacl command to remove the ACL for user1:
# setfacl -x u:user1 /data/backup/file1

Step 5. Verify that the ACL has been removed:
# getfacl /data/backup/file1
# file: file1
# owner: root
# group: root
user: rw-
group: r--
mask: r--
other: r--
Now login as user1 and try to modify it should not be able to modify file1.

Step 6. If you have multiple ACLs set up on a single file, you can remove them all with the -b option
# setfacl -b filename

Grub Configuration File

GRUB has only a single config file, /boot/grub/grub.conf actually have soft links with /etc/grub.conf. When GRUB starts, it reads its configuration from the main config file. You can make changes on the command line to test different features of GRUB.
Now let’s look at the new version of the grub.conf file for RHEL6:
# cat grub.conf
default=0
timeout=5
splashimage=(hd0,0)/grub/splash.xpm.gz
hiddenmenu
title Red Hat Enterprise Linux (2.6.32-71.el6.x86_64)
root (hd0,0)
kernel /vmlinuz-2.6.32-71.el6.x86_64 ro root=/dev/mapper/vg_rhel01-lv_root
rd_LVM_LV=vg_rhel01/lv_root rd_LVM_LV=vg_rhel01/lv_swap rd_NO_LUKS rd_NO_MD
rd_NO_DM LANG=en_US.UTF-8 SYSFONT=latarcyrheb-sun16 KEYBOARDTYPE=pc
KEYTABLE=us crashkernel=auto rhgb quiet
initrd /initramfs-2.6.32-71.el6.x86_64.img

Now let's have a look the meaning of these options
default=0 means default kernel will load that is Linux, 1 means i want to load other OS or kernel if  installed
timeout=5 means you have 5 sec. to select manual options. if you want to modify kernel before booting you need to interrupt booting within 5 seconds.
splashimage= location of file that will use during booting.
title= display name of Kernel or O.S.
root(hd0,0)= where is boot partition is located in my case partition 0 on disk 0.
kernel = used kernel parameters like as encryption, RAID, LVM, language etc. Don't change any grub options until you don't know exact meaning of that otherwise you might be unable to boot system if you misconfigure any option.
Now use any file editor to modify options and reboot your system to see results. If there is any problem write to us on comment box we will try to help you.

Network Setting in RHEL6

In this blog we will look, how to configure network setup to allow system to communicate to each other.
Networking is an important factor because without it, you would not be able to communicate with your network, or share files with your users.
When you’re working with network interfaces, there are two files you need to know:
/etc/sysconfig/network :This file contains gateway and hostname information.
/etc/sysconfig/network-scripts :This directory contains all the interface config files for your system.

Let’s start by looking at the hostname and networking information:
# cat /etc/sysconfig/network
NETWORKING=yes
NETWORKING_IPV6=yes
HOSTNAME=RHEL01
The first two lines tell the system whether or not to enable networking for IPv4 and IPv6. By default, they are both enabled. The third option defines the system hostname. Each network interface has its own config file in this directory that follows the format ifcfg-ethX, where X is the number of the network card. For example,
# cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE=eth0
BOOTPROTO=dhcp
HWADDR=08:00:27:30:74:AA
ONBOOT=yes
DHCP_HOSTNAME=RHEL01
TYPE=Ethernet

DEVICE=              interface you are working with.
BOOTPROTO=    protocol in use in my case it is DHCP.
HWADDR=          MAC address of device.
ONBOOT=           interface is enable during booting.
TYPE=                  you are using Ethernet technology.

You can launch system-config-network-tui utillity to change ip address if required.
Or you can also use following command to assign static ip address.
# ifconfig eth0 172.168.1.1 netmask 255.255.255.0

To bring the interface down, use ifdown:
# ifdown eth0

To bring the interface up use ifup:
# ifup eth0

To view the current IP address of the eth0 interface, use the following command:
# ifconfig eth0

When you made any changes with your adapter do'nt forget to restart the network service:
# service network restart

Additional network commands
ping command Tests the connectivity between two hosts
example #ping -c 2 192.168.1.1

traceroute command Looks for step by step path from host to host
example #traceroute 192.168.1.1

netstat command Shows information about connections (open, closed, and listening)
exmaple #netstat -tuape |grep sshd
tcp 0 0 *:ssh *:* LISTEN root 8627 2674/sshd
If nothing is returned, there is chance that the service isn't running or listening.

route command Shows routing information
#route

When you really need to see the details of what is going you can use a packet capture utility to view data being sent across the interfaces on your machine. you can use the tcpdump utility.
# tcpdump –i eth0 –w capturefile
-i means interface
-w means write in to file (capture file is the name of file)

To review the information you've captured, call the tcpdump program again:
# tcpdump –r capturefile | less
-r means read from file

VIM editor

Many times users may need to edit a file, so there are many files editor that you can use to edit files like as nano, vi, vim, emacs, gvim, gedit etc. Vim stands for "Vi IMproved". Vim is a text editor which includes almost all the commands from vi editor and few more. Apart from the vim command, the vim packages may also provide gvim, the Gnome version of vim. vim can operate in two modes: command mode and insert mode.
The editor always starts in command mode. it is used to copy, move, replace, delete, and perform some other functions. These are some popular vi commands:

Moving commands
 h   to move the cursor to the left
 l   to move it to the right
 k   to move up
 j   to move down

Save and exit commands
:w      will save (write) the file.
:q!     forces the exit without saving.
:wq    will save and exit.
:wq!   overrides read-only permission.

Copy and paste commands
dd    will delete a lines.
dw    will delete a word.
x      will delete the character on which the cursor is positioned.
yy    will copy a whole line.
p      will paste copied data.

Search commands
/search  will perform the search any word you will put, replace serach with word that you want to search.
:num      replace num with number to go for particular line.

Insert mode is used to insert text in the file. To go insert mode press i and you will see insert message on bottom side, if you want to come back in command mode just press ESC key.
 a will append a new line.
 i will insert text on current cursor position.
 o will insert a blank line under the current cursor position.

For more information there is a built-in tool called vimtutor that can be used learn a lot, just type
#vimtutor

Understanding Runlevel

Runlevels:
When the system boots up, it queries for the default runlevel, which is defined in the /etc/inittab file. When that default runlevel is decided, the system boots into that particular runlevel. The different runlevels are essentially “states,” which allow services to be started or stopped depending on the runlevel you are using. There are total six runlevels which are shown in the /etc/inittab file.

0 Halt essentially the system is power off
1 Single-user mode is used to enter single-user mode, which you can use to perform maintenance like as reset the root user’s password.
2 Multiuser with partial services without networking.
3 Full multiuser with networking (text mode)
4 Not used
5 Full multiuser graphical mode (provides a GUI desktop login)
6 Reboot

Runlevel Utilities
Let’s now look at the many system utilities that help you manage the system in different runlevels.
1- shutdown     Brings the system to a powered-off state or can reboot the system
2- halt         Powers down the system
3- reboot       Reboots the system
4- poweroff     Works the same as the halt command
5- chkconfig    Manages what runlevels services start and stop at
6- runlevel     Displays the current and previous runlevels
7- init         Changes runlevels
8- ntsysv       Works similarly to chkconfig in that it is a menu-driven service management utility

Let's look some examples:
# shutdown -h now
 complete power off,
# shutdown -r now
reboot the system
# shutdown -h 120
As a final example, delay the shutdown by 2 minutes:

You can also change the current runlevel you’re in by using the init command.
Step 1. Check the runlevel you’re in:
# runlevel
N 5
According to output you can see you are working on runlevel 5.
As an alternative, you can also use the who command to produce the same results:
# who -r
run-level 5 2010-09-05 09:45 last=S
Step 2. Because you are in runlevel 5, change over to runlevel 3:
# init 3
Now you will switch from runlevel 5 to runlevel 3.

Breaking root Password in RHEL6

Some time you may need to recover your root password if you forget this, it is very simple to break root
password in linux. use the following steps to break root password.

Breaking root password:
1- reboot your system.
2- When system ask to select OS press any key to interrupt default OS selection.
3- press ‘e’ to edit kernel parameter before booting.
4- Choose the second option ‘Kernel/vmlinuz-2.6.i8, again press ‘e’.
5- Type ‘1’ at the lend of the line to go in single user mode.
6- Then press ESC key to return back and then press ‘b’ to boot system.
7- Now system will reboot and start with single user mode prompt.
8- Here type sh3.2# passwd -d root  then press enter this will remove password for root user.
10-Now reboot your system and you will be able to login without password where you can change password for root.
But people says that linux is highly secure but how when anyone can break password as so easy.
Oh dear linux is really secure but you need to do some security configuration. In next section we will learn how to protect grub from being modify. Now if you will try to break root password you need to know grub password.

Grub Security (set password on grub after installation):
1-Open terminal and type following command to generate md5 encrypted password
# grub-md5-crypt
Password:
Confirm password:
(Here you will see encrypted code, copy this carefully no any extra character like as space).
2-Now edit grub.conf file with any editor.
# vim /boot/grub/grub.conf
Here you will see a lot of option go to under "hiddenmenu" and type following syntax
Password --md5 paste encrypted password that you have copied
3-Save this file.
4-Reboot your system and try to modify grub to break root password, it will prompt for grub password.
Now your root password is protected.

Configure RAID in RHEL6

Redundant Array of Inexpensive Disk:
RAID Disk partitions technology that allow more advanced features such as redundancy and better performance. This technology is usually used on server based storage where a large amount of storage required with fault tolerance. Before we describe how to implement RAID, let’s look at the different types of RAID Levels: There are many types of RAID Levels but right now i am going to describe only those that are required for RHCE exam preparation:

A- RAID 0 (Striping): disks are grouped together to form one large drive. This offers better performance at the cost of availability. If any single disk in the RAID fail, the entire set of disks becomes unusable. It require minimum two disks. For eaxample suppose you have two disks wtih 50GB in size, you can combine both to treat as a single disk to achieve 100Gb space.

B- RAID 1 (Mirroring): disks are copied from one to another, allowing for redundancy. If one disk fail, the other disk takes over, having an exact copy of data from the original disk but here is slow write speed. Two disk minimum.

C- RAID 5 (Striping with parity): disks are similar to RAID 0 and are join together to form one large drive. The difference here is that 25% of the disk is used for a parity bit, which allows the disks to be recovered if a single disk fail. RAID 5 require minimum three disks.
While RAID can be implemented at the hardware level, the Red Hat exams are not hardware based and therefore focus on the software implementation of RAID. Next, let’s use the three free disk drives (hdb, hdc, and hdd) to set up a RAID array.

Step 1. Install the following package:
# yum install -y mdadm

Step 2. Verify the install:
# rpm -qa | grep mdadm
mdadm-3.1.3-1.el6.x86_64
Now we are going to start with a RAID 5 setup, so you need to make partitions on at least three different disks. You can use the mdadm command to create any RAID array.
Syntax: mdadm [options]

Options:
-a  Adds a disk into a current array.
-C --create Creates a new RAID array.
-D --detail Prints the details of an array.
-f   Fails a disk in the array.
-l --level Specifies level (type) of RAID array to create.
-n --raid-devices Specifies the devices in the RAID array.
-S --stop Stops an array.
-v --verbose Provides verbose output.

Step 3. You can use the following command to create a new RAID array (/dev/md0), which is a RAID 5, and it contains three disks:
# mdadm -Cv /dev/md0 —level=5 -n3 /dev/sda6 /dev/sda7 /dev/sda8
mdadm: Defaulting to version 1.2 metadata
mdadm: array /dev/md0 started.

Step 4. Use the mdadm command again to verify that the RAID array has been created successfully:
# mdadm –D /dev/md0
/dev/md0:
Version : 1.2
Creation Time : Thu jul 27 14:09:23 2013
Raid Level : raid5
Array Size : 16769024 (15.99 GiB 17.17 GB)
Used Dev Size : 8384512 (8.00 GiB 8.59 GB)
Raid Devices : 3
Total Devices : 3

Step 5. View the status of the newly created RAID array:
# cat /proc/mdstat

What to Do When a Disk Fails:
Suppose that a disk in the array failed. In that case, you need to remove that disk from the array and replace it with a working one.

Step 1. To fail a disk in the array, use this command:
# mdadm /dev/md0 -f /dev/sda6
mdadm: set /dev/sda6 faulty in /dev/md0
Step 2. Verify that the disk in the array has failed by looking at the details of the RAID array:
# mdadm -D /dev/md0
Number Major Minor RaidDevice State
0 8 17 0 active sync /dev/sda7
1 8 33 1 active sync /dev/sda8
2 0 0 2 removed
3 8 49 - faulty spare
/dev/sda6

Now that you know that the disk has failed, you need to remove it from the array so it can be replaced.
Step 3. To remove a disk from the array, use this command:
# mdadm /dev/md0 -r /dev/sda6
mdadm: hot removed /dev/sda6 from /dev/md0

Step 4. Look at the last few lines of the RAID details again:
# mdadm -D /dev/md0
/dev/md0:
Number Major Minor RaidDevice State
0 8 17 0 active sync /dev/sda7
1 8 33 1 active sync /dev/sda8
2 0 0 2 removed
You can see from the last line of the output that the disk has been “removed.”

Step 5. When the disk is partitioned, you can add it back to the array as follows:
# mdadm /dev/md0 -a /dev/sda6
mdadm: re-added /dev/sda6
Step 6. Verify that it has been added properly:
# mdadm -D /dev/md0
/dev/md0:
Number Major Minor RaidDevice State
0 8 17 0 active sync /dev/sda7
1 8 33 1 active sync /dev/sda8
3 8 49 2 spare rebuilding /dev/sda6
Note: Notice that the state of the drive is “rebuilding" it may take approx 2 minute to rebuid please wait and verify again.

Deleting a RAID Array
:
Now that you have successfully implemented a RAID array, you can take it apart by deleting the array.
Step 1. To delete an array, first stop it:
# mdadm -vS /dev/md0
mdadm: stopped /dev/md0
Step 2. Then remove the RAID array device:
# mdadm --remove /dev/md0

Configure Quota in Linux

Quota is a feature that allow you to set specific limit for specific user or group on particular disk partition. There are two types of limits A-soft limit: when user exceed their soft limit a warning appear but user is allowed to store data. B-Hard limit when exceed hard limit user is not allowed to store data beyond this limit.
For a working example, you can configure quotas on the /companydata file system so that you can limit the amount of data that users can store in this directory.

Follow these steps to apply quota.
You need to install the required packages before you can use quotas on your system.
To install the quota package, use the following:
# yum install – y quota

Verify that the package is installed successfully:
# rpm -qa | grep quota
quota-3.17-10.el6.x86_64

Although Red Hat supports quotas in the kernel by default but you can verify quota support from the kernel with the following command:
# grep -i config_quota /boot/config-`uname -r`
CONFIG_QUOTA=y
CONFIG_QUOTACTL=y
y means that the kernel support quotas.
After verifying that the package is installed and that the kernel does support quotas, you can start configuring Quota.

To start setting up quotas, let’s look at some of the commands:
quotaon    Turns on quota tracking
quotaoff   Turns off quota tracking
edquota    Edits the settings of a user’s quota
quota       Allows each user to see his disk consumption
repquota   Generates a report of quota usage
quotacheck Initializes a quota database

Configure quota
You first need to edit the /etc/fstab file to specify which file systems you want to utilize quotas. You can
apply quota limit for users, groups, or both.

Step 1. In the /etc/fstab file, edit the following line:
For example if i want to apply quota on /dev/sda5 partition which is mounted on /companydata and filesystem uses as ext4.

#vim /etc/fstab
/dev/sda5 /companydata ext4 defaults,usrquota,grpquota 1 2
Save and close the file.

Step 2. You now need to remount the /companydata file system before the changes take effect.
# mount -o remount /companydata

There are two files that maintain quotas for users and groups:
aquota.users User quota file
aquota.group Group quota file

To start the quota system, you use the quotacheck command.
Syntax: quotacheck [options] <partition>
-c Don’t read existing quota files
-u Checks user quotas
-g Checks group quotas
-m Doesn’t remount the file system as read-only

Step 3. Create the quota files:
# quotacheck -ugm /companydata/

Step 4. Verify that the quota files were created successfully:
# ls /companydata/
aquota.group aquota.user lost+found

Step 5. Run the command manually the first time just to make sure that quotas are turned on:
# quotaon -v /companydata/

Step 6. Now set the limit with edquota command
Syntax: edquota [-u | -g] [username | groupname]
Change the line for the /dev/sda5 file system to look like the following:
# edquota -u kamal
Disk quotas for user kamal (uid 502):
Filesystem     blocks   soft    hard   inodes soft hard
/dev/sda5       0       2000   2500   0       0   0
(where 2000 is soft limit and 2500 is hard limit in KB)
Save your changes and close the file.

Step 7. Login as kamal user and create some files and directories, Use the repquota command to verify uses quota limit.
# repquota -uv /companydata/

Manage Services in Linux

Service Management
On any system it is important to manage the running services. Managing services enables you to stop, start, restart services whenever needed. In Linux, services can also be called daemons that's why most of the services end with a "d" such as sshd, httpd, dhcpd, vsftpd etc.

TO manage services at each runlevel, you can use the chkconfig command.
Syntax: chkconfig [option] service_name.
Options that you can use:

--list [name] Shows the status of the service at each runlevel.
--level <levels> Enables or disables the service at the given levels.
 <service_name>  <on|off|

Step 1. To check the status of the sshd service use following command:
# chkconfig --list sshd
sshd 0:off 1:off 2:on 3:on 4:on 5:on 6:off
According to output you can understand the sshd service will be started at runlevels 2, 3, 4, and 5. It will be stopped at runlevels 0, 1, and 6.

Step 2. Use the off option to disable the service at boot.:
# chkconfig sshd off

Step 4. Re-enable the SSH service:
# chkconfig sshd on
Aside from using the chkconfig command, you can do the same task by using the ntsysv command.
#ntsysv
And you will see a menu-driven window where you can manage services.

You can also use the service command. You can use this to start, stop, and query the status of services.
Step 1. Usually, it is a good idea to always check the status of the service first:
# service ntpd status
ntpd is stopped

Step 2. When you know that the service is stopped, you can start it:
# service ntpd start
Starting ntpd: [ OK ]

Step 3. Stop the NTP service:
# service ntpd stop
Shutting down ntpd: [ OK ]

Step4. To restart the sshd service
# service sshd restart

Linux Booting Process

Booting is an important process of any operating system, you should know how this process began. When a computer start up booting process began in following sequence.

1-The BIOS is the first program that is run. After it is loaded,

2-The BIOS begins to test the system through the Power On Self Test (POST) and then starts loading peripheral devices.

3-The BIOS then looks for the boot device and passes control to it.

4-The boot device contains the master boot record (MBR), which starts to boot the system via the bootloader.

5-The Grand Unified Bootloader has become the default bootloader for Red Hat, Ubuntu, and many other versions of Linux

6-When GRUB loads, you are given a list of kernels and additional operating systems (if available) from which you can choose to boot. By default, there is a configurable 5-second timeout value that chooses the default kernel if you don’t select manually.

7-After GRUB loads the kernel, it passes control over to the kernel, which in turn begins to initialize and configure the computer’s hardware. During the boot process, everything is logged to the /var/log/dmesg file.

8-When the required system’s drivers are in place, the kernel executes the /sbin/init program.

9-The init program is the first process created by the kernel. It is responsible for the rest of the boot process and setting up the environment for the user.

10-Finally now you can login in your system.

The above section described the boot process and how it works. The first part of that process deals with the bootloader, GRUB. In this section, we look at GRUB and its role in the boot process more in depth.
The GRUB bootloader is broken down into different stages. The code contained on the master boot record (MBR) is considered GRUB stage 1. It loads GRUB stage 1.5, which tries to identify the file system type (optional), or it can call GRUB stage 2 directly. Stage 2 calls the kernel and loads it into memory. In stage 1, GRUB needs to search the MBR looking for an active partition from which to boot the kernel. GRUB has its own format for looking through hard disks.
The syntax of this format is:
(xdn[,m]) where xd is the drive, n is the number of the disk, and m denotes the partition number. As stage 2 starts, it presents you with a list of kernels along with a listing of options that you can use to modify the parameters passed to the kernel during boot up. Now let’s look at how to edit those entries:

Grub Boot Options:
e Edit the commands before booting
a Modify or append the kernel arguments before booting
c Open the GRUB command line

You can use the a option to modify any parameters you want to pass to the kernel. This includes changing the runlevel that the system will boot.
Here are the different modes that you can boot into:
Single-User Mode Used to perform maintenance tasks such as forget the root password
Runlevel 2 or 3 Used to load only partial services during the boot process
Emergency Mode Used to perform tasks on an unbootable system
Rescue Mode Used to fix boot issues and reinstall GRUB

Wednesday, July 17, 2013

Repaire Grub in RHEL6

GRUB Repaire in Linux

The GRUB Is Corrupt



                                                      
If you are having trouble booting the system and you have determined that the master boot record (MBR) is corrupt, you need to boot into rescue mode. Use the RedHat DVD, boot from it, and choose the option to enter rescue mode and you will be redirected on shell prompt where you can perform repair task. Before repair grub i will recommend to you that please read my grub section to understand about grub and its functions.

Step 1. After you boot, when you see prompt enter the GRUB shell:
# grub
Probing devices to guess BIOS drives. This may take a long time. completions of a device/filename. Now you will redirect on following prompt.
grub>

Step 2. Locate the root drive by using following command:
grub> root
(hd0,0): Filesystem type is unknown, partition type 0x8e

Step 3. Reinstall the MBR from the GRUB shell: use following command to reinstall grub.
grub> setup (hd0)
Checking if “/boot/grub/stage1” exists... no
Checking if “/grub/stage1” exists... yes
Checking if “/grub/stage2” exists... yes
Checking if “/grub/e2fs_stage1_5” exists... yes
Running “embed /grub/e2fs_stage1_5 (hd0)”... 26 sectors are embedded.
Running “install /grub/stage1 (hd0) (hd0)1+26 p (hd0,0)/grub/stage2
/grub/grub.conf”... succeeded
Done.
Here you can see grub has been successfully reinstalled.
Step 4. Reboot the system to validate that the system boots properly:
# reboot

Configure DHCP in RHEL6

Configure DHCP in RHEL6

Dynamic Host Configuration Protocol (DHCP) is a network protocol that automatically assigns TCP/IP information (including the IP address, gateway, and DNS servers) to client machines.


DHCP is also useful if an administrator wants to change the IP addresses of a large number of systems. Instead of reconfiguringall the systems, he can just edit one DHCP configuration file on the server for the new set of IP addresses.

Configuring a DHCP Server
First, install the package as the superuser:
# yum install dhcp
The sample configuration file can be found at /usr/share/doc/dhcp-<version>/dhcpd.conf.sample. You can copy this sample file over /etc/dhcp/dhcpd.conf, and then make changes according to your network need.
#cp /usr/share/doc/dhcp-<version>/dhcpd.conf.sample /etc/dhcp/dhcpd.conf

#vim /etc/dhcp/dhcpd.conf


#lease time setting

default-lease-time 600;
max-lease-time 7200;

#Subnet declaration

#The routers, subnet-mask, domain-search, and domainname-servers, options are used for any host statements declared below it. Additionally, a subnet can be declared, a subnet declaration must be in range of your  server ip range. If it is not, the DHCP server fails to start
.
subnet 192.168.1.0 netmask 255.255.255.0 {
option routers             192.168.1.254;
option subnet-mask         255.255.255.0;
option domain-name-servers 192.168.1.1;
range 192.168.1.10 192.168.1.100;

#Static IP address using DHCP if you want to fix an ip for particular system

host kamal {
hardware ethernet 00:A0:78:8E:9E:AA;
fixed-address 192.168.1.4;
}

#now save and exit file

#service dhcpd restart
#chkconfig dhcpd on


Configuring a DHCP Client

#vim /etc/sysconfig/network-scripts/ifcfg-eth0
#file should contain the following lines:

DEVICE=eth0
BOOTPROTO=dhcp
ONBOOT=yes
save and exit
#service network restart

it will try to obtain ip from dhcp server
#ifconfig    (to verify)

Configure NFS Server in RHEL6




The Network File Systems (NFS) protocol works great when it comes to Linux systems because it allows for client flexibility, centralized management of files, and some other great features.


To configure NFS

A-Installing Packages.
# yum install -y nfs-utils nfs4-acl-tools

Important configuration files:

/etc/sysconfig/nfs            Contains the main config files for the NFS service

/etc/exports                     Contains a list of resources that will be exported to
                                         clients
/var/lib/nfs/etab               Contains a list of currently exported resources

/var/lib/nfs/rmtab             Contains a list of remotely mounted resources
------------------------------------------------------------------------------------------------------
Now add data that you want to share on the network and set other options.
The syntax of the /etc/exports file is
<mountpoint>  <host><permissions/options>
# vim /etc/exports
/sharedata *.*(rw,sync)

It means i want to share my /sharedata directory to any network with read and write permissoin along with sychronization enabled.

Now restart and on required services
# service nfs restart
# service rpcbind restart
# service xinetd restart
# service nfslock start

# chkconfig nfs on
# chkconfig nfslock on
# chkconfig rpcbind on

Here is what a manual export of resources would look like:
# exportfs -avr
exporting *:/home

This command is used to verify that all the parts of the NFS service are running properly.
#rpcinfo -p    

Use iptables to create the additional firewall rules:
# iptables -I INPUT  -p tcp -m tcp --dport 2049 -j ACCEPT
# getsebool -a | grep nfs

Troubleshooting NFS commands:
#mountstats             Shows information about mounted NFS shares
#nfsstat                   Shows statistics of exported resources
#nfsiostat                Shows statistics of NFS mounted shares

View exported resources (whether or not they are mounted):
# cat /var/lib/nfs/etab

Connect from client
# yum install -y nfs-utils nfs4-acl-tools
# chkconfig rpcbind on

# mount –t nfs 172.168.1.1:/shareddata /mnt/mountpoint
#cd /mnt/mountpoint
#ls
Here you will see file that you have shared through nfs.

Configure SAMBA Server in RHEL6





Samba
Samba, which uses the CIFS/SMB protocol, is commonly brought up when you want Linux and Windows machines to be able to share files together.


Step 1. Install the required packages for Samba:
# yum install –y samba samba-common samba-client

Step 2. You need to edit the main config file to set up the Samba server
and directories that you’d like to make into Samba shares.

#vim /etc/samba/smb.conf

### Samba Share for Company Data ###
[company_data]

### Define a comment for the share ###
comment = Directory for all employees within the company

### Allow users to access the share and define its location ###
browseable = yes
path = /opt/company_data

### Make the share writable and define access for valid users ###
valid users = kamal
writable = yes

Step 3. Save the file and exit.

Step 4. Check the syntax of the config file:

# testparm
Load smb config files from /etc/samba/smb.conf
Processing section “[company_data]”
Loaded services file OK.

[company_data]
comment = Directory for all employees within the company
path = /opt/company_data
valid users = kamal
read only = No

Create your first Samba user and enable it.
# smbpasswd -a kamal
New SMB password:
Retype new SMB password:
Added user kamal.

# smbpasswd -e kamal


Step 5. If you haven’t done so already, start the Samba service:
# service smb start
Starting SMB services: [ OK ]

Step 6. SELinux and Firewall Configuration
If you are accustomed to Windows systems, you should already know what ports
you need to open on the firewall.

# iptables -I INPUT  -p tcp -m tcp --dport 137 -j ACCEPT
# iptables -I INPUT  -p udp -m udp --dport 138 -j ACCEPT
# iptables -I INPUT  -p udp -m udp --dport 139 -j ACCEPT
# iptables -I INPUT  -p tcp -m tcp --dport 445 -j ACCEPT

# service iptables save

# service iptables restart

# service smb restart

now go on windows system and open run then type \\sambaserverip

it will ask for user/password type and enjoy?????

Configure Apache in RHEL6




The most commonly used web server in the world today is Apache and with good reason.  Built with security in mind, Apache is a solid and stable web server that has been around for years.


There is also an option to use the SSL protocol, making websites safe and secure.

Step 1. Install the two required packages:
        # yum install –y httpd mod_ssl

During the installation, a directory (/var/www) is created with a set of subdirectories. This directory tree is the place where you store your websites. There are also a few config files to look at:

/etc/httpd/conf/httpd.conf     Main config file
/var/log/httpd                      Log file directory for the web server

Step 2.
make sure that the service is set to start when the system boots:
# chkconfig httpd on

Step 3.
Here are some common options for the configuration file

#vim /etc/httpd/conf/httpd.conf

ServerRoot          Defines where the config files are held
Timeout               Specifies the time before a request times out (120 seconds
                            is the default)
Listen                  Indicates the port number to listen on (default is 80)
DocumentRoot    Defines where the website files are located
ServerName        Defines a server name or IP address and port number

ofter making changes save and exit

Test the config file:
# service httpd configtest

Use iptables to create the additional firewall rules:

# iptables -I INPUT  -p tcp -m tcp --dport 80 -j ACCEPT
# service iptables save
# service iptables restart

change SElinux if required

#service httpd restart

To access:
----------
Install the required package:
# yum install -y elinks
# elinks 192.168.100 (welcome page should we display).
==========================================================================

Apache security  

1- host-based authentication

You use the Listen option to define an IP address and a port for incoming request.listen 192.168.1.100:80 (if your server have multiple ip and you want assign single ip)

In the <Directory> section, let’s set up Allow from and Deny from options.

#Allow all hosts to connect:
Allow from all

#To allow only a specific IP or host, use the following:
Allow from 172.168.1.2

#You can also specify a domain:
Allow from .example.com

#The deny options work in the same manner. To deny from a whole subnet,
 use the following:
Deny from 192.168.1
--------------------------------------------------------------------------------------------------------------
2- user-based autentication

Define the following under the main server section in the config file:

<Directory “/var/www/html”>

AuthType           Basic
AuthName         “Password Restricted Area”
AuthUserFile      /etc/httpd/userfile
Require user      kamal

</Directory

AuthType           Defines the authentication type
AuthName         Adds a comment for the user to see on login
AuthUserFile     Specifies the file used to define username and password
Require             Specifies the users or groups that can log in

Create the sole user who will need access to this site:
# htpasswd -cm /etc/httpd/userfile kamal
-c    create new file
-m    generate MD5 encrypted password
#service httpd restart

Try to open website it should prompt for password