Professional Documents
Culture Documents
www.thegeekstuff.com
Table of Contents
Introduction........................................................... 7 About the Author.................................................... 8 Copyri ht ! "isclai#er............................................ $
%ersion.............................................................................. $
www.thegeekstuff.com
"isplay Total Connect Ti#e of 1sers ...................0, 5xecute Co##ands in the 'ack round ...............0)ed 'asics < 7ind and 6eplace 1sin 6e 5x ........03 A*k Introduction = /rint 5xa#ples ..................... 30 %i# 5ditor +a2i ation 7unda#entals ..................34 Ch#od Co##and 5xa#ples................................ 40 %ie* &ultiple Lo 7iles in 8ne Ter#inal ..............4, Less Co##and................................................... 40 > et 5xa#ples ................................................. 48
Chapter 3. /)1@ /),@ /)-@ /)0 and /68&/TAC8&&A+".............................................. $Hack Hack Hack Hack Hack Hack Hack -8. -$. 00. 01. 0,. 0-. 00. /)1 < "efault Interaction /ro#pt .......................$/), < Continuation Interacti2e /ro#pt ...............$0 /)- < /ro#pt 1sed by )elect Co##and...............$3 /)0 < /ro#pt to /refix Tracin 8utput ................$7 /68&/TAC8&&A+" .......................................... $8 Custo#iBe 'ash /ro#pt 1sin /)1...................... $$ Colorful 'ash /ro#pt 1sin /)1........................100
www.thegeekstuff.com
/ass*ord /rotection of Cip files ....................... 11Tar Co##and 5xa#ples ................................... 11Co#bine Bip@ bBip, *ith Tar ...........................113 'C is 5aByD 'BE Co##and 5xa#ples..................114 Cpio 5xa#ples ................................................. 1,0
www.thegeekstuff.com
Install /H/ fro# )ource ................................... 1$4 Install &y)GL .................................................. 1$$ Install LA&/ )tack............................................ ,00 Install :A&//.................................................. ,10 )ecure ?our Apache >eb )er2er ....................... ,1, Apachectl and Httpd Tips.................................. ,14 )etup Apache %irtual Host Confi uration...........,,6otate Apache Lo s 7iles.................................. ,,3
and /erfor#ance..,-$
8$. 7ree Co##and................................................. ,-$ $0. Top Co##and ................................................. ,00 $1. "f Co##and ................................................... ,0$,. "u Co##and ................................................... ,00 $-. Lsof Co##ands ............................................... ,03 $0. %#stat Co##and ............................................ ,07 $3. +etstat Co##and ........................................... ,08 $4. )ysctl Co##and .............................................. ,31 $7. +ice Co##and ................................................ ,3, $8. 6enice Co##and ............................................. ,30 $$. Fill Co##and .................................................. ,34 100. /s Co##and.................................................. ,38 101. )ar Co##and ................................................ ,40
www.thegeekstuff.com
10 A#aBin
www.thegeekstuff.com
Introduction
There are only 10 types of people in the world those who understand binary, those who dont, and those who understand gray code Geek
There are total of 101 hacks in this book that will help you build a strong foundation in inu!. "ll the hacks in this book are e!plained with appropriate inu! command e!amples that are easy to follow. This book contains 12 chapters. #hapters 1 $ 3 e!plain %pen&&' tips and tricks( #) command hacks( and se*eral essential inu! commands including grep( find and many more. #hapters 4 $ 6 co*er date manipulation( inu! command prompt customi+ation( archi*e and compression commands. #lear e!amples are pro*ided. #hapter , $ - e!plain critical inu! sysadmin tasks( package installation on *arious distros( and bash command line history with clear e!amples #hapter 10 . 12 co*er "/0 stack installation and se*eral inu! system monitoring and performance commands with practical e!amples.
" note on the e!amples1 /ost e!amples are identified in the following way.
5xa#ple "escription
Lines of code for you to type, with the result you will see on screen. "dditional clarification or discussion will appear below the code section in plain te!t. ,
www.thegeekstuff.com
2f you ha*e any @uestions while reading this book( don>t hesitate to reach out to me. Aou can connect with me on the following1 Twitter 9Bthegeekstuff; Cacebook page
2f you want to write to me directly( use this contact form to reach out to me.
www.thegeekstuff.com
Copyri ht ! "isclai#er
#opyright E 200- . 2011 $ 4amesh 5atara6an. "ll rights reser*ed. 5o part of this book may be reproduced( translated( posted or shared in any form( by any means. The information pro*ided in this book is pro*ided Fas isF with no implied warranties or guarantees.
%ersion
%ersion 1.0 2.0 "ate 12 $ Ceb $ 20016 $ 5o* . 2011 6e2isions Cirst :dition &econd :dition
www.thegeekstuff.com
8ash is the default shell on inu!. 2f you are spending lot of time on inu! en*ironment( you should master the 8ash command line features to become efficient. "part from being an interacti*e shell( 8ash is also a scripting language( which allows you to automate your tasks using 8ash shell scripting. 8ash 101 'acks is a downloadable e8ook that contains 101 practical e!amples on both 8ash command line and shell scripting( that will help you understand e*erything you need to know about 8ash.
Get Your Copy of: Bash 101 Hacks eBook http://www.the eekstuff.co!/"ash#101#hacks#e"ook/
10
www.thegeekstuff.com
2f you are spending lot of time on H52I J inu!( you3ll be manipulating te!t files fre@uently. Aou may be making the similar edits on multiple configuration files on one or more ser*ers. Aou may be digging huge log files 9or data files; looking for certain information. &ed and "wk 101 'acks is a downloadable e8ook that contains 101 practical e!amples on *arious ad*anced &ed and "wk features( that will help you understand e*erything you need to know about &ed and "wk.
Get Your Copy of: $ed and %wk 101 Hacks eBook http://www.the eekstuff.co!/sed#awk#101#hacks#e"ook/
11
www.thegeekstuff.com
+a ios Core
2f you are a sysadmin( dba( network administrator( or someone who is responsible for keeping the 2T infrastructure up and running( the following might sound familiar to you. Aou don3t know when you3ll run out of disk space( or when the ser*er will go down( or when the database will crash( or when one of the critical ser*ices running on the ser*er will fail. Aou are worried that right people 9or team; are not getting notified about the ser*er or ser*ices issues at the right time. Aou 9or your team; are constantly working on finding and fi!ing issues as they show up.
Aou should implement a robust monitoring solution that will notify you when there is an issue. 2t should also notify the right people at the right time about a potential issue( e*en before it becomes critical. 5agios #ore 3 e8ook is the only guide you3ll e*er need to get your 2T infrastructure monitored using 5agios #ore( and it will help you to understand e*erything you need to know to implement 5agios #ore 3.
Get Your Copy of: &a ios Core eBook http://www.the eekstuff.co!/na ios#core#e"ook/
12
www.thegeekstuff.com
Get Your Copy of: 'i! 101 Hacks eBook http://www.the eekstuff.co!/(i!#101#hacks#e"ook/
13
www.thegeekstuff.com
14
www.thegeekstuff.com
To make this change permanent( add e!port #)0"T'KJetc to your LJ.bashMprofile &imilar to the 0"T' *ariable( you can add more than one directory entry in the #)0"T' *ariable( separating them with 1 ( as shown below. e-port C./%+H0.:1:/etc:/(ar
This hack can be *ery helpful under the following situations1 %racle )8"s fre@uently working under N%4"# :M'%/:( can set the #)0"T' *ariable to the oracle home Hni! sysadmins fre@uently working under Jetc( can set the #)0"T' *ariable to Jetc )e*elopers fre@uently working under pro6ect directory JhomeJpro6ects( can set the #)0"T' *ariable to JhomeJpro6ects :nd.users fre@uently accessing the subdirectories under their home directory( can set the #)0"T' *ariable to L 9home directory;
www.thegeekstuff.com
2nstead of e!ecuting cd ..J..J..J.. to na*igate four le*els up( use one of the following four alias methods1
H..nI
2n the e!ample below( ..4 is used to go up 4 directory le*el( ..3 to go up 3 directory le*el( ..2 to go up 2 directory le*el. "dd the following alias to your LJ.bashMprofile and re.login. alias ..02cd ..2 alias ..302cd ../..2 alias ..402cd ../../..2 alias ..502cd ../../../..2 alias ..602cd ../../../../..2
) cd /t!p/(ery/lon /directory/structure/that/is/too/deep ) ..5 *Note: use ..5 to ) pwd /t!p/(ery/lon /directory/structure/ o up 5 directory le(el,
only dots
2n the e!ample below( P.. 9fi*e dots; is used to go up 4 directory le*el. Typing 5 dots to go up 4 directory structure is really easy to remember( as when you type the first two dots( you are thinking Qgoing up one directoryR( after that e*ery additional dot( is to go one le*el up.
16
www.thegeekstuff.com
&o( use P. 9four dots; to go up 3 directory le*el and .. 9two dots; to go up 1 directory le*el. "dd the following alias to your LJ.bashMprofile and re.login for the P.. 9fi*e dots; to work properly. alias ..02cd ..2 alias ...02cd ../..2 alias ....02cd ../../..2 alias .....02cd ../../../..2 alias ......02cd ../../../../..2 ) cd /t!p/(ery/lon /directory/structure/that/is/too/deep ) ..... *Note: use ..... 7fi(e dots8 to ) pwd /t!p/(ery/lon /directory/structure/ o up 5 directory le(el,
cd follo*ed by
2n the e!ample below( cdP.. 9cd followed by fi*e dots; is used to go up 4 directory le*el. /aking it 5 dots to go up 4 directory structure is really easy to remember( as when you type the first two dots( you are thinking Qgoing up one directoryR( after that e*ery additional dot( is to go one le*el up. &o( use cdP. 9cd followed by four dots; to go up 3 directory le*el and cdP 9cd followed by three dots; to go up 2 directory le*el. "dd the following alias to your LJ.bashMprofile and re.login for the abo*e cdP.. 9fi*e dots; to work properly. alias cd..02cd ..2 alias cd...02cd ../..2 alias cd....02cd ../../..2 alias cd.....02cd ../../../..2 alias cd......02cd ../../../../..2
1,
www.thegeekstuff.com
) cd /t!p/(ery/lon /directory/structure/that/is/too/deep ) cd..... *Note: use cd..... to ) pwd /t!p/(ery/lon /directory/structure o up 5 directory le(el,
cd follo*ed by
2n the e!ample below( cd4 9cd followed by number 4; is used to go up 4 directory le*el. alias cd102cd ..2 alias cd302cd ../..2 alias cd402cd ../../..2 alias cd502cd ../../../..2 alias cd602cd ../../../../..2
a )in le
&ometimes when you create a new directory( you may cd to the new directory immediately to perform some work as shown below. ) !kdir #p /t!p/su"dir1/su"dir3/su"dir4 ) cd /t!p/su"dir1/su"dir3/su"dir4 ) pwd /t!p/su"dir1/su"dir3/su"dir4
1D
www.thegeekstuff.com
=ouldn3t it be nice to combine both mkdir and cd in a single commandG "dd the following to the .bashMprofile and re.login. ) (i ."ash9profile function !kdircd 78 : !kdir #p 2;<2 == e(al cd 2>2>;;)>22? @
5ow( perform both mkdir and cd at the same time using a single command as shown below1 ) !kdircd /t!p/su"dir1/su"dir3/su"dir4 *Note: +his creates the directory and cd to it auto!atically, ) pwd /t!p/su"dir1/su"dir3/su"dir4
Hack 0. To
le 'et*een "irectories
Aou can toggle between the last two current directories using cd . as shown below. ) cd /t!p/(ery/lon /directory/structure/that/is/too/deep ) cd /t!p/su"dir1/su"dir3/su"dir4 ) cd ) pwd /t!p/(ery/lon /directory/structure/that/is/too/deep
) cd ) pwd /t!p/su"dir1/su"dir3/su"dir4 1-
www.thegeekstuff.com
)irs will always print the current directory followed by the content of the stack. :*en when the directory stack is empty( dirs command will still print only the current directory as shown below. ) popd #"ash: popd: directory stack e!pty ) dirs 1 ) pwd /ho!e/ra!esh
'ow to use pushd and popdG et us first create some temporary directories and push them to the directory stack as shown below. ) !kdir /t!p/dir1 ) !kdir /t!p/dir3 ) !kdir /t!p/dir4 ) !kdir /t!p/dir5 20
www.thegeekstuff.com
) cd /t!p/dir1 ) pushd . ) cd /t!p/dir3 ) pushd . ) cd /t!p/dir4 ) pushd . ) cd /t!p/dir5 ) pushd . ) dirs /t!p/dir5 /t!p/dir5 /t!p/dir4 /t!p/dir3 /t!p/dir1 *Note: +he first directory 7/t!p/dir58 of the dir co!!and output is always the current directory and not the content fro! the stack.,
"t this stage( the directory stack contains the following directories1 /t!p/dir5 /t!p/dir4 /t!p/dir3 /t!p/dir1
The last directory that was pushed to the stack will be at the top. =hen you perform popd( it will cd to the top directory entry in the stack and remo*e it from the stack. "s shown abo*e( the last directory that was pushed into the stack is JtmpJdir4. &o( when we do a popd( it will cd to the JtmpJdir4 and remo*e it from the directory stack as shown below. ) popd 21
www.thegeekstuff.com
) pwd /t!p/dir5 *Note: %fter the a"o(e popd, directory $tack Contains: /t!p/dir4 /t!p/dir3 /t!p/dir1, ) popd ) pwd /t!p/dir4 *Note: %fter the a"o(e popd, directory $tack Contains: /t!p/dir3 /t!p/dir1, ) popd ) pwd /t!p/dir3 *Note: %fter the a"o(e popd, directory $tack Contains: /t!p/dir1, ) popd ) pwd /t!p/dir1 *Note: %fter the a"o(e popd, directory $tack is e!ptyA, ) popd #"ash: popd: directory stack e!pty
22
www.thegeekstuff.com
23
www.thegeekstuff.com
a specific key*ord on a
2n this e!ample( grep looks for the te!t Sohn inside JetcJpasswd file and displays all the matching lines. ) rep Dohn /etc/passwd
%ption .*( will display all the lines e!cept the match. 2n the e!ample below( it displays all the records from JetcJpassword that doesn>t match Sohn. +ote. There are se*eral lines in the JetcJpassword that doesn3t contain the word Sohn. %nly the first line of the output is shown below. ) rep #( Dohn /etc/passwd
E"ourne:-:10F5:10F5:Dason Bourne:/ho!e/E"ourne:/"in/"ash
www.thegeekstuff.com
) 3
Aou can also get the total number of lines that did not match the specific pattern by passing option .c*. ) 4G rep #c( Dohn /etc/passwd
the caseJ
0ass the option .i 9ignore case;( which will ignore the case while searching. ) rep #i Eohn /etc/passwd
Hse option .r 9recursi*e; for this purpose. 2n the e!ample below( it will search for the te!t FSohnF by ignoring the case inside all the subdirectories under JhomeJusers. This will display the output in the format of Ffilename1 line that matching the patternF. Aou can also pass the option .l( which will display only the name of the file that matches the pattern. ) rep #ri Eohn /ho!e/users
/ho!e/users/su"dir1/letter.t-t:Dohn, +hanks for your contri"ution. /ho!e/users/na!e9list.t-t:Dohn $!ith /ho!e/users/na!e9list.t-t:Dohn .oe ) rep #ril Eohn /root 25
www.thegeekstuff.com
/ho!e/users/su"dir1/letter.t-t /ho!e/users/na!e9list.t-t
Additional Grep Examples: Get a Grip on the GrepA H 16 /ractical Grep Co!!and I-a!ples +he /ower of J Co!!ands H Jcat, Jless, J rep, Jdiff I-a!ples K Linu- Grep LM, Grep %&., Grep &L+ Lperator I-a!ples
'e innin
of line K L M
2n grep command( caret &ymbol T matches the e!pression at the start of a line. 2n the following e!ample( it displays all the line which starts with the 5o* 10. i.e "ll the messages logged on 5o*ember 10. ; rep 2N&o( 102 !essa es.1 s134 ntpd*3351,: ti!e reset O0.1KK5KG s
&o( 10 01:13:66
&o( 10 01:1K:1K s134 ntpd*3351,: synchroniPed to LLC%L708, stratu! 10 &o( 10 01:1F:5G s134 ntpd*3351,: synchroniPed to 16.1.14.14, stratu! 4 &o( 10 14:31:3C s134 ntpd*3351,: ti!e reset O0.15CCC5 s 26
www.thegeekstuff.com
&o( 10 14:36:5C s134 ntpd*3351,: synchroniPed to LLC%L708, stratu! 10 &o( 10 14:3C:3K s134 ntpd*3351,: synchroniPed to 16.1.14.14, stratu! 4
The T matches the e!pression in the beginning of a line( only if it is the first character in a regular e!pression. T5 matches line beginning with 5.
Dul 13 1K:01:0G clone!e kernel: Qernel lo ter!inatin . Lct 3F 0C:3G:65 clone!e kernel: Qernel lo ter!inatin .
Crom the abo*e output you can come to know when all the kernel log has got terminated. Sust like T matches the beginning of the line only if it is the first character( N matches the end of the line only if it is the last character in a regular e!pression.
!essa es:0 anaconda.lo :4 The abo*e commands displays the count of the empty lines a*ailable in the messages and anaconda.log files.
2,
www.thegeekstuff.com
5ow let us search for a word which has any single character followed by ello. i.e hello( cello etc.( ; rep 2.ello2 input
3. hi hello 4. hi Pello how are you 5. cello 6. aello C. eello 2n case if you want to search for a word which has only 4 character you can gi*e grep .w QP.R where single dot represents any single character.
2D
www.thegeekstuff.com
!essa es.5:Dul 13 1K:01:03 clone!e kernel: %C/B: /CB interrupt for de(ice 0000:00:11.0 disa"led !essa es.5:Lct 3F 0C:3G:5G clone!e kernel: %C/B: /S#+i!er BL /ort: 0-100F !essa es.5:Lct 3F 0C:41:0C "to(!FK1 kernel: sda3 sda4 sda: sda1
!essa es.5:Lct 3F 0C:41:0C "to(!FK1 kernel: sd 0:0:0:0: %ttached scsi disk sda . . 2n the abo*e e!ample it matches for kernel and colon symbol followed by any number of spacesJno space and Q.R matches any single character.
Additional Grep Reg-Ex Examples: Me ular I-pressions in Grep Co!!and with 10 I-a!ples H /art B %d(anced Me ular I-pressions in Grep Co!!and with 10 I-a!ples H /art BB
The following command looks for all the files under Jetc directory with mail in the filename. 2-
www.thegeekstuff.com
The following command will list all the files in the system greater than 100/8. ) find / #type f #siPe O100S
Ho* to find files that are not #odified in the last x nu#ber of daysJ
The following command will list all the files that were modified more than 60 days ago under the current directory. ) find . #!ti!e OC0
Ho* to find files that are #odified in the last x nu#ber of daysJ
The following command will list all the files that were modified in the last two days under the current directory. ) find . H!ti!e #3
Ho* to delete all the archi2e files *ith extension E.tar. B and reater than 100&'J
0lease be careful while e!ecuting the following command as you don3t want to delete the files by mistake. The best practice is to e!ecute the same command with ls $l to make sure you know which files will get deleted when you e!ecute the command with rm. ) find / #type f #na!e R.tar. P #siPe O100S #e-ec ls #l :@ >? ) find / #type f #na!e R.tar. P #siPe O100S #e-ec r! #f :@ >?
30
www.thegeekstuff.com
Ho* to archi2e all the files that are not #odified in the last x nu#ber of daysJ
The following command finds all the files not modified in the last 60 days under JhomeJ6smith directory and creates an archi*e files under Jtmp in the format of ddmmyyyyMarchi*e.tar. ) find /ho!e/Es!ith #type f #!ti!e OC0 T -ar s tar #c(f /t!p/Udate VOWdW!WYV9archi(e.tarU
Additional Find Examples: So!!y, B found itA X 16 /ractical Linu- Yind Co!!and I-a!ples .addy, B found itA, 16 %weso!e Linu- Yind Co!!and I-a!ples 7/art38
O Pde2Pnull
This will be *ery helpful when you are debugging shell scripts( where you don3t want to display the echo statement and interested in only looking at the error messages. ) cat file.t-t Z /de(/null ) ./shell#script.sh Z /de(/null
31
www.thegeekstuff.com
,O Pde2Pnull
This is also helpful when you are interested in *iewing only the standard output and don3t want to *iew the error messages. ) cat in(alid#file#na!e.t-t 3Z /de(/null ) ./shell#script.sh 3Z /de(/null
+ote. %ne of the most effecti*e ways to use this is in the crontab( where you can suppress the output and error message of a cron task as shown below. 40 1 R R R co!!and Z /de(/null 3Z=1
www.thegeekstuff.com
; Eoin e!ployee.t-t "onus.t-t 100 Dason $!ith ;6,000 300 Dohn .oe ;600 400 $anEay Gupta ;4,000 500 %shok $har!a ;1,360
www.thegeekstuff.com
; tr %#J a#P [ depart!ent.t-t 100 finance 300 !arketin 400 product de(elop!ent 500 sales
2. 7et a list of all the U.conf file under JetcJ. There are different ways to get the same result. Collowing e!ample is only to demonstrate the use of !args. The output of the find command in this e!ample is passed to the ls $l one by one using !args. ) find /etc #na!e 2R.conf2 T -ar s ls Hl
3. 2f you ha*e a file with list of H4 s that you would like to download( you can use !args as shown below. ) cat url#list.t-t T -ar s w et Hc
www.thegeekstuff.com
5. #opy all the images to an e!ternal hard.dri*e. ) ls R.Ep T -ar s #n1 #i cp :@ /e-ternal#hard# dri(e/directory
; cat na!es.t-t I!!a +ho!as:100:Sarketin %le- Dason:300:$ales Sadison Mandy:400:/roduct .e(elop!ent $anEay Gupta:500:$upport &isha $in h:600:$ales
&ort a te!t file in ascending order ; sort na!es.t-t %le- Dason:300:$ales I!!a +ho!as:100:Sarketin Sadison Mandy:400:/roduct .e(elop!ent &isha $in h:600:$ales $anEay Gupta:500:$upport
www.thegeekstuff.com
; sort #r na!es.t-t $anEay Gupta:500:$upport &isha $in h:600:$ales Sadison Mandy:400:/roduct .e(elop!ent I!!a +ho!as:100:Sarketin %le- Dason:300:$ales
&ort a colon delimited te!t file on 2nd field 9employeeMid; ; sort #t: #k 3 na!es.t-t I!!a +ho!as:100:Sarketin %le- Dason:300:$ales Sadison Mandy:400:/roduct .e(elop!ent $anEay Gupta:500:$upport &isha $in h:600:$ales
&ort a tab delimited te!t file on 3rd field 9departmentMname; and suppress duplicates ; sort #t: #u #k 4 na!es.t-t I!!a +ho!as:100:Sarketin Sadison Mandy:400:/roduct .e(elop!ent %le- Dason:300:$ales $anEay Gupta:500:$upport
&ort the passwd file by the 3rd field 9numeric userid; ; sort #t: #k 4n /etc/passwd T !ore root:-:0:0:root:/root:/"in/"ash "in:-:1:1:"in:/"in:/s"in/nolo in dae!on:-:3:3:dae!on:/s"in:/s"in/nolo in ad!:-:4:5:ad!:/(ar/ad!:/s"in/nolo in 36
www.thegeekstuff.com
lp:-:5:K:lp:/(ar/spool/lpd:/s"in/nolo in
&ort JetcJhosts file by ip.address ; sort #t . #k 1,1n #k 3,3n #k 4,4n #k 5,5n /etc/hosts 13K.0.0.1 localhost.localdo!ain localhost 1G3.1CF.100.101 de(#d".the eekstuff.co! de(#d" 1G3.1CF.100.103 prod#d".the eekstuff.co! prod#d" 1G3.1CF.101.30 1G3.1CF.101.31 de(#we".the eekstuff.co! de(#we" prod#we".the eekstuff.co! prod#we"
#ombine sort with other commands ps =ef Q sort 1 &ort the output of process list ls <al Q sort R0n 1 ist the files in the ascending order of the file. si+e. i.e sorted by 5th filed and displaying smallest files first. ls <al Q sort R0nr 1 ist the files in the descending order of the file.si+e. i.e sorted by 5th filed and displaying largest files first.
3,
www.thegeekstuff.com
2. 2f you want to know how many lines are duplicates( do the following. The first field in the following e!amples indicates how many duplicates where found for that particular line. &o( in this e!ample the lines beginning with "le! and :mma were found twice in the namesd.t!t file. ; sort na!esd.t-t T uni_ Hc 3 %le- Dason:300:$ales 3 I!!a +ho!as:100:Sarketin 1 Sadison Mandy:400:/roduct .e(elop!ent 1 &isha $in h:600:$ales 1 $anEay Gupta:500:$upport
3. The following displays only the entries that are duplicates. ; sort na!esd.t-t T uni_ Hcd 3 %le- Dason:300:$ales 3 I!!a +ho!as:100:Sarketin
3D
www.thegeekstuff.com
)isplay 1st and 3rd field from a colon delimited file ; cut #d: #f 1,4 na!es.t-t I!!a +ho!as:Sarketin %le- Dason:$ales Sadison Mandy:/roduct .e(elop!ent $anEay Gupta:$upport &isha $in h:$ales
)isplay only the first D characters of e*ery line in a file ; cut #c 1#F na!es.t-t I!!a +ho %le- Das Sadison $anEay G &isha $i
/isc #ut command e!amples cut <d. <f1 PetcPpass*d )isplays the uni! login names for all the users in the system. free Q tr <s S S Q sed SPL&e#PDdS Q cut <dT T <f, )isplays the total memory a*ailable on the system.
www.thegeekstuff.com
$iPe: 45C Blocks: 1C BL Block: 50GC .e(ice: F01h/305Gd Bnode: 3KGF6C \id: 70/root8 %ccess: 70C55/#rw#r##r##8
%ccess: 300G#01#01 03:6F:40.000000000 #0F00 Sodify: 300C#0C#01 30:53:3K.000000000 #0K00 Chan e: 300K#03#03 15:1K:3K.000000000 #0F00 ; stat /ho!e/ra!esh Yile: U/ho!e/ra!eshV $iPe: 50GC directory .e(ice: F04h/3061d Blocks: F Bnode: 663150G BL Block: 50GC Links: K Gid:
\id: 7501/ra!esh8
%ccess: 300G#01#01 13:1K:53.000000000 #0F00 Sodify: 300G#01#01 13:0K:44.000000000 #0F00 Chan e: 300G#01#0G 13:0K:44.000000000 #0F00
)isplay the status of the filesystem using option $f ; stat #f / Yile: 2/2 B.: 0 &a!elen: 366 +ype: e-t3/e-t4 %(aila"le: Blocks: +otal: 36KG56K 1FKCGGF $iPe: 50GC Bnodes: +otal: 1410K30 Yree: 300F03K Yree: 1316FG3
Additional Stat Examples: \ni- $tat Co!!and: How +o Bdentify Yile %ttri"utes
40
www.thegeekstuff.com
) diff #w na!e9list.t-t na!e9list9new.t-t 3c3,4 [ Dohn .oe ### Z Dohn S .oe Z Dason Bourne
Additional Di
Examples:
41
www.thegeekstuff.com
ed in user
=ith the option $d( it will break down the output for the indi*idual days. 2n this e!ample( 23*e been logged in to the system for more than 6 hours today. %n )ec 1st( 2 was logged in for about 1 hour. ; ac Hd .ec .ec .ec .ec +oday 1 3 4 5 total total total total total 1.0F 0.GG 4.4G 5.60 C.10
42
www.thegeekstuff.com
ðod 1. 1se !
Aou can e!ecute a command 9or shell script; as a background 6ob by appending an ampersand to the command as shown below. ; ./!y#shell#script.sh =
ðod ,. +ohup
"fter you e!ecute a command 9or shell script; in the background using Y( if you logout from the session( the command will get killed. To a*oid that( you should use nohup as shown below. ; nohup ./!y#shell#script.sh =
www.thegeekstuff.com
connect to the same session again to see e!actly what is happening on the screen. To do that( you should use screen command. inu! screen command offers the ability to detach a session that is running some process( and then attach it at a later time. =hen you reattach the session later( your terminals will be there e!actly in the way you left them earlier.
ðod 0. At Co##and
Hsing at command you can schedule a 6ob to run at a particular date and time. Cor e!ample( to e!ecute the backup script at 10 a.m tomorrow( do the following. ; at #f "ackup.sh 10 a! to!orrow
Additional !ac"ground #ommand Examples: B , Y , =, Ctrl#J H 6 I-a!ples to Sana e \ni- Back round Do"s \ni- &ohup: Mun a Co!!and or $hell#$cript I(en after You Lo out $creen Co!!and I-a!ples: Get Control of Linu- / \ni+er!inal at, at_, atr!, "atch Co!!ands usin G I-a!ples
44
www.thegeekstuff.com
C "7& can be any of the following 1 g 4eplace all the instance of 4:7:I0 with 4:0 "#:/:5T n #ould be any number(replace nth instance of the 4:7:I0 with 4:0 "#:/:5T. p 2f substitution was made( then prints the new pattern space. i match 4:7:I0 in a case.insensiti*e manner. w file 2f substitution was made( write out the result to the gi*en file. 45
www.thegeekstuff.com
et us first create thegeekstuff.t!t file that will be used in all the e!amples mentioned below. ; cat the eekstuff.t-t ) Bnstruction Guides 1. Linu- $ysad!in, Linu- $criptin 3. .ata"ases # Lracle, !y$bL etc. 4. $ecurity 7Yirewall, &etwork, Lnline $ecurity etc8 5. $tora e in Linu6. /roducti(ity 7+oo !any technolo ies to e-plore, not !uch ti!e a(aila"le8 ) %dditional Y%b$ C. `indows# $ysad!in, re"oot etc. etc.
sed sPP
2n the e!ample below( in the output line Q1. inu!.Hni! &ysadmin( inu! &cripting etcR only first inu! is replaced by inu!.Hni!. 2f no flags are specified the first match of line is replaced. ; sed Vs/Linu-/Linu-#\ni-/V the eekstuff.t-t ) Bnstruction Guides 1. Linu-#\ni- $ysad!in, Linu- $criptin 3. .ata"ases # Lracle, !y$bL etc. 4. $ecurity 7Yirewall, &etwork, Lnline $ecurity etc8 5. $tora e in Linu-#\ni6. /roducti(ity 7+oo !any technolo ies to e-plore, not !uch ti!e a(aila"le8 ) %dditional Y%b$ C. `indows# $ysad!in, re"oot etc. etc.
46
www.thegeekstuff.com
sed sPP
The below sed command replaces all occurrences of inu! to inu!.Hni! using global substitution flag QgR. ; sed Vs/Linu-/Linu-#\ni-/ V the eekstuff.t-t ) Bnstruction Guides 1. Linu-#\ni- $ysad!in, Linu-#\ni- $criptin 3. .ata"ases # Lracle, !y$bL etc. 4. $ecurity 7Yirewall, &etwork, Lnline $ecurity etc8 5. $tora e in Linu-#\ni6. /roducti(ity 7+oo !any technolo ies to e-plore, not !uch ti!e a(aila"le8 ) %dditional Y%b$ C. `indows# $ysad!in, re"oot etc. etc.
sed sPP,
2n the e!ample below( in the output line Q1. inu! &ysadmin( inu!.Hni! &cripting etc.R only 2nd occurrence of inu! is replaced by inu!.Hni!. ; sed Vs/Linu-/Linu-#\ni-/3V the eekstuff.t-t ) Bnstruction Guides 1. Linu- $ysad!in, Linu-#\ni- $criptin 3. .ata"ases # Lracle, !y$bL etc. 4. $ecurity 7Yirewall, &etwork, Lnline $ecurity etc8 5. $tora e in Linu6. /roducti(ity 7+oo !any technolo ies to e-plore, not !uch ti!e a(aila"le8 ) %dditional Y%b$ sed C. `indows# $ysad!in, re"oot etc. 5. `rite Chan es to a Yile and /rint the Chan es \sin s// pw etc.
The e!ample below has substitution with three flags. 2t substitutes all the occurrence of inu! to inu!.Hni! and prints the substituted output as well as written the same to the gi*en the file. 4,
www.thegeekstuff.com
; sed #n Vs/Linu-/Linu-#\ni-/ pw outputV the eekstuff.t-t 1. Linu-#\ni- $ysad!in, Linu-#\ni- $criptin 5. $tora e in Linu-#\ni; cat output 1. Linu-#\ni- $ysad!in, Linu-#\ni- $criptin 5. $tora e in Linu-#\ni6. $u"stitute Lnly `hen the Line Satches with the /attern \sin sed etc. etc.
2n this e!ample( if the line matches with the pattern Q.R( then it replaces all the characters from Q.R with the empty. ; sed V/>#/s/>#.R// V the eekstuff.t-t ) Bnstruction Guides 1. Linu- $ysad!in, Linu- $criptin 3. .ata"ases 4. $ecurity 7Yirewall, &etwork, Lnline $ecurity etc8 5. $tora e in Linu6. /roducti(ity 7+oo !any technolo ies to e-plore, not !uch ti!e a(aila"le8 ) %dditional Y%b$ C. `indows etc.
www.thegeekstuff.com
5. $tora e in Li 6. /roducti(ity 7+oo !any technolo ies to e-plore, not !uch ti!e a(aila" ) %dditional Y C. `indows# $ysad!in, re"oot e
sed
)elete all the comment lines from a file as shown below using sed command. ; sed #e Vs/).R//V the eekstuff.t-t etc.
4. $ecurity 7Yirewall, &etwork, Lnline $ecurity etc8 5. $tora e in Linu6. /roducti(ity 7+oo !any technolo ies to e-plore, not !uch ti!e a(aila"le8 C. `indows# $ysad!in, re"oot etc. F. Ili!inate Co!!ents and I!pty Lines \sin sed
2n the following e!ample( there are two commands separated by ][3 Cirst command replaces the lines starting with the ^ to the blank lines &econd command deletes the empty lines. ; sed #e Vs/).R//?/N;/dV the eekstuff.t-t etc.
4-
www.thegeekstuff.com
6. /roducti(ity 7+oo !any technolo ies to e-plore, not !uch ti!e a(aila"le8 C. `indows# $ysad!in, re"oot etc. G. Con(ert .L$ newlines 7CM/LY8 to \ni- for!at \sin sed
sed
2n this e!ample( the regular e!pression gi*en in the sed command matches the html tags and replaces with the empty. ; sed #e Vs/[*NZ,RZ// V +his ["Z is [/"Z an [iZe-a!ple[/iZ. +his is an e-a!ple.
Any Questions? .iscuss it here: $ed +utorial: Yind and Meplace +e-t Bnside a Yile \sin Me IAdditional Sed Su$stitution Examples: %d(anced $ed $u"stitution I-a!ples
8perations
"wk is a programming language which allows easy manipulation of structured data and the generation of formatted reports. "wk stands for the names of its authors Q"ho( =einberger( and _ernighanR 50
www.thegeekstuff.com
The "wk is mostly used for pattern scanning and processing. 2t searches one or more files to see if they contain lines that matches with the specified patterns and then perform associated actions. &ome of the key features of "wk are1 "wk *iews a te!t file as records and fields. ike common programming language( "wk has *ariables( conditionals and loops "wk has arithmetic and string operators. "wk can generate formatted reports "wk reads from a file or from its standard input( and outputs to its standard output. "wk does not get along with non.te!t files.
2n the abo*e awk synta!1 search pattern is a regular e!pression. "ctions $ statement9s; to be performed. se*eral patterns and actions are possible in "wk. file $ 2nput file. &ingle @uotes around program is to a*oid shell not to interpret any of its special characters.
A*k >orkin
ðodolo y
1. "wk reads the input files one line at a time. 2. Cor each line( it matches with gi*en pattern in the gi*en order( if matches performs the corresponding action. 3. 2f no pattern matches( no action will be performed. 4. 2n the abo*e synta!( either search pattern or action are optional( 8ut not both. 51
www.thegeekstuff.com
5. 2f the search pattern is not gi*en( then "wk performs the gi*en actions for each line of the input. 6. 2f the action is not gi*en( print all that lines that matches with the gi*en patterns which is the default action. ,. :mpty braces with out any action does nothing. 2t wont perform default printing operation. D. :ach statement in "ctions should be delimited by semicolon. et us create employee.t!t file which has the following content( which will be used in the e!amples mentioned below. ; cat e!ployee.t-t 100 300 400 500 600 +ho!as Dason $anEay &isha Mandy Sana er .e(eloper $ysad!in Sana er .B% $ales +echnolo y +echnolo y Sarketin +echnolo y ;6,000 ;6,600 ;K,000 ;G,600 ;C,000
2n the abo*e e!ample pattern is not gi*en. &o the actions are applicable to all the lines. "ction print with out any argument prints the whole line by default. &o it prints all the lines of the file with out fail. "ctions has to be enclosed with in the braces.
52
www.thegeekstuff.com
2n the abo*e e!ample it prints all the line which matches with the ]Thomas3 or ]5isha3. 2t has two patterns. "wk accepts any number of patterns( but each set 9patterns and its corresponding actions; has to be separated by newline.
2n the abo*e e!ample N2 and N5 represents 5ame and &alary respecti*ely. =e can get the &alary using N5C also( where N5C represents last field. 2n the print statement ](3 is a concatenator. 53
www.thegeekstuff.com
; awk VBIGB& :print 2&a!e>t.esi nation>t.epart!ent>t$alary2?@ Z :print ;3,2>t2,;4,2>t2,;5,2>t2,;&Y?@ Z I&.:print 2Meport Generated>n##############2? Z @V e!ployee.t-t &a!e +ho!as Dason $anEay &isha Mandy .esi nation .epart!ent Sana er .e(eloper $ysad!in Sana er .B% $ales +echnolo y +echnolo y Sarketin +echnolo y $alary ;6,000 ;6,600 ;K,000 ;G,600 ;C,000
2n the abo*e e!ample( it prints headline and last file for the reports. 54
www.thegeekstuff.com
2n the abo*e e!ample( first field 9N1; is employee id. &o if N1 is greater than 200( then 6ust do the default print action to print the whole line.
%perator L is for comparing with the regular e!pressions. 2f it matches the default action i.e print whole line will be performed.
55
www.thegeekstuff.com
Then at the end of the process( 6ust print the *alue of count which gi*es you the number of employees in Technology department.
Any Questions? .iscuss it here: %wk Bntroduction +utorial H K %wk /rint I-a!ples Additional A%" Examples: \nderstand %wk 'aria"les with 4 /ractical I-a!ples F /owerful %wk Built#in 'aria"les H Y$, LY$, M$, LM$, &M, &Y, YBLI&%SI, Y&M K /owerful %wk Lperators I-a!ples 7\nary, Binary, %rith!etic, $trin , %ssi n!ent, Conditional, Me #I- %wk Lperators8 %`Q %rrays I-plained with 6 /ractical I-a!ples
www.thegeekstuff.com
8y using the repeat factor in ?2/ we can do this operation for 5 times. Cor e!ample( when you want to go down by 10 lines( then type Q106R. =ithin a line if you want to na*igate to different position( you ha*e 4 other options. 0 $ go to the starting of the current line. T $ go to the first non blank character of the line. N $ go to the end of the current line. gM $ go to the last non blank character of the line.
www.thegeekstuff.com
=%4) $ =%4) consists of a se@uence of non.blank characters( separated with white space. word $ word consists of a se@uence of letters( digits and underscores. :!ample to show the difference between =%4) and word 1-2.16D.1.1 $ single =%4) 1-2.16D.1.1 $ se*en words.
www.thegeekstuff.com
a $ 7o to the beginning of the current paragraph. 8y pressing a again and again mo*e to the pre*ious paragraph beginnings. b $ 7o to the end of the current paragraph. 8y pressing b again and again mo*e to the ne!t paragraph end( and again.
?im `Jpattern filename1 7o to the particular pattern3s line inside the file( first occurrence from first. 2n the following e!ample( it will open the 4:")/: file and 6ump to the first occurrence of the word QinstallR. (i! O/install MI%.SI
?im `Gpatten filename1 7o to the particular pattern3s line inside the file( first occurrence from last. 2n the following e!ample( it will open the 4:")/: file and 6ump to the last occurrence of the word QbugR. (i! Oc"u MI%.SI 5-
www.thegeekstuff.com
Any Questions? .iscuss it here: F Issential 'i! Iditor &a(i ation Yunda!entals &ore 'im Examples: 'i! search and replace H 13 powerful find and replace e-a!ples. How +o add "ook!arks inside the 'i! editor How +o record and play inside the 'i! editor Correct spellin Iditor !istakes auto!atically inside the 'i!
Collowing are the symbolic representation of three different permissions1 r is for read permission( w is for write permission( ! is for e!ecute permission.
60
www.thegeekstuff.com
The following are few e!amples on how to use the symbolic representation on chmod.
61
www.thegeekstuff.com
Chan e execute per#ission only on the directories Kfiles are not affectedM
%n a particular directory if you ha*e multiple sub.directories and files( the following command will assign e!ecute permission only to all the sub.directories in the current directory 9not the files in the current directory;. ; ch!od uOa R 5ote1 2f the files has e!ecute permission already for either the group or others( the abo*e command will assign the e!ecute permission to the user.
Any Questions? .iscuss it here: K Ch!od Co!!and I-a!ples for Be inners Additional chmod Examples: Be inners Guide to Yile and .irectory /er!issions 7 u!ask, ch!od, read, write, e-ecute 8
7iles in 8ne
Typically you may open multiple terminals to *iew tail .f of multiple files. Cor e!ample( if you want to *iew "pache errorMlog and accessMlog at the same time you may do the following in two different terminals. 62
www.thegeekstuff.com
8ut( waitc =ouldn3t it be nice if you can e!ecute multiple uni! tail command in single terminal using one of the following methodsG ; !ulti#tail.sh error9lo 7or8 ; tail #f /(ar/lo /syslo #f /(ar/lo /auth.lo access9lo
This hack e!plains two methods on how to e!ecute multiple inu! tail .f at the same time in single terminal.
www.thegeekstuff.com
) show tails of each in "ack round. tail #f ;file = done ) wait .. until C+MLOC wait
5ow( open multiple files using this new shell script as shown below. ; ./!ulti#tail.sh error9lo access9lo
Any Questions? .iscuss it here: 4 Sethods +o 'iew tail #f output of Sultiple Lo Yiles in Lne +er!inal
64
www.thegeekstuff.com
The na*igation keys in less command are similar to ?im editor. This hack e!plains less command na*igation and other operations which will make you a better command line warrior.
Hse the following shortcut for the less command backward search 1 G $ search for a pattern which will take you to the pre*ious occurrence. n $ for ne!t match in backward direction 5 $ for pre*ious match in forward direction
Tip1 2f you don>t bother about which direction the search is happening( and you want to search file path( or H4 ( such as QJhomeJrameshJR( you can use backward search 9Gpattern; which will be handy as you don3t want to escape slashes each time. $earch /ath Bn forward: />/ho!e>/ra!esh>/ Bn "ackward: c/ho!e/ra!esh/
www.thegeekstuff.com
#T4 `8 $ backward one window #T4 `) $ forward half window #T4 `H $ backward half window
Count #a ic
&imilar to ?im editor na*igation command( you can gi*e 106 to scroll 10 lines down( or 10k to go up by 10 lines. 106 $ 10 lines forward. 10k $ 10 lines backward. #T4 `7 $ show the current file name along with line( byte and percentage statistics.
66
www.thegeekstuff.com
&ultiple file pa in
/ethod 11 Aou can open multiple files by passing the file names as arguments. ; less file1 file3
/ethod 21 =hile you are *iewing file1( use 1e to open the file2 as shown below. N less file1 :e file3
5a*igation across files1 =hen you opened more than two files 9 for e.g $ less U ;( use the following keys to na*igate between files. 1n $ go to the ne!t file. 1p $ go to the pre*ious file.
Any Questions?
6,
www.thegeekstuff.com
.iscuss it here: Less Co!!and: 10 +ips for Iffecti(e &a(i ation Additional (ess Examples: Lpen = 'iew 10 .ifferent Yile +ypes with Linu- Less Co!!and
=hile downloading it will show a progress bar with the following information1 \age of download completion 9for e.g. 31\ as shown below; Total amount of bytes downloaded so far 9for e.g. 1(213(5-2 bytes as shown below; #urrent download speed 9for e.g. 6D.2_Js as shown below; 4emaining time to download 9for e.g. eta 34 seconds as shown below;
6D
www.thegeekstuff.com
)ownload in progress1 ; w et http://www.openssK.or /repos/tar"alls/str-36# 0.G.3.1.tar."P3 $a(in to: Ustr-36#0.G.3.1.tar."P3.1V CF.3Q/s eta 45s
)ownload completed1 ; w et http://www.openssK.or /repos/tar"alls/str-36# 0.G.3.1.tar."P3 $a(in to: Ustr-36#0.G.3.1.tar."P3V KC.FQ/s in 66s
100W*0000000000000000000000Z, 4,F63,4K5
:*en though the downloaded file is in +ip format( it will get stored in the file as shown below. ; ls download9script.phpcsrc9id0KK01 6-
www.thegeekstuff.com
Correct. To correct this issue( we can specify the output file name using the .% option as1 ; w et #L ta list.Pip http://www.(i!.or /scripts/download9script.phpcsrc9id0KK01
* et =
=hile e!ecuting the wget( by default it will try to occupy full possible bandwidth. This might not be acceptable when you are downloading huge files on production ser*ers. &o( to a*oid that we can limit the download speed using the $limit.rate as shown below. 2n the following e!ample( the download speed is limited to 200k ; w et ##li!it#rate0300k http://www.openssK.or /repos/tar"alls/str-36# 0.G.3.1.tar."P3
* et <c
4estart a download which got stopped in the middle using wget .c option as shown below. ; w et #c http://www.openssK.or /repos/tar"alls/str-36# 0.G.3.1.tar."P3
This is *ery helpful when you ha*e initiated a *ery big file download which got interrupted in the middle. 2nstead of starting the whole download again( you can start the download from where it got interrupted using option .c +ote. 2f a download is stopped in middle( when you restart the download again without the option .c( wget will append .1 to the filename automatically as a file with the pre*ious name already e!ist. 2f a file with .1 already e!ist( it will download the file with .2 at the end.
,0
www.thegeekstuff.com
* et <b
Cor a huge download( put the download in background using wget option .b as shown below. ; w et #" http://www.openssK.or /repos/tar"alls/str-36# 0.G.3.1.tar."P3 Continuin in "ack round, pid 1GF5. Lutput will "e written to Uw et#lo V.
2t will initiate the download and gi*es back the shell prompt to you. Aou can always check the status of the download using tail .f as shown below. ; tail #f w et#lo $a(in to: Ustr-36#0.G.3.1.tar."P3.5V 1W C6.6Q 6Ks 6W FC.CQ 56s KW 1F3S 5Cs GW 6K.GQ 5Ks 0Q ...... ........ ......... .......... 160Q .......... ............. .......... 360Q .......... ............. .......... 400Q .......... ............. ..........
&ask 1ser A ent and "isplay * et like 'ro*ser 1sin * et =user<a ent
&ome websites can disallow you to download its page by identifying that the user agent is not a browser. &o you can mask the user agent by using $user.agent options and show wget like a browser as shown below. ; w et ##user#a ent02SoPilla/6.0 7a11? \? Linu- iCFC? en# \$? r(:1.G.0.48 Gecko/300F0G351C Yirefo-/4.0.42 \ML#+L# .L`&LL%.
* et =spider
=hen you are going to do scheduled download( you should check whether download will happen fine or not at scheduled time. To do so( copy the line e!actly from the schedule( and then add $spider option to check. ,1
www.thegeekstuff.com
; w et ##spider .L`&LL%.#\ML
2f the H4 gi*en is correct( it will say ; w et ##spider download#url $pider !ode ena"led. Check if re!ote file e-ists. H++/ re_uest sent, awaitin response... 300 LQ Len th: unspecified *te-t/ht!l, Me!ote file e-ists and could contain further links, "ut recursion is disa"led ## not retrie(in .
This ensures that the downloading will get success at the scheduled time. 8ut when you had gi*e a wrong H4 ( you will get the following error. ; w et ##spider download#url $pider !ode ena"led. Check if re!ote file e-ists. H++/ re_uest sent, awaitin response... 505 &ot Yound Me!ote file does not e-ist ## "roken linkAAA
Aou can use the spider option under following scenarios1 #heck before scheduling a download. /onitoring whether a website is a*ailable or not at certain inter*als. #heck a list of pages from your bookmark( and find out which pages are still e!ists.
* et =tries
2f the internet connection has problem( and if the download file is large there is a chance of failures in the download. 8y default wget retries 20 times to make the download successful.
,2
www.thegeekstuff.com
2f needed( you can increase retry attempts using $tries option as shown below. ; w et ##tries0K6 .L`&LL%.#\ML
> et <i
Cirst( store all the download files or H4 s in a te!t file as1 ; cat Z download#file#list.t-t \ML1 \ML3 \ML4 \ML5
5e!t( gi*e the download.file.list.t!t as argument to wget using .i option as shown below. ; w et #i download#file#list.t-t
* et =#irror
Collowing is the command line which you want to e!ecute when you want to download a full website and made a*ailable for local *iewing. ; w et ##!irror #p ##con(ert#links #/ ./LLC%L#.BM `IB$B+I# \ML $mirror 1 turn on options suitable for mirroring. .p 1 download all files that are necessary to properly display a gi*en 'T/ page. $con*ert.links 1 after the download( con*ert the links in document for local *iewing. .0 .J %#" .)24 1 sa*e all the files and directories to the specified directory.
,3
www.thegeekstuff.com
1sin
* et =
Aou ha*e found a website which is useful( but don3t want to download the images you can specify the following. ; w et ##reEect0 if `IB$B+I#+L#BI#.L`&LL%.I.
Lo
#essa es to a lo
* et <o
=hen you wanted the log to be redirected to a log file instead of the terminal. ; w et #o download.lo .L`&LL%.#\ML
=hen you want to stop download when it crosses 5 /8 you can use the following wget command line.
; w et #b6! #i YBLI#`HBCH#H%$#\ML$
5ote1 This @uota will not get effect when you do a download a single H4 . That is irrespecti*e of the @uota si+e e*erything will get downloaded when you specify a single file. This @uota is applicable only for recursi*e downloads.
* et <r <A
,4
www.thegeekstuff.com
CT0 download using wget with username and password authentication. ; w et ##ftp#user0\$IM&%SI ##ftp#password0/%$$`LM. .L`&LL%.#\ML
,5
www.thegeekstuff.com
&ometimes it is necessary to *iew debug messages to troubleshoot any &&' connection issues. pass .* 9lowercase *; option to the ssh as shown below to *iew the ssh debug messages. :!ample without &&' client debug message1 ; ssh #l Es!ith re!otehost.e-a!ple.co! warnin : Connectin to re!otehost.e-a!ple.co! failed: &o address associated to the na!e
:!ample with &&' client debug message1 ; ssh #( #l Es!ith re!otehost.e-a!ple.co! de"u : $shConfi /sshconfi .c:3F4F/ssh39parse9confi 9e-t: Setaconfi parsin stopped at line 4. de"u : $shConfi /sshconfi .c:C4K/ssh9confi 9set9para!9(er"ose: $ettin (aria"le ]'er"oseSode^ to ]Y%L$I^. de"u : $shConfi /sshconfi .c:4140/ssh9confi 9read9file9e-t: Mead 1K para!s fro! confi file. de"u : $sh3/ssh3.c:1K0K/!ain: \ser confi usin defaults. 7Looked for ]/ho!e/Es!ith/.ssh3/ssh39confi ^8 de"u : Connectin 7$LCQ$ not used8 file not found,
,6
www.thegeekstuff.com
))H
=hen you3*e logged on to the remotehost using ssh from the localhost( you may want to come back to the localhost to perform some acti*ity and go back to remote host again. 2n this case( you don3t need to disconnect the ssh session to the remote host. 2nstead( follow the steps below. 1. ogin to remotehost from localhost1 localhost; ssh #l Es!ith re!otehost
3. To come back to the localhost temporarily( type the escape character L and #ontrol.d. =hen you type L you will not see that immediately on the screen until you press W#ontrol.dX and press enter. &o( on the remotehost in a new line enter the following key strokes for the below to work1 LW#ontrol.dX re!otehost; )*+ *1,O $topped ssh #l Es!ith re!otehost
localhost;
4. 5ow you are back to the localhost and the ssh remotehost client session runs as a typical H52I background 6ob( which you can check as shown below1 ,,
www.thegeekstuff.com
5. Aou can go back to the remote host ssh without entering the password again by bringing the background ssh remotehost session 6ob to foreground on the localhost. localhost; g -.
2. %n the remotehost( type ssh escape character L followed by s as shown below. This will display lot of useful statistics about the current &&' connection. re!otehost; *Note: +he 1s is not (isi"le on the co!!and line when you type., re!ote host: re!otehost local host: localhost re!ote (ersion: $$H#1.GG#Lpen$$H94.Gp1 local (ersion: $$H#3.0#4.3.G.1 $$H $ecure $hell co!pressed "ytes in: 160C unco!pressed "ytes in: 1C33 ,D
www.thegeekstuff.com
co!pressed "ytes out: 5GGK unco!pressed "ytes out: 611F packets in: 16 packets out: 35 rekeys: 0 %l orith!s: Chosen key e-chan e al orith!: diffie#hell!an# roup1#sha1 Chosen host key al orith!: ssh#dss Co!!on host key al orith!s: ssh#dss,ssh#rsa %l orith!s client to ser(er: Cipher: aes13F#c"c S%C: h!ac#sha1 Co!pression: Pli" %l orith!s ser(er to client: Cipher: aes13F#c"c S%C: h!ac#sha1 Co!pression: Pli" localhost;
,-
www.thegeekstuff.com
2n sshdMconfig( the lines that start with ^ are comments. Cor those options that uses the default *alues( the sshdMconfig file contains a commented line with the option and its default *alue. This makes it easier for us( as we can see the %pen&&' option name and the default *alue without ha*ing to lookup somewhere else. Cor e!ample( sshdMconfig file contains the following commented line. This indicates that the 0ubkey"uthentication option contains QyesR as the default *alue. ; rep #i pu"key /etc/ssh/sshd9confi
)/u"key%uthentication yes
2f you like to change this( you should remo*e the comment and change the *alue 9from yes to no; as shown below. ; (i /etc/ssh/sshd9confi /u"key%uthentication no
2 showed the abo*e only as an e!ample. Aou don3t need to change the default *alue of 0ubkey"uthentication option( as allowing public key authentication is good. Aou don3t need to modify any of the default *alues in the sshdMconfig file e!cept the , options mentioned in this hack.
www.thegeekstuff.com
forced to login as their account first( before they can do ]su .3( this makes the auditing easier. "dd the following entry to sshdMconfig to disable root to login to the ser*er directly. ; (i /etc/ssh/sshd9confi /er!itMootLo in no
"dd the following entry to the sshdMconfig file to allow only the users who belong to a specific group to login. 2n the e!ample below only users who belong to sysadmin and dba group can login to the system. ; (i /etc/ssh/sshd9confi D1
www.thegeekstuff.com
"dd the following entry to the sshdMconfig file to deny users who belong to a specific group to login. 2n the e!ample below users who belong to de*elopers and @a group cannot login to the system. ; (i /etc/ssh/sshd9confi .enyGroups de(elopers _a
+ote. Aou can use combination of all the "llow and )eny directi*es. 2t is processed in this order1 )enyHsers( "llowHsers( )eny7roups( and finally "llow7roups
www.thegeekstuff.com
Crom your logs 9J*arJlogJsecure;( if you see lot of in*alid logins using ssh for accounts that don3t e!ist on your system( from the ip.address that you don3t recogni+e( it might be some brute.force attack. Those kind of ssh in*alid login will stop( if you change the port number. 0lease note that this causes little incon*enience to your team who login to the system( as they need to know both the ip.address and the port number.
www.thegeekstuff.com
8y default ssh will listen on all of the abo*e ip.addresses. 2f you want users to login only using ip.address 200 and 202( do the following in your sshdMconfig ; (i /etc/ssh/sshd9confi Listen%ddress 1G3.1CF.10.300 Listen%ddress 1G3.1CF.10.303
2f you want ssh client to e!it 9timeout; automatically after 10 minutes 9600 seconds;( modify the sshdMconfig file and set the following two parameters as shown below. ; (i /etc/ssh/sshd9confi Client%li(eBnter(al C00 Client%li(eCountSa- 0
D4
www.thegeekstuff.com
Any Questions? .iscuss it here: K .efault Lpen$$H $ecurity Lptions that You $hould Chan e
Transfer this putty.registry.reg file from source machine to destination machine. %n the destination machine( import the 0uTTA &&' session registry( by right mouse.click on the putty.registry.reg and click on ]/erge3. This will transfer all the 0uTTA session information from one windows system to another.
www.thegeekstuff.com
transferred all 0uTTA sessions( e!ecute Qputty .cleanupR from the command line as shown below. C:Zputty #cleanup
This will display a warning message. #lick on ]Aes3 to wipe.out all 0uTTA session and random seed files from the =indows registry. This is a better process to delete all sa*ed 0uTTA sessions from =indows registry instead of deleting one.by.one from the 0uTTA session list.
&ore 0u112 1ips: +ur"ochar e /u++Y with 13 /owerful %dd#Lns 10 %weso!e /u++Y +ips and +ricks You /ro"a"ly .idn^t Qnow I-tre!e Sakeo(er \sin /u++Y Connection Sana er
D6
www.thegeekstuff.com
Cor e!ample( to set system date to San 31st 200-( 1011- p.m( 53 seconds ) date 0141331G300G.64
Aou can also change system date using set argument as shown below. ) date 0141331G300G.64 ) date OWYW!Wd #s 2300G01412 ) date #s 201/41/300G 33:1G:642 ) date #s 241 D%& 300G 33:1G:642 ) date set0241 D%& 300G 33:1G:642
D,
www.thegeekstuff.com
To set the time only1 ) date OW+ #s 233:1G:642 ) date OW+Wp #s 210:1G:64/S2
Hse hwclock without any parameter( to *iew the current hardware date and time1 ) hwclock
#heck the clock file to *erify whether the system is set for HT#1 ) cat /etc/sysconfi /clock JL&I02%!erica/Los9%n eles2 \+C0false %MC0false
DD
www.thegeekstuff.com
; date ##date0V1GK0#01#01 00:00:01 \+C O6 hoursV OWs 1F001 ; date VOCurrent .ate: W!/Wd/WyWnCurrent +i!e:WH:WS:W$V Current .ate: 01/01/0G Current +i!e:0F:31:51 ; date O2Wd#W!#WY2 01#01#300G ; date O2Wd/W!/WY2 01/01/300G ; date O2W%,WB Wd WY2 +hursday,Danuary 01 300G
D-
www.thegeekstuff.com
The following are the different format options you can pass to the date command1 \) date 9mmJddJyy; \d day of month 901..31; \m month 901..12; \y last two digits of year 900..--; \a locale3s abbre*iated weekday name 9&un..&at; \" locale3s full weekday name( *ariable length 9&unday..&aturday; \b locale3s abbre*iated month name 9San..)ec; \8 locale3s full month name( *ariable length 9Sanuary..)ecember; \' hour 900..23; \2 hour 901..12; \A year 91-,0P;
; date ##date021 day a o2 `ed .ec 41 0F:3K:14 /$+ 300F ; date ##date021 days a o2 `ed .ec 41 0F:3K:1F /$+ 300F ; date ##date021 !onth a o2 Son .ec 1 0F:3K:34 /$+ 300F
-0
www.thegeekstuff.com
; date ##date02yesterday2 `ed .ec 41 0F:3K:45 /$+ 300F ; date ##date0210 !onths 3 day a o2 +hu Ye" 3F 0F:3K:51 /$+ 300F
www.thegeekstuff.com
$at Dan
-2
www.thegeekstuff.com
ra!esh<de(#d" 1Z cd /etc/!ail ra!esh<de(#d" /etc/!ailZ *&ote: /ro!pt chan ed to 2userna!e<hostna!e current#dirZ2 for!at,
Collowing 0&1 codes are used in this e!ample1 Ou $ Hsername Oh $ 'ostname Ow . Cull pathname of current directory. 0lease note that when you are in the home directory( this will display only L as shown abo*e
5ote that there is a space at the end in the *alue of 0&1. 0ersonally( 2 prefer a space at the end of the prompt for better readability. /ake this setting permanent by adding e!port 0&1KROuBOh OwX R to either .bashMprofile 9or; .bashrc as shown below.
-3
www.thegeekstuff.com
ra!esh<de(#d" 1Z (i 1/."ash9profile ra!esh<de(#d" 1Z (i 1/."ashrc *&ote: %dd e-port /$102>u<>h >wZ 2 to one of the a"o(e files,
www.thegeekstuff.com
2 found it *ery helpful and easy to read( when 2 break my long commands into multiple lines using O. 2 ha*e also seen others who don3t like to break.up long commands.
-5
www.thegeekstuff.com
*Note: +his displays the default 2)c2 for select co!!and pro!pt,
-6
www.thegeekstuff.com
*Note: +his displays the default 2OO2 while tracin output usin set #-,
www.thegeekstuff.com
e-port /$50V;0.;LB&I&LO V set #echo 2/$5 de!o script2 ls #l /etc/ T wc #l du #sh 1 ra!esh<de(#d" 1Z ./ps5.sh ../ps5.sh.4O echo V/$5 de!o scriptV /$5 de!o script ../ps5.sh.5O ls #l /etc/ ../ps5.sh.5O wc #l 354 ../ps5.sh.6O du #sh /ho!e/ra!esh 5FQ /ho!e/ra!esh
*Note: +his displays the !odified 2:script#na!e@.:line# nu!"er@O2 while tracin the output usin set #-,
2f you want to display the *alue of 04%/0TM#%//"5) in the same line as the 0&1( use the echo .n as shown below.
-D
www.thegeekstuff.com
ra!esh<de(#d" 1Z e-port /MLS/+9CLSS%&.02echo #n *;7date O WH:WS:W$8,2 *33:0F:61,ra!esh<de(#d" 1Z *Note: +his displays the /MLS/+9CLSS%&. and /$1 output on the sa!e line,
Any Questions? .iscuss it here: Bash $hell: +ake Control of /$1, /$3, /$4, /$5 and /MLS/+9CLSS%&.
/)1
--
www.thegeekstuff.com
Aou can also use Ot to display the current time in the hh1mm1ss format as shown below1 ra!esh<de(#d" 1Z e-port /$102>u<>h *>t,Z 2 ra!esh<de(#d" *13:53:66,Z
Aou can also use OB to display the current time in 12.hour amJpm format as shown below1 ra!esh<de(#d" 1Z e-port /$102*><, >u<>hZ 2 *05:13 /S, ra!esh<de(#d"Z
www.thegeekstuff.com
Hse the following codes and create your own personal 0&1 inu! prompt that is functional and suites your taste. Oa an " bell character 90,; Od the date in Q=eekday /onth )ateR format 9e.g.( QTue /ay 26f; O)aformatb . the format is passed to strftime93; and the result is inserted into the prompt string[ an empty format results in a locale.specific time representation. The braces are re@uired Oe an " escape character 9033; Oh the hostname up to the first part O' the hostname O6 the number of 6obs currently managed by the shell Ol the basename of the shell3s terminal de*ice name On newline Or carriage return Os the name of the shell( the basename of N0 9the portion following the final slash; Ot the current time in 24.hour ''1//1&& format OT the current time in 12.hour ''1//1&& format OB the current time in 12.hour amJpm format O" the current time in 24.hour ''1// format Ou the username of the current user O* the *ersion of bash 9e.g.( 2.00; O? the release of bash( *ersion ` patch le*el 9e.g.( 2.00.0; 101
www.thegeekstuff.com
Ow the current working directory( with N'%/: abbre*iated with a tilde O= the basename of the current working directory( with N'%/: abbre*iated with a tilde Oc the history number of this command O^ the command number of this command ON if the effecti*e H2) is 0( a ^( otherwise a N Onnn the character corresponding to the octal number nnn OO a backslash Og begin a se@uence of non.printing characters( which could be used to embed a terminal control se@uence into the prompt Oh end a se@uence of non.printing character
Aou can add the following line to your LJ.bashMprofile or LJ.bashrc to make this change permanent1 ; (i ."ash9profile function httpdcount : ps au- T rep httpd T rep #( 102 rep T wc #l
www.thegeekstuff.com
5ote1 Aou can also use Qpgrep httpd e wc $lR instead of the Qps au! e grep httpd e grep .* grep e wc $lR in the abo*e httpdcount function.
Aou can also write the LJbinJtotalfilesi+e.sh as shown below without the for loop. 103
www.thegeekstuff.com
/)1
)isplay prompt in blue color( along with username( host and current directory information . Hse the following is for light blue prompt1 ; e-port /$102>e*0?45!>u<>h >wZ >e*! 2
Hse the following for dark blue prompt1 ; e-port /$102>e*1?45!>u<>h >wZ >e*! 2 Oeg . 2ndicates the beginning of color prompt ![ym . 2ndicates color code. Hse the color code *alues mentioned below. Oegm . indicates the end of color prompt
#olor #ode Table1 8lack 0[30 8lue 0[34 7reen 0[32 #yan 0[36 4ed 0[31 0urple 0[35 8rown 0[33 104
www.thegeekstuff.com
g5ote1 4eplace 0 with 1 for dark colorh /ake the color change permanent by adding the following lines your LJ.bashMprofile or LJ.bashrc ; (i 1/."ash9profile $+%M+CLLLM0V>e*0?45!V? I&.CLLLM02>e*0!2 e-port /$102;$+%M+CLLLM>u<>h >wZ ;I&.CLLLM2
"dd the following to your LJ.bashMprofile or LJ.bashrc to make the abo*e background and foreground color permanent. ; (i 1/."ash9profile $+%M+YGCLLLM0V>e*0?45!V? $+%M+BGCLLLM02>e*5K!2 I&.CLLLM02>e*0!2 e-port /$102;$+%M+YGCLLLM;$+%M+BGCLLLM>u<>h >wZ ;I&.CLLLM2
0lay around by using the following background color and choose the one that match your taste1 105
www.thegeekstuff.com
www.thegeekstuff.com
Aou can re.login for the changes to take effect or source the .bashMprofile as shown below. ;. ./."ash9profile ; pro!pt ra!esh<de(#d" *14:03:14,Z
tput
Aou can also change color of the 0&1 prompt using tput as shown below1 ; e-port /$102>*;7tput "old8;7tput set" 58;7tput setaf K8>,>u<>h:>w ; >*;7tput s r08>,f
tput #olor #apabilities1 tput setab g1.,h . &et a background color using "5&2 escape tput setb g1.,h . &et a background color tput setaf g1.,h . &et a foreground color using "5&2 escape tput setf g1.,h . &et a foreground color
tput Te!t /ode #apabilities1 tput bold . &et bold mode tput dim . turn on half.bright mode tput smul . begin underline mode tput rmul . e!it underline mode tput re* . Turn on re*erse mode tput smso . :nter standout mode 9bold on r!*t; tput rmso . :!it standout mode tput sgr0 . Turn off all attributes 10,
www.thegeekstuff.com
#olor #ode for tput1 0 $ 8lack 1 $ 4ed 2 $ 7reen 3 $ Aellow 4 $ 8lue 5 $ /agenta 6 $ #yan , . =hite
Any Questions? .iscuss it here: Bash $hell /$1: 10 I-a!ples to Sake Your Linu- /ro!pt like %n elina Dolie Additional tput Examples: G \&Ba / Linu- tput I-a!ples: Control Your +er!inal Color and Cursor
10D
www.thegeekstuff.com
) Pip (ar#lo #files.Pip /(ar/lo /R addin : (ar/lo /acpid 7deflated F1W8 addin : (ar/lo /anaconda.lo addin : (ar/lo /anaconda.-lo addin : (ar/lo /"oot.lo 7deflated KGW8 7deflated K4W8 7deflated F3W8 addin : (ar/lo /anaconda.syslo
addin : (ar/lo /audit/ 7stored 0W8 7stored 0W8 addin : (ar/lo /"oot.lo .1 7deflated 50W8 addin : (ar/lo /"oot.lo .3 7deflated 53W8 addin : (ar/lo /"oot.lo .4 7deflated 50W8 addin : (ar/lo /"oot.lo .5 7deflated 50W8
www.thegeekstuff.com
addin : (ar/lo /spooler.1 7stored 0W8 addin : (ar/lo /spooler.5 7stored 0W8 addin : (ar/lo /httpd/ 7stored 0W8 addin : (ar/lo /rp!pk s.1 7deflated CFW8 addin : (ar/lo /anaconda.lo 7deflated KGW8 addin : (ar/lo /secure.3 7deflated G4W8
To see a detailed output during un+ip pass the $* option as shown below. ) unPip #( (ar#lo .Pip %rchi(e: (ar#lo .Pip Len th Sethod $iPe Matio .ate +i!e ######## ###### ####### ##### 4CG F1W KGW 1G1C .efl:& (ar/lo /acpid CMC#43 #### #### &a!e ###### e3ffdc0c 45cc04a1
1465C .efl:& 3G00 (ar/lo /anaconda.lo skip.. KCF0 .efl:& (ar/lo /wt!p.1 511
G6W
feFKCeeG
www.thegeekstuff.com
F3W
C4FCaG6e
####### 3F0G33G
itJ
111
www.thegeekstuff.com
e*el - is the ma!imum compression. This will be slower when compared to default le*el. 2n my opinion( unless you are compressing a huge file( you should always use le*el -.
2n the e!ample below( 2 used e*el 0( default e*el 6( and e*el compression on a same directory. &ee the compressed file si+e yourself. ) Pip (ar#lo #files#default.Pip /(ar/lo /R ) Pip #0 (ar#lo #files#0.Pip /(ar/lo /R ) Pip #G (ar#lo #files#G.Pip /(ar/lo /R ) ls #ltr #rw#r##r## 1 root root (ar#lo #files#default.Pip #rw#r##r## 1 root (ar#lo #files#0.Pip #rw#r##r## 1 root (ar#lo #files#G.Pip root root 3F1K35F Dan 51516401 Dan 36F3C10 Dan 1 14:06 1 14:06 1 14:0C
testin : (ar/lo /acpid testin : (ar/lo /anaconda.lo testin : (ar/lo /anaconda.syslo skip... testin : (ar/lo /wt!p 112
LQ
www.thegeekstuff.com
LQ LQ
The abo*e option is good if you are using the command inside a shell. script for background 6obs. 'owe*er( when you are performing the compression interacti*ely on the command.line( you don3t want the password to be *isible in the history. &o( use the option $e as shown below to assign the password. ) Pip #e (ar#lo #protected.Pip /(ar/lo /R Inter password: 'erify password: updatin : (ar/lo /acpid 7deflated F1W8 updatin : (ar/lo /anaconda.lo 7deflated KGW8
=hen you are uncompressing a password protected file( it will ask for the password as shown below. ) unPip %rchi(e: (ar#lo #protected.Pip (ar#lo #protected.Pip
www.thegeekstuff.com
Ho* can I create a sin le backup file of all files and subdirectories under #y ho#e directoryJ
The following command creates a single archi*e backup file called myMhomeMdirectory.tar under Jtmp. This archi*e will contain all the files and subdirectories under JhomeJ6smith. %ption c( stands for create an archi*e. %ption * stands for *erbose mode( displays additional information while e!ecuting the command. %ption f indicates the archi*e file name mentioned in the command.
114
www.thegeekstuff.com
Additional 1ar Examples: +he \lti!ate +ar Co!!and +utorial with 10 /ractical I-a!ples
"dd option + to the tar command when dealing with tar.g+ compressed file. ) tar c(fP /t!p/!y9ho!e9directory.tar. P /ho!e/Es!ith ) tar -(fP /t!p/!y9ho!e9directory.tar. P ) tar t(fP /t!p/!y9ho!e9directory.tar. P 5ote1 Hsing g+ip is faster when compared to b+ip2.
115
www.thegeekstuff.com
There are se*eral inu! b+ commands a*ailable to manipulate the b+ip2 files. This hack e!plains *arious b+ commands with 6 practical e!amples.
Co#pressin
a file usin
bBip,
=hen you compress a file using b+ip2 command( it creates a compressed file with U.b+2 e!tension as shown below. ; "Pip3 trace ; ls #l trace."P3 #rw#r##r## 1 root root 651CK Dan 34 300G trace."P3
bB rep
b+grep command is used to search for a string or a pattern 9regular e!pression; on b+ip2 compressed files. b+grep will apply grep to data from files in the b+ip2 format without re@uiring on.disk decompression. &o all the options of a grep command will be applied for b+grep also. &ynta!1 "P rep rep#options #e pattern filena!e 116
www.thegeekstuff.com
2n the below e!ample( trace.b+2 is a compressed trace file which is of si+e 5D/. ; "P rep #i 2CL&$LLI0.R2 3010#10#11+0F:50:3F.100 3010#10#11+0F:50:3G.KK3 3010#10#11+0F:50:6F.150 3010#10#11+0F:51:3K.65K 3010#10#11+0F:51:6K.GC3 3010#10#11+0F:53:3F.4G3 3010#10#11+0F:53:6K.K31 trace."P3 s71CGF68: CL&$LLI0/de(/pts/0 s71K0418: CL&$LLI0/de(/pts/0 s71K0GG8: CL&$LLI0/de(/pts/0 s71K1C58: CL&$LLI0/de(/pts/0 s71K3448: CL&$LLI0/de(/pts/0 s71K3G58: CL&$LLI0/de(/pts/0 s71K54G8: CL&$LLI0/de(/pts/0
2f b+grep is not there( you ha*e to decompress the file manually and do a grep on that( where b+grep does this process internally and gi*es you the re@uired output. b+egrep and b+fgrep commands will apply egrep and fgrep operation on b+ip2 files respecti*ely.
bBcat
2f you want only to read the compressed file without decompressing it( use the b+cat command as shown below. ; "Pcat trace."P3 0: IMM: `ed $ep 33 0G:6G:53 3010: s711164/5KK63CKKKG5C508: *chk9s_lcode.scp:G3,: .ata"ase: LM%#01C64: una"le to e-tend ta"le L/C9L/.L/ C9HB$+9SI$$%GI$ 7LpC60#168 0: IMM: `ed $ep 33 0G:6G:5K 3010: s711164/5KK63CKKKG5C508: *chk9s_lcode.scp:G3,: .ata"ase: LM%#01C64: una"le to e-tend ta"le L/C9L/.L/ C9HB$+9SI$$%GI$ 7LpC60#168 Metry. 7LpC61#338 .ata"ase: LM%#01C64: una"le to e-tend ta"le L/C9L/.L/C9HB$+9SI$$%GI$ "y C5 in ta"lespace L/C9C 7LpC60#168 . 11,
www.thegeekstuff.com
. b+cat command displays the uncompressed content into standard output file for the users to *iew the content.
/a in
b+less and b+more command allows you to *iew the content of b+ip2 compressed files page by page. b+more works on files compressed with b+ip2 and also on uncompressed files. ; "Pless trace."P3 ; "P!ore trace."P3 0: IMM: `ed $ep 33 0G:6G:53 3010: s711164/5KK63CKKKG5C508: *chk9s_lcode.scp:G3,: .ata"ase: LM%#01C64: una"le to e-tend ta"le L/C9L/.L/ C9HB$+9SI$$%GI$ 7LpC60#168 0: IMM: `ed $ep 33 0G:6G:5K 3010: s711164/5KK63CKKKG5C508: *chk9s_lcode.scp:G3,: .ata"ase: LM%#01C64: una"le to e-tend ta"le L/C9L/.L/ C9HB$+9SI$$%GI$ 7LpC60#168 Metry. 7LpC61#338 .ata"ase: LM%#01C64: una"le to e-tend ta"le L/C9L/.L/C9HB$+9SI$$%GI$ "y C5 in ta"lespace L/C9C 7LpC60#168 . . ##Sore##
bBc#p
Aou can compare two b+ip2 compressed file using b+cmp command. 2t internally uses cmp command to compare the content of the compressed contents. 'ere you can see the output of comparison of the two normal files and compressed files. 11D
www.thegeekstuff.com
; c!p $yste!.t-t.001 $yste!.t-t.003 $yste!.t-t.001 $yste!.t-t.003 differ: "yte 30, line 3 ; "Pc!p $yste!.t-t.001."P3 $yste!.t-t.003."P3 # /t!p/"Pdiff.cs _G4303G differ: "yte 30, line 3
bBdiff
2n inu!( diff command will compare two files and gi*e you the lowdown on 6ust how different they are. 2f you gi*e b+2 files to diff command( it will not be in a position to e!plain the difference. Cor b+ip2 compressed files( b+diff command gi*es the differences of two b+ip2 compressed files as shown below. ; "Pdiff $yste!.t-t.001."P3 $yste!.t-t.003."P3 3c3 [ 0: IMM: Son $ep 3K 13:1G:45 3010: s711164/1106F350C58: *chk9s_lcode.scp:G3,: .ata"ase: LM%#01C65: una"le to e-tend inde- L/C9L/.L/Ca 9%&&L9&\S "y C5 in ta"lespace L/C9B&.Ia1 ### Z 0: IMM: `ed $ep 33 0G:6G:53 3010: s711164/5KK63CKKKG5C508: *chk9s_lcode.scp:G3,: .ata"ase: LM%#01C64: una"le to e-tend ta"le L/C9L/. L/C9HB$+9SI$$%GI$ "y C5 in ta"lespace L/C9C 5,6c5 [ Metry. 7LpC61#338 [ .ata"ase: LM%#01C65: una"le to e-tend indeL/C9L/.L/Ca9%&&L9&\S "y C5 in ta"lespace L/C9B&.Ia1 ### Z 0: IMM: `ed $ep 33 0G:6G:5K 3010: s711164/5KK63CKKKG5C508: *chk9s_lcode.scp:G3,: .ata"ase: LM%#01C64: una"le to e-tend ta"le L/C9L/. L/C9HB$+9SI$$%GI$ "y C5 in ta"lespace L/C9C
11-
www.thegeekstuff.com
Any Questions? .iscuss it here: "Pip3, "P rep, "Pc!p, "Pdiff, "Pcat, "Pless, "P!ore e-a!ples
120
www.thegeekstuff.com
"s seen abo*e( the ls command passes the three ob6ect filenames to cpio command and cpio generates the ob6ect.cpio archi*e.
cpio <7
=e already know how to use the tar command effecti*ely. )id you know that you can also use cpio command to create tar files as shown belowG ; ls T cpio #o( #H tar #Y sa!ple.tar
"s seen abo*e( instead of redirecting the standard output you can mention the output archi*e filename with the option .C.
cpio co##and
Aou can also e!tract a tar file using cpio command as shown below. ; cpio #id( #Y sa!ple.tar
121
www.thegeekstuff.com
Create a E.cpio Archi2e *ith the 8ri inal files that a )y#bolic Link /oints
cpio archi*e can be created with the original files that a symbolic link is referring to as shown below. ; ls T cpio #oL( Z/t!p/test.cpio
E.cpio
The modification time of the files can be preser*ed when we are restoring the cpio archi*e files as shown below. ; ls T cpio #o!( Z/t!p/test.cpio
www.thegeekstuff.com
cpio option .p makes cpio to use pass through mode. 2ts like piping cpio .o into cpio .i. cpio option .d creates leading directories as needed in the target directory.
Any Questions? .iscuss it here: Linu- cpio I-a!ples: How to Create and I-tract cpio %rchi(es 7and tar archi(es8 Additional cpio Examples: How to 'iew, Sodify and Mecreate initrd.i! Co!!and \sin cpio
123
www.thegeekstuff.com
ControlR6
2 strongly belie*e that this may be your most fre@uently used feature of history. =hen you3*e already e!ecuted a *ery long command( you can simply search history using a keyword and re.e!ecute the same command without ha*ing to type it fully. 0ress #ontrol`4 and type the keyword. 2n the following e!ample( 2 searched for red( which displayed the pre*ious command Qcat JetcJredhat.releaseR in the history that contained the word red. ) *&ote: /ress CtrlOM fro! the co!!and pro!pt, which will display the re(erse#i#search pro!pt as shown "elow, 7re(erse#i#search8Ured]: cat /etc/redhat#release *&ote: /ress enter when you see your co!!and, which will e-ecute the co!!and fro! the history, ) cat /etc/redhat#release Yedora release G 7$ulphur8
&ometimes you want to edit a command from history before e!ecuting it. Cor e.g. you can search for httpd( which will display ser*ice httpd stop from the command history( select this command and change the stop to start and re.e!ecute it again as shown below. 124
www.thegeekstuff.com
) *&ote: /ress CtrlOM fro! the co!!and pro!pt, which will display the re(erse#i#search pro!pt, 7re(erse#i#search8Uhttpd]: ser(ice httpd stop *&ote: /ress either left arrow or ri ht arrow key when you see your co!!and, which will display the co!!and for you to edit, "efore e-ecutin it, ) ser(ice httpd start
0 different
&ometime you may end up repeating the pre*ious commands for *arious reasons. Collowing are the 4 different ways to repeat the last e!ecuted command. 1. Hse the up arrow to *iew the pre*ious command and press enter to e!ecute it. 2. Type cc and press enter from the command line 3. Type c.1 and press enter from the command line. 4. 0ress #ontrol`0 will display the pre*ious command( press enter to e!ecute it
www.thegeekstuff.com
option <c
&ometime you may want to clear all the pre*ious history. 'owe*er you may still want to keep the history mo*ing forward. ) history #c
126
www.thegeekstuff.com
2n the e!ample below( the cT ne!t to the *i command gets the first argument from the pre*ious command 9i.e cp command; to the current command 9i.e *i command;. ) cp anaconda#ks.cf anaconda#ks.cf ) (i AN (i anaconda#ks.cf anaconda#ks.cf ."ak
2n the e!ample below( ccp1N searches for the pre*ious command in history that starts with cp and takes the last argument 9in this case( which is also the second argument as shown abo*e; of cp and substitutes it for the ls .l command as shown below. ) ls #l Acp:; ls #l /really/a/(ery/lon /path/lon #filena!e.t-t
12,
www.thegeekstuff.com
Typically when you type history from command line( it displays the command^ and the command. Cor auditing purpose( it may be beneficial to display the timestamp along with the command as shown below. ) e-port HB$++BSIYLMS%+0^WY W+ ] ) history T !ore 1 3 4 5 300F#0F#06 1G:03:4G ser(ice network restart 300F#0F#06 1G:03:4G e-it 300F#0F#06 1G:03:4G id 300F#0F#06 1G:03:4G cat /etc/redhat#release
5ote1 Aou can also setup the following alias to *iew the recent history commands. alias h10Vhistory 10V alias h30Vhistory 30V alias h40Vhistory 40V
www.thegeekstuff.com
HI)T7IL5
8y default( history is stored in LJ.bashMhistory file. "dd the following line to the .bashMprofile and relogin to the bash shell( to store the history command in .commandlineMwarrior file instead of .bashMhistory file. 23m yet to figure out a practical use for this. 2 can see this getting used when you want to track commands e!ecuted from different terminals using different history file name. ) (i 1/."ash9profile HB$+YBLI0/root/.co!!andline9warrior
*Note: +here are three pwd co!!ands in history, after e-ecutin pwd 4 ti!es as shown a"o(e, ) e-port HB$+CL&+MLL0i noredups ) pwd 12-
www.thegeekstuff.com
) pwd ) pwd ) history T tail #4 6C 6K 6F e-port HB$+CL&+MLL0i noredups pwd history T tail #5
*Note: +here is only one pwd co!!and in the history, e(en after e-ecutin pwd 4 ti!es as shown a"o(e,
www.thegeekstuff.com
) history T tail #C 46 4C 4K 4F 4G 50 e-port HB$+CL&+MLL0erasedups pwd history T tail #4 ls Hltr ser(ice httpd stop history T tail #C ot
*Note: +here is a space at the "e innin i nore this co!!and fro! history, ) history T tail #4 131
www.thegeekstuff.com
CK CF CG
HI)T)IC5
2f you want to disable history all together and don3t want bash shell to remember the commands you3*e typed( set the '2&T&2d: to 0 as shown below. ) e-port HB$+$BJI00 ) history ) *Note: History did not display anythin ,
www.thegeekstuff.com
F1
history
Any Questions? .iscuss it here: 16 I-a!ples +o Saster Linu- Co!!and Line History
DJstrin
5xa#ple
et us assume that you>*e e!ecuted the following command at some point and it is somewhere in the history. ; /usr/local/apache3/"in/apachectl restart
133
www.thegeekstuff.com
ater when you want to e!ecute the same command( if you try the following it will fail because it is looking for a line that starts with QapacheR. ; Aapache #"ash: Aapache: e(ent not found
'owe*er if you do the following( it will look for any command that contains the string QapacheR and e!ecute it as shown below. ; Acapache /usr/local/apache3/"in/apachectl restart
Lstr1Lstr,L 5xa#ple
&ometimes you might check whether a file e!ists using a @uick ls command as shown below. ; ls /etc/sysconfi /network
%nce you *erify that the file e!ists( to *iew the content of the file using *i( you don>t need to type the whole file name again. 2nstead do the following( which will replace the word >ls> in the pre*ious command with the word >*i> and e!ecute the command. ; NlsN(i (i /etc/sysconfi /network
DD.N 5xa#ple
2n this e!ample( the following command takes a copy of the JetcJpasswd file to the home directory as passwd.bak. ; cp /etc/passwd /ho!e/ra!esh/passwd."ak
%nce you create the backup of the file( if you want to open the backup file( you don>t need to type the whole backup file name again. 2nstead( 134
www.thegeekstuff.com
you can use the last argument of the pre*ious command along with >*i> command as shown below. ; (i AA:; (i /ho!e/ra!esh/passwd."ak
0lease note that Qc1NR is e!actly same as Qcc1NR. &o( the abo*e e!ample can also be e!ecuted as shown below. ; (i A:; (i /ho!e/ra!esh/passwd."ak
Dstrin .n 5xa#ple
=hen you e!ecute a command that has multiple arguments 9as shown in the tar command e!ample below;( you can e!tract only a specific argument from it for later use. ; tar c(fP 1/sysconfi .tar. P /etc/sysconfi /R
5ow if you want to ls the newly created tar.g+ file( you can do the following( which will take the 2nd argument of the pre*ious tar command. ; ls #l Atar:3 ls #l 1/sysconfi .tar
Additional !ash 3istory Expansion Examples: 16 Linu- Bash History I-pansion I-a!ples You $hould Qnow
135
www.thegeekstuff.com
"fter you3*e installed brand new disks on your ser*er( you ha*e to use tools like fdisk to partition it accordingly. Collowing are the 5 typical actions 9commands; that you can e!ecute inside fdisk. n $ 5ew 0artition creation d $ )elete an e!isting partition p . 0rint 0artition Table w $ =rite the changes to the partition table. i.e sa*e. @ $ iuit the fdisk utility
Create a partition
2n the following e!ample( 2 created a Jde*Jsda1 primary partition. ) dis" 4de54sda
Co!!and 7! for help8: p .isk /de(/sda: 3FK.0 GB, 3FK006454K55 "ytes 366 heads, C4 sectors/track, 45FG4 cylinders \nits 0 cylinders of 1C0C6 R 613 0 F3363F0 "ytes .e(ice Boot $tart Ind Blocks Bd $yste!
www.thegeekstuff.com
p p
/artition nu!"er 71#58: . Yirst cylinder 71#45FG4, default 18: \sin default (alue 1 Last cylinder or OsiPe or OsiPeS or OsiPeQ 71#45FG4, default 45FG48: \sin default (alue 45FG4
Co!!and 7! for help8: % +he partition ta"le has "een alteredA Callin $yncin ioctl78 to re#read partition ta"le. disks.
ot created successfully
.isk /de(/sda: 3FK.0 GB, 3FK006454K55 "ytes 366 heads, C4 sectors/track, 45FG4 cylinders \nits 0 cylinders of 1C0C6 R 613 0 F3363F0 "ytes .e(ice Boot /de(/sda1 $tart 1 Ind 45FG4 Blocks 3F03KKGG1 Bd F4 $yste! Linu-
13,
www.thegeekstuff.com
Additional
dis" Examples:
#ke,fsk
"fter partitioning the disks( it is still not ready for usage( as we need to format the disk. "t this stage( if you try to *iew the disk information( it will gi*e the following error message indicating that no *alid superblock is present. ) tune3fs #l /de(/sda1 tune3fs 1.46 73F#Ye"#30058 tune3fs: Bad !a ic nu!"er in super#"lock while tryin open /de(/sda1 CouldnVt find (alid filesyste! super"lock. to
Aou can also pass the following optional parameter to the mke2fs. .m 0 1 reser*ed.blocks.percentage $ This indicates the percentage of the filesystem blocks reser*ed for the root user. )efault is 5\. 2n the following e!ample( it is set to 0. .b 40-6 1 block.si+e specified in bytes. ?alid *alues are 1024( 204D and 40-6 bytes per block.
www.thegeekstuff.com
Yilesyste! la"el0 L$ type: LinuBlock siPe050GC 7lo 038 Yra !ent siPe050GC 7lo 038 306455 inodes, K00CG5GK "locks 0 "locks 70.00W8 reser(ed for the super user Yirst data "lock00 Sa-i!u! filesyste! "locks0K14041CF 314G "lock roups roup, 43KCF fra !ents per roup roup 43KCF "locks per GC inodes per
$uper"lock "ackups stored on "locks: 43KCF, GF405, 1C4F50, 33G4KC, 3G5G13, F1G300, FF5K4C, 1C06C43, 3C6530F, 50GC000, KGC3C35, 1134G535, 305F0000, 34FFKFK3 `ritin `ritin done inode ta"les: done super"locks and filesyste! accountin infor!ation:
+his filesyste! will "e auto!atically checked e(ery 43 !ounts or 1F0 days, whiche(er co!es first. \se tune3fs #c or #i to o(erride.
The abo*e command will create an e!t2 filesystem. To create an e!t3 file system do the following1 ) !kfs.e-t4 /de(/sda1 ) !ke3fs HE /de(/sda1
13-
www.thegeekstuff.com
To automatically mount the filesystem after the reboot( add the following entry to the JetcJfstab /de(/sda1 /ho!e/data"ase e-t4 defaults 0 3
tune,fs
Hse the tune2fs $l Jde*Jsda1 to *iew the filesystem information as shown below. ) tune3fs #l /de(/sda1 tune3fs 1.46 73F#Ye"#30058 Yilesyste! (olu!e na!e: Last !ounted on: Yilesyste! \\B.: """"aaaaae11 Yilesyste! !a ic nu!"er: Yilesyste! re(ision ): Yilesyste! features: sparse9super .efault !ount options: Yilesyste! state: /ho!e/data"ase [not a(aila"leZ f134566C#e134#1345#a"cd# 0-IY55 1 7dyna!ic8 resiPe9inode filetype 7none8 not clean 140
www.thegeekstuff.com
Irrors "eha(ior: Yilesyste! L$ type: Bnode count: Block count: Meser(ed "lock count: Yree "locks: Yree inodes: Yirst "lock: Block siPe: Yra !ent siPe: Meser(ed G.+ "locks: Blocks per Bnodes per roup: roup: roup: roup: Yra !ents per
Continue Linu10G5G13 15014FGG5 0 1CF5F5F1 1015GCG 0 305F 305F 613 1C4F5 1C4F5 13F F +ue Dul +hu %u Yri Dan 3 30 +ue Dul 1 00:0C:04 300F 16663000 7C !onths8 $at .ec 3K 34:0C:04 300F 0 7user root8 0 7 roup root8 11 13F tea 13456F3G#134C#5134#Gaaa# id: 1 00:0C:04 300F 31 06:6F:36 300F 3 16:50:4C 300G
Bnode "locks per Last !ount ti!e: Last write ti!e: Sount count:
Yilesyste! created:
Sa-i!u! !ount count: Last checked: Check inter(al: &e-t check after: Meser(ed "locks uid: Meser(ed "locks Yirst inode: Bnode siPe: .efault directory hash: .irectory Hash $eed: ccccc1343G3"
141
www.thegeekstuff.com
Aou can also use the tune2fs to tune the e!2Je!t3 filesystem parameter. Cor e!ample( if you want to change the Cilesystem *olume name( you can do it as shown below. ) tune3fs #l /de(/sda1 T Yilesyste! (olu!e na!e: rep (olu!e /ho!e/data"ase
) tune3fs #L data"ase#ho!e /de(/e!cpowera1 tune3fs 1.46 73F#Ye"#30058 ) tune3fs #l /de(/sda1 T Yilesyste! (olu!e na!e: rep (olu!e data"ase#ho!e
Hse mkswap to setup a inu! swap area in the JhomeJswap.fs file that was created abo*e. ) !kswap /ho!e/swap#fs
&etting up swapspace *ersion 1( si+e K 536D66 k8 %nce the file is created and has been setup for inu! swap area( it is time to enable the swap using swapon as shown below. 142
www.thegeekstuff.com
) swapon /ho!e/swap#fs
"dd the following line to JetcJfstab and reboot the system for the swap to take into effect. /ho!e/swap#fs swap swap defaults 0 0
Additional S%ap Examples: 3 `ays to %dd $wap $pace \sin dd, !kswap and swapon
?erify that the user got added successfully. ) rep Es!ith /etc/passwd
www.thegeekstuff.com
Additional 6ser #reation Examples: +he \lti!ate Guide to Create \sers in Linu- / \ni+he \lti!ate Guide for Creatin $tron /asswords
144
www.thegeekstuff.com
roup
?alidate that the group was created successfully. ) rep de(eloper /etc/ roup
de(elopers:-:611:
roup
Aou cannot use useradd to modify an e!isting user( as you3ll get the following error message. ) useradd #G de(elopers Es!ith useradd: user Es!ith e-ists ) user!od # de(elopers Es!ith
Es!ith:-:610: de(elopers:-:611:Es!ith
145
www.thegeekstuff.com
ssh<key< en
Inter passphrase 7e!pty for no passphrase8: */ress enter key, Inter sa!e passphrase a ain: */ess enter key, Your identification has "een sa(ed in /ho!e/Es!ith/.ssh/id9rsa. Your pu"lic key has "een sa(ed in /ho!e/Es!ith/.ssh/id9rsa.pu". +he key fin erprint is: 44:"4:fe:af:G6:G6:1F:11:41:d6:de:GC:3f:f3:46:fG Es!ith<local#host
ssh<
www.thegeekstuff.com
&ow try lo in into the !achine, with fssh ]re!ote# host^e, and check in: .ssh/authoriPed9keys to !ake sure we ha(en^t added e-tra keys that you weren^t e-pectin .
the
Last lo in: $un &o( 1C 1K:33:44 300F fro! 1G3.1CF.1.3 *Note: $$H did not ask for password., Es!ith<re!ote#host; *Note: You are on re!ote#host here,
Any Questions? .iscuss it here: 4 $teps to /erfor! $$H Lo in `ithout /assword \sin ssh#key en = ssh#copy#id
>ith ssh<
=hen no *alue is passed for the option .i and 2f LJ.sshJidentity.pub is not a*ailable( ssh.copy.id will display the following error message. Es!ith<local#host; ssh#copy#id #i re!ote#host
14,
www.thegeekstuff.com
2f you ha*e loaded keys to the ssh.agent using the ssh.add( then ssh. copy.id will get the keys from the ssh.agent to copy to the remote.host. i.e( it copies the keys pro*ided by ssh.add . command to the remote. host( when you don3t pass option .i to the ssh.copy.id. Es!ith<local#host; ssh#a ent ;$HILL Es!ith<local#host; ssh#add #L +he a ent has no identities. Es!ith<local#host; ssh#add Bdentity added: /ho!e/Es!ith/.ssh/id9rsa 7/ho!e/Es!ith/.ssh/id9rsa8 Es!ith<local#host; ssh#add #L ssh#rsa %%%%B4&PaC1yc3I%%%%BBw%%%bI%sDBIBL-ftEFa$-Sa4dFtCD(SKG. aHrt/h+Yp_KkBIS\&P%pny-sHpH1tb/Lw00 /ho!e/Es!ith/.ssh/id9rsa Es!ith<local#host; ssh#copy#id #i re!ote#host Es!ith<re!ote#host^s password: &ow try lo in into the !achine, with fssh ]re!ote# host^e, and check in: .ssh/authoriPed9keys to !ake sure we ha(en^t added e-tra keys that you weren^t e-pectin . *Note: +his has added the key displayed "y ssh#add #L,
www.thegeekstuff.com
the remote.host. 2f two or three of them e!ist( it should copy identity.pub as default. 2. The a ent has no identities. =hen the ssh.agent is running and the ssh.add . returns QThe agent has no identitiesR 9i.e no keys are added to the ssh.agent;( the ssh.copy.id will still copy the message QThe agent has no identitiesR to the remote.host3s authori+edMkeys entry. 3. "uplicate entry in authoriBedAkeys. 2 wish ssh.copy.id *alidates duplicate entry on the remote.host3s authori+edMkeys. 2f you e!ecute ssh.copy.id multiple times on the local.host( it will keep appending the same key on the remote.host3s authori+edMkeys file without checking for duplicates. :*en with duplicate entries e*erything works as e!pected. 8ut( 2 would like to ha*e my authori+edMkeys file clutter free.
www.thegeekstuff.com
month1 "llowed range 1 $ 12. 1 K Sanuary. 12 K )ecember. )ay.of.week1 "llowed range 0 $ ,. &unday is either 0 or ,.
Crontab exa#ples
1. 4un at 12101 a.m. 1 minute after midnight e*eryday. This is a good time to run backup when the system is not under load. 1 0 R R R /root/"in/"ackup.sh
2. 4un backup e*ery weekday 9/on $ Cri; at 1115- p.m. 6G 11 R R 1,3,4,5,6 /root/"in/"ackup.sh
Crontab 8ptions
The following are the a*ailable options with crontab1 crontab $e 1 :dit the crontab file. This will create a crontab( if it doesn3t e!ist 150
www.thegeekstuff.com
crontab $l 1 )isplay the crontab file. crontab .r 1 4emo*e the crontab file. crontab .ir 1 This will prompt user before deleting a crontab.
Additional #ron Examples: Linu- Cronta": 16 %weso!e Cron Do" I-a!ples How to Mun Cron I(ery 6 Sinutes, $econds, Hours, .ays, Sonths Cron 's %nacron: How to $etup %nacron on Linu- 7`ith an I-a!ple8
&a ic
The magic &ys4@ key is a key combination in the inu! kernel which allows the user to perform *arious low le*el commands regardless of the system3s state. 2t is often used to reco*er from free+es( or to reboot a computer without corrupting the filesystem. The key combination consists of "lt`&ys4@`commandkey. 2n many systems the &ys4@ key is the printscreen key. Cirst( you need to enable the &ys4@ key( as shown below. echo 212 Z /proc/sys/kernel/sysr_
www.thegeekstuff.com
]k3 $ _ills all the process running on the current *irtual console. 3s3 $ This will attempt to sync all the mounted file system. ]b3 . 2mmediately reboot the system( without unmounting partitions or syncing. ]e3 $ &ends &27T:4/ to all process e!cept init. ]m3 $ %utput current memory information to the console. ]i3 . &end the &27_2 signal to all processes e!cept init
]r3 . &witch the keyboard from raw mode 9the mode used by programs such as I11;( to I "T: mode. 3s3 $ sync all mounted file system. ]t3 . %utput a list of current tasks and their information to the console. ]u3 . 4emount all mounted filesystems in readonly mode. ]o3 $ &hutdown the system immediately. ]p3 $ 0rint the current registers and flags to the console. ]0.-V . &ets the console log le*el( controlling which kernel messages will be printed to your console. ]f3 . =ill call oomMkill to kill process which takes more memory. ]h3 $ Hsed to display the help. 8ut any other keys than the abo*e listed will print help.
=e can also do this by echoing the keys to the JprocJsysr@.trigger file. Cor e!ample( to re.boot a system you can perform the following. echo 2"2 Z /proc/sysr_#tri er
To perform a safe reboot of a inu! computer which hangs up( do the following. This will a*oid the fsck during the ne!t re.booting. i.e 0ress "lt`&ys4@`letter highlighted below. un6aw 9take control of keyboard back from I11; t5rminate 9send &27T:4/ to all processes( allowing them to terminate gracefully;( 152
www.thegeekstuff.com
)ync 9flush data to disk;( 1nmount 9remount all filesystems read.only;( re'oot.
Any Questions? .iscuss it here: $afe Me"oot Lf Linu- \sin Qey Sa ic $ysM_
153
www.thegeekstuff.com
) parted G&\ /arted 3.4 \sin /de(/sda `elco!e to G&\ /artedA +ype VhelpV to (iew a list of co!!ands. 7parted8 +o choose a different hard disk, use the select co!!and as shown "elow. 7parted8 select /de(/sd"
2t will throw the following error message when it doesn3t find the gi*en hard disk name. Irror: Irror openin Metry/Cancelc y /de(/sd": &o !ediu! found
Hsing the print command( you can *iew all the a*ailable partitions in the selected hard disk. The print command also displays hard disk properties such as model( si+e( sector si+e and partition table as shown below. 7parted8 print Sodel: %+% `.C `.6000B/'+#K 7scsi8 .isk /de(/sda: 600GB $ector siPe 7lo ical/physical8: 613B/50GCB /artition +a"le: !sdos &u!"er 1 3 4 5 $tart 105GkB 10CSB 16.FGB 3CCGB Ind 10CSB 16.FGB 3CCGB 600GB $iPe 106SB 16.KGB 361GB 345GB 154 +ype pri!ary pri!ary pri!ary e-tended Yilesyste! Yla s fat1C ntfs ntfs dia "oot
www.thegeekstuff.com
6 K F C G
#kpart
mkpart command is used to create either primary or logical partition with the &T"4T and :5) disk locations. The below e!ample creates partition with si+e around 1578. The &T"4T and :5) points passed to the mkpart command are in the units of /8s. 7parted8 !kpart pri!ary 10C 1C1KG
Aou can also enable boot option on a partition as shown below. inu! reser*es 1.4 or 1.3 partition number for primary partition and the e!tended partition starts from number 5. 7parted8 set 1 "oot on
#kpart
Hse mkpart command to create a new partition of a specific si+e. This will create the partition of a specific type such as primary( logical or e!tended without creating the file system. 8efore creating the partition( e!ecute a print command to *iew the current layout. 7parted8 print Sodel: %+% `.C `.6000B/'+#K 7scsi8 .isk /de(/sda: 600GB $ector siPe 7lo ical/physical8: 613B/50GCB /artition +a"le: !sdos
155
www.thegeekstuff.com
&u!"er 1 3 4 5 6 C K F
Yilesyste! Yla s fat1C ntfs ntfs e-t5 linu-#swap7(18 e-t5 e-t3 dia "oot
Hse mkpart to create a new logical partition with 12,78 si+e as shown below. 7parted8 !kpart lo ical 4K3K4K 600000
:!ecute the print command to *iew the new layout as shown below. 7parted8 print Sodel: %+% `.C `.6000B/'+#K 7scsi8 .isk /de(/sda: 600GB $ector siPe 7lo ical/physical8: 613B/50GCB /artition +a"le: !sdos &u!"er 1 3 4 5 6 C K F G $tart 105GkB 10CSB 16.FGB 3CCGB 3CCGB 41CGB 435GB 455GB 4K4GB Ind 10CSB 16.FGB 3CCGB 600GB 41CGB 435GB 455GB 4C5GB 600GB $iPe 106SB 16.KGB 361GB 345GB 60.0GB KGGGSB 30.0GB 30.0GB 13KGB 156 +ype pri!ary pri!ary pri!ary e-tended lo ical lo ical lo ical lo ical lo ical e-t5 linu-#swap7(18 e-t5 e-t3 Yilesyste! Yla s fat1C ntfs ntfs dia "oot
www.thegeekstuff.com
7parted8
#kfs
2f you use fdisk command to partition your hard disk( you need to e!it the fdisk utility( and use the mkfs e!ternal program to create a file system on the partition. 'owe*er using parted utility( you can also create filesystem. Hse the parted3s mkfs command to create a file system on a partition. Aou should be careful while doing this( as all the e!isting data in the partition will be lost during the file system creation. The supported filesystems in parted are e!t2( mips( fat16( fat32( linu!.swap( reiserfs 9if libreiserfs is installed;. et us change the file system of partition number D 9that is shown in the print output below; from e!t4 to e!t2 file system. 7parted8 print Sodel: %+% `.C `.6000B/'+#K 7scsi8 .isk /de(/sda: 600GB $ector siPe 7lo ical/physical8: 613B/50GCB /artition +a"le: !sdos &u!"er 1 3 4 5 6 C K F $tart 105GkB 10CSB 16.FGB 3CCGB 3CCGB 41CGB 435GB 455GB Ind 10CSB 16.FGB 3CCGB 600GB 41CGB 435GB 455GB 4C5GB $iPe 106SB 16.KGB 361GB 345GB 60.0GB KGGGSB 30.0GB 30.0GB +ype pri!ary pri!ary pri!ary e-tended lo ical lo ical lo ical lo ical e-t5 linu-#swap7(18 e-t5 e-t5 Yilesyste! Yla s fat1C ntfs ntfs dia "oot
15,
www.thegeekstuff.com
4C5GB
600GB
14CGB
lo ical
e-t5
"s shown below( use the mkfs command to change the file system type of partition number D. mkfs command will prompt you for partition number and file system type. 7parted8 !kfs `arnin : +he e-istin file syste! will "e destroyed and all data on the partition will "e lost. .o you want to continuec Yes/&oc y /artition nu!"erc F Yile syste! typec *e-t3,c e-t3
:!ecute the print command again( to *erify that the file system type for partition number D was changed to e!2. 7parted8 print Sodel: %+% `.C `.6000B/'+#K 7scsi8 .isk /de(/sda: 600GB $ector siPe 7lo ical/physical8: 613B/50GCB /artition +a"le: !sdos &u!"er 1 3 4 5 6 C K F G $tart 105GkB 10CSB 16.FGB 3CCGB 3CCGB 41CGB 435GB 455GB 4C5GB Ind 10CSB 16.FGB 3CCGB 600GB 41CGB 435GB 455GB 4C5GB 600GB $iPe 106SB 16.KGB 361GB 345GB 60.0GB KGGGSB 30.0GB 30.0GB 14CGB 15D +ype pri!ary pri!ary pri!ary e-tended lo ical lo ical lo ical lo ical lo ical e-t5 linu-#swap7(18 e-t5 e-t3 e-t5 Yilesyste! Yla s fat1C ntfs ntfs dia "oot
www.thegeekstuff.com
7parted8
#kpartfs
Hsing mkpartfs parted command( you can also create a partitions with a specific filesystem. This is similar to mkpart( but with the additional feature of creating file system on a partition. 8efore mkpartfs following is the layout of the partitions. 7parted8 print Sodel: %+% `.C `.6000B/'+#K 7scsi8 .isk /de(/sda: 600GB $ector siPe 7lo ical/physical8: 613B/50GCB /artition +a"le: !sdos &u!"er 1 3 4 5 6 C K F $tart 105GkB 10CSB 16.FGB 3CCGB 3CCGB 41CGB 435GB 455GB Ind 10CSB 16.FGB 3CCGB 600GB 41CGB 435GB 455GB 4C5GB $iPe 106SB 16.KGB 361GB 345GB 60.0GB KGGGSB 30.0GB 30.0GB +ype pri!ary pri!ary pri!ary e-tended lo ical lo ical lo ical lo ical e-t5 linu-#swap7(18 e-t5 Yilesyste! Yla s fat1C ntfs ntfs dia "oot
2n the following e!ample( mkpartfs will create a new fat32 partition of si+e 12,78. 7parted8 !kpartfs lo ical fat43 4K3K4K 600000
"s you see below( the partition number - is successfully created. 15-
www.thegeekstuff.com
7parted8 print Sodel: %+% `.C `.6000B/'+#K 7scsi8 .isk /de(/sda: 600GB $ector siPe 7lo ical/physical8: 613B/50GCB /artition +a"le: !sdos &u!"er 1 3 4 5 6 C K F G 7parted8 $tart 105GkB 10CSB 16.FGB 3CCGB 3CCGB 41CGB 435GB 455GB 4K4GB Ind 10CSB 16.FGB 3CCGB 600GB 41CGB 435GB 455GB 4C5GB 600GB $iPe 106SB 16.KGB 361GB 345GB 60.0GB KGGGSB 30.0GB 30.0GB 13KGB +ype pri!ary pri!ary pri!ary e-tended lo ical lo ical lo ical lo ical lo ical fat43 l"a e-t5 linu-#swap7(18 e-t5 Yilesyste! Yla s fat1C ntfs ntfs dia "oot
resiBe
Hsing resi+e parted command( you can increase or decrease the partition si+e of a partition as shown in the e!ample below. 7parted8 resiPe G $tartc Indc *4K4GB,c 4K4GB *600GB,c 560GB
"s shown abo*e( parted command will always warn whene*er you are attempting to do something dangerous 9i.e 1 rm( resi+e( mkfs;. The si+e of partition - is actually reduced from 12,78 to ,,78. ?erify that the partition is resi+ed properly using the print command as shown below. 160
www.thegeekstuff.com
7parted8 print Sodel: %+% `.C `.6000B/'+#K 7scsi8 .isk /de(/sda: 600GB $ector siPe 7lo ical/physical8: 613B/50GCB /artition +a"le: !sdos &u!"er 1 3 4 5 6 C K F G $tart 105GkB 10CSB 16.FGB 3CCGB 3CCGB 41CGB 435GB 455GB 4K4GB Ind 10CSB 16.FGB 3CCGB 600GB 41CGB 435GB 455GB 4C5GB 560GB $iPe 106SB 16.KGB 361GB 345GB 60.0GB KGGGSB 30.0GB 30.0GB KK.4GB +ype pri!ary pri!ary pri!ary e-tended lo ical lo ical lo ical lo ical lo ical fat43 l"a e-t5 linu-#swap7(18 e-t5 Yilesyste! Yla s fat1C ntfs ntfs dia "oot
0arted allows you to type unambiguous abbre*iation for commands like QpR for print( QselR for select(etc.
cp
The entire data from one partition can be copied to another partition using the cp command. Aou should also remember that the content of the destination will be deleted before copy starts. /ake sure that the destination partition has enough si+e to hold the data from the source partition. Hsing the QpR command 9print; to display the current partition layout. 7parted8 p Sodel: %+% `.C `.6000B/'+#K 7scsi8 .isk /de(/sda: 600GB $ector siPe 7lo ical/physical8: 613B/50GCB 161
www.thegeekstuff.com
/artition +a"le: !sdos &u!"er 1 3 4 5 6 C K F G 10 $tart 105GkB 10CSB 16.FGB 3CCGB 3CCGB 41CGB 435GB 455GB 4K4GB 5C1GB Ind 10CSB 16.FGB 3CCGB 600GB 41CGB 435GB 455GB 4C5GB 560GB 600GB $iPe 106SB 16.KGB 361GB 345GB 60.0GB KGGGSB 30.0GB 30.0GB KK.4GB 4G.3GB +ype pri!ary pri!ary pri!ary e-tended lo ical lo ical lo ical lo ical lo ical lo ical e-t5 linu-#swap7(18 e-t5 e-t3 fat43 e-t3 l"a Yilesyste! Yla s fat1C ntfs ntfs dia "oot
2t is recommended to unmount both source and destination partition before doing copy. 2n this e!ample we are going to copy the content from partition D to partition 10. The following shows the content of the corresponding partitions before copy. ) !ount /de(/sdaF /!nt ) cd /!nt ) ls #l total 63 #rw#r##r## 1 root root #rw#r##r## 1 root root ) u!ount /!nt ) !ount /de(/sda10 /!nt ) cd /!nt ) ls #l total 5F 162 0 3011#0G#3C 33:63 partF 30 3011#0G#3C 33:63 test.t-t
www.thegeekstuff.com
Hse the parted cp command to copy partition D to partition 10 as shown below. 7parted8 cp F 10 rowin file syste!... G6W 7ti!e left 00:4F8
The following shows the content of the partition 10 after the copy. "s you see below( the content of partition D is copied o*er 9o*erwritten; to the partition 10. ) !ount /de(/sda10 /!nt ) cd /!nt ) ls #l total 63 #rw#r##r## 1 root root #rw#r##r## 1 root root 0 3011#0G#3C 33:63 partF 30 3011#0G#3C 33:63 test.t-t
5ote1 =hen you copy across partitions of different filesystem9for e!ample src 1 e!t2 and dst 1 e!t4;( the destination partition3s file system is actually con*erted to the file system of source partition 9i.e 1 e!t2; .
r#
To delete an unwanted or unused partition( use the parted rm command and specify the partition number as shown below. 7parted8 r! /artition nu!"erc G 7parted8
"s you see below( the partition number - is now deleted. 163
www.thegeekstuff.com
7parted8 print Sodel: %+% `.C `.6000B/'+#K 7scsi8 .isk /de(/sda: 600GB $ector siPe 7lo ical/physical8: 613B/50GCB /artition +a"le: !sdos &u!"er 1 3 4 5 6 C K F $tart 105GkB 10CSB 16.FGB 3CCGB 3CCGB 41CGB 435GB 455GB Ind 10CSB 16.FGB 3CCGB 600GB 41CGB 435GB 455GB 4C5GB $iPe 106SB 16.KGB 361GB 34GB 60.0GB KGGGSB 30.0GB 30.0GB +ype pri!ary pri!ary pri!ary e-tended lo ical lo ical lo ical lo ical e-t5 linu-#swap7(18 e-t5 e-t3 Yilesyste! Yla s fat1C ntfs ntfs dia "oot
Any Questions? .iscuss it here: G Linu- /arted Co!!and I-a!ples H !kpart, !kpartfs, resiPe partitions
164
www.thegeekstuff.com
&ource and destination could be either local or remote. 2n case of remote( specify the login name( remote ser*er name and location.
www.thegeekstuff.com
5ow let us see the timestamp on one of the files that was copied from source to destination. "s you see below( rsync didn3t preser*e timestamps during sync. ; ls #l /(ar/opt/installation/in(entory/s(a.-!l /root/te!p/s(a.-!l #r##r##r## 1 "in "in G5G Dun 1F 300G /(ar/opt/installation/in(entory/s(a.-!l #r##r##r## 1 root "in G5G $ep 3 300G /root/te!p/s(a.-!l
)ync usin
rsync <a
5ow( e!ecuting the same command pro*ided in e!ample 1 98ut with the rsync option .a; as shown below1 ; rsync #aP( /(ar/opt/installation/in(entory/ /root/te!p/ "uildin ./ s(a.-!l s(B.-!l . sent 3C5GG "ytes recei(ed 1105 "ytes speedup is 1.C4 166 6630C.00 "ytes/sec total siPe is 55FCK file list ... done
www.thegeekstuff.com
"s you see below( rsync preser*ed timestamps during sync. ; ls #l /(ar/opt/installation/in(entory/s(a.-!l /root/te!p/s(a.-!l #r##r##r## 1 root "in G5G Dun 1F 300G /(ar/opt/installation/in(entory/s(a.-!l #r##r##r## 1 root "in /root/te!p/s(a.-!l G5G Dun 1F 300G
www.thegeekstuff.com
speedup is 3.FK
=hile doing synchroni+ation with the remote ser*er( you need to specify username and ip.address of the remote ser*er. Aou should also specify the destination directory on the remote ser*er. The format is usernameBmachinename1path "s you see abo*e( it asks for password while doing rsync from local to remote ser*er. &ometimes you don3t want to enter the password while backing up files from local to remote ser*er. Cor e!ample( 2f you ha*e a backup shell script( that copies files from local to remote ser*er using rsync( you need the ability to rsync without ha*ing to enter the password. To do that( setup ssh password less login as we e!plained earlier.
16D
www.thegeekstuff.com
Additional RS2N# Examples: How to Backup Linu-c 16 rsync Co!!and I-a!ples C rsync I-a!ples to I-clude Sultiple Yiles and .irectories usin e-clude#fro!
Co##and 5xa#ples
#hkconfig command is used to setup( *iew( or change ser*ices that are configured to start automatically during the system startup. This hack contains , practical e!amples that e!plains how to use the chkconfig command.
Aou can also specifically check whether it is configured for a particular run le*el or not. ) (i check1.sh chkconfi network ##le(el 4 == echo 2&etwork ser(ice is confi ured for le(el 42 16-
www.thegeekstuff.com
chkconfi network ##le(el 1 == echo 2&etwork ser(ice is confi ured for le(el 12 ) ./check1.sh &etwork ser(ice is confi ured for le(el 4
To *iew only the ser*ices that are configured to be started during system startup( do the following. 0lease note that this assumes that your system startup le*el is 3. chkconfi ##list T rep 4:on
To *iew the startup configuration of a particular ser*ice( grep the output of ]chkconfig $list3 for that ser*ice. chkconfi ##list T rep network
www.thegeekstuff.com
##list T
rep ipta"les
##add ipta"les ##list T 0:off rep ipta"les 1:off 3:on 4:on 5:on
+ote. Qchkconfig $addR only adds an e!isting ser*ice to the list of startup. 2f the ser*ice doesn3t e!ist( you should first install it before adding it to the system startup list. =hile this is pretty ob*ious( it is worth to mention it( as a newbie might make this mistake.
1:off
To remo*e it from the startup list( use the $del option as shown below. ) chkconfi ) chkconfi ##del ipCta"les ##list T rep ipCta"les
www.thegeekstuff.com
Aou can also combine multiple le*els. The following e!ample will turn off nfsser*er for both le*el 3 and 5. ) chkconfi ##le(el 46 nfsser(er off
0:off
-inetd "ased ser(ices: ) cd /etc/rc.d/rc4.d ) ls T rep -inetd Q0F-inetd $15-inetd ) cd /etc/rc.d/rc6.d 1,2
www.thegeekstuff.com
) ls T
rep -inetd
Q0F-inetd $15-inetd
) ls /etc/rc.d/rc4.d T ) ls /etc/rc.d/rc6.d T
"fter you add the nfsser*er ser*ice( you3ll see the symbolic links under these directories. ) chkconfi nfsser(er ) cd ##add nfsser(er 0:off 1:off 3:off 4:on 5:off 6:on C:off
) ls #l T
lrw-rw-rw- 1 root root 13 3011#0C#1F 00:63 Q0Fnfsser(er #Z ../nfsser(er lrw-rw-rw- 1 root root 13 3011#0C#1F 00:63 $15nfsser(er #Z ../nfsser(er
1,3
www.thegeekstuff.com
) cd /etc/rc.d/rc6.d ) ls #l T rep nfsser(er lrw-rw-rw- 1 root root 13 3011#0C#1F 00:63 Q0Fnfsser(er #Z ../nfsser(er lrw-rw-rw- 1 root root 13 3011#0C#1F 00:63 $15nfsser(er #Z ../nfsser(er
=hen you turn off the ser*ice either using $del option or $le*el option( the corresponding symbolic link file under rc!.d directory will be deleted as shown below. ) chkconfi ##le(el 6 nfsser(er off T rep nfsser(er
) ls /etc/rc.d/rc6.d
Any Questions? .iscuss it here: K Linu- chkconfi Co!!and I-a!ples H %dd, Me!o(e, 'iew, Chan e $er(ices
1,4
www.thegeekstuff.com
'owe*er( if you ha*e the same 6ob scheduled in anacron( you can be sure that it will be e!ecuted once the laptop come back up.
Anacrontab 7or#at
Sust like how cron has JetcJcrontab( anacron has JetcJanacrontab. JetcJanacrontab file has the anacron 6obs mentioned in the following format. period delay Eo"#identifier co!!and
7ield 1 is 6ecurrence period. This is a numeric *alue that specifies the number of days. 1 $ daily , $ weekly 30 $ monthly 5 $ This can be any numeric *alue. 5 indicates number of days 5ote1 Aou can also use ]Bmonthly3 for a 6ob that needs to be e!ecuted monthly.
7ield , is "elay. This indicates the delay in minutes. i.e I number of minutes anacron should wait before e!ecuting the 6ob after the the machine starts. 7ield - is 9ob identifier. 2t is the name for the 6ob3s timestamp file. 2t should be uni@ue for each 6ob. This will be a*ailable as a file under the J*arJspoolJanacron directory. This file will contain a single line that indicates the last time when this 6ob was e!ecuted. ) ls #1 /(ar/spool/anacron/ test.daily cron.daily cron.!onthly cron.weekly 1,5
www.thegeekstuff.com
7ield 0 is co##and. #ommand or shell script that needs to be e!ecuted. Sust like shell scripts( comments inside anacrontab file starts with ^
Anacron 5xa#ple
The following e!ample e!ecutes the JhomeJsathiyaJbackup.sh script once in e*ery , days. %n the day when the backup.sh 6ob is supposed to e!ecuted( if the system is down for some reason( anacron will e!ecute the backup.sh script 15 minutes after the system comes back up 9without ha*ing to wait for another , days;. ) cat /etc/anacronta" K 16 test.daily /ho!e/sathiya/"ackup.sh /"in/sh
1,6
www.thegeekstuff.com
$+%M+9HL\M$9M%&GI04#33
%n top of the user defined delay specified in the 2nd field of the JetcJanacrontab file( anacron also randomly adds ! number of minutes. The ! is defined by the 4"5)%/M): "A *ariable in the JetcJanacrontab file. 8y default this is set to 45 in the file. This means that anacron will add ! minutes 9randomly picked from 0 and 45;( and add this to the user defined delay. ) rep M%&.LS /etc/anacronta"
M%&.LS9.IL%Y056
Cron %s Anacron
#ron and anacron has its own ad*antages and disad*antages. )epending on your re@uirement( use one of them. Cron /inimum granularity is minute 9i.e Sobs can be scheduled to be e!ecuted e*ery minute; #ron 6ob can be scheduled by any normal user 9 if not restricted by super user #ron e!pects system to be running 24 ! ,. 2f a 6ob is scheduled( and system is down during that time( 6ob is not e!ecuted. 2deal for ser*ers Anacron /inimum granularity is only in days
"nacron can be used only by super user 9 but there are workarounds to make it usable by normal user ; "nacron doesn3t e!pect system to be running 24 ! ,. 2f a 6ob is scheduled( and system is down during that time( it start the 6obs when the system comes back up. 2deal for desktops and laptops 1,,
www.thegeekstuff.com
Hse cron when a 6ob has to be e!ecuted at a particular hour and minute
Hse anacron when a 6ob has to be e!ecuted irrespecti*e of hour and minute
Any Questions? .iscuss it here: Cron 's %nacron: How to $etup %nacron on Linu- 7`ith an I-a!ple8
8efore you start building new set of rules( you might want to clean.up all the default rules( and e!isting rules. Hse the iptables flush command as shown below to do this. ipta"les #Y 7or8 ipta"les ##flush
=hen you make both 250HT( and %HT0HT chain3s default policy as )4%0( for e*ery firewall rule re@uirement you ha*e( you should define two rules. i.e one for incoming and one for outgoing.
1,D
www.thegeekstuff.com
2n all our e!amples below( we ha*e two rules for each scenario( as we3*e set )4%0 as default policy for both 250HT and %HT0HT chain. 2f you trust your internal users( you can omit the last line abo*e. i.e )o not )4%0 all outgoing packets by default. 2n that case( for e*ery firewall rule re@uirement you ha*e( you 6ust ha*e to define only one rule. i.e define rule only for incoming( as the outgoing is "##:0T for all packets.
))H
incoming ssh connections on eth0
ipta"les #% B&/\+ #i eth0 #p tcp ##dport 33 #! state ##state &I`,I$+%BLB$HI. #E %CCI/+ ipta"les #% L\+/\+ #o eth0 #p tcp ##sport 33 #! state ##state I$+%BLB$HI. #E %CCI/+
1,-
www.thegeekstuff.com
Allo* Inco#in
The following rules allow incoming ssh connections only from 1-2.16D.100.I network. ipta"les #% B&/\+ #i eth0 #p tcp #s 1G3.1CF.100.0/35 ##dport 33 #! state ##state &I`,I$+%BLB$HI. #E %CCI/+ ipta"les #% L\+/\+ #o eth0 #p tcp ##sport 33 #! state ##state I$+%BLB$HI. #E %CCI/+
2n the abo*e e!ample( instead of J24( you can also use the full subnet mask. i.e Q1-2.16D.100.0J255.255.255.0f.
Additional 701a$les Examples: 36 Sost Yre_uently \sed Linu- B/+a"les Mules I-a!ples B/+a"les +a"les, Chains, Mules Yunda!entals How to %dd Yirewall Mules Bnco!in and Lut oin Mule I-a!ples
1D0
www.thegeekstuff.com
yu# install
To install a package( do ]yum install packagename3. This will also identify the dependencies automatically and install them. The following e!ample installs postgres@l package. ) yu! install post res_l.-FC9C5 Mesol(in Bnstall .ependencies 3 /acka e7s8
Bs this ok *y/&,: y Munnin +ransaction : post res_l#li"s#G.0.5#6.fc16.-FC9C5 : post res_l#G.0.5#6.fc16.-FC9C5 1/3 3/3
Bnstallin Bnstallin
8y default ]yum install3( will prompt you to accept or decline before installing the packages. 2f you want yum to install automatically without prompting( use .y option as shown below. ) yu! #y install post res_l.-FC9C5 1D1
www.thegeekstuff.com
yu# re#o2e
To remo*e a package 9along with all its dependencies;( use ]yum remo*e package3 as shown below. ) yu! re!o(e post res_l.-FC9C5
/acka e post res_l.-FC9C5 0:G.0.5#6.fc16 will "e erased Bs this ok *y/&,: y Munnin Irasin +ransaction : post res_l#G.0.5#6.fc16.-FC9C5 1/1
1p rade an existin
packa e usin
yu# update
2f you ha*e a older *ersion of a package( use ]yum update package3 to upgrade it to the latest current *ersion. This will also identify and install all re@uired dependencies. ) yu! update post res_l.-FC9C5
yu# search
2f you don3t know the e!act package name to be installed( use ]yum search keyword3( which will search all the packages that matches the ]keyword3 and display it. The following e!amples searches the yum repository for all the packages that matches the keyword ]firefo!3 and lists the a*ailable packages. ) yu! search firefoLoaded plu ins: lan packs, presto, refresh#packa ekit 00000000000000 &/$ Satched: firefo- 0000000000000000000000 firefo-.-FC9C5 : SoPilla Yirefo- `e" "rowser no!e#do#plu ins#firefo-.-FC9C5 !oPilla#firetray#firefo-.-FC9C5 !oPilla#ad"lockplus.noarch : SoPilla Yirefo- e-tension !oPilla#noscript.noarch : SoPilla Yirefo- e-tension 1D2
www.thegeekstuff.com
5ame and summary matches only( use Fsearch allF for e*erything.
yu#
%nce you search for a package using yum search( you can use ]yum info package3 to *iew additional information about the package. The following e!amples displays additional information about the samba.common package. ) yu! info sa!"a#co!!on.iCFC Loaded plu ins: lan packs, presto, refresh#packa ekit %(aila"le /acka es &a!e %rch Ipoch 'ersion Melease $iPe Mepo $u!!ary \ML License : sa!"a#co!!on : iCFC : 1 : 4.6.11 : K1.fc16.1 : G.G S : updates : Yiles used "y "oth $a!"a ser(ers and clients : http://www.sa!"a.or / : G/L(4O and LG/L(4O
.escription : $a!"a#co!!on pro(ides files necessary for "oth the ser(er and client
Additional 26& Examples: 16 Linu- Yu! Co!!and I-a!ples H Bnstall, \ninstall, \pdate /acka es
1D3
www.thegeekstuff.com
Installin
rp# <i2h
40/ filename has packagename( *ersion( release and architecture name. Cor e!ample( 2n the /y&i .client.3.23.5,.1.i3D6.rpm file1 /y&i .client $ 0ackage 5ame 3.23.5, $ ?ersion 1 $ 4elease i3D6 $ "rchitecture
=hen you install a 40/( it checks whether your system is suitable for the software the 40/ package contains( figures out where to install the files located inside the rpm package( installs them on your system( and adds that piece of software into its database of installed 40/ packages. The following rpm command installs /ys@l client package. ) rp! #i(h Sy$bL#client#4.34.6K#1.i4FC.rp!
1D4
www.thegeekstuff.com
rpm command and options .i 1 install a package .* 1 *erbose .h 1 print hash marks as the package archi*e is unpacked.
Aou can also use dpkg on )ebian( pkgadd on &olaris( depot on '0.HI to install packages.
rp# <;a
Aou can use rpm command to @uery all the packages installed in your system. ) rp! #_a cdrecord#3.01#10.K.el6 "lueP#li"s#4.K#1.1 setarch#3.0#1.1 . . .@ @uery operation .a @ueries all installed packages
To identify whether a particular rpm package is installed on your system( combine rpm and grep command as shown below. Collowing command checks whether cdrecord package is installed on your system. ) rp! #_a T rep VcdrecordV
rp# <;
The abo*e e!ample lists all currently installed package. "fter installation of a package to check the installation( you can @uery a particular package and *erify as shown below. ) rp! #_ Sy$bL#client Sy$bL#client#4.34.6K#1 1D5
www.thegeekstuff.com
5ote1 To @uery a package( you should specify the e!act package name. 2f the package name is incorrect( then rpm command will report that the package is not installed.
rp# =
4pm command pro*ides an option $@ueryformat( which allows you to gi*e the header tag names( to list the packages. :nclose the header tag with in ab. ) rp! #_a ##_ueryfor!at VW:na!e#W:(ersion@#W:release@ W :siPe@>nV cdrecord#3.01#10.K 13435 "lueP#li"s#4.K#1.1 6C45 setarch#3.0#1.1 3466C4 . .
et us say( you ha*e list of files and you would want to know which package owns all these files. rpm command has options to achie*e this. The following e!ample shows that JusrJbinJmys@laccess file is part of the /y&i .client.3.23.5,.1 rpm. ) rp! #_f /usr/"in/!ys_laccess Sy$bL#client#4.34.6K#1
1D6
www.thegeekstuff.com
rp# <;ip
rpm command pro*ides a lot of information about the installed packages. ) rp! #_ip Sy$bL#client#4.34.6K#1.i4FC.rp! &a!e 'ersion Melease Group $iPe $i nature /acka er \ML $u!!ary : Sy$bL#client Melocations: 7not relocata"le8 : 4.34.6K : 1 'endor: Sy$bL %B Build .ate: Son 0G Dun 3004 Build Host: "uild.!ys_l.co! License: G/L / LG/L
: %pplications/.ata"ases
.escription : +his packa e is a standard Sy$bL client. .i 1 *iew information about an rpm .p 1 specify a package name
1D,
www.thegeekstuff.com
rp# <;lp
To list the content of a 40/ package( use the following command( which will list out the files without e!tracting into the local directory folder. ; rp! #_lp o(pc#3.1.10.rp! /usr/"in/!ys_laccess /usr/"in/!ys_ldata /usr/"in/!ys_lper! . . /usr/"in/!ys_lad!in @ 1 @uery the rpm file l 1 list the files in the package p 1 specify the package name
rp# <;6/
To *iew the list of packages on which this package depends( ) rp! #_Mp Sy$bL#client#4.34.6K#1.i4FC.rp! /"in/sh /usr/"in/perl
Additional R0& Examples: M/S Co!!and: 16 I-a!ples to Bnstall, \ninstall, \p rade, buery M/S /acka es
1DD
www.thegeekstuff.com
This hack( using "pache 2 installation as an e!ample( e!plains how to use apt.U commands to *iew( install( remo*e( or upgrade packages.
/acka e +a#e
2f you are installing "pache 2( you may guess that the package name is apache2. To *erify whether it is a *alid package name( you may want to search the repository for that particular package name as shown below. The following e!ample shows how to search the repository for a specific package name. ; apt#cache search Napache3; apache3 # %pache H++/ $er(er !etapacka e
dpk
8efore installing a package( you may want to make sure it is not already installed as shown below using dpkg .l command. ; dpk #l T rep #i apache
apache3 apache3#!p!#worker apache3#utils apache3.3#co!!on li"apr1 li"aprutil1 li"p_6 0 up raded, K newly installed, 0 to re!o(e and 3C not up raded.
1D-
www.thegeekstuff.com
Additional apt-8 #ommand Examples: How +o Sana e /acka es \sin apt# et, apt#cache, apt# file and dpk Co!!ands 7 `ith 14 /ractical I-a!ples 8
1-0
www.thegeekstuff.com
2f the source code you>*e downloaded is in the format application.tar.b+2( use the following command to uncompress it. tar -(fE application.tar."P3
Confi ure
%nce you uncompress the source tar file( it will create a subdirectory in the name of the application. #) to this directory. cd application
)o a .Jconfigure ..help which will display all application specific configuration options that are a*ailable to you. ./confi ure ##help
2n most cases( you can 6ust do .Jconfigure which will use all default *alues to perform the configuration. This will perform necessary pre.re@ checks. This will also generate the /akefile re@uired for the installation. ./confi ure
Cinally( do >make install> which will install the application in the appropriate location. !ake install
1-1
www.thegeekstuff.com
"o*nload Apache
)ownload "pache from httpd.apache.org. The current stable release is 2.2.1,. %nce you get the direct H4 to download the latest stable *ersion of "pache( use wget as shown below to download it directly to you ser*er. cd 1 w et http://www.en .lsu.edu/!irrors/apache//httpd/httpd# 3.3.1K.tar. P tar -(fP httpd#3.3.1K.tar. P
To install an "pache module( you would typically say $enable.amodule. nameb. Cor e!ample( to install && with "pache( it is $enable.ssl. To install ldap module( it is $enable.ldap. 1-2
www.thegeekstuff.com
To uninstall any default module that comes with "pache( you would typically say $disable.amodule.nameb. Cor e!ample( to disable basic authentication in "pache( it is $disable.auth.basic 2n this e!ample( we will install "pache with all default modules( with addition of $enable.ssl 9to install modMssl for && support;( and $enable. so( which helps to load modules in "pache during run.time *ia the )ynamic &hared %b6ect 9)&%; mechanism( rather than re@uiring a recompilation. ./confi ure ##ena"le#ssl ##ena"le#so !ake !ake install
+ote. 8y default the abo*e installs "pache under JusrJlocalJapache2. 2f you like to change this location( use $prefi! option in the .Jconfigure.
?iew the httpd.ssl.conf to re*iew all the default && configurations. Cor most cases( you don3t need to modify anything in this file. (i /usr/local/apache3/conf/e-tra/httpd#ssl.conf
The && certificate and key are re@uired before we start the "pache. The ser*er.crt and ser*er.key file mentioned in the httpd.ssl.conf needs to be created before we mo*e forward. 1-3
www.thegeekstuff.com
The abo*e command will ask for the password. /ake sure to remember this password. Aou need this while starting your "pache later. 2f you don3t pro*ide a password( you3ll get the following error message. 3516:error:3F0CG0C6:li"7508:\B9set9result:result too s!all:ui9li".c:F5G:You !ust type in 5 to F1G1 characters
5e!t( generate a certificate re@uest file 9ser*er.csr; using the abo*e ser*er.key file. openssl re_ #new #key ser(er.key #out ser(er.csr
Cinally( generate a self signed ssl certificate 9ser*er.crt; using the abo*e ser*er.key and ser*er.csr file. openssl -60G #re_ #days 4C6 #in ser(er.csr #si nkey ser(er.key #out ser(er.crt
Cor more details refer to1 'ow To 7enerate && _ey( #&4 and &elf &igned #ertificate Cor "pache
1-4
www.thegeekstuff.com
This will prompt you to enter the password for your pri*ate key. %pache/3.3.1K !od9ssl/3.3.1K 7/ass /hrase .ialo 8 $er(er www.e-a!ple.co!:554 7M$%8 Inter pass phrase: LQ: /ass /hrase .ialo successful.
8y default "pache && runs on 443 port. %pen a web browser and *erify that you can access your "pache using https1JJayour.ip.addressb
Any Questions? .iscuss it here: How +o Bnstall %pache 3 with $$L on Linu- 7with !od9ssl, openssl8 Additional Apache 7nstall Examples: How +o Generate $$L Qey, C$M and $elf $i ned Certificate Yor %pache 1-5
www.thegeekstuff.com
/rere;uisites
"pache web ser*er should already be installed. 4efer to my pre*ious post on 'ow to install "pache 2 on inu!. 2f you are planning to use 0'0 with /y&i ( you should ha*e /y &i already installed.
"o*nload /H/
)ownload the latest source code from 0'0 )ownload page. #urrent stable release is 5.2.6. /o*e the source to JusrJlocalJsrc and e!tract is as shown below. ) "Pip3 #d php#6.3.C.tar."P3 ) tar -(f php#6.3.C.tar
Install /H/
?iew all configuration options a*ailable for 0'0 using .Jconfigure $.help 9two hyphen in front of help;. The most commonly used option is $. prefi!Kainstall.dir.nameb to install 0'0 on a user defined directory. ) cd php#6.3.C ) ./confi ure ##help 2n the following e!ample( 0'0 will be compiled and installed under the default location JusrJlocalJlib with "pache configuration and /y&i support.
1-6
www.thegeekstuff.com
/ake sure the httpd.conf has the following line that will get automatically inserted during the 0'0 installation process. LoadSodule php69!odule !odules/li"php6.so
7o to http1JJlocal.hostJtest.php ( which will show a detailed information about all the 0'0 configuration options and 0'0 modules installed on the system.
1-,
www.thegeekstuff.com
Trouble shootin
durin
installation
5rror 1. configure1 error1 !ml2.config not found1 =hile performing the .Jconfigure during 0'0 installation( you may get the following error1 ) ./confi ure ##with#ap-s30/usr/local/apache3/"in/ap-s ##with#!ys_l Confi urin checkin checkin checkin e-tensions whether to ena"le LBBaSL support... yes li"-!l3 install dir... no for -!l3#confi path... not found. /lease check your
2nstall thelib!ml2.de*el and +lib.de*el as shown below to the fi! this issue. ) rp! #i(h /ho!e/downloads/linu-#iso/li"-!l3#de(el#3.C.3C# 3.1.3.0.1.i4FC.rp! /ho!e/downloads/linu-#iso/Pli"#de(el# 1.3.4#4.i4FC.rp! /reparin ...))))))))))))))))))))))))))))))))))))) *100W, 1:Pli"#de(el))))))))))))))))))))))))))))))))))))) * 60W, 3:li"-!l3#de(el)))))))))))))))))))))))))))))))))) *100W,
5rror ,. configure1 error1 #annot find /y&i header files. =hile performing the .Jconfigure during 0'0 installation( you may get the following error1 ) ./confi ure ##with#ap-s30/usr/local/apache3/"in/ap-s ##with#!ys_l checkin for Sy$bL \&Ba socket location... /(ar/li"/!ys_l/!ys_l.sock confi ure: error: Cannot find Sy$bL header files under yes. &ote that the Sy$bL client li"rary is not "undled any!oreA
1-D
www.thegeekstuff.com
2nstall the /y&i .de*el.community package as shown below to fi! this issue. ) rp! #i(h /ho!e/downloads/Sy$bL#de(el#co!!unity#6.1.36# 0.rhel6.i4FC.rp! /reparin ...)))))))))))))))))))))))))))))))))))))) *100W, 1:Sy$bL#de(el#co!!unity))))))))))))))))))))))))))) *100W,
Any Questions? .iscuss it here: Bnstruction Guide to Bnstall /H/6 fro! $ource on Linu-
2f you want to remo*e the e!isting default /y&i that came with the inu! distro ( do the following. )o not perform this on an system where the /y&i database is getting used by some application. 1--
www.thegeekstuff.com
rep #i !ys_l
!ys_lclient10#4.34.6F#5.MHIL5.1 *local#host,) rp! #e !ys_l ##nodeps warnin : /etc/!y.cnf sa(ed as /etc/!y.cnf.rp!sa(e *local#host,) rp! #e !ys_lclient10
*local#host,) rp! #i(h Sy$bL#ser(er#co!!unity#6.1.36# 0.rhel6.i4FC.rp! Sy$bL#client#co!!unity#6.1.36# 0.rhel6.i4FC.rp! /reparin ...))))))))))))))))))))))))))))))))))))))) *100W, 1:Sy$bL#client#co!!unity))))))))))))))))))))))))))) * 60W, 3:Sy$bL#ser(er#co!!unity))))))))))))))))))))))))))) *100W,
This will also display the following output and start the /y&i daemon automatically. /LI%$I MISISBIM +L $I+ % /%$$`LM. YLM +HI Sy$bL root \$IMA +o do so, start the ser(er, then issue the followin co!!ands: /usr/"in/!ys_lad!in #u root password Vnew#passwordV /usr/"in/!ys_lad!in #u root #h !edica3 password Vnew# passwordV %lternati(ely you can run: /usr/"in/!ys_l9secure9installation
200
www.thegeekstuff.com
$tartin Gi(in
Sy$bL.*
LQ
2nstall the Q'eader and ibrariesR that are part of the /y&i .de*el packages. *local#host,) rp! #i(h Sy$bL#de(el#co!!unity#6.1.36# 0.rhel6.i4FC.rp! /reparin ...))))))))))))))))))))))))))))))))))))))) *100W, 1:Sy$bL#de(el#co!!unity )))))))))))))))))))))))))) *100W,
5ote1 =hen 2 was compiling 0'0 with /y&i option from source on the inu! system( it failed with the following error. 2nstalling the /y&i . de*el.community package fi!ed this problem in installing 0'0 from source. confi ure: error: Cannot find Sy$bL header files under yes. 5ote that the /y&i client library is not bundled anymorec
The best option is to run the mys@lMsecureMinstallation script that will take care of all the typical security related items on the /y&i as shown below. %n a high le*el this does the following items1 #hange the root password 4emo*e the anonymous user )isallow root login from remote machines 201
www.thegeekstuff.com
*local#host,) /usr/"in/!ys_l9secure9installation &L+I: M\&&B&G %LL /%M+$ LY +HB$ $CMB/+ B$ MICLSSI&.I. YLM %LL Sy$bL $IM'IM$ B& /ML.\C+BL& \$IA /LI%$I MI%. I%CH $+I/ C%MIY\LLYA Inter current password for root 7enter for none8: LQ, successfully used password, !o(in Chan e the root passwordc *Y/n, Y &ew password: Me#enter new password: /assword updated successfullyA Meloadin pri(ile e ta"les.. ... $uccessA on...
Me!o(e anony!ous usersc *Y/n, Y .isallow root lo in re!otelyc *Y/n, Y Me!o(e test data"ase and access to itc *Y/n, Y Meload pri(ile e ta"les nowc *Y/n, Y installation should now "e secure. +hanks for usin Sy$bLA
202
www.thegeekstuff.com
!ys_l 'er 15.15 .istri" 6.1.36#rc, for redhat#linu-# nu 7iCFC8 usin readline 6.1
#onnect to the /y&i database using the root user and make sure the connection is successful. *local#host,) !ys_l #u root #p Inter password: !ys_lZ
Collows the steps below to stop and start /y&i *local#host,) ser(ice !ys_l status Sy$bL runnin 7136FF8 * LQ ,
Any Questions? .iscuss it here: Howto Bnstall Sy$bL on LinuAdditional &ySQ( 7nstall Examples: How to Bnstall Sy$bL .ata"ase \sin Yu! roupinstall
203
www.thegeekstuff.com
?u#
rep httpd
2f the abo*e command did not return anything( install apache as shown below ) yu! install httpd
?erify that "pache got installed successfully ) rp! #_a T rep #i http
httpd#tools#3.3.G#1.fcG.i4FC httpd#3.3.G#1.fcG.i4FC
:nable httpd ser*ice to start automatically during system startup using chkconfig. &tart the "pache as shown below. ) chkconfi httpd on
?u#
Aum is *ery smart to identify all the dependencies and install those automatically. Cor e!ample( while installing mys@l.ser*er using yum( it also automatically installs the depended mys@l.libs( perl.)82( mys@l( perl.)8)./y&i packages as shown below. 204
www.thegeekstuff.com
0artial output of the abo*e yum install mys@l.ser*er command1 .ependencies Mesol(ed +ransaction $u!!ary 00000000000000000000000000000000000000000000000000000000 Bnstall \pdate Me!o(e 6 /acka e7s8 0 /acka e7s8 0 /acka e7s8
+otal download siPe: 16 S Bs this ok *y/&,: y Munnin +ransaction : !ys_l#li"s : perl#.BB : !ys_l : perl#.B.#Sy$bL : !ys_l#ser(er *1/6, *3/6, *4/6, *5/6, *6/6,
?erify whether /y&i got installed properly. ) rp! #_a T rep #i !ys_l
www.thegeekstuff.com
) !ys_l #' !ys_l 'er 15.13 .istri" 6.0.61a, for redhat#linu-# nu 7i4FC8 usin readline 6.0
The first time when you start mys@ld( it will gi*e additional information message indicating to perform post.install configuration as shown below. BnitialiPin Bnstallin Yillin Sy$bL data"ase: Sy$bL syste! ta"les... LQ
help ta"les... LQ
+o start !ys_ld at "oot ti!e you ha(e to copy support#files/!ys_l.ser(er to the ri ht place for your syste! /LI%$I MISISBIM +L $I+ % /%$$`LM. YLM Sy$bL root \$IM A $tart the ser(er, then issue the followin co!!ands: /usr/"in/!ys_lad!in #u root password Vnew#passwordV /usr/"in/!ys_lad!in #u root #h de(#d" password Vnew# passwordV %lternati(ely you can run: /usr/"in/!ys_l9secure9installation
206
www.thegeekstuff.com
$tartin Sy$bL: * LQ ,
To fi! this problem( you need to assign a password to mys@l root account as shown below. :!ecute mys@lMsecureMinstallation script( which performs the following acti*ities1 "ssign the root password 4emo*e the anonymous user )isallow root login from remote machines 4emo*e the default sample test database
) /usr/"in/!ys_l9secure9installation
0artial output of mys@lMsecureMinstallation script1 Inter current password for root 7enter for none8: LQ, successfully used password, !o(in $et root passwordc *Y/n, Y &ew password: *&ote: Inter the !ys_l root password here, Me#enter new password: /assword updated successfullyA Me!o(e anony!ous usersc *Y/n, Y .isallow root lo in re!otelyc *Y/n, Y Me!o(e test data"ase and access to itc *Y/n, Y 20, on...
www.thegeekstuff.com
?erify the /y&i post.install acti*ities. 5ow root access without password is denied. ) !ys_l #u root IMMLM 1056 73F0008:%ccess denied for user VrootV<VlocalhostV7usin password:&L8
Test database is not a*ailable anymore. ) !ys_l #u root #p Inter password: !ys_lZ show data"ases? O####################O T .ata"ase T O####################O T infor!ation9sche!a T T !ys_l T O####################O 3 rows in set 70.00 sec8
?u#
0artial output of yum install php1 .ependencies Mesol(ed +ransaction $u!!ary 20D
www.thegeekstuff.com
00000000000000000000000000000000000000000000000000000000 Bnstall \pdate Me!o(e 4 /acka e7s8 0 /acka e7s8 0 /acka e7s8
+otal download siPe: 4.F S Bs this ok *y/&,: y Munnin +ransaction : php#co!!on : php#cli : php *1/4, *3/4, *4/4,
?erify that php got installed successfully. ) rp! #_a T rep #i php
0artial output of yum install php.mys@l1 .ependencies Mesol(ed +ransaction $u!!ary 0000000000000000000000000000000000000000000000000000 Bnstall 3 /acka e7s8 20-
www.thegeekstuff.com
\pdate Me!o(e
+otal download siPe: 154 k Bs this ok *y/&,: y Munnin +ransaction : php#pdo : php#!ys_l *1/3, *3/3,
2f you need additional 0'0 modules( install them using yum as shown below. ) yu! install php#co!!on php#!"strin php#-!l php# d php#!crypt php#de(el
Any Questions? .iscuss it here: How +o Bnstall Lr \p rade L%S/ \sin Yu!
www.thegeekstuff.com
"lso( I"/00 is a*ailable for inu!( =indows( /ac %&( and &olaris.
"o*nload :A&//
)ownload I"/00 from !ampp in sourceforge.
Install :A&//
:!tract the tar file under Jopt directory. ) cd /opt ) tar -(Pf -a!pp#linu-#1.K.4a.tar. P
211
www.thegeekstuff.com
Any Questions? .iscuss it here: a%S//: Iasy %pache, Sy$bL, /H/, /erl Bnstall
roup
8y default( apache might run as nobody or daemon. 2t is good to run apache in its own non.pri*ileged account. Cor e!ample1 apache. #reate apache group and user. roupadd apache useradd #d /usr/local/apache3/htdocs # /"in/false apache apache #s
/odify the httpd.conf( and set Hser and 7roup appropriately. ) (i httpd.conf \ser apache Group apache 212
www.thegeekstuff.com
"fter this( if you restart apache( and do ps .ef( you3ll see that the apache is running as QapacheR 9:!cept the 1st httpd process( which will always run as root;. ) ps #ef T root apache apache apache apache apache rep #i http T awk V:print ;1@V
2n the abo*e1 %ptions 5one $ &et this to 5one( which will not enable any optional e!tra features. %rder deny(allow $ This is the order in which the Q)enyR and Q"llowR directi*es should be processed. This processes the QdenyR first and QallowR ne!t. )eny from all $ This denies re@uest from e*erybody to the root directory. There is no "llow directi*e for the root directory. &o( nobody can access it.
213
www.thegeekstuff.com
"llow access to bin directory for this group. chown #M root:apachead!in /usr/local/apache3/"in ch!od #M KK0 /usr/local/apache3/"in
"llow access to conf directory for this group. chown #M root:apachead!in /usr/local/apache3/conf ch!od #M KK0 /usr/local/apache3/conf
"dd appropriate members to this group. 2n this e!ample( both ramesh and 6ohn are part of apacheadmin ) (i /etc/ roup apachead!in:-:1131:ra!esh,Eohn
www.thegeekstuff.com
can click on the indi*idual image file to *iew it( or click on a sub. directory to see its content. To disable directory browsing( you can either set the *alue of %ptions directi*e to Q5oneR or Q.2nde!esR. " $ in front of the option name will remo*e it from the current list of options enforced for that directory. 2nde!es will display a list of a*ailable files and sub.directories inside a directory in the browser 9only when no inde!.html is present inside that folder;. &o( 2nde!es should not be allowed. [.irectory /Z Lptions &one Lrder allow,deny %llow fro! all [/.irectoryZ 7or8 [.irectory /Z Lptions #Bnde-es Lrder allow,deny %llow fro! all [/.irectoryZ
www.thegeekstuff.com
Lptions &one %llowL(erride &one Lrder allow,deny %llow fro! all [/.irectoryZ
Additional Apache 3ardening Examples: 10 +ips to $ecure Your %pache `e" $er(er on \&Ba / Linu-
216
www.thegeekstuff.com
*&ote: you can use either apachectl or httpd as shown a"o(e, ) ps #ef T rep http
root 360F0 1 0 34:3C 00:00:00 /usr/s"in/httpd #f conf/httpd.conf.de"u apache 360GG 360F0 0 34:3F 00:00:00 /usr/s"in/httpd #f conf/httpd.conf.de"u *&ote: ps shows the httpd runnin file, with httpd.conf.de"u
%nce you are satisfied with the changes and "pache runs without any problem with httpd.conf.debug( you can copy the changes to httpd.conf and start the "pache normally as shown below. ) cp httpd.conf.de"u ) apachectl stop ) apachectl start ) ps #ef T root start dae!on start rep httpd 1 0 34:3F 00:00:00 /usr/s"in/httpd #k 0 34:3F 00:00:00 /usr/s"in/httpd #k usin the httpd.conf
36115
36116 36115
www.thegeekstuff.com
2f you want to go back to original configuration using the default )ocument4oot 9J*arJwwwJhtml;( simply restart the "pache as shown below. ) httpd #k stop ) apachectl start
0ossible *alues you can pass to option .e are1 debug( info( notice( warn( error( crit( alert( emerg
option
21D
www.thegeekstuff.com
21-
www.thegeekstuff.com
Qeep%li(e 7http9core.c8 `hether persistent connections should "e Ln or Lff %llowed in R.conf only outside [.irectoryZ, [YilesZ or [LocationZ LoadSodule 7!od9so.c8 a !odule na!e and the na!e of a shared o"Eect file to load it fro! %llowed in R.conf only outside [.irectoryZ, [YilesZ or [LocationZ
chan es
Hse option .t to *alidate whether there are any issues with a specific "pache configuration file. 2n the e!ample shown below( it displays that there is a problem at line 14D in the httpd.conf.debug. modMauthMbasicso is missing a . 9period; before the so. ) httpd #t #f conf/httpd.conf.de"u httpd: $ynta- error on line 15F of /etc/httpd/conf/httpd.conf.de"u : Cannot load /etc/httpd/!odules/!od9auth9"asicso into ser(er: /etc/httpd/!odules/!od9auth9"asicso: cannot open shared o"Eect file: &o such file or directory Lnce you fi- the issue, it will display $ynta- LQ. ) httpd #t #f conf/httpd.conf.de"u $ynta- LQ
www.thegeekstuff.com
$er(erVs Sodule Sa ic &u!"er: 30061116:16 Co!piled usin : %/M 1.3.13, %/M#\til 1.3.13
$er(er co!piled with.... #. %/%CHI9S/S9.BM02ser(er/!p!/prefork2 #. %/M9H%$9$I&.YBLI #. H++/.9MLL+02/etc/httpd2 #. $\IaIC9BB&02/usr/s"in/sue-ec2 #. .IY%\L+9/B.LLG02lo s/httpd.pid2 #. .IY%\L+9$CLMIBL%M.02lo s/apache9runti!e9status2 #. .IY%\L+9LLCQYBLI02lo s/accept.lock2 #. .IY%\L+9IMMLMLLG02lo s/error9lo 2 #. %/9+Y/I$9CL&YBG9YBLI02conf/!i!e.types2 #. $IM'IM9CL&YBG9YBLI02conf/httpd.conf2 ...
2f you want display only the "pache *ersion number( use the option .* 9lower.case *; as shown below. ) httpd #( $er(er (ersion: %pache/3.3.G 7\ni-8 $er(er "uilt: Dul 15 300F 16:4C:6C
www.thegeekstuff.com
/odify the httpd.conf and add 2f)efine directi*e called load.ldap 9you can name this anything you want;. [Bf.efine load#ldapZ LoadSodule ldap9!odule !odules/!od9ldap.so LoadSodule authnP9ldap9!odule !odules/!od9authnP9ldap.so [/Bf.efineZ
=hen you are testing ldap and would like to oad the ldap related modules( pass the load.ldap to %ption .)( as shown below1 ) httpd #k start #e de"u #.load#ldap #f /etc/httpd/conf/httpd.conf.de"u *$un %u 1K 15:15:6F 300F, *de"u , !od9so.c735C8: loaded !odule ldap9!odule *$un %u 1K 15:15:6F 300F, *de"u , !od9so.c735C8: loaded !odule authnP9ldap9!odule *&ote: /ass #.load#ldap, to load the ldap !odules into %pache,
) apachectl start *&ote: $tart the %pache nor!ally, if you donVt want to load the ldap !odules.,
Any Questions? .iscuss it here: G +ips to \se %pachectl and Httpd like a /ower \ser
222
www.thegeekstuff.com
) (i /usr/local/apache3/conf/e-tra/httpd#(hosts.conf &a!e'irtualHost R:F0 ['irtualHost R:F0Z $er(er%d!in ra!esh<the eekstuff.co! .ocu!entMoot 2/usr/local/apache3/docs/the eekstuff2 $er(er&a!e the eekstuff.co! 223
www.thegeekstuff.com
$er(er%lias www.the eekstuff.co! IrrorLo Custo!Lo [/'irtualHostZ ['irtualHost R:F0Z $er(er%d!in ra!esh<top6freeware.co! .ocu!entMoot 2/usr/local/apache3/docs/top6freeware2 $er(er&a!e top6freeware.co! $er(er%lias www.top6freeware.co! IrrorLo Custo!Lo [/'irtualHostZ 2lo s/top6freeware/error9lo 2 2lo s/top6freeware/access9lo 2 co!!on 2lo s/the eekstuff/error9lo 2 2lo s/the eekstuff/access9lo 2 co!!on
=hen something is not configured properly( it will display warning message( including Qdirectory does not e!itR message as shown below. ) /usr/local/apache3/"in/httpd #$ `arnin : .ocu!entMoot */usr/local/apache3/docs/top6freeware, does not e-ist `arnin : IrrorLo does not e-ist $ynta- LQ */usr/local/apache3/lo s/the eekstuff,
224
www.thegeekstuff.com
5ow( when you go to thegeekstuff.com 9or www.thegeekstuff.com;( the apache will ser*e the files from JusrJlocalJapache2JdocsJthegeekstuff directory. =hen you go to top5freeware.com 9or www.top5freeware.com;( the same apache running on the same ser*er will ser*e the files from JusrJlocalJapache2JdocsJtop5freeware directory. Sust to reiterate( for the name.based *irtual host to work properly( the )5& entry for both these websites should be pointing to the same e!ternal ip.address of the physical ser*er where the "pache webser*er is running.
Any Questions? .iscuss it here: How +o $etup %pache 'irtual Host Confi uration 7`ith I-a!ples8
www.thegeekstuff.com
datee-t !a-a e 40 postrotate /usr/"in/killall #H\/ httpd ls #ltr /usr/local/apache3/lo s T !ail #s 2;HL$+&%SI: %pache restarted and lo files rotated2 ra!esh<the eekstuff.co! endscript @
5ote1 4efer to our logrotate tutorial 9with 15 e!amples; that e!plains more details about how to use logrotate options. 2n the abo*e JetcJlogrotate.dJapache e!ample1 si+e 100/ $ %nce the accessMlog( and errorMlog reaches 100/( it will be rotated. Aou can also use 100k 9for _b;( 1007 9for 78;. 2nstead of si+e( you can also rotate apache logs using fre@uency 9daily( weekly( monthly;. compress $ 2ndicates that the rotated log file will be compressed. 8y default this uses g+ip. &o( the rotated file will ha*e .g+ e!tension. datee!t . "ppends the date in AAAA//)) format to the rotated log files. i.e 2nstead of accessMlog.1.g+( it creates accessMlog. 20110616.g+ ma!age . 2ndicates how long the rotated log files should be kept. 2n this e!ample( it will be kept for 30 days. postrotate and endscript $ "ny commands enclosed between these two parameter will be e!ecuted after the log is rotated.
I#portant. %nce you rotate the log files( you want apache to write the new log messages to the newly created accessMlog and errorMlog. &o( you need to send the 'H0 signal to the apache as shown here. /ake sure to do JusrJbinJkillall .'H0 httpd( which will restart the apache after rotating the log files 94ead more about kill;.
226
www.thegeekstuff.com
"lso( you might want to send an email to yourself indicating that the log file is rotated( along with the output of ls .ltr command as the body of the email. i.e "dd the following between QpostrotateR and QendscriptR option 9after the killall command;. ls #ltr /usr/local/apache3/lo s T !ail #s 2;HL$+&%SI: %pache restarted and lo files rotated2 ra!esh<the eekstuff.co!
The JetcJcron.dailyJlogrotate script runs e*eryday that will perform log rotate of all the files as specified in the JetcJlogrotate.conf and all the file under JetcJlogrotate.d directory. "fter adding the abo*e JetcJlogrotate.dJapache file( for testing purpose( you can manually call the logrotate script as shown below. ) /etc/cron.daily/lo rotate
%nce the log files are rotated( do a ls to *erify them. "s we e!plained abo*e( the rotated log files will be kept for 30 days. ) ls /usr/local/apache3/lo s access9lo error9lo access9lo #30110K1C. P error9lo #30110K1C. P
Any Questions? .iscuss it here: How to Motate %pache Lo Additional (ogrotate Examples: +he \lti!ate Lo rotate Co!!and +utorial with 10 I-a!ples 22, Yiles in Linu-
www.thegeekstuff.com
=hen you logout of the interacti*e shell( following is the se@uence of e!ecution1 22D
www.thegeekstuff.com
0lease note that JetcJbashrc is e!ecuted by LJ.bashrc as shown below1 ) cat 1/."ashrc if * #f /etc/"ashrc ,? then . /etc/"ashrc fi
5ote1 =hen a non.interacti*e shell starts up( it looks for :5? en*ironment *ariable( and e!ecute the file.name *alue mentioned in the :5? *ariable.
22-
www.thegeekstuff.com
/$102/etc/profileZ 2 *&ote: re#lo in to see the pro!pt chan e as shown "elow, Last lo in: $at $ep 3K 1C:54:6K 300F fro! 1G3.1CF.1.3 /etc/profileZ
0lease make sure LJ.bashMprofile doesn3t ha*e any 0&1 for the abo*e to work properly. 2. LJ.bashMprofile gets e!ecuted1 "dd following 0&1 to LJ.bashMprofile( LJ.bashMlogin( LJ.profile and LJ.bashrc. 4e.login to make sure the inu! prompt changes to the 0&1 *alue set inside the LJ.bashMprofile as shown below. /etc/profileZ rep /$1 1/."ash9profile
e-port /$1021/."ashrcZ 2 *&ote: \pon re#lo in, it e-ecuted /etc/profile first and 1/."ash9profile ne-t. $o, it took the /$1 fro! 1/."ash9profile as shown "elow. Bt also did not e-ecute 1/."ash9lo in, as 1/."ash9profile e-ists, Last lo in: $at $ep 3K 1C:5F:11 300F fro! 1G3.1CF.1.3 1/."ash9profileZ
230
www.thegeekstuff.com
3. LJ.bashMlogin gets e!ecuted. 4ename the .bashMprofile to something else. 4e.login to make sure the inu! prompt changes to the 0&1 *alue set inside the LJ.bashMlogin as shown below. 1/."ash9profileZ !( ."ash9profile "ash9profile9not9used *&ote: \pon re#lo in, it e-ecuted /etc/profile first. $ince it cannot find 1/."ash9profile, it e-ecuted 1/."ash9lo in, Last lo in: $at $ep 3K 1C:60:66 300F fro! 1G3.1CF.1.3 1/"ash9lo inZ
4. LJ.profile gets e!ecuted. 4ename the .bashMlogin to something else. 4e.login to make sure the inu! prompt changes to the 0&1 *alue set inside the LJ.profile as shown below. 1/."ash9lo inZ !( ."ash9lo in "ash9lo in9not9used *&ote: \pon re#lo in, it e-ecuted /etc/profile first. $ince it cannot find 1/."ash9profile and 1/."ash9lo in, it e-ecuted 1/.profile, Last lo in: $at $ep 3K 1C:6C:4C 300F fro! 1G3.1CF.1.3 1/.profileZ
5. LJ.bashrc gets e!ecuted for non.login shell testing. :!ecuting QbashR at the command prompt will gi*e another non.login shell( which will in*oke .bashrc as shown below. 1/.profileZ "ash *&ote: +his displays /$1 fro! ."ashrc as shown "elow., 1/."ashrcZ e-it *&ote: %fter e-itin lo in shell, fro! non#lo in shell, we are "ack to
231
www.thegeekstuff.com
1/.profileZ
Any Questions? .iscuss it here: I-ecution se_uence for ."ash9profile, ."ashrc, ."ash9lo in, .profile and ."ash9lo out
C Like )yntax
The second form of bash for loop is similar to the ]#3 programming language for loop( which has three e!pressions 9initiali+ation( condition and update;. for 77 e-pr1? e-pr3? e-pr4 88 do co!!ands done 8efore the first iteration( e!pr1 is e*aluated. This is usually used to initiali+e *ariables for the loop. "ll the statements between do and done are e!ecuted repeatedly as long as the *alue of e!pr2 is T4H:. "fter each loop iteration( e!pr3 is e*aluated. This is usually used to increment a loop counter.
The following e!amples show how to use this synta! in the bash for loop.
Loop usin
C<)tyle
7enerate and display 5 random numbers using the bash #.style for loop1 ; cat for10.sh for 77 i01? i [0 4? iOO 88 do 232
www.thegeekstuff.com
echo 2Mando! nu!"er ;i: ;M%&.LS2 done ; ./for10.sh Mando! nu!"er 1: 34430 Mando! nu!"er 3: 60K0 Mando! nu!"er 4: 16303
'ash 7or
=hen you don>t pro*ide the start( condition( and increment in a #.style for loop( it will e!ecute fore*er. Aou need to press #trl.# to stop the loop. ; cat for11.sh i01? for 77 ? ? 88 do sleep ;i echo 2&u!"er: ;77iOO882 done
5ote1 )on3t forget you will need to press #trl.# to break from this e!ample1 ; ./for11.sh &u!"er: 1 &u!"er: 3 &u!"er: 4
2n the bash c.style loop( in addition to incrementing the *alue that is used in the condition( you can also increment some other *alue or perform some other action. 2n both the initiali+ation section and the increment section of the #.style for loop( you can use multiple statements separated with a comma. This e!ample uses i for control and manipulates 6 separately1 233
www.thegeekstuff.com
; cat for13.sh for 77i01, E010? i [0 6 ? iOO, E0EO688 do echo 2&u!"er ;i: ;E2 done ; ./for13.sh &u!"er 1: 10 &u!"er 3: 16 &u!"er 4: 30 &u!"er 5: 36 &u!"er 6: 40
Additional !ash For (oop Examples: 13 Bash Yor Loop I-a!ples for Your Linu- $hell $criptin
a )hell )cript
To debug a shell script use set $!* inside the shell script at the top.
co##and.
let totalsiPe0;totalsiPeO;filesiPe done echo 2+otal file siPe in current directory: ;totalsiPe2
234
www.thegeekstuff.com
co##and.
co##and inside.
"dd set $!* inside the shell script now to debug the output as shown below. ; cat filesiPe.sh )A/"in/"ash set #-( for filesiPe in ;7ls #l . T do let totalsiPe0;totalsiPeO;filesiPe done echo 2+otal file siPe in current directory: ;totalsiPe2 rep 2N#2 T awk V:print ;6@V8
co##and inside.
www.thegeekstuff.com
option.
2nstead of gi*ing the set $!* inside the shell script( you can also pro*ide that while e!ecuting the shell script as shown below. ; "ash #-( filesiPe.sh
:cho statement with a special character [ . semi.colon is a command terminator in bash. 2n the following e!ample( QThe 7eekR works for the echo and Q&tuffR is treated as a separate inu! command and gi*es command not found. ; echo +he Geek? $tuff +he Geek #"ash: $tuff: co!!and not found
To a*oid this you can add a O in front of semi.colon( which will remo*e the special meaning of semi.colon and 6ust print it as shown below. ; echo +he Geek>? $tuff +he Geek? $tuff
)in le Guote
Hse single @uote when you want to literally print e*erything inside the single @uote. :*en the special *ariables such as N'%&T5"/: will be print as N'%&T5"/: instead of printing the name of the inu! host. 236
www.thegeekstuff.com
Current \ser0Uwhoa!iU ?
"ouble Guote
Hse double @uotes when you want to display the real meaning of special *ariables. ; echo 2Hostna!e0;HL$+&%SI ? Sessa e0>; is \$.2 Hostna!e0de(#d" ? Current \ser0Uwhoa!iU ?
)ouble @uotes will remo*e the special meaning of all characters e!cept the following1 N 0arameter &ubstitution. Z 8ack@uotes ON iteral )ollar &ign. Oj iteral 8ack@uote. OF :mbedded )ouble@uote. OO :mbedded 8ackslashes.
www.thegeekstuff.com
%le- Dason:300:$ales Sadison Mandy:400:/roduct .e(elop!ent $anEay Gupta:500:$upport &isha $in h:600:$ales
The following shell script e!plains how to read specific fields from this employee.t!t file. ; (i read#e!ployees.sh )A/"in/"ash BY$0: echo 2I!ployee &a!es:2 echo 2###############2 while read na!e e!pid dept do echo 2;na!e is part of ;dept depart!ent2 done [ 1/e!ployees.t-t
"ssign e!ecute pri*ilege to the shell script and e!ecute it. ; ch!od uO- read#e!ployees.sh ; ./read#e!ployees.sh I!ployee &a!es: ############### I!!a +ho!as is part of Sarketin depart!ent %le- Dason is part of $ales depart!ent Sadison Mandy is part of /roduct .e(elop!ent depart!ent $anEay Gupta is part of $upport depart!ent &isha $in h is part of $ales depart!ent
23D
www.thegeekstuff.com
and
free command displays all the necessary information about system physical 94"/; and swap memory. $ynta-: free *options,
#/O "uffers/cache:
6A&
option t displays the QTotalR line( which is sum of physical and swap memory *alues option o is to hide the buffersJcache line from the abo*e e!ample.
) free H!to total Se!: 1010 used GF4 free shared 3K 230 "uffers 1K0 cached C01
www.thegeekstuff.com
$wap: +otal:
1GF4 3GG5
0 GF4
1GF4 3011
C/1
:!ecute top without any option from the command line( which will display the output shown below. The top command output will keep displaying the real.time *alues( until you press Q#ontrol ` cR or @ to e!it from the command output. ) top top # 14:10:14 up 1K1 days, 30:31, a(era e: 0.01, 0.06, 0.00 +asks: 1G5 total, 0 Po!"ie Cpu7s8: 0.CW us, 0.0W hi, 0.0W si 4 users, load
Se!: 1045C35k total, 1K5650k "uffers $wap: free, 3041C0Fk total, C16G05k cached /M &B 16 httpd
'BM+
MI$
+BSIO 1
0 41F3F
240
www.thegeekstuff.com
1G oracle 1C perl
0 0
3KG! 10K!
1F! 3F!
1K! $ C505 $
1 0
There are se*eral command line options and interacti*e options a*ailable for top commands. et us re*iew couple of essential options for top command.
&elect sort field *ia field letter( type any other key to return 241
www.thegeekstuff.com
Ho* to add additional fields Kfor e. . C/1 Ti#eM to the top outputJ
=hile the top command is running( press f( which will display the following message and show all fields a*ailable for display( press l( which will add the #0H Time to the display columns in the top output. Current Yields: 1:.ef %IHBLb+`Q&S"cdf Eplrsu(yPa for window
Toggle fields *ia field letter( type any other key to return
Ho* to et the full path na#e and para#eters of the runnin processesJ
=hile the top command is running( press c( which will display full pathname of running processes as shown below in the command column. i.e 2nstead of httpd( it displays JusrJlocalJapache2JbinJhttpd. /B. \$IM CLSS%&. 11G13 apache 0.3 0:5C.46 /M &B 'BM+ MI$ $HM $ WC/\ WSIS +BSIO 1
1 runnin , 1G4 sleepin , 3.CW sy, F.0W sy, 1.4W sy, 0.0W ni, FC.FW id, 0.0W ni, F3.5W id, 0.0W ni, G6.0W id,
242
www.thegeekstuff.com
0.0W sy,
0.0W wa,
Se!: 1045C35k total, 1K5650k "uffers $wap: free, 3041C0Fk total, C16G05k cached
Additional 1op #ommand Examples: 16 /ractical Linu- +op Co!!and I-a!ples +op on $teroids H 16 /ractical Linu- H+L/ I-a!ples How +o Capture \ni- +op Co!!and Lutput to a Yile in Meada"le Yor!at BY+L/ Guide: .isplay &etwork Bnterface Bandwidth \sa e on Linu-
www.thegeekstuff.com
/de(/sda1 /de(/sd"1
C5G 14KG
55G CKG
1KG K0G
K4W 5GW
/ /ho!e/user
Ho* #uch space is taken by #y ho#e directory and all its subdirectoriesJ
2n the following e!ample( option .s stands for summary only. i.e it displays only the total si+e of JhomeJ6smith and not the indi*idual si+es of all the subdirectories inside the JhomeJ6smith. %ption .h displays the information in a human readable format. i.e _ for _8( / for /8 and 7 for 78. The L indicates the user home directory. This command is same as Qdu .sh JhomeJ6smithR ) du #sh 1 430S /ho!e/Es!ith
244
www.thegeekstuff.com
To get the subdirectories under JhomeJ6smith listed( e!ecute the abo*e command without the s option.
init 1 /s"in/init
245
www.thegeekstuff.com
MIG MIG
F,1 F,1
64K4C 6C43F
1C4GC5 1CCF11
The lsof command by itself without may return lot of records as output( which may not be *ery meaningful e!cept to gi*e you a rough idea about how many files are open in the system at any gi*en point of *iew as shown below. ) lsof T wc #l 40G4
" system administrator can use this command to get some idea on what users are e!ecuting on the system.
www.thegeekstuff.com
(i
MIG
0 3F3130 14510F 6KGK013 0 100 0 0 3F3130 14510F 6KGK013 0 0 100 0 0 3F3130 14510F 6KGK013 0 0 100 0 0 3F3130 14510F 6KGK013 0 0 100 0
&e#ory section
&wpd field1 Hsed swap space Cree field1 "*ailable free 4"/ 8uff field1 4"/ used for buffers #ache field1 4"/ used for filesystem cache 24,
www.thegeekstuff.com
)*ap )ection
&i field1 "mount of memory swapped from disk per second &o field1 "mount of memory swapped to disk per second
I8 )ection
8i field1 8locks recei*ed from disk 8o field1 8locks sent to disk.
)yste# )ection
2n field1 5umber of interrupts per second. #s field1 5umber of conte!t switches per second.
C/1 )ection
Hs field1 Time spend running user code. 9non.kernel code; &y field1 Time spent running kernel code. 2d field1 2dle time. =a field1 Time spent waiting for the 2%
Additional 5mstat Examples: 35 iostat, (!stat and !pstat I-a!ples for Linu/erfor!ance Sonitorin
24D
www.thegeekstuff.com
"isplay Acti2e Connections *ith /rocess I" and /ro ra# +a#e
This could be *ery helpful to identify which program has initiated a specific network connection. ) netstat #tap %cti(e Bnternet connections 7ser(ers and esta"lished8 /roto Mec(#b $end#b Local %ddress $tate /B.//ro ra! na!e tcp LB$+I& tcp LB$+I& 0 0 0 R:nrpe 1C3KK/-inetd Yorei n %ddress R:R R:R
24-
www.thegeekstuff.com
tcp 45 0 localhost.localdo!ain:65331 localhost.localdo!ain:50FG CLL$I9`%B+ 3GFF1/httpd tcp 0 431C de(#d":ssh cpe#KC#G5# 316#165.soca:5CF3 I$+%BLB$HI. 11K1K/sshd: ra!esh
"isplay 6outin
Table
) netstat H#route Qernel B/ routin 1G3.1CF.1.0 R 1C3.355.0.0 R default 1G3.1CF.1.1 ta"le Gen!ask 366.366.0.0 0.0.0.0 Yla s S$$ irtt Bface 0 0 0 0 0 0 eth0 eth0 eth0 \ \G 366.366.366.0 \ .estination Gateway
www.thegeekstuff.com
ti!esta!p re_uest: 4 address !ask re_uest: 4 6F166F BCS/ !essa es sent 0 BCS/ !essa es failed BCS/ output histo ra!: destination unreacha"le: 60KG echo replies: 6KC5KC ti!esta!p replies: 4
www.thegeekstuff.com
kernel.e-ec#shield 0 1 net.core.so!a-conn 0 13F net.ip(5.tcp9window9scalin net.ip(5.tcp9w!e! 0 50GC net.ip(C.route.!tu9e-pires 0 C00 sunrpc.udp9slot9ta"le9entries 0 1C (!."lock9du!p 0 0 0 1 1C4F5 1410K3
www.thegeekstuff.com
//B. /MB 0 1C 45
&B 0 1G
'$J 31K3 0 0
$+%+ ++Y $ c c c
6 #10
5 0 6156 1 36 10 43135 1F6G3 # $&s c 0:0F /usr/"in/python /usr/"in/rhn#applet# ui ##s!#client# id default5 5 0 615K 6153 1C 0 463F C05 # 0:00 /s"in/pa!9ti!esta!p9check #d root 1 604 1K663 51F0 1C 0 1530F 4G30 # 0:01 /ho!e/www/apache3/"in/httpd #f /ho!e/www/apache3/conf/httpd.conf #k start $ $ c c
5ow( let us e!ecute the same shell script with a different nice *alue as shown below. ; nice #10 ./nice#test.sh = *1, 1401C 253
www.thegeekstuff.com
; ps a-l T
*Note: Cth colu!n with (alue 10 is the nice (alue for the shell#script.,
5ote1 %nly root user can set a negati*e nice *alue. ogin as root and try the same. 0lease note that there is a double dash before the 10 in the nice command below. ) nice ##10 ./nice#test.sh = *1, 140C0 ) ps a-l T rep nice#test GC5 wait $[ pts/1
*Note: Cth colu!n with (alue #10 is the nice (alue of the shell#script.,
www.thegeekstuff.com
processJ
2n the e!ample below( an e!isting shell.script is running at nice *alue of 10. 96th column in the ps output; ; ps a-l T rep nice#test GCF wait $& pts/1
To increase the nice *alue 9thus reducing the priority;( e!ecute the renice command as shown below. ; renice 1C #p 14356 14356: old priority 10, new priority 1C ; ps a-l T rep nice#test GCF wait $& pts/1
*Note: &ow, the Cth colu!n of the nice#test.sh 7/B. 143568 shows the new nice (alue of 1C.,
processJ
2n the e!ample below( an e!isting shell.script is running at a nice *alue of 10. 96th column in the ps output; ; ps a-l T rep nice#test GCF wait $& pts/1
2n increase the priority( gi*e a lower nice *alue as shown below. 'owe*er( only root can increase the priority of a running process( else you3ll get the following error message. ; renice 6 #p 14365 255
www.thegeekstuff.com
renice: 14365: setpriority: /er!ission denied Lo in as root to increase the priority of a runnin process ; su # ) renice 6 #p 14365 14365: old priority 10, new priority 6 ) ps a-l T rep nice#test GCF wait $& pts/1
*Note: +he Cth colu!n now shows a lower nice (alue of 6 7increased priority8,
processJ
Cirst( identify the process id of the particular process that you would like to kill using the ps command. %nce you know the process id( pass it as a parameter to the kill command. The e!ample below shows how to kill the hanging apache httpd process. 0lease note that typically you should use Qapachectl stopR to stop apache. ) ps au- T rep httpd '$J M$$ ++Y $+%+ $+%M+
\$IM /B. WC/\ WSIS +BSI CLSS%&. apache $ 411FC Dul3C 0.0 0:50
256
www.thegeekstuff.com
apache $
411FK Dul3C
0.0 0:4K
0lease note that the abo*e command tries to terminate the process graciously by sending a signal called &27T:4/. 2f the process does not get terminated( you can forcefully terminate the process by passing a signal called &27_2 ( using the option .- as shown below. Aou should either be the owner of the process or a pri*ileged user to kill a process. ) kill #G 411FC 411FK
"nother way to kill multiple processes easily is by adding the following two functions to the .bashMprofile. function ps rep 78 : ps au- T @ function pster! 78 : * ;:)@ #e_ 0 , == echo 2usa e: ;Y\&C&%SI $+MB&G2 == return 0 local pid pid0;7ps a- T ;1 @V8 rep 2;12 T rep #( rep T awk V: print rep 2;12 T rep #( V repV
V;1V / process7es8:>n;pid2
5ow do the following( to identify and kill all httpd processes. ) ps rep http 25,
www.thegeekstuff.com
\$IM /B. WC/\ WSIS +BSI CLSS%&. apache $ apache $ 411FC Dul3C 411FK Dul3C 0.0 0:50 0.0 0:4K
'$J
M$$ ++Y
$+%+ $+%M+
Additional <ill Examples: 5 `ays to Qill a /rocess H kill, killall, pkill, -kill
in the syste#J
www.thegeekstuff.com
apache Dul3C
411FK 0:4K
Aou can also use Fps .ef e moreF( to get a similar output
0:01 /usr/local/s"in/sshd 1:0F /usr/local/s"in/sshd 0:00 0:00 >9 /usr/local/s"in/sshd >9 #"ash >9 ps a-uf
5ote1 Aou can also use pstree command to display process in tree structure.
www.thegeekstuff.com
$s $s $s $s $s $s
0:01 /oracle/"in/tnslsnr 0:00 ora9_0039!ed 0:00 ora9cE_09!ed 0:01 ora9p!on9!ed 0:00 ora9psp09!ed 0:03 oracle!ed 7LLC%L0&L8
260
www.thegeekstuff.com
&ar #ollects( 4eports 9displays; and &a*es the performance data. et us look at all the three aspects separately
)a1 shell<script
JusrJlibJsa1 in.turn calls the JusrJlibJsadcs. sa1 is in*oked from the crontab as shown below. 4un this e*ery 5 minutes or 15 minutes depending on your need. 2 prefer to schedule it for e*ery 5 minutes in the cron tab as shown below. R/6 R R R R root /usr/li"/sa/sa1 1 1
)a, shell<script
JusrJlibJsa2 is a shell script that will write a daily report in the J*arJlogJsaJsagddh file( where dd is the current day. 2n*oke the sa2 from the crontab once a day at midnight. ) 6G 34 R R R root /usr/li"/sa/sa3 H%
5ote1 JetcJcron.dJsysstat files comes with the sysstat package that includes some default *alue for the sa1 and sa2( which you can change accordingly.
)ar Co##and
Linu- 3.C.G#53.ILs!p 7de(#d"8 13:00:01 %S Widle 13:06:01 %S G6.56 C/\ all Wuser 4.K0 Wnice 0.00
261
www.thegeekstuff.com
13:10:01 %S G5.1C 13:16:01 %S G6.11 13:30:01 %S G5.G4 13:36:01 %S G6.34 13:40:01 %S G6.34 $kipped.. %(era e: all G5.3G
5.6C
0.00
1.00
0.16
5ote1 2f you need a break down of the performance data for the indi*idual #0H3s( e!ecute the following command. ) sar #u #/ %LL
sar co##and
01/01/300G tps 1.C6 5.0F rd9sec/s 1.3F F.11 wr9sec/s 56.54 31.F1
5.CC 1.FG
130.KK 4.1K
CG.56 F.03
262
www.thegeekstuff.com
"isplay net*orkin
)tatistics usin
sar co##and
) sar #n .I' T !ore Linu- 3.C.G#53.ILs!p 7de(#d"8 01/01/300G r-"yt/s 36.41 101CG.K5 13:00:01 %S BY%CI r-pck/s t-pck/s t-"yt/s r-c!p/s t-c!p/ s r-!cst/s 13:06:01 %S 34.44 0.00 13:10:01 %S 131KF.6K lo 0.0 0 0.1K 0.00 0.1C
eth0 0.00
63.G3 0.00
64.C5 0.00
) sar #n $LCQ T!ore Linu- 3.C.G#53.ILs!p 7de(#d"8 13:00:01 %S 13:06:01 %S 13:10:01 %S 13:16:01 %S totsck 60 60 64 tcpsck 14 14 14 01/01/300G udpsck 4 5 6 rawsck 0 0 0 ip#fra 0 0 0
Additional SAR Examples: 10 \seful $ar 7$ysstat8 I-a!ples for Linu- /erfor!ance Sonitorin
263
www.thegeekstuff.com
264
www.thegeekstuff.com
+a ios Core Aou should implement a robust monitoring solution that will notify you when there is an issue. 2t should also notify the right people at the right time about a potential issue( e*en before it becomes critical. 5agios #ore 3 e8ook is the only guide you3ll e*er need to get your 2T infrastructure monitored using 5agios #ore( and it will help you to understand e*erything you need to know to implement 5agios #ore 3.
265
www.thegeekstuff.com
10 A#aBin 'ooks
Cor further reading on inu!( 2 recommend the following books. The 10 inu! books mentioned here by no means are comprehensi*e or authoritati*e list. 8ut( these 10 8ooks are few of my fa*orites that 2 en6oyed reading o*er the years and 2 strongly belie*e will enhance your technical abilities on inu!( if you ha*e not read them yet. 1. ))H@ The )ecure )hell@ by "aniel 9. 'arrett@ 6ichard 5. )il2er#an and 6obert (. 'yrnes. This is hands.down the best book on &&'. This book e!plains both theoretical and practical aspects of &&'. Hsing &&' as an end.user is fairly straight forward . 8ut( configuring &&' as an administrator is comple! and in*ol*es a detailed understanding of &&'. This is a must read for any system administrator. The e!amples in this book show e!actly what needs to be done differently for the different fla*ors of &&' such as &&'1( &&'2 and %pen&&'. 2. 5ssential )yste# Ad#inistration@ by Wleen 7risch. This is an e!cellent book for those who like to become a Hni! &ystem "dministrator. This book co*ers all the typical system administration tasks. This is a perfect companion when you are dealing with multiple fla*ors of Hni!( as it has e!amples for "2I( Cree8&)( '0.HI( inu!( &olaris and Tru64. 23*e used the pocket *ersion of this book < :ssential &ystem "dministration 0ocket 4eference( when 2 was managing multiple fla*ors of Hni! systems at the same time. 3. Linux )er2er Hacks@ %olu#e 8ne@ by 6ob 7licken er. 100 awesome practical hacks packed in one book. &etup a inu! test bed and try out all these hacks. These hacks are neatly grouped into different sections < &er*er 8asics( 4e*ision #ontrol( 8ackups( 5etworking( /onitoring( &&'( &cripting( and 2nformation &er*ers. %nce you3*e mastered these hacks( you should absolutely read inu! &er*er 'acks( ?olume Two( by =illiam *on 'agen and 8rian Sones( which has 100 inu! hacks focused on authentication( monitoring( security( performance and connecti*ity. 4. "+) and 'I+"@ by Cricket Liu and /aul AlbitB. &e*eral years ago( 2 configured my first )5& by reading online documentation. 2 brought this book to understand how )5& 266
www.thegeekstuff.com
and 825) works. 23*e already upgraded this book twice when a newer edition was released. This should definitely be in your library( if you are a serious system administrator. 5. 1nderstandin the Linux Fernel@ by "aniel 'o2et and &arco Cesati. 2f you are a serious de*eloper on inu! en*ironment or a sysadmin( this is a must read. This books e!plains the inner workings of the inu! _ernel 2.6 in a structured and logical way. This talks about how _enel handles the /emory /anagement( 0rocess scheduling( 2J% architecture and 8lock de*ices. %*erall this book is a treat for geeks who are curious to e!plore what is under the hood of inu!. 6. The A>F /ro ra##in Lan ua e@ by Alfred %. Aho@ 'rian >. Ferni han@ /eter 9. >einber er. This is a classic book written written by the authors of "wk. 2f you are dealing with te!t based data files on inu! en*ironment( mastering "wk will help you to @uickly create scripts to automate your data file manipulation 6obs. ,. Linux Cookbook@ by Carla )chroder. This book co*ers inu! features from both users and system administrators point of *iew. There are two chapters dedicated for installing and managing software on 40/.based system and )ebian. 2f you use 4ed'at( the inu! 0ocket 7uide( by )aniel S. 8arrett is an e!cellent addition to your library( which co*ers all the essential inu! command with a sample usage. D. Linux 7ire*alls@ by &ichael 6ash. To build a secure inu! system( you must read this book. There are @uiet few books out there for iptables. 8ut( this one talks specifically about the fundamentals of how to configure an 2ntrusion )etection &ystem using iptables( psad and fwsnort. 2f you want a comprehensi*e handy reference of all the things iptables can do with specific e!amples( inu! 2ptables 0ocket 4eference( by 7regor 5. 0urdy is the best. -. Linux Ad#inistration Handbook@ by 52i +e#eth@ (arth )nyder and Trent 6. Hein. )uring my early days of system administration( 23*e referred this book fre@uently. This is pretty detailed book with close to 1000 pages and 30 chapters that are nicely grouped together in three high le*el sections < 8asic "dministration( 5etworking and 8unch %3 &tuff. 10. 'e innin 1buntu Linux@ by Feir Tho#as and 9ai#e )ica#. Cor those who like to transition from =indows to 26,
www.thegeekstuff.com
inu!( install Hbuntu inu! on one of your old laptop or desktop and get this book. 2 strongly belie*e in spreading the news about inu! to those who don3t use it. 2f you want any of your lo*ed ones or friends to learn inu!( install Hbuntu on an old laptop and gi*e this book as a gift to them. They3ll definitely be *ery thankful to you.
&ore Recommended !oo"s: Yor %dditional Linu- and Lpen $ource Melated Books that B reco!!end, (isit +he Geek $tuff Book $tore at %!aPon
26D
www.thegeekstuff.com
5xtended 6eadin
Collowing are few articles from the The 7eek &tuff blog for your e!tended reading. #heck out The 7eek &tuff "rchi*es section for more articles. 1. 50 inu! &ysadmin Tutorials 2. 50 /ost Cre@uently Hsed inu! #ommands 9=ith :!amples; 3. Hni! & #ommand1 15 0ractical :!amples 4. Turbocharge 0uTTA with 12 0owerful "dd.%ns 5. wget Tutorial1 15 "wesome :!amples to )ownload Ciles from 2nternet 6. 0ing Tutorial1 15 :ffecti*e 0ing #ommand :!amples ,. 5agios . :nterprise /onitoring &olution 5agios Sumpstart 7uide /onitor =indow &er*er /onitor inu! &er*er /onitor 5etwork &witch /onitor ?05 )e*ice Crom open&&' to open&&' Crom open&&' to &&'2 Crom &&'2 to &&'2
-. 'ello =orld :!amples 9 earn a programming language; 10. H52I &ed Tips and Tricks 11. Hbuntu Tips and Tricks 12. /y&i Tutorials 13. 0ostgre&i Tutorials 14. ?i J ?im Tips and Tricks ?im /acro Tutorial1 'ow To 4ecord and 0lay 'ow To Hse ?im as 0erl 2): and #J#`` 2): "utomatic =ord #ompletion in ?im 26-
www.thegeekstuff.com
15. 3 &teps to "dd #ustom 'eader to a Cile Hsing ?im 16. The Hltimate 7uide for #reating &trong 0asswords 1,. 6 &teps to &ecure Aour 'ome =ireless 5etwork 1D. Cirefo! "dd.%n1 'ire , 0ersonal 8odyguards to 8rowse 2nternet &ecurely 1-. Tripwire Tutorial1 inu! 'ost 8ased 2ntrusion )etection &ystem 20. /idnight #ommander 9mc; 7uide1 0owerful Te!t based Cile /anager for Hni!
$u"scri"e to recei(e free Linu- tutorials directly to your e!ail in"o- re ularly.
2,0
www.thegeekstuff.com
Thank ?ou
2 hope you found the Linux 101 Hacks e8ook helpful. 2 sincerely appreciate all the support gi*en by you and other regular readers of my thegeekstuff.com blog. Aou ha*e encouraged me in more ways than you know. 2f you liked this e8ook( and would like to support me( consider buying my other e8ooks1 8ash 101 'acks &ed and "wk 101 'acks ?im 101 'acks 5agios #ore 3
2f you ha*e any suggestions( or feedback( or @uestions while reading this ebook( don>t hesitate to reach out to me. Aou can connect with me on the following1 Twitter 9Bthegeekstuff; Cacebook page
2f you want to write to me directly( you can use this contact form to reach out to me.
2,1