Pages

Friday, November 14, 2014

HP Smart Array RAID status on CentOS

(1) You can download the rpm from here:

 wget ftp://ftp.hp.com/pub/softlib2/software1/pubsw-linux/p1257348637/v71527/hpacucli-9.10-22.0.x86_64.rpm

Check the controller status
-----------------------------
#hpacucli controller all show status

Check the logical drive
------------------------
#hpacucli controller slot=0 logicaldrive all show status

Check the physical drives
--------------------------
hpacucli controller slot=0 physicaldrive all show status


Adaptec Raid Monitoring


You can download the source from here

http://download.adaptec.com/raid/storage_manager/asm_linux_x64_v7_31_18856.tgz

/usr/StorMan/arcconf getconfig 1


/opt/adaptec-monitor.pl
===================
#!/usr/bin/perl -w
# adaptec-monitor.sh - Monitors Adaptec Hardware RAID

use strict;
open(my $arcout, "/usr/StorMan/arcconf getconfig 1|") or die $!;
my @arcout;
while(<$arcout>) {
chomp;
push(@arcout,$_);

}
close($arcout);

my $cont_trouble;
my %disk_trouble;
my $disk_number;

for(@arcout) {
if(/Status of logical device\s+:\s+(Degraded|Missing|SMART-ERROR|Offline|Warning|Critical|Bad|Unknown|Device-Error)/) {
$cont_trouble = $1;
}
if(/Device #(\d+)/) {
$disk_number = $1;
}
if (/State\s+:\s+(Degraded|Missing|SMART-ERROR|Offline|Warning|Critical|Bad|Unknown|Device-Error)/) {
$disk_trouble{ $disk_number } = $1;
}
}

if($cont_trouble) {
&mailit($cont_trouble);
}

while ( my ($key, $value) = each(%disk_trouble) ) {
&mailit($key,$value);
}

sub mailit {

my $title='RAID Issue!';
my $to='<email_id>';
my $from= 'root@server';
my $subject='RAID issue detected on hostname';

open(MAIL, "|/usr/sbin/sendmail -t");

## Mail Header
print MAIL "To: $to\n";
print MAIL "From: $from\n";
print MAIL "Subject: $subject\n\n";
## Mail Body
if ($_[1]) {
print MAIL "Disk Status: #$_[0]: $_[1]\n";
}
else { print MAIL "Controller Status: $_[0]\n" }
close(MAIL);

}


[root@op1 backup]# crontab -l
* */1 * * * /usr/bin/perl /opt/adaptec-monitor.pl

ARP

Current arp cache
==============
root@server [~]# arp -n
Address      HWtype  HWaddress           Flags Mask  Iface
70.167.140.1 ether   00:00:0C:9F:F0:04   C           eth0

Clearing arp cache with verbose
======================
root@server [~]# ip -s -s neigh flush all
70.167.140.1 dev eth0 lladdr 00:00:0c:9f:f0:04 ref 42 used 17/0/65 REACHABLE
*** Round 1, deleting 1 entries ***
70.167.140.1 dev eth0  ref 42 used 0/0/0 INCOMPLETE
*** Round 2, deleting 1 entries ***
*** Flush is complete after 2 rounds ***

Current entries
============
root@server [~]# arp -n
Address      HWtype  HWaddress           Flags Mask  Iface
69.167.140.1 ether   00:00:0C:9F:F0:04   C           eth0

Delete specific arp entries
==================
root@server [~]# arp -d 192.168.1.1
root@server [~]# arp -d 192.168.1.2

Add a static arp entry
===================
root@server [~]# arp -s 192.168.1.10 00:00:93:12:04:57

Saturday, July 12, 2014

WP-Login Mod security Rule


(1)Compile apache to enable mod_security

(2)Make sure SecDataDir is present.

(3)If you do not have a SecDataDir anywhere then add it and also create the directory, for example:

mkdir /usr/local/apache/logs/modsec
chown root:nobody /usr/local/apache/logs/modsec
----------------------------------------------------------------------
root@server [/usr/local/apache/conf]# cat /usr/local/apache/conf/modsec2.conf | grep SecDataDir
SecDataDir /usr/local/apache/logs/modsec 
root@server [/usr/local/apache/conf]# 
-------------------------------------------------------------------

(4)Add the rule in a seperate file as follows.
-------------------------------------------------------------------

root@server [/usr/local/apache/conf]# cat modsec2.wplogin.conf
<LocationMatch "/wp-login.php">
SecAction initcol:ip=%{REMOTE_ADDR},pass,nolog,id:313371
SecAction "phase:5,deprecatevar:ip.counter=3/30,pass,nolog,id:313372"
SecRule IP:COUNTER "@gt 1" "phase:2,pause:3000,deny,status:406,setenv:RATELIMITED,skip:1,log,id:313373"
SecAction "phase:2,pass,setvar:ip.counter=+1,nolog,id:313374"
</LocationMatch> 
root@server [/usr/local/apache/conf]# 
-------------------------------------------------------------------
(5) Add the Include file accordingly as follows.
----------------------------------------------------------------
[root@server/usr/local/apache/conf]# cat modsec2.conf | grep Include
Include "/usr/local/apache/conf/modsec2.user.conf"
Include "/usr/local/apache/conf/modsec2.wplogin.conf"
[root@server/usr/local/apache/conf]#
---------------------------------------------------------------
(6)Make sure that following ErrorDocument is existing
[root@mserver]# cat /usr/local/apache/conf/includes/errordocument.conf | grep 406
# 406 - Not Acceptable
ErrorDocument 406 /406.shtml
[root@server/usr/local/apache/conf]# 
--------------------------------------------------------------


exclude few IPs from the rule
---------------------------------
root@server [/usr/local/apache/conf]# cat modsec2.wplogin.conf
<LocationMatch "/wp-login.php">
SecAction initcol:ip=%{REMOTE_ADDR},pass,nolog,id:313371
SecRule  REMOTE_ADDR  "@pmFromFile /usr/local/apache/conf/whitlist.txt"  "nolog,allow,id:313372"
SecAction "phase:5,deprecatevar:ip.counter=3/30,pass,nolog,id:313372"
SecRule IP:COUNTER "@gt 1" "phase:2,pause:3000,deny,status:406,setenv:RATELIMITED,skip:1,log,id:313373"
SecAction "phase:2,pass,setvar:ip.counter=+1,nolog,id:313374"
</LocationMatch> 
root@server [/usr/local/apache/conf]# 
-----------------------------------

Monday, July 7, 2014

Yum update notification script

#!/bin/bash
EMAIL="naven@domain.com"
rm -f /tmp/alert
tail /var/log/yum.log > /tmp/alert
diff /opt/orig /tmp/alert
if [ $? -ne 0 ]; then
#Send alert email
echo "please check /var/log/yum.log"| /bin/mail -s "Packages update notification from `hostname` -- ( IP- Addess )" ${EMAIL}
tail /var/log/yum.log > /opt/orig
fi

OpenVZ - Reverse path filtering (rp_filter ) - sysctl.conf


I have changed rp_filter (Reverse path filtering ) to loose mode (rp_filter = 2) on the hardware node. I belive that this has fixed the intermittent network connection loss in the VM's.

####syct entries###
net.netfilter.nf_conntrack_max = 196608
net.nf_conntrack_max = 196608
net.ipv4.conf.default.rp_filter = 2
net.ipv4.conf.all.rp_filter = 2

Grubs Batch Feature

In grub.conf you have default= yeah,  where you specify which kernel is booted. leave this set to a kernel that you know is good and working. then to test a new kernel, you can tell grub to try that kernel only once with this command before you reboot

echo "savedefault --default=0 --once" | grub --batch


 if the server hangs, get the customer to reboot the server and it will then go back to the good kernel from grub.conf

Reduce the disk space/shrink the LVM in an Linux HVM using kpartx

kpartx -av /dev/vg_67/vm102_img

It will then say something about mapping the partition, and will probably create this:
/dev/vg_67/vm102_img1

This relates to that one partition.

now you can do
e2fsck -f -y /dev/vg_67/vm102_img1
resize2fs /dev/vg_67/vm102_img1 24G

then disable kpartx on the lv

kpartx -d /dev/vg_67/vm102_img

now lvreduce to 25G

lvrdeuce -L 25G /dev/vg_67/vm102_img

then you can use kpartx once more to increase the partition to fill the LV, just resize2fs /path you dont need to specify a size.

resize2fs /dev/vg_67/vm102_img

Permanent Change of the Time Zone on a Node/Server



First, make a backup of the existing localtime file.

mv /etc/localtime /etc/localtime.bak
Next, create the link:

ln -s /usr/share/zoneinfo/Europe/London /etc/localtime

Now you just need to test your change. Run “date” from the command line, and ensure that the appropriate time, date, and timezone are reported.

The settings will be reverted, if we haven't made the below change.

You need to edit the file /etc/sysconfig/clock and add the entry ZONE="Europe/London" and save the file.

Sunday, July 6, 2014

Xen: Create bridge manually with the bond0

ifcfg-eth0

DEVICE=eth0
BOOTPROTO=none
ONBOOT=yes
MASTER=bond0
SLAVE=yes
ISALIAS=no

ifcfg-eth1

DEVICE=eth1
BOOTPROTO=none
ONBOOT=yes
MASTER=bond0
SLAVE=yes
ISALIAS=no

ifcfg-eth1

DEVICE=bond0
BOOTPROTO=none
BONDING_OPTS="mode=1 miimon=100"
ONBOOT=yes
BRIDGE=xenbr0

ifcfg-xenbr0

DEVICE=xenbr0
BOOTPROTO=static
IPADDR=x.x.x.x
NETMASK=x.x.x.x
ONBOOT=yes
TYPE=bridge

vi /etc/xen/xend-config.sxp
Comment out ALL (network-script network-bridge)

service xend restart
service network restart

Sunday, June 15, 2014

HDD Health Check Alert


Physical Disk with Smartctl
---------------------------------------

for i in `lshw -class disk -class tape | grep "logical name" | cut -d: -f2`; do echo Disk $i ; echo "=========================================" ;smartctl --all $i | grep 'Status\|Drive' ; echo " "; done > /tmp/output.txt
mail -s "HDD Health Check Alert: `hostname`" user@domain.com  < /tmp/output.txt
rm -f /tmp/output.txt

With MegaRaid Controller
---------------------------------------

for i in `/opt/MegaRAID/MegaCli/MegaCli64 -PDlist -a0|grep Device.Id | awk '{print $3}'` ; do echo Device $i ; smartctl -a -d sat+megaraid,$i /dev/sda|grep 'PASSED\|Reallocated_Sector_Ct\|Temperature_Celsius'; echo " "; done > /tmp/output.txt
mail -s "HDD Health Check Alert: `hostname`" user@domain.com < /tmp/output.txt
rm -f /tmp/output.txt

Saturday, June 14, 2014

Commandline fix for the Wordpress DB Connection error


Run the below command from your wordpress installation folder.

for i in `find -iname wp-config.php` ; do j=$(grep 'DB_NAME' $i | awk -F "'" '{print $4}') ; k=$(grep 'DB_USER' $i | awk -F "'" '{print $4}') ;l=$(grep 'DB_PASSWORD' $i | awk -F "'" '{print $4}') ; echo GRANT ALL PRIVILEGES ON $j.* TO $k@"localhost" identified by "'$l'"";" ; done

Wednesday, June 11, 2014

Script to block IP address which has more connection to the port 80


###This will block the IP which has more than 50 connection to the port 80#####
netstat -anpl | awk '{print $5}'| grep :80 | grep -v [a-z] | cut -d : -f1 | sort -n | uniq -c | sort -n | tail -5 | awk '($1>50){print $2}' > /tmp/iplist.txt
ip_address="<server_IP>"
for i in `cat /tmp/iplist.txt`; do
if [ $i != $ip_address ]
then
iptables -A INPUT -s $i -j DROP
iptables -A FORWARD -s $i -j DROP
netstat -anp | grep $i | awk '{print $7}' | cut -d \/ -f1 | grep -oE "[[:digit:]]{1,}" | xargs kill
fi
done
service iptables save;
rm -f /tmp/iplist.txt

Tuesday, May 13, 2014

Multiple subnets on a single ethernet interface under OpenVZ

You can't simply install OpenVZ and configure your containers to use IP addresses on either block.  By default, OpenVZ will not broadcast ARP packets for IP blocks that it doesn't have a venet interface for - even though you may be bridging your containers to your ethernet device.

Fix:
Edit your /etc/vz/vz.conf file and change the 'NEIGHBOUR_DEVS=detect' to 'NEIGHBOUR_DEVS=all', save and reboot and everything should work beautifully.

Monday, May 12, 2014

Postfix Virtual mailbox for a user

(1) Create a system user and set password.
Here it is: linux

(2) Install postfix

#yum install postfix

(3) Made the following changes in the postfix configuration

mydestination = $myhostname, $mydomain, example.com
virtual_alias_maps = hash:/etc/postfix/virtual

(4) Specify the virtual mailbox in the file.

root@server]#tail -2 /etc/postfix/virtual

mail@example.com linux
                                                                    VIRTUAL(5)
[root@server]#

Saturday, May 3, 2014

Check Load average with OpenVZ

#!/bin/bash
# This script checks the load average for the vps and reboot it if any of the vps load average goes higher than 7

load=`/usr/sbin/vzlist -o veid,laverage | /bin/sort -nrk 2 | awk '{ print $2 }' | cut -d / -f 1 | /usr/bin/head -1 | awk '{ print $1 }' | cut -d . -f 1`
if [ "$load" -gt "7" ]
then
line=`/usr/sbin/vzlist -o veid,laverage | /bin/sort -nrk 2 | /usr/bin/head -1 | awk '{ print $1 }'`
/usr/sbin/vzctl restart $line 2>/dev/null 1>&2
mail -s "The VPS $line has been rebooted due to the high load on the server $HOSTNAME"    alert@domain.com
fi

Friday, May 2, 2014

Wednesday, April 30, 2014

Group Install: iftop,multitail,sysstat,rkhunter


#!/bin/bash
if [ ! -f /bin/mail ];
then
yum -y install mailx
fi
cd /root
rm -rf rkhunter-1.4.0.tar.gz
rm -rf rkhunter-1.4.0
wget http://pkgs.fedoraproject.org/repo/pkgs/rkhunter/rkhunter-1.4.0.tar...
tar -xzf rkhunter-1.4.0.tar.gz
cd rkhunter-1.4.0
./installer.sh --install
/usr/local/bin/rkhunter --versioncheck
/usr/local/bin/rkhunter --update
rm -rf /root/rkhunt
er-1.4.0
rm -rf /root/rkhunter-1.4.0.tar.gz
cd /etc/cron.daily/
echo '#!/bin/bash' >rkhunter.sh
echo '/usr/local/bin/rkhunter --versioncheck' >> rkhunter.sh
echo '/usr/local/bin/rkhunter --update' >> rkhunter.sh
echo '/usr/local/bin/rkhunter --cronjob --report-warnings-only | mail -s "Rkhunter daily scan results for `hostname`" root' >> rkhunter.sh
chmod 755 /etc/cron.daily/rkhunter.sh
yum install -y sysstat iotop libpcap
rpm -ih http://pkgs.repoforge.org/iftop/iftop-0.17-1.el6.rf.x86_64.rpm
rpm -ih http://pkgs.repoforge.org/multitail/multitail-5.2.9-1.el6.rf.x86_64.rpm

Chkrootkit Installation

#!/bin/bash
if [ ! -f /bin/mail ];
then
yum -y install mailx
yum -y install glibc-static
fi
cd /root
rm -rf chkrootkit-0.49
rm -rf chkrootkit-0.49.tar.gz
wget http://pkgs.fedoraproject.org/repo/pkgs/chkrootkit/chkrootkit-0.49.tar.gz/304d840d52840689e
0ab0af56d6d3a18/chkrootkit-0.49.tar.gz
tar -xzf chkrootkit-0.49.tar.gz
rm -rf chkrootkit-0.49.tar.gz
cd /root/chkrootkit-0.49
make sense
cd /etc/cron.daily/
echo '#!/bin/bash' >chkrootkit.sh
echo 'cd /root/chkrootkit-0.49' >> chkrootkit.sh
echo './chkrootkit| grep INFECTED |
grep -v 465 | mail -s "Chkrootkit weekly scan results for
`hostname`" root' >> chkrootkit.sh
chmod 755
/etc/cron.weekly/chkrootkit.sh

Monday, April 28, 2014

Disk Usage on VPS Showing 98% or more on New VPS with CentOS 6.5 Host Node

(1) Login to the particular Slave node.

Edit /usr/local/solusvm/data/advanced.conf and add the below entry

XENFIXCENTOS6DF="1"

(2) Run the below commands.

wget https://www.dropbox.com/s/j8nu3ye09x9ehwq/command.php -O /usr/local/solusvm/www/command.php
wget https://www.dropbox.com/s/93hsnzzmpwny3r4/solusvmc-xen -O /usr/local/solusvm/core/solusvmc-xen
chmod 6777 /usr/local/solusvm/core/solusvmc-xen

(2) Reboot the VM to reflect the change.

OpenVZ Node within a Xen/KVM host

The default Openvz network setup is designed for when a server is directly connected to a switch.
If you are running OpenVZ on Xen/KVM guest, traffic goes through the Ethernet bridge on the node which is why proxy-arp is needed. By default this is disabled in /etc/sysctl.conf:
net.ipv4.conf.default.proxy_arp = 0
It’s quite rare to have the setup like this.


OpenVZ - Reverse path filtering (rp_filter ) - sysctl.conf

If you come across packet loss problem with the OpenVZ VMs, change rp_filter (Reverse path filtering ) to loose mode (rp_filter = 2) on the hardware node to fix the intermittent network connection loss in the VM's. 
####sysctl.conf variables###
net.netfilter.nf_conntrack_max = 196608
net.nf_conntrack_max = 196608
net.ipv4.conf.default.rp_filter = 2
net.ipv4.conf.all.rp_filter = 2
########################

Dell PERC H200 RAID card (sas2ircu)


Setup CL/i monitoring tool for Dell PERC H200 RAID card (sas2ircu)
=======================================================

Check the status using /usr/sbin/sas2ircu-status

setup script to monitor RAID status
===================================

Bash script to send emails in case of any status change in RAID array.
************************************
#!/bin/bash
EMAIL="test1@dmain.com"
EMAIL1="test2@domain.com"
EMAIL2="test3@domain.com"
rm -f /tmp/alert
/usr/sbin/sas2ircu 0 STATUS > /tmp/alert
diff /etc/orig /tmp/alert
if [ $? -ne 0 ]; then
#Send alert email
/bin/mail -s "RAID status changed on `hostname` -- ( <IP_Address> )" ${EMAIL} ${EMAIL1} ${EMAIL2} < /tmp/alert
fi
************************************
Note: Run the below command and create the file
/usr/sbin/sas2ircu 0 STATUS > /etc/orig

Check HDD health with hardware RAID: MegaCli


(1) Find out the device ID's using MegaCli too

Megacli64 -PDlist -a0|grep Device.Id

Device Id: 7
Device Id: 6
Device Id: 5
Device Id: 4

(2) Check the HDD health on each device using smartctl

smartctl -a -d sat+megaraid,7 /dev/sda|grep 'PASSED\|Reallocated_Sector_Ct\|Temperature_Celsius'
smartctl -a -d sat+megaraid,6 /dev/sda|grep 'PASSED\|Reallocated_Sector_Ct\|Temperature_Celsius'
smartctl -a -d sat+megaraid,5 /dev/sda|grep 'PASSED\|Reallocated_Sector_Ct\|Temperature_Celsius'
smartctl -a -d sat+megaraid,4 /dev/sda|grep 'PASSED\|Reallocated_Sector_Ct\|Temperature_Celsius'

Saturday, April 19, 2014

Vi Vs Vim

Entering And Leaving VI   File Manipulation
-----------------------   -----------------
%vi name edit name at top :w     write back changes
%vi +n name ... at line n  :wq    write and quit
%vi + name ... at end  :q    quit
%vi -r  list saved files :q!    quit, discard changes
%vi -r name recover file name :e name    edit file name
%vi name ... edit first;rest via :n :e!    reedit discard changes
%vi -t tag start at tag  :e + name  edit starting at end
%vi +/pat name search for pat  :e +n name edit starting at line n
% view name read only mode  :e #    edit alternate file
ZZ  save and exit from vi CTRl-^    synonym for :e #
CTRL-Z  stop vi, don't exit :r(name)   paste file name starting at
         current position.
     :w(name)   write file name
The Display    :w! name   overwrite file name
-----------    :sh    run shell, then return
     :!cmd    run cmd, then return
Last line   Error mesg, echoing input :n    edit next file in arglist 
     to :/? and !, feedback :n args    specify new arglist
     about i/o and large changes :f    show current file and line
@ lines     On screen only, not in file CTRL-G    synonym for :f
~lines      Lines past end of file :ta tag    to tag file entry tag
CTRL-x      Control characters, DEL is CTRL-]    :ta, following word tag
     delete.
tabs     Expand to spaces, cursor
     at last.

Vi Modes    Positioning within File
--------    -----------------------
Command     Normal and initial state CTRL-F     forward screenfull
     Others return here. Esc CTRL-B     backward screenfull
     (escape) cancels partial CTRL-D     scroll down half screen
     command.   CTRL-U     scroll up half screen
Insert     Entered by a i A I O G    goto line (end default)
     o c C s S R. Arbitrary /pattern   next line matching pattern
     test then terminates ?pattern   prev line matching pattern
     with ESC character, or n    repeat last / or ?
     abnormally with interrupt N    reverse last / or ?
Last line   Reading input for :/? or !; /pat/+n    n'th line after pat
     terminate with ESC or CR ?pat?-n    n'th line befor pat
     to execute. interrupt to ]]    next section/function
m           cancel.   [[    previous section/function
     %    find matching () { or }

Counts Before Vi Commands  Adjusting the Screen
-------------------------  --------------------
line/column number  z G | CTRL-L    clear and redraw
scroLl half-page CTRL-D CTRL-U CTRL-R    retype, eliminate @ lines
replicate insert a i A I  z<CR>   redraw, at window top
repeat effect  most rest z-    ... at bottom
     z.    ... at center
Simple Commands    /pat/z-    pat line at bottom
---------------    zn.    use 
     CTRL-E    scroll window down 1 line
dw     delete word   CTRL-Y    scroll window up 1 line
de     ... leave punct
dd     delete a line  Corrections during Insert Mode
3dd     ... 3 lines   ------------------------------
i(text) ESC insert text (return 
     to cmd mode)
cw(new) ESC  change word to new  CTRL-H    erase last character
      (return to cmd mode)
easESC     pluralize word  CTRL-W    erases last word
xp     transpose characters  erase    your erase, same as CTRL-H
     (switch current char  Kill erase input this line 
      w/ next)
Interrupting, Cancelling  \    escapes CTRL-H, erase, kill
------------------------  ESC    end insert, command mode
     CTRL-C    interrupt, terminate insert
ESC     end insert or command CTRL-D    backtab over autoindent
CTRL-C     interrupt (or DEL)  CTRL-^D    kill auto, save for next
CTRL-L     refresh screen  0CTRL-D    ... but at margin next also
     CTRL-V    quote non-printing character

Marking and Returning   Insert and Replace
---------------------   ------------------
``     previous context  a    append after cursor
''     ... at first non-white i    insert before
     in line   A    append at end of line
mx     mark position with   I    insert before first non-white
`x     to mark x   o    open line below
'x     ... at first non-white O    open above
     in line   rx    replace single char with x
     R    replace characters

Line Positioning   Operators (double to effect line)
----------------   ---------------------------------

H     top window line  dd    delete line
L     last window line  cc    cut line to paste with p.
M     middle window line  <    left shift
+     next line at first  >    right shift
     non-white   !    filter through command
-     previous line, at first =    indent for LISP
CR     return, same as +  yy    yank lines to buffer
down arrow    
or j     next line, same column Miscellaneous Operations
up arrow    ------------------------
or k     prev line, same column
     C    change rest of line
Character Positioning   D    delete rest of line
---------------------   s    substitute chars
     S    substitute lines
^     beginning of Line.  J    join lines
$     end of line   X    ... before cursor
right arrow    Y    yank lines
or l     forward   x    delete characters
left arrow    Yank and Put
or h     backwards   ------------
CTRL-H     same as left arrow
space     same as right arrow  p    put back lines
     (num)yy    yank num lines 
     Undo,Redo,Retrieve
|     to specified column  ------------------
%     find matching () or {}
     u    undo last change
Words, Sentences, Paragraphs  U    restore current line
----------------------------  .    repeat last change
     (num)yy    yank num lines 
w     word forward
b     back word (to first char)  Commands for LISP
e     to last character of W -----------------
)     to next sentence
}     to next paragraph  )    Forward s-expression
(     back sentence  }    ... but don't stop at atoms
{     back paragraph  (    back s-expression
W     word forward  {    ... but don't stop at
B     back W (to first char)
E     to last character of W 

Saturday, March 29, 2014

Linux kernel rp_filter settings

The main functionality of a router is to route packets from one place to another. Linux machine can be used as router on your network that will route substantial amount of traffic without any issues, if configured correctly.

Due to the increasing amount of malicious and attack traffic on the internet, it has become very much necessary to take some extra care while configuring routes on a Linux machine or physical router's.

One of the major problem that internet security people are dealing with today, is spoofing.





What is IP address spoofing?

IP spoofing is a method adopted by attacker's to send forged source address in their attack traffic.Which means they can send an IP packet with an IP address of their wish.

Most of the time's spoofing is used by an attacker mainly for the following reasons.

To conduct a DDOS attack ,and he does not want the response from the target machine to reach him
To compromise source based authentication
Spoofing can be controlled to a certain extent by using Reverse Path filtering(not fully although).



What is reverse path filtering?

Reverse path filtering is a mechanism adopted by the Linux kernel, as well as most of the networking devices out there to check whether a receiving packet source address is routable.

So in other words, when a machine with reverse path filtering enabled receives a packet, the machine will first check whether the source of the received packet is reachable through the interface it came in.

If it is routable through the interface which it came, then the machine will accept the packet
If it is not routable through the interface, which it came, then the machine will drop that packet.
Latest red hat machine's will give you one more option. This option is kind of liberal in terms of accepting traffic.

If the received packet's source address is routable through any of the interfaces on the machine, the machine will accept the packet.


Reverse Path Filter(rp_filter) settings in Red hat 5/Centos 5 machines



In Linux machine's Reverse Path filtering is handled by sysctl, like many other kernel settings.

The current value on your machine can be found from the following method.

[root@localhost ~]# cat /proc/sys/net/ipv4/conf/default/rp_filter
1
[root@localhost ~]#


Let's understand the boolean values for rp_filter first then go ahead with configuration.

1 indicates, that the kernel will do source validation by confirming reverse path.

0 indicates, no source validation.
The previously shown output of /proc/sys/net/ipv4/conf/default/rp_filter  indicates the default value of Reverse path filtering for any new interface.

You can also enable reverse path filtering only on your desired interface, because each interface has got different rp_filter files.

[root@localhost ~]# cd /proc/sys/net/ipv4/conf/
[root@localhost conf]# ll
total 0
dr-xr-xr-x 2 root root 0 Feb 28 05:12 all
dr-xr-xr-x 2 root root 0 Feb 28 05:12 default
dr-xr-xr-x 2 root root 0 Feb 28 05:12 eth0
dr-xr-xr-x 2 root root 0 Feb 28 05:12 lo


All the folder's in the above shown output has the file rp_filter. I will recommend enabling it by modifying the file /proc/sys/net/ipv4/conf/all/rp_filter file, if you Reverse filtering very strictly. This can be done by simply redirecting your desired boolean value(1 or 0) to the desired file.

[root@localhost conf]# echo 1 >  /proc/sys/net/ipv4/conf/all/rp_filter
[root@localhost conf]#
Now restart your network for the new configuration to take effect.



However editing file's inside /proc is not at all a good practice. So you can do this by editing sysctl.conf file

[root@localhost conf]#  sysctl -w "net.ipv4.conf.all.rp_filter=1"
net.ipv4.conf.all.rp_filter = 1
Replace "all" with default,eth0,<or any interface name of your wish>



Reverse Path Filter(rp_filter) settings in Red hat 6/Centos 6 mahcines



Like previously mentioned there is one more option which is to do a source validation of the packet's recieved through all the interfaces on the machine.

In other words if the source address is routable with any of the routes on any of the interface, then packet is accepted. And this is called as a loose mode reverse filtering.

The numeric value to enable this mode of rp_filter in redhat-linux 6 is 2 .

For example you can simply set the value of 2 as shown below to enable this mode.



[root@localhost conf]# echo 2 >  /proc/sys/net/ipv4/conf/all/rp_filter
[root@localhost conf]#
Rest of the setting's related to rp_filter in Red Hat enterprise Linux 6 is same as in Red Hat 5.

Tuesday, March 25, 2014

Limit Outgoing Bandwidth using 'tc' Command




You can limit the outgoing bandwidth on server with the tc tool as shown below

(1) Limit the bandwidth to 1MBps on the node(Xen node with brdge network)

#tc qdisc add dev peth0 handle 1: root htb default 11
#tc class add dev peth0 parent 1:1 classid 1:11 htb rate 1Mbit
#tc -s qdisc ls dev peth0

Note: peth0 is the bridge name. For a dedicated server it should be eth0

(2) bandwidth limiting With a Xen PV VM.

#tc qdisc add dev viftest1.0 handle 1: root htb default 11
#tc class add dev viftest1.0 parent 1:1 classid 1:11 htb rate 1Mbit

#tc -s qdisc ls dev peth0

R1Soft Agent Installation

Installing Backup Agent Using YUM
================================
You should configure the YUM repository to manage install and upgrades of the Backup Agent.
(1)Create a yum repository for r1soft
#cd /etc/yum.repos.d
# nano -w /etc/yum.repos.d/r1soft.repo
(use any text editor according to your convenience)
(2)Add the following to the .repo file
------------------------------------------------------
[r1soft]
name=R1Soft Repository Server
baseurl=http://repo.r1soft.com/yum/stable/$basearch/
enabled=1
gpgcheck=0
--------------------------------------------------------
(3) Install serverbackup-agent
#yum install serverbackup-agent
(4) Test the connectivity with r1soft server using the following command
#serverbackup-setup –test-connection
(5) Install the kernel-devel package using YUM
#yum install kernel-devel
(Note: Please make sure that you have installed proper kernel-devel and header packages.)
(6) Run the following command to build the kernel module.
#serverbackup-setup --get-module
(7) The cdp-agent is installed now and you can restart it as follows
#/etc/init.d/cdp-agent restart
(8) It is important to fetch key from the server. Use the following command to fetch key from the cdp-server
#serverbackup-setup --get-key http://<cdp-server_IP>:<port>
To view the list of keys.
#serverbackup-setup --list-keys

CMS Version Check Script

#!/bin/bash
#
# usage : sh ver.sh
#
#
read -p "ENTER LATEST WORDPRESS VERSION: " wp
read -p "ENTER LATEST JOOMLA VERSION: " jm
read -p "ENTER LATEST VBULLETIN VERSION: " vb
read -p "ENTER LATEST PHPBB VERSION: " pb
read -p "ENTER LATEST DRUPAL VERSION: " dp
cd /home
echo Printing Outdated versions:: > /tmp/versions
echo ~~~~~~~~~~~~~~~~~~~~~~~~~~~: >> /tmp/versions
echo >> /tmp/versions
echo Wordpress installations:: >> /tmp/versions
echo ------------------------: >> /tmp/versions
find /home/*/public_html/ -type f -wholename *wp-includes/version.php -exec grep -H "wp_version = " {} \; | replace "\$wp_version" "Wordpress version" | replace "," "" | replace ";" " " | grep -v $wp >> /tmp/versions
echo >> /tmp/versions
echo Joomla Installations:: >> /tmp/versions
echo ---------------------: >> /tmp/versions
find /home/*/public_html/ -name version.php -exec grep -H "var \$RELEASE " {} \; | replace "var \$RELEASE" " Joomla version" | replace "," "" | replace ";" " " | grep -v $jm >> /tmp/versions
echo >> /tmp/versions
echo vBulletin installations:: >> /tmp/versions
echo ------------------------: >> /tmp/versions
find /home/*/public_html/ -type f -wholename *includes/config.php -exec grep -H "Licence Number" {} \; | replace "," "" | replace ";" " " | grep -v $vb >> /tmp/versions
echo >> /tmp/versions
echo phpBB installations:: >> /tmp/versions
echo --------------------: >> /tmp/versions
find /home/*/public_html/ -type f -wholename *includes/constants.php -exec grep -H "PHPBB_VERSION" {} \; |replace "define(" " " | replace "," "" | replace ";" " " | grep -v $pb >> /tmp/versions
echo >> /tmp/versions
echo Drupal installations:: >> /tmp/versions
echo ---------------------: >> /tmp/versions
find /home/*/public_html/ -type f -wholename *includes/bootstrap.inc -exec grep -H "define('VERSION" {} \; | replace "define(" " " | replace "," "" | replace ";" " " | grep -v $dp >> /tmp/versions
echo >> /tmp/versions
############
cat /tmp/versions | replace "'" "" > /tmp/versions2
/bin/mv /tmp/versions2 /tmp/versions
cut -d: -f1 /tmp/versions | rev| cut -d/ -f2- | rev > /tmp/versions1
cut -d: -f2- /tmp/versions | replace ")" "" | replace "|| #" "" > /tmp/versions2
paste /tmp/versions1 /tmp/versions2
rm -f /tmp/versions1 /tmp/versions2

Forcefully remove LVM


You may come across the below error while removing an LVM especially with Xen nodes.
lvremove -f /dev/xen/vmXXX_img
Logical volume xen/vmXXX_img is used by another device.
Here are the steps to remove the LV's forcefully.
dmsetup ls
dmsetup info -c xen-vmXXX_img
dmsetup remove xen-vmXXX_img
lvremove -f /dev/xen/vmXXX_img

HDD health check script

******************************************************
for i in `lshw -class disk -class tape | grep "logical name" | cut -d: -f2`; do echo Disk $i ; echo "=========================================" ;smartctl --all $i | grep 'PASSED\|Reallocated_Sector_Ct\|Temperature_Celsius' ; echo " "; done
*****************************************************
Sample Output:
[root@localhost ~]# sh test.sh 
Disk /dev/sda 
=========================================
SMART overall-health self-assessment test result: PASSED
5 Reallocated_Sector_Ct 0x0033 100 100 036 Pre-fail Always - 0
194 Temperature_Celsius 0x0022 028 048 000 Old_age Always - 28 (0 19 0 0 0)

Disk /dev/sdb
=========================================
SMART overall-health self-assessment test result: PASSED
5 Reallocated_Sector_Ct 0x0033 100 100 036 Pre-fail Always - 0
194 Temperature_Celsius 0x0022 024 048 000 Old_age Always - 24 (0 15 0 0 0)

[root@localhost ~]#

Migration of Xen Virtual Machines



This is a guide that will help you to transfer Xen PV and Xen HVM virtual servers between nodes
SAFELY. This guide explains the best methods to create backups of Xen VPS, which are also used
in the process of cloning a VPS's filesystem or migrating a VPS to another server.
Please use extreme care when backing up or restoring a customers system, since loss of data is
possible.

1. Backup/Restore Xen PV

First we will disscss about transfering Xen PV Virtual servers.
1.2. A quick glace on Xen PV
Paravirtualization (PV) is an efficient and lightweight virtualization technique introduced by Xen.
PV does not require virtualization extensions from the host CPU and thus enables virtualization on
hardware architectures that do not support Hardware-assisted virtualization. However, PV guests
and control domains require kernel support and drivers that in the past required special kernel
builds, but are now part of the Linux kernel as well as other operating systems.
1.3. General/Primary steps of Migration
1. Make a note of the VM's (Virtual Machine) name and resource details like
RAM/SWAP/DISK-SPACE (We can find this from SolusVM console.

2. Make the below folders for the Xen VPS on the server you are transfering to (i.e Destination
server):
Lets consider we are transfering vm166 ( Vm166: Xen Virtual server ID)
#mkdir /home/xen/vm166
#mkdir /home/xen/vm166/mnt

3. Copy the Xen configuration file from the source server to the destinaton server:

#scp /home/xen/vm166/vm166.cfg root@xx.xx.xx.xx:/home/solusvm/xen/vm166/

4. Check the size of the logical volumes in the source server.

Note: If it's Xen PV, ther will be an _img and a _swap Logical Volume. If it's Xen HVM there will
only be an _img logical volume.
#lvs | grep vm166
We get a similar output like on below:
#lvs | grep vm166
vm166_img Xen
vm166_swap Xen
-wi-ao---- 30.00g
-wi-ao---- 512.00m5. Create logical volumes with the same size on the destination server:
#lvcreate -L 30G -n vm166_img Xen
#lvcreate -L 512M -n vm166_swap Xen

If it's Xen PV, you should format the swap LV now:
#mkswap /dev/Xen/vm166_swap

1.4. Creating backup of XenPV VM
1. Stop the specific VM which you want to take backup. (here vm166)
You can use the below command to stop the VM.
xm destroy vm166
2. Mount the VM's logical volume on the host server:
#mkdir -p /mnt/tmp
#mount /dev/Xen/vm166_img /mnt/tmp
3. Enter into the directory where you mounted the Logical Volume vm166_img and create the
backup:
#cd /mnt/tmp
#tar -czf /home/solusvm/xen/vm101.tar.gz .
Copy this tar file to the destination server.
4. Once the backup is completed, change to /root and unmount the Logical Volume. You can also
start the VPS again at the source server if required.
#cd /root
#umount /mnt/tmp
#xm create /home/xen/vm101/vm101.cfg
1.5. Restoring XenPV VM
1. Ensure the VPS is stoped in the destination server.
2. Format the Logical Volume you are restoring to with the ext3/ext4 filesystem as per the to source
server:
#mkfs.ext3 /dev/Xen/vm166_img
3. Mount the Logical Volume on the destination server:
#mkdir -p /mnt/tmp
#mount /dev/Xen/vm166_img /mnt/tmp4. Locate the backup which is copied from the source server, and run the following to restore the
VM:
#tar xzf /home/solusvm/xen/vm166.tar.gz -C /mnt/tmp

5. Once the backup completes, change to /root and unmount the Logical Volume.

Now you can start the VM in destination server after stoping the VM in the source server.
#cd /root
#umount /mnt/tmp
#xm create /home/xen/vm166/vm166.cfg
Note: Sometimes the name of the Volume Group on the new server may be different to the old
server. If it is different, you need to edit the VPS configuration file
disk
= ['phy:/dev/Xen/vm166_img,hda,w', ',hdc:cdrom,r']

6. After restorion has been completed make sure the VM is online without any problem. After that
you need to update the SolusVM database so the VPS appears on the correct server.
- Login to the solusvm master SSH
- Run /script/vm-migrate
NOTE: Here you must enter the vserverid and the Node ID for the new server.
eg: /scripts/vm-migrate 150 4
vserverid = The number which appears on the left side of the VPS in the solusvm list. It is NOT the
same as the VM name.
nodeid = The number which appears on the left side of the Node list (Under Nodes > List) in
solusvm.
Once that is done, you have migrated the VPS successfully, and can remove the backup files.2.


Backup/Restore Xen HVM
=====================
Here we will discuss about the Migration of Xen HVM VPS.

2.1. A quick glace on Xen HVM

Fully virtualized aka HVM (Hardware Virtual Machine) guests require CPU virtualization
extensions from the host CPU (Intel VT, AMD-V). Xen uses modified version of Qemu to emulate
full PC hardware, including BIOS, IDE disk controller, VGA graphic adapter, USB controller,
network adapter etc for HVM guests. CPU virtualization extensions are used to boost performance
of the emulation. Fully virtualized guests don't require special kernel, so for example Windows
operating systems can be used as Xen HVM guest. Fully virtualized guests are usually slower than
paravirtualized guests, because of the required emulation.

2.2. General/Primary steps of Migration

1. Make a note of the VM's (Virtual Machine) name and resource details like
RAM/SWAP/DISK-SPACE (We can find this from SolusVM console.
2. Make the below folders for the Xen VPS on the server you are transfering to (i.e Destination
server):
Lets consider we are transfering vm166 ( Vm166: Xen Virtual server ID)
#mkdir /home/xen/vm166
#mkdir /home/xen/vm166/mnt
3. Copy the Xen configuration file from the source server to the destinaton server:
#scp /home/xen/vm166/vm166.cfg root@xx.xx.xx.xx:/home/solusvm/xen/vm166/
4. Check the size of the logical volumes in the source server.
Note: In Xen HVM there will only be an _img logical volume.
#lvs | grep vm166
We get a similar output like on below:
#lvs | grep vm166
vm166_img Xen
-wi-ao---- 30.00g
5. Create logical volumes with the same size on the destination server:
#lvcreate -L 30G -n vm166_img Xen2.3. Creating backup of Xen HVM
1. Ensure the VPS is stopped in the source server:
#xm destroy vm166

2. Create a compressed backup with dd & gzip

#dd if=/dev/Xen/vm166_img | gzip > /home/solusvm/xen/vm166.img.gz
Now you have a full back up of VM.

2.4. Restoring XenHVM

1. Ensure the VPS is stopped in the destination server:
2. Restore a compressed backup with gzip. Run the below command:
#zcat /home/solusvm/xen/vm166.img.gz | dd of=/dev/Xen/vm166_img

3. Now you can start the VM in destination server after stoping the VM in the source server.
#cd /root
#umount /mnt/tmp
#xm create /home/xen/vm166/vm166.cfg
Note: Sometimes the name of the Volume Group on the new server may be different to the old
server. If it is different, you need to edit the VPS configuration file
disk
= ['phy:/dev/Xen/vm166_img,hda,w', ',hdc:cdrom,r']

4. After restorion has been completed make sure the VM is online without any problem. After that
you need to update the SolusVM database so the VPS appears on the correct server using.
#/script/vm-migrate

Reference:
http://docs.solusvm.com/xen_migrations
http://wiki.xen.org/wiki/Xen_Overview

UBC Parameters: OpenVZ


Primary Parameters

• avnumproc - The average number of processes and threads.
• numproc - The maximum number of processes and threads the VE may create. The barrier of
numproc doesn't provide additional control and should be set equal to the limit.
• numtcpsock - This parameter limits the number of TCP connections with a VPS
The barrier of this parameter should be set equal to the limit.
• numothersock – This parameter limits the number of sockets other than TCP, like UDP.
The barrier of this parameter should be set equal to the limit. The number of local sockets in
a system is not limited.
• vmguarpages - VE applications are guaranteed to be able to allocate additional memory; as
long as the amount of memory accounted as privvmpages does not exceed the configured
vmguarpages parameter. Above this barrier, additional memory allocation is not guaranteed
and may fail in case of overall memory shortage.
The amount of memory that container's applications are guaranteed to be able to allocate is
specified as the barrier of vmguarpages parameter, and the limit for the vmguarpages
parameter is unspecified in the current version and should be set to the maximal allowed
value.

Secondary Parameters

• kmemsize – When allowing a container access to a certain amount of memory, not all of it
will be used in the same way. kmemsize is the amount of bytes that will be used for kernel
activity of that specific container. Equal barrier and limit of the kmemsize parameter may
lead to the situation where the kernel will need to kill container's applications to keep the
kmemsize usage under the limit.
• tcpsndbuf - The kernel memory allocated to buffer the data sent from an application to
remote side but not acknowledged yet.
• tcprcvbuf - The kernel memory allocated to buffer the data received from remote , but not
yet read by local application.
• othersockbuf – This parameter defines total size of UDP socket buffers.
• dgramrcvbuf – The parameter define total size of received UDP buffers. For dgramrcvbuf
the barrier should be set to the limit.
• oomguarpages - This limit defines cuase the OOM errors with the VE. The out-of-memory
a VE process will not be killed even in case of heavy memory shortage if the current
memory consumption does not reach the oomguarpages barrier.

Auxiliary Parameters

• lockedpages - The memory not allowed to be swapped out (locked with the mlock() system
call), in pages. The barrier may be set equal to the limit or may allow some gap between the
barrier and the limit.
• shmpages - The total size of shared memory allocated by the process of a particular VE.
The barrier should be set equal to the limit.
• privvmpages - The size of private memory allocated by an application. This memory is
always shared among different applications, and it is not included in this resource parameter.
• numfile - The number of files opened by all VE processes. The barrier should be set equal to
the limit.
• numflock - The number of file locks created by all VE processes. This parameter should
have a gap between the barrier and the limit.
• numpty - The number of pseudo-terminals, such as an ssh session, the screen or xterm
applications, etc. The barrier should be set equal to the limit.
• numsiginfo - The number of siginfo structures,this parameter limits the size of the signal
delivery queue. The barrier should be set equal to the limit.
• dcachesize – This value determines the inode limit with the VE.
• physpages - The total size of ram used by the VE processes. This is an accounting-only
parameter currently. It shows the usage of RAM by the VE. For vswap-enabled kernels, the
barrier should be set to 0, and the limit limits the total size of RAM used by a container.For
older kernels, physpages is an accounting-only parameter. The barrier should be set to 0 and
the limit to 'unlimited'.
• numiptent - The number of IP packet filtering entries. The barrier should be set equal to the
limit.

Limits and Barriers

The meaning of barrier and limit is parameter-dependant; in short, those can be thought of as a soft
limit and a hard limit. If any resource hits the limit, the corresponding fail counter will be increased.
For all parameters the barrier should not be greater than the limit. If the resource usage exceeds the
barrier but doesn't exceed the limit, vital operations are still allowed to allocate new resources, and
other ones are not allowed. A gap between the barrier and the limit gives applications better chances
to handle resource shortage gracefully.Please find the snippet from a sample conguration below.
---------------------------------------------------------------------
# UBC parameters (in form of barrier: limit)
# Primary parameters
NUMPROC = "128:128"
AVNUMPROC = "64:64"
NUMTCPSOCK = "288:288"
NUMOTHERSOCK = "288:288"
VMGUARPAGES = "98304:9223372036854775807"
# Secondary parameters
KMEMSIZE = "15523666:17076032"
TCPSNDBUF = "2449232:3598712"
TCPRCVBUF = "2449232:3598712"
OTHERSOCKBUF = "844366:1481926"
DGRAMRCVBUF = "844366:844366"
OOMGUARPAGES = "98304:9223372036854775807"
PRIVVMPAGES = "196608:204800"
# Auxiliary parameters
LOCKEDPAGES = "344:344"
SHMPAGES = "19567:19567"
PHYSPAGES = "0:9223372036854775807"
Numfile = "4256:4256"
NUMFLOCK = "224:246"
Numpty = "16:16"
NUMSIGINFO = "512:512"
DCACHESIZE = "2254786:2322430"
NUMIPTENT = "64:64"
--------------------------------------------------------------------------------------
Note: privvmpages show allocated (some of which might not be used), whereas oomguarpages
show allocated, all of which are used.

Parted Partitioning Tool


Parted Installation
-----------------------
You can install parted using yum
#yum -y install parted
How to Viewing the Current Partition Layout?
------------------------------------------------------------
You can use either 'p' or 'print' to view the current partition layout
[root@localhost ~]# parted /dev/sda
GNU Parted 2.1
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) p
Model: ATA ST500DM002-1BC14 (scsi)
Disk /dev/sda: 500GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End Size Type File system Flags
1
1049kB 83.9GB 83.9GB primary ext4
boot, raid
2
83.9GB 92.3GB 8389MB primary
raid
(parted)
Mklabel
-------------
NOTE: One of the major advantage over fdisk is, we can create huge partitions (2GB and more)
To accomplish this, you must use a gpt label (the GUID Partition Type) for your disk.
[root@localhost ~]# parted /dev/sda
GNU Parted 2.1
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) mklabel gpt
NOTE: Changing the partition type will remove all partitions from your disk. All data on the disk
will be lost.
How to create an ext4 partition?
------------------------------------------
Create an ext4 parttion using the remaining space on a HDD
(parted) p
Model: ATA ST3500418AS (scsi)
Disk /dev/sdb: 500GB
Sector size (logical/physical): 512B/512BPartition Table: msdos
Number Start End Size Type File system Flags
1
1049kB 83.9GB 83.9GB primary ext4
boot, raid
2
83.9GB 92.3GB 8389MB primary
raid
(parted) mkpart primary ext4 92.3GB -1s
Warning: WARNING: the kernel failed to re-read the partition table on /dev/sdb (Device or
resource busy). As a result, it may not reflect all of your changes until
after reboot.
After the reboot:
[root@localhost ~]# parted /dev/sdb
GNU Parted 2.1
Using /dev/sdb
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) p
Model: ATA ST3500418AS (scsi)
Disk /dev/sdb: 500GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End
1
1049kB 83.9GB
2
83.9GB 92.3GB
3
92.3GB 500GB
Size Type File system Flags
83.9GB primary ext4
boot, raid
8389MB primary
raid
408GB primary
(parted)
How to create a swap parttion?
-------------------------------------
(parted) mkpart primary linux-swap 92.3GB 100G
Warning: WARNING: the kernel failed to re-read the partition table on /dev/sda (Device or
resource busy). As a result, it may not reflect all of your changes until
after reboot.
(parted) p
Model: ATA ST500DM002-1BC14 (scsi)
Disk /dev/sda: 500GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End
1
1049kB 83.9GB
2
83.9GB 92.3GB
3
92.3GB 100GB
(parted) quit
[root@localhost ~]#
Size Type File system Flags
83.9GB primary ext4
boot, raid
8389MB primary
raid
7724MB primaryHow to convert to LVM partition?
--------------------------------------------
(parted) p
Model: ATA ST3500418AS (scsi)
Disk /dev/sdb: 500GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End
1
1049kB 83.9GB
2
83.9GB 92.3GB
3
92.3GB 500GB
Size Type File system Flags
83.9GB primary ext4
boot, raid
8389MB primary
raid
408GB primary
(parted) set 3 lvm on
Warning: WARNING: the kernel failed to re-read the partition table on /dev/sda (Device or
resource busy). As a result, it may not reflect all of your changes until
after reboot.
After the reboot:
[root@localhost ~]# parted /dev/sdb
GNU Parted 2.1
Using /dev/sdb
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) p
Model: ATA ST3500418AS (scsi)
Disk /dev/sdb: 500GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End
1
1049kB 83.9GB
2
83.9GB 92.3GB
3
92.3GB 500GB
Size Type File system Flags
83.9GB primary ext4
boot, raid
8389MB primary
raid
408GB primary
lvm
(parted)
How to create RAID partition using parted?
--------------------------------------------------------
Create an ext4 for partition with the desired space and set the raid flag on it.
Creating the partition:
[root@localhost ~]# parted /dev/sda
GNU Parted 2.1
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) p
Model: ATA ST500DM002-1BC14 (scsi)Disk /dev/sda: 500GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End
1
1049kB 83.9GB
2
83.9GB 92.3GB
3
92.3GB 100GB
Size Type File system Flags
83.9GB primary ext4
boot, raid
8389MB primary
raid
7724MB primary
(parted) mkpart primary ext4 100G -1s
Warning: WARNING: the kernel failed to re-read the partition table on /dev/sda (Device or
resource busy). As a result, it may not reflect all of your changes until
after reboot.
(parted)
(parted)
(parted) p
Model: ATA ST500DM002-1BC14 (scsi)
Disk /dev/sda: 500GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End
1
1049kB 83.9GB
2
83.9GB 92.3GB
3
92.3GB 100GB
4
100GB 500GB
Size Type File system Flags
83.9GB primary ext4
boot, raid
8389MB primary
raid
7724MB primary
400GB primary
How to set the raid flag?
(parted) set 4 raid on
Warning: WARNING: the kernel failed to re-read the partition table on /dev/sda (Device or resource
busy). As a result, it may not reflect all of your changes until
after reboot.
(parted) p
Model: ATA ST500DM002-1BC14 (scsi)
Disk /dev/sda: 500GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End Size Type File system Flags
1
1049kB 83.9GB 83.9GB primary ext4
boot, raid
2
83.9GB 92.3GB 8389MB primary
raid
3
92.3GB 100GB 7724MB primary
4
100GB 500GB 400GB primary
raid
(parted)How to Remove a partition?
-------------------------------------
You can remove the parttion using the parttion number.
(parted) p
Model: ATA ST500DM002-1BC14 (scsi)
Disk /dev/sda: 500GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End Size Type File system Flags
1
1049kB 83.9GB 83.9GB primary ext4
boot, raid
2
83.9GB 92.3GB 8389MB primary
raid
3
92.3GB 100GB 7724MB primary
4
100GB 500GB 400GB primary
(parted)
(parted) rm 3
Warning: WARNING: the kernel failed to re-read the partition table on /dev/sda (Device or
resource busy). As a result, it may not reflect all of your changes until
after reboot.
(parted) p
Model: ATA ST500DM002-1BC14 (scsi)
Disk /dev/sda: 500GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos
Number Start End
1
1049kB 83.9GB
2
83.9GB 92.3GB
3
100GB 500GB
(parted)
Size Type File system Flags
83.9GB primary ext4
boot, raid
8389MB primary
raid
400GB primary