Sie sind auf Seite 1von 45

2/27/12 Uni Toolbo

1/45 cb.vu/unitoolbo.html
UNI X T OOL BOX
This document is a collection of Unix/Linux/BSD commands and tasks which are useful for IT work or for
advancedusers.Thisisapracticalguidewithconciseexplanations,howeverthereaderissupposedtoknow
whats/heisdoing.
1. System
2. Processes
3. FileSystem
4. Network
5. SSHSCP
6. VPNwithSSH
7. RSYNC
8. SUDO
9. EncryptFiles
10. EncryptPartitions
11. SSLCertificates
12. CVS
13. SVN
14. UsefulCommands
15. InstallSoftware
16. ConvertMedia
17. Printing
18. Databases
19. DiskQuota
20. Shells
21. Scripting
22. Programming
23. OnlineHelp
2/27/12 Uni Toolbo
2/45 cb.vu/unitoolbo.html
1 SYSTEM
Hardware|Statistics|Users|Limits|Runlevels|rootpassword|Compilekernel|Repairgrub
Runningkernelandsysteminformation
# uhane -a # uet the keheJ ves1oh {ahd B5u ves1oh}
# JsbeJease -a # FuJJ eJease 1hfo of ahy L5B d1st1but1oh
# cat 7etc75u5E-eJease # uet 5u5E ves1oh
# cat 7etc7deb1ahves1oh # uet ueb1ah ves1oh
Use/etc/uT5TRrelease with uT5TR= lsb (Ubuntu), redhat, gentoo, mandrake, sun (Solaris), and so on. See
also7etc71ssue.
# upt1ne # 5hoW hoW Johg the systen has beeh uhh1hg + Joad
# hosthane # systen's host hane
# hosthane -1 # u1spJay the TP addess of the host. {L1hux ohJy}
# nah h1e # uesc1pt1oh of the f1Je systen h1eachy
# Jast eboot # 5hoW systen eboot h1stoy
1.1HardwareInformations
Kerneldetectedhardware
# dnesg # uetected hadWae ahd boot nessages
# Jsdev # 1hfonat1oh about 1hstaJJed hadWae
# dd 1f=7dev7nen bs=1k sk1p=7B couht=25 2>7dev7huJJ | st1hgs -h B # Read BTu5
Linux
# cat 7poc7cpu1hfo # CPU nodeJ
# cat 7poc7nen1hfo # hadWae nenoy
# gep henTotaJ 7poc7nen1hfo # u1spJay the phys1caJ nenoy
# Watch -h1 'cat 7poc71hteupts' # Watch chahgeabJe 1hteupts coht1huousJy
# fee -n # Used ahd fee nenoy {-n fo hB}
# cat 7poc7dev1ces # Cohf1gued dev1ces
# Jspc1 -tv # 5hoW PCT dev1ces
# Jsusb -tv # 5hoW U5B dev1ces
# JshaJ # 5hoW a J1st of aJJ dev1ces W1th the1 popet1es
# dn1decode # 5hoW uhT75hBTu5. hW 1hfo fon the BTu5
FreeBSD
# sysctJ hW.nodeJ # CPU nodeJ
# sysctJ hW # u1ves a Jot of hadWae 1hfonat1oh
# sysctJ hW.hcpu # hunbe of act1ve CPUs 1hstaJJed
# sysctJ vn # henoy usage
# sysctJ hW.eaJnen # hadWae nenoy
# sysctJ -a | gep nen # KeheJ nenoy sett1hgs ahd 1hfo
# sysctJ dev # Cohf1gued dev1ces
# pc1cohf -J -cv # 5hoW PCT dev1ces
# usbdevs -v # 5hoW U5B dev1ces
# atacohtoJ J1st # 5hoW ATA dev1ces
# cancohtoJ devJ1st -v # 5hoW 5C5T dev1ces
1.2Load,statisticsandmessages
Thefollowingcommandsareusefultofindoutwhatisgoingononthesystem.
# top # d1spJay ahd update the top cpu pocesses
# npstat 1 # d1spJay pocessos eJated stat1st1cs
# vnstat 2 # d1spJay v1tuaJ nenoy stat1st1cs
# 1ostat 2 # d1spJay T7u stat1st1cs {2 s 1htevaJs}
# systat -vnstat 1 # B5u sunnay of systen stat1st1cs {1 s 1htevaJs}
# systat -tcp 1 # B5u tcp cohhect1ohs {ty aJso -1p}
# systat -hetstat 1 # B5u act1ve hetWok cohhect1ohs
# systat -1fstat 1 # B5u hetWok taff1c though act1ve 1htefaces
# systat -1ostat 1 # B5u CPU ahd ahd d1sk thoughput
# ta1J -h 5uu 7va7Jog7nessages # Last 5uu keheJ7sysJog nessages
# ta1J 7va7Jog7Wah # 5ysten Wah1hgs nessages see sysJog.cohf
1.3Users
# 1d # 5hoW the act1ve use 1d W1th Jog1h ahd goup
# Jast # 5hoW Jast Jog1hs oh the systen
# Who # 5hoW Who 1s Jogged oh the systen
# goupadd adn1h # Add goup "adn1h" ahd use coJ1h {L1hux75oJa1s}
# useadd -c "CoJ1h BascheJ" -g adn1h -n coJ1h
# usenod -a -u <goup> <use> # Add ex1st1hg use to goup {ueb1ah}
# goupnod -A <use> <goup> # Add ex1st1hg use to goup {5u5E}
# usedeJ coJ1h # ueJete use coJ1h {L1hux75oJa1s}
# adduse oe # FeeB5u add use oe {1hteact1ve}
# nuse oe # FeeB5u deJete use oe {1hteact1ve}
# pW goupadd adn1h # Use pW oh FeeB5u
# pW goupnod adn1h -n heWnenbe # Add a heW nenbe to a goup
# pW useadd coJ1h -c "CoJ1h BascheJ" -g adn1h -n -s 7b1h7tcsh
# pW usedeJ coJ1h pW goupdeJ adn1h
2/27/12 Uni Toolbo
3/45 cb.vu/unitoolbo.html
Encryptedpasswordsarestoredin/etc/shadowforLinuxandSolarisand/etc/master.passwdonFreeBSD.If
the master.passwd is modified manually (say to delete a password), run # pWdnkdb -p naste.passWd to
rebuildthedatabase.
Totemporarilypreventloginssystemwide(forallusersbutroot)usenologin.Themessageinnologinwillbe
displayed(mightnotworkwithsshpresharedkeys).
# echo "5oy ho Jog1h hoW" > 7etc7hoJog1h # {L1hux}
# echo "5oy ho Jog1h hoW" > 7va7uh7hoJog1h # {FeeB5u}
1.4Limits
Some application require higher limits on open files and sockets (like a proxy web server, database). The
defaultlimitsareusuallytoolow.
Linux
Per she///scr|pt
The shell limits are governed by uJ1n1t. The status is checked with uJ1n1t -a. For example to change the
openfileslimitfrom1024to10240do:
# uJ1n1t -h 1u24u # Th1s 1s ohJy vaJ1d W1th1h the sheJJ
TheuJ1n1tcommandcanbeusedinascripttochangethelimitsforthescriptonly.
Per user/process
Loginusersandapplicationscanbeconfiguredin7etc7secu1ty7J1n1ts.cohf.Forexample:
# cat 7etc7secu1ty7J1n1ts.cohf
* had hpoc 25u # L1n1t use pocesses
aste1sk had hof1Je 4u9uu # L1n1t appJ1cat1oh opeh f1Jes
System w|de
Kernellimitsaresetwithsysctl.Permanentlimitsaresetin7etc7sysctJ.cohf.
# sysctJ -a # v1eW aJJ systen J1n1ts
# sysctJ fs.f1Je-nax # v1eW nax opeh f1Jes J1n1t
# sysctJ fs.f1Je-nax=1u24uu # Chahge nax opeh f1Jes J1n1t
# echo "1u24 5uuuu" > 7poc7sys7het71pv471pJocaJpotahge # pot ahge
# cat 7etc7sysctJ.cohf
fs.f1Je-nax=1u24uu # Penaheht ehty 1h sysctJ.cohf
# cat 7poc7sys7fs7f1Je-h # hoW nahy f1Je desc1ptos ae 1h use
FreeBSD
Per she///scr|pt
UsethecommandJ1n1tsincshortcshorasinLinux,useuJ1n1tinanshorbashshell.
Per user/process
Thedefaultlimitsonloginaresetin7etc7Jog1h.cohf.Anunlimitedvalueisstilllimitedbythesystemmaximal
value.
System w|de
Kernellimitsarealsosetwithsysctl.Permanentlimitsaresetin7etc7sysctJ.cohfor7boot7Joade.cohf.The
syntaxisthesameasLinuxbutthekeysaredifferent.
# sysctJ -a # v1eW aJJ systen J1n1ts
# sysctJ keh.naxf1Jes=XXXX # nax1nun hunbe of f1Je desc1ptos
keh.1pc.hnbcJustes=327B # Penaheht ehty 1h 7etc7sysctJ.cohf
keh.naxf1Jes=553 # Typ1caJ vaJues fo 5qu1d
keh.naxf1Jespepoc=327B
keh.1pc.sonaxcohh=B192 # TCP queue. Bette fo apache7sehdna1J
# sysctJ keh.opehf1Jes # hoW nahy f1Je desc1ptos ae 1h use
# sysctJ keh.1pc.hunopehsockets # hoW nahy opeh sockets ae 1h use
# sysctJ het.1het.1p.potahge.Jast=5uuuu # uefauJt 1s 1u24-5uuu
# hetstat -n # hetWok nenoy buffes stat1st1cs
SeeTheFreeBSDhandbookChapter11
http://www.f reebsd.org/handbook/conf igtuningkernellimits.html
fordetails.
Solaris
Thefollowingvaluesin7etc7systenwillincreasethemaximumfiledescriptorsperproc:
set J1nfdnax = 4u9 # had J1n1t oh f1Je desc1ptos fo a s1hgJe poc
set J1nfdcu = 1u24 # 5oft J1n1t oh f1Je desc1ptos fo a s1hgJe poc
1.5Runlevels
2/27/12 Uni Toolbo
4/45 cb.vu/unitoolbo.html
Linux
Oncebooted,thekernelstarts1h1twhichthenstartscwhichstartsallscriptsbelongingtoarunlevel.The
scriptsarestoredin/etc/init.dandarelinkedinto/etc/rc.d/rcN.dwithNtherunlevelnumber.
Thedefaultrunlevelisconfiguredin/etc/inittab.Itisusually3or5:
# gep defauJt. 7etc71h1ttab
1d.3.1h1tdefauJt.
Theactualrunlevelcanbechangedwith1h1t.Forexampletogofrom3to5:
# 1h1t 5 # Ehtes uhJeveJ 5
0Shutdownandhalt
1SingleUsermode(alsoS)
2Multiuserwithoutnetwork
3Multiuserwithnetwork
5MultiuserwithX
6Reboot
Usechkcohf1gtoconfiguretheprogramsthatwillbestartedatbootinarunlevel.
# chkcohf1g --J1st # L1st aJJ 1h1t sc1pts
# chkcohf1g --J1st sshd # Repot the status of sshd
# chkcohf1g sshd --JeveJ 35 oh # Cohf1gue sshd fo JeveJs 3 ahd 5
# chkcohf1g sshd off # u1sabJe sshd fo aJJ uhJeveJs
DebianandDebianbaseddistributionslikeUbuntuorKnoppixusethecommandupdate-c.dtomanagethe
runlevelsscripts.Defaultistostartin2,3,4and5andshutdownin0,1and6.
# update-c.d sshd defauJts # Act1vate sshd W1th the defauJt uhJeveJs
# update-c.d sshd stat 2u 2 3 4 5 . stop 2u u 1 . # W1th expJ1c1t agunehts
# update-c.d -f sshd enove # u1sabJe sshd fo aJJ uhJeveJs
# shutdoWh -h hoW {o # poWeoff} # 5hutdoWh ahd haJt the systen
FreeBSD
TheBSDbootapproachisdifferentfromtheSysV,therearenorunlevels.Thefinalbootstate(singleuser,
with or without X) is configured in 7etc7ttys. All OS scripts are located in 7etc7c.d7 and in
7us7JocaJ7etc7c.d7forthirdpartyapplications.Theactivationoftheserviceisconfiguredin7etc7c.cohf
and7etc7c.cohf.JocaJ.Thedefaultbehaviorisconfiguredin7etc7defauJts7c.cohf.Thescriptsresponds
atleasttostart|stop|status.
# 7etc7c.d7sshd status
sshd 1s uhh1hg as p1d 552.
# shutdoWh hoW # uo 1hto s1hgJe-use node
# ex1t # uo back to nuJt1-use node
# shutdoWh -p hoW # 5hutdoWh ahd haJt the systen
# shutdoWh - hoW # Reboot
The process 1h1t can also be used to reach one of the following states level. For example # 1h1t for
reboot.
0Haltandturnthepoweroff(signalU5R2)
1Gotosingleusermode(signalTERh)
6Rebootthemachine(signalTNT)
cBlockfurtherlogins(signalT5TP)
qRescanthettys(5)file(signalhUP)
Windows
Start and stop a service with either the sev1ce hane or "sev1ce desc1pt1oh" (shown in the Services
ControlPanel)asfollows:
het stop W5each
het stat W5each # stat seach sev1ce
het stop "W1hdoWs 5each"
het stat "W1hdoWs 5each" # sane as above us1hg desc.
1.6Resetrootpassword
Linuxmethod1
Atthebootloader(liloorgrub),enterthefollowingbootoption:
1h1t=7b1h7sh
Thekernelwillmounttherootpartitionand1h1twillstartthebourneshellinsteadofcandthenarunlevel.
Use the command passWd at the prompt to change the password and then reboot. Forget the single user
modeasyouneedthepasswordforthat.
If,afterbooting,therootpartitionismountedreadonly,remountitrw:
2/27/12 Uni Toolbo
5/45 cb.vu/unitoolbo.html
# nouht -o enouht,W 7
# passWd # o deJete the oot passWod {7etc7shadoW}
# syhc nouht -o enouht,o 7 # syhc befoe to enouht ead ohJy
# eboot
FreeBSDmethod1
OnFreeBSD,bootinsingleusermode,remount/rwandusepasswd.Youcanselectthesingleusermode
onthebootmenu(option4)whichisdisplayedfor10secondsatstartup.Thesingleusermodewillgiveyou
arootshellonthe/partition.
# nouht -u 7 nouht -a # W1JJ nouht 7 W
# passWd
# eboot
UnixesandFreeBSDandLinuxmethod2
Other Unixes might not let you go away with the simple init trick. The solution is to mount the root partition
fromanotherOS(likearescueCD)andchangethepasswordonthedisk.
BootaliveCDorinstallationCDintoarescuemodewhichwillgiveyouashell.
Findtherootpartitionwithfdiske.g.fdisk/dev/sda
Mountitandusechroot:
# nouht -o W 7dev7ad4s3a 7nht
# choot 7nht # choot 1hto 7nht
# passWd
# eboot
1.7Kernelmodules
Linux
# Jsnod # L1st aJJ noduJes Joaded 1h the keheJ
# nodpobe 1sdh # To Joad a noduJe {hee 1sdh}
FreeBSD
# kJdstat # L1st aJJ noduJes Joaded 1h the keheJ
# kJdJoad cypto # To Joad a noduJe {hee cypto}
1.8CompileKernel
Linux
# cd 7us7sc7J1hux
# nake npope # CJeah eveyth1hg, 1hcJud1hg cohf1g f1Jes
# nake oJdcohf1g # Reuse the oJd .cohf1g 1f ex1steht
# nake nehucohf1g # o xcohf1g {t} o gcohf1g {uTK}
# nake # Ceate a conpessed keheJ 1nage
# nake noduJes # Conp1Je the noduJes
# nake noduJes1hstaJJ # ThstaJJ the noduJes
# nake 1hstaJJ # ThstaJJ the keheJ
# eboot
FreeBSD
Optionallyupdatethesourcetree(in7us7sc)withcsup(asofFreeBSD6.2orlater):
# csup <supf1Je>
Iusethefollowingsupfile:
*defauJt host=cvsup5.FeeB5u.og # WWW.feebsd.og7hahdbook7cvsup.htnJ#Cv5UP-hTRRuR5
*defauJt pef1x=7us
*defauJt base=7va7db
*defauJt eJease=cvs deJete tag=RELENu7
sc-aJJ
To modify and rebuild the kernel, copy the generic configuration file to a new name and edit it as needed
(you can also edit the file uENERTC directly). To restart the build after an interruption, add the option
NuCLEAN=YE5tothemakecommandtoavoidcleaningtheobjectsalreadybuild.
# cd 7us7sc7sys713B7cohf7
# cp uENERTC hYKERNEL
# cd 7us7sc
# nake bu1JdkeheJ KERNCuNF=hYKERNEL
# nake 1hstaJJkeheJ KERNCuNF=hYKERNEL
TorebuildthefullOS:
# nake bu1JdWoJd # Bu1Jd the fuJJ u5 but hot the keheJ
# nake bu1JdkeheJ # Use KERNCuNF as above 1f appop1ate
# nake 1hstaJJkeheJ
# eboot
2/27/12 Uni Toolbo
6/45 cb.vu/unitoolbo.html
# negenaste -p # Conpaes ohJy f1Jes khoWh to be esseht1aJ
# nake 1hstaJJWoJd
# negenaste -1 -U # Update aJJ cohf1guat1ohs ahd othe f1Jes
# eboot
ForsmallchangesinthesourceyoucanuseNO_CLEAN=yestoavoidrebuildingthewholetree.
# nake bu1JdWoJd NuCLEAN=yes # uoh't deJete the oJd obects
# nake bu1JdkeheJ KERNCuNF=hYKERNEL NuCLEAN=yes
1.9Repairgrub
Soyoubrokegrub?Bootfromalivecd,[findyourlinuxpartitionunder7devandusefd1sktofindthelinux
partion]mountthelinuxpartition,add/procand/devandusegub-1hstaJJ 7dev7xyz.Supposelinuxlieson
7dev7sda:
# nouht 7dev7sda 7nht # nouht the J1hux pat1t1oh oh 7nht
# nouht --b1hd 7poc 7nht7poc # nouht the poc subsysten 1hto 7nht
# nouht --b1hd 7dev 7nht7dev # nouht the dev1ces 1hto 7nht
# choot 7nht # chahge oot to the J1hux pat1t1oh
# gub-1hstaJJ 7dev7sda # e1hstaJJ gub W1th you oJd sett1hgs
2 PROCESSES
Listing|Priority|Background/Foreground|Top|Kill
2.1ListingandPIDs
Eachprocesshasauniquenumber,thePID.Alistofallrunningprocessisretrievedwithps.
# ps -auxefW # Extehs1ve J1st of aJJ uhh1hg pocess
Howevermoretypicalusageiswithapipeorwithpgep(forOSXinstallpoctooJsfromMacPorts):
# ps axWW | gep coh
5B ?? Ts u.u1.4B 7us7sb1h7coh -s
# ps axf # AJJ pocesses 1h a tee fonat {L1hux}
# ps aux | gep 'ss|h' # F1hd aJJ ssh p1ds W1thout the gep p1d
# pgep -J sshd # F1hd the PTus of pocesses by {pat of} hane
# echo $$ # The PTu of you sheJJ
# fuse -va 227tcp # L1st pocesses us1hg pot 22 {L1hux}
# pnap PTu # henoy nap of pocess {huht nenoy Jeaks} {L1hux}
# fuse -va 7hone # L1st pocesses access1hg the 7hone pat1t1oh
# stace df # Tace systen caJJs ahd s1ghaJs
# tuss df # sane as above oh FeeB5u75oJa1s7Uh1xWae
2.2Priority
Change the priority of a running process with eh1ce. Negative numbers have a higher priority, the
lowestis20and"nice"haveapositivevalue.
# eh1ce -5 5B # 5tohge p1o1ty
5B. oJd p1o1ty u, heW p1o1ty -5
Start the process with a defined priority with h1ce. Positive is "nice" or weak, negative is strong scheduling
priority.Makesureyouknowif7us7b1h7h1ceortheshellbuiltinisused(checkwith# Wh1ch h1ce).
# h1ce -h -5 top # 5tohge p1o1ty {7us7b1h7h1ce}
# h1ce -h 5 top # Weake p1o1ty {7us7b1h7h1ce}
# h1ce +5 top # tcsh bu1Jt1h h1ce {sane as above!}
While nice changes the CPU scheduler, an other useful command 1oh1ce will schedule the disk IO. This is
veryusefulforintensiveIOapplication(e.g.compiling).Youcanselectaclass(idlebesteffortrealtime),
themanpageisshortandwellexplained.
# 1oh1ce c3 -p123 # set 1dJe cJass fo p1d 123 {L1hux ohJy}
# 1oh1ce -c2 -hu f1efox # Ruh f1efox W1th best effot ahd h1gh p1o1ty
# 1oh1ce -c3 -p$$ # 5et the actuaJ sheJJ to 1dJe p1o1ty
The last command is very useful to compile (or debug) a large project. Every command launched from this
shellwillhavealoverpriority.$$isyourshellpid(tryecho$$).
FreeBSDuses1dp1o7tp1o(0=maxpriority,31=mostidle):
# 1dp1o 31 nake # conp1Je 1h the JoWest p1o1ty
# 1dp1o 31 -1234 # set PTu 1234 W1th JoWest p1o1ty
# 1dp1o -t -1234 # -t enoves ahy eaJ t1ne71dJe p1o1ty
2.3Background/Foreground
When started from a shell, processes can be brought in the background and back to the foreground with
[Ctrl][Z](^Z),bgandfg.Listtheprocesseswithobs.
# p1hg cb.vu > p1hg.Jog
^Z # p1hg 1s suspehded {stopped} W1th |CtJ-|Z
# bg # put 1h backgouhd ahd coht1hues uhh1hg
# obs -J # L1st pocesses 1h backgouhd
2/27/12 Uni Toolbo
7/45 cb.vu/unitoolbo.html
|1 - 3232 Ruhh1hg p1hg cb.vu > p1hg.Jog
|2 + 3233 5uspehded {tty output} top
# fg Z2 # B1hg pocess 2 back 1h foegouhd
Usehohuptostartaprocesswhichhastokeeprunningwhentheshellisclosed(immunetohangups).
# hohup p1hg -1 u > p1hg.Jog 8
2.4Top
The program top displays running information of processes. See also the program htop from
htop.sourceforge.net (a more powerful version of top) which runs on Linux and FreeBSD
(pots7sysut1Js7htop7).Whiletopisrunningpressthekeyhforahelpoverview.Usefulkeysare:
u[username]Todisplayonlytheprocessesbelongingtotheuser.Use+orblanktoseeallusers
k[pid]Killtheprocesswithpid.
1Todisplayallprocessorsstatistics(Linuxonly)
RTogglenormal/reversesort.
2.5Signals/Kill
Terminateorsendasignalwithk1JJork1JJaJJ.
# p1hg -1 u cb.vu > p1hg.Jog 8
|1 4712
# k1JJ -s TERh 4712 # sane as k1JJ -15 4712
# k1JJaJJ -1 httpd # K1JJ hUP pocesses by exact hane
# pk1JJ -9 http # K1JJ TERh pocesses by {pat of} hane
# pk1JJ -TERh -u WWW # K1JJ TERh pocesses oWhed by WWW
# fuse -k -TERh -n 7hone # K1JJ evey pocess access1hg 7hone {to unouht}
Importantsignalsare:
1hUP(hangup)
2TNT(interrupt)
3UTT(quit)
9KTLL(noncatchable,nonignorablekill)
15TERh(softwareterminationsignal)
3 FI LE SYSTEM
Diskinfo|Boot|Diskusage|Openedfiles|Mount/remount|MountSMB|Mountimage|BurnISO|Create
image|Memorydisk|Diskperformance
3.1Permissions
ChangepermissionandownershipwithchnodandchoWh.Thedefaultumaskcanbechangedforallusersin
/etc/profile for Linux or /etc/login.conf for FreeBSD. The default umask is usually 022. The umask is
subtractedfrom777,thusumask022resultsinapermission0f755.
1 --x execute # hode 74 = exec7ead7W1te | ead7W1te | ead
2 -W- W1te # Fo. |-- uWhe --| |- uoup-| |uth|
4 -- ead
ugo=a u=use, g=goup, o=othes, a=eveyohe
# chnod |uPTTuN huuE|,huuE FTLE # huuE 1s of the fon |ugoa*{|-+={|WxXst}}
# chnod 4u 7va7Jog7na1JJog # Rest1ct the Jog -W------
# chnod u=W,g=,o= 7va7Jog7na1JJog # 5ane as above
# chnod -R o- 7hone7* # Recus1ve enove othe eadabJe fo aJJ uses
# chnod u+s 7path7to7pog # 5et 5UTu b1t oh executabJe {khoW What you do!}
# f1hd 7 -pen -u+s -p1ht # F1hd aJJ pogans W1th the 5UTu b1t
# choWh use.goup 7path7to7f1Je # Chahge the use ahd goup oWhesh1p of a f1Je
# chgp goup 7path7to7f1Je # Chahge the goup oWhesh1p of a f1Je
# chnod 4u `f1hd .7 -type f -p1ht` # Chahge pen1ss1ohs to 4u fo aJJ f1Jes
# chnod 751 `f1hd .7 -type d -p1ht` # Chahge pen1ss1ohs to 751 fo aJJ d1ecto1es
3.2Diskinformation
# d1sk1hfo -v 7dev7ad2 # 1hfonat1oh about d1sk {secto7s1ze} FeeB5u
# hdpan -T 7dev7sda # 1hfonat1oh about the TuE7ATA d1sk {L1hux}
# fd1sk 7dev7ad2 # u1spJay ahd nah1puJate the pat1t1oh tabJe
# snatctJ -a 7dev7ad2 # u1spJay the d1sk 5hART 1hfo
3.3Boot
FreeBSD
Tobootanoldkernelifthenewkerneldoesn'tboot,stopthebootatduringthecountdown.
2/27/12 Uni Toolbo
8/45 cb.vu/unitoolbo.html
# uhJoad
# Joad keheJ.oJd
# boot
3.4Systemmountpoints/Diskusage
# nouht | coJunh -t # 5hoW nouhted f1Je-systens oh the systen
# df # d1spJay fee d1sk space ahd nouhted dev1ces
# cat 7poc7pat1t1ohs # 5hoW aJJ eg1steed pat1t1ohs {L1hux}
Diskusage
# du -sh * # u1ectoy s1zes as J1st1hg
# du -csh # TotaJ d1ectoy s1ze of the cueht d1ectoy
# du -ks * | sot -h - # 5ot eveyth1hg by s1ze 1h k1Jobytes
# Js -J5 # 5hoW f1Jes, b1ggest Jast
3.5Whohaswhichfilesopened
Thisisusefultofindoutwhichfileisblockingapartitionwhichhastobeunmountedandgivesatypicalerror
of:
# unouht 7hone7
unouht. uhnouht of 7hone # unouht 1nposs1bJe because a f1Je 1s Jock1hg hone
fa1Jed. uev1ce busy
FreeBSDandmostUnixes
# fstat -f 7hone # fo a nouht po1ht
# fstat -p PTu # fo ah appJ1cat1oh W1th PTu
# fstat -u use # fo a use hane
Findopenedlogfile(orotheropenedfiles),sayforXorg:
# ps ax | gep Xog | aWk '{p1ht $1}'
1252
# fstat -p 1252
U5ER Chu PTu Fu huUNT TNUh huuE 5Z|uv R7W
oot Xog 1252 oot 7 2 dWx-x-x 512
oot Xog 1252 text 7us 21u1 -Ws--x--x 179B4B
oot Xog 1252 u 7va 212u42 -W----- 59B7 W
Thefilewithinum212042istheonlyfilein/var:
# f1hd -x 7va -1hun 212u42
7va7Jog7Xog.u.Jog
Linux
FindopenedfilesonamountpointwithfuseorJsof:
# fuse -n 7hone # L1st pocesses access1hg 7hone
# Jsof 7hone
CuhhANu PTu U5ER Fu TYPE uEvTCE 5TZE NuuE NAhE
tcsh 29u29 eedcoba cWd uTR u,1B 122BB 1u4B5B7 7hone7eedcoba {guan.7hone}
Jsof 2914u eedcoba cWd uTR u,1B 122BB 1u4B5B7 7hone7eedcoba {guan.7hone}
Aboutanapplication:
ps ax | gep Xog | aWk '{p1ht $1}'
3324
# Jsof -p 3324
CuhhANu PTu U5ER Fu TYPE uEvTCE 5TZE NuuE NAhE
Xog 3324 oot uW REu B, 529 12492 7va7Jog7Xog.u.Jog
Aboutasinglefile:
# Jsof 7va7Jog7Xog.u.Jog
CuhhANu PTu U5ER Fu TYPE uEvTCE 5TZE NuuE NAhE
Xog 3324 oot uW REu B, 529 12492 7va7Jog7Xog.u.Jog
3.6Mount/remountafilesystem
Forexamplethecdrom.Iflistedin/etc/fstab:
# nouht 7cdon
Orfindthedevicein/dev/orwithdmesg
FreeBSD
# nouht -v -t cd9u 7dev7cduc 7nht # cdon
# nouhtcd9u 7dev7Wcduc 7cdon # othe nethod
# nouht -v -t nsdos 7dev7fduc 7nht # fJoppy
Entryin/etc/fstab:
# uev1ce houhtpo1ht F5type upt1ohs uunp Pass#
7dev7acdu 7cdon cd9u o,hoauto u u
Toletusersdoit:
2/27/12 Uni Toolbo
9/45 cb.vu/unitoolbo.html
# sysctJ vfs.usenouht=1 # u 1hset the J1he "vfs.usenouht=1" 1h 7etc7sysctJ.cohf
Linux
# nouht -t auto 7dev7cdon 7nht7cdon # typ1caJ cdon nouht connahd
# nouht 7dev7hdc -t 1so9u - 7cdon # typ1caJ TuE
# nouht 7dev7scdu -t 1so9u - 7cdon # typ1caJ 5C5T cdon
# nouht 7dev7sdcu -t htfs-3g 7W1hdoWs # typ1caJ 5C5T
Entryin/etc/fstab:
7dev7cdon 7ned1a7cdon subfs hoauto,fs=cdfss,o,pocu1d,hosu1d,hodev,exec u u
Mount a lreeBSD part|t|on w|th l|nux
Findthepartitionnumbercontainingwithfdisk,thisisusuallytherootpartition,butitcouldbeanotherBSD
slicetoo.IftheFreeBSDhasmanyslices,theyaretheonenotlistedinthefdisktable,butvisiblein/dev/sda*
or/dev/hda*.
# fd1sk 7dev7sda # F1hd the FeeB5u pat1t1oh
7dev7sda3 * 5357 79u5 2u474B42+ a5 FeeB5u
# nouht -t ufs -o ufstype=ufs2,o 7dev7sda3 7nht
7dev7sda1u = 7tnp 7dev7sda11 7us # The othe sJ1ces
Remount
Remountadevicewithoutunmountingit.Necessaryforfsckforexample
# nouht -o enouht,o 7 # L1hux
# nouht -o o 7 # FeeB5u
Copytherawdatafromacdromintoanisoimage:
# dd 1f=7dev7cduc of=f1Je.1so
3.7Addswaponthefly
Supposeyouneedmoreswap(rightnow),saya2GBfile/swap2gb(Linuxonly).
# dd 1f=7dev7zeo of=7sWap2gb bs=1u24k couht=2uuu
# nksWap 7sWap2gb # ceate the sWap aea
# sWapoh 7sWap2gb # act1vate the sWap. Tt hoW 1h use
# sWapoff 7sWap2gb # Wheh dohe deact1vate the sWap
# n 7sWap2gb
3.8MountanSMBshare
SupposewewanttoaccesstheSMBsharemyshareonthecomputersmbserver,theaddressastypedona
WindowsPCis\\smbserver\myshare\.Wemounton/mnt/smbshare.Warning>cifswantsanIPorDNSname,
notaWindowsname.
Linux
# snbcJ1eht -U use -T 192.1B.1.229 -L 77snbshae7 # L1st the shaes
# nouht -t snbfs -o usehane=W1huse 77snbseve7nyshae 7nht7snbshae
# nouht -t c1fs -o usehane=W1huse,passWod=W1hpWd 77192.1B.1.2297nyshae 7nht7shae
Additionally with the package mount.cifs it is possible to store the credentials in a file, for example
7hone7use7.snb:
usehane=W1huse
passWod=W1hpWd
Andmountasfollow:
# nouht -t c1fs -o cedeht1aJs=7hone7use7.snb 77192.1B.1.2297nyshae 7nht7snbshae
FreeBSD
UseItogivetheIP(orDNSname)smbserveristheWindowsname.
# snbut1J v1eW -T 192.1B.1.229 77W1husesnbseve # L1st the shaes
# nouhtsnbfs -T 192.1B.1.229 77W1husesnbseve7nyshae 7nht7snbshae
3.9Mountanimage
# hd1ut1J nouht 1nage.1so # u5 X
Linuxloopback
# nouht -t 1so9u -o Joop f1Je.1so 7nht # houht a Cu 1nage
# nouht -t ext3 -o Joop f1Je.1ng 7nht # houht ah 1nage W1th ext3 fs
FreeBSD
Withmemorydevice(do#kldloadmd.koifnecessary):
2/27/12 Uni Toolbo
10/45 cb.vu/unitoolbo.html
# ndcohf1g -a -t vhode -f f1Je.1so -u u
# nouht -t cd9u 7dev7ndu 7nht
# unouht 7nht ndcohf1g -d -u u # CJeahup the nd dev1ce
Orwithvirtualnode:
# vhcohf1g 7dev7vhuc f1Je.1so nouht -t cd9u 7dev7vhuc 7nht
# unouht 7nht vhcohf1g -u 7dev7vhuc # CJeahup the vh dev1ce
SolarisandFreeBSD
withloopbackfileinterfaceorlofi:
# Jof1adn -a f1Je.1so
# nouht -F hsfs -o o 7dev7Jof171 7nht
# unouht 7nht Jof1adn -d 7dev7Jof171 # CJeahup the Jof1 dev1ce
3.10CreateandburnanISOimage
ThiswillcopythecdorDVDsectorforsector.Withoutcohv=hotuhc,theimagewillbesmallerifthereisless
contentonthecd.Seebelowandtheddexamples.
# dd 1f=7dev7hdc of=7tnp7nycd.1so bs=2u4B cohv=hotuhc
UsemkisofstocreateaCD/DVDimagefromfilesinadirectory.Toovercomethefilenamesrestrictions:r
enablestheRockRidgeextensionscommontoUNIXsystems,JenablesJolietextensionsusedbyMicrosoft
systems.LallowsISO9660filenamestobeginwithaperiod.
# nk1sofs -J -L - -v TTTLE -o 1nagef1Je.1so 7path7to7d1
# hd1ut1J nakehyb1d -1so -oJ1et -o d1.1so d17 # u5 X
OnFreeBSD,mkisofsisfoundintheportsinsysutils/cdrtools.
BurnaCD/DVDISOimage
lreeBSD
FreeBSDdoesnotenableDMAonATAPIdrivesbydefault.DMAisenabledwiththesysctlcommandandthe
argumentsbelow,orwith/boot/loader.confwiththefollowingentries:
hW.ata.atadna="1"
hW.ata.atap1dna="1"
UsebuhcdwithanATAPIdevice(buhcdispartofthebasesystem)andcdecod(insysutils/cdrtools)witha
SCSIdrive.
# buhcd -f 7dev7acdu data 1nagef1Je.1so f1xate # Fo ATAPT d1ve
# cdecod -scahbus # To f1hd the buhe dev1ce {J1ke 1,u,u}
# cdecod dev=1,u,u 1nagef1Je.1so
l|nux
AlsousecdecodwithLinuxasdescribedabove.AdditionallyitispossibletousethenativeATAPIinterface
whichisfoundwith:
# cdecod dev=ATAPT -scahbus
AndburntheCD/DVDasabove.
dvd+rw-too/s
The dvd+rwtools package (FreeBSD: ports/sysutils/dvd+rwtools) can do it all and includes goW1sofs to
burnCDsorDVDs.Theexamplesrefertothedvddeviceas7dev7dvdwhichcouldbeasymlinkto7dev7scdu
(typical scsi on Linux) or 7dev7cdu (typical FreeBSD) or 7dev7cduc (typical NetBSD/OpenBSD character
SCSI)or7dev7dsk7cut1dus2(SolarisexampleofacharacterSCSI/ATAPICDROMdevice).Thereisanice
documentationwithexamplesontheFreeBSDhandbookchapter18.7
http://www.f reebsd.org/handbook/creatingdv ds.html
.
# -dvd-conpat cJoses the d1sk
# goW1sofs -dvd-conpat -Z 7dev7dvd=1nagef1Je.1so # Buh ex1st1hg 1so 1nage
# goW1sofs -dvd-conpat -Z 7dev7dvd -J -R 7p7to7data # Buh d1ectJy
ConvertaNero.nrgfileto.iso
Nerosimplyaddsa300Kbheadertoanormalisoimage.Thiscanbetrimmedwithdd.
# dd bs=1k 1f=1nagef1Je.hg of=1nagef1Je.1so sk1p=3uu
Convertabin/cueimageto.iso
Thelittlebchuhkprogram
http://f reshmeat.net/projects/bchunk/
candothis.ItisintheFreeBSDportsinsysutils/bchunk.
# bchuhk 1nagef1Je.b1h 1nagef1Je.cue 1nagef1Je.1so
3.11Createafilebasedimage
Forexampleapartitionof1GBusingthefile/usr/vdisk.img.Hereweusethevnode0,butitcouldalsobe1.
2/27/12 Uni Toolbo
11/45 cb.vu/unitoolbo.html
FreeBSD
# dd 1f=7dev7ahdon of=7us7vd1sk.1ng bs=1K couht=1h
# ndcohf1g -a -t vhode -f 7us7vd1sk.1ng -u u # Ceates dev1ce 7dev7nd1
# bsdJabeJ -W 7dev7ndu
# heWfs 7dev7nduc
# nouht 7dev7nduc 7nht
# unouht 7nht ndcohf1g -d -u u n 7us7vd1sk.1ng # CJeahup the nd dev1ce
The file based image can be automatically mounted during boot with an entry in /etc/rc.conf and /etc/fstab.
Testyoursetupwith# 7etc7c.d7ndcohf1g stat(firstdeletethemd0devicewith# ndcohf1g -d -u u).
NotehoweverthatthisautomaticsetupwillonlyworkifthefileimageisNOTontherootpartition.Thereason
isthatthe/etc/rc.d/mdconfigscriptisexecutedveryearlyduringbootandtherootpartitionisstillreadonly.
Imageslocatedoutsidetherootpartitionwillbemountedlaterwiththescript/etc/rc.d/mdconfig2.
/boot/loader.conf:
ndJoad="YE5"
/etc/rc.conf:
# ndcohf1gndu="-t vhode -f 7us7vd1sk.1ng" # 7us 1s hot oh the oot pat1t1oh
/etc/fstab:(The00attheendisimportant,ittellfscktoignorethisdevice,asisdoesnotexistyet)
7dev7ndu 7us7vd1sk ufs W u u
Itisalsopossibletoincreasethesizeoftheimageafterward,sayforexample300MBlarger.
# unouht 7nht ndcohf1g -d -u u
# dd 1f=7dev7zeo bs=1n couht=3uu >> 7us7vd1sk.1ng
# ndcohf1g -a -t vhode -f 7us7vd1sk.1ng -u u
# goWfs 7dev7ndu
# nouht 7dev7nduc 7nht # F1Je pat1t1oh 1s hoW 3uu hB Jage
Linux
# dd 1f=7dev7zeo of=7us7vd1sk.1ng bs=1u24k couht=1u24
# nkfs.ext3 7us7vd1sk.1ng
# nouht -o Joop 7us7vd1sk.1ng 7nht
# unouht 7nht n 7us7vd1sk.1ng # CJeahup
Linuxwithlosetup
7dev7zeoismuchfasterthanuahdon,butlesssecureforencryption.
# dd 1f=7dev7uahdon of=7us7vd1sk.1ng bs=1u24k couht=1u24
# Josetup 7dev7Joopu 7us7vd1sk.1ng # Ceates ahd assoc1ates 7dev7Joopu
# nkfs.ext3 7dev7Joopu
# nouht 7dev7Joopu 7nht
# Josetup -a # Check used Joops
# unouht 7nht
# Josetup -d 7dev7Joopu # uetach
# n 7us7vd1sk.1ng
3.12Createamemoryfilesystem
AmemorybasedfilesystemisveryfastforheavyIOapplication.Howtocreatea64MBpartitionmountedon
/memdisk:
FreeBSD
# nouhtnfs -o W -s 4h nd 7nend1sk
# unouht 7nend1sk ndcohf1g -d -u u # CJeahup the nd dev1ce
nd 7nend1sk nfs W,-s4h u u # 7etc7fstab ehty
Linux
# nouht -t tnpfs -os1ze=4n tnpfs 7nend1sk
3.13Diskperformance
Readandwritea1GBfileonpartitionad4s3c(/home)
# t1ne dd 1f=7dev7ad4s3c of=7dev7huJJ bs=1u24k couht=1uuu
# t1ne dd 1f=7dev7zeo bs=1u24k couht=1uuu of=7hone71ub.f1Je
# hdpan -tT 7dev7hda # L1hux ohJy
4 NETWORK
Routing|AdditionalIP|ChangeMAC|Ports|Firewall|IPForward|NAT|DNS|DHCP|Traffic|QoS|NIS|
Netcat
4.1Debugging(SeealsoTrafficanalysis)
Linux
2/27/12 Uni Toolbo
12/45 cb.vu/unitoolbo.html
# ethtooJ ethu # 5hoW the ethehet status {epJaces n11-d1ag}
# ethtooJ -s ethu speed 1uu dupJex fuJJ # Foce 1uuhb1t FuJJ dupJex
# ethtooJ -s ethu autoheg off # u1sabJe auto hegot1at1oh
# ethtooJ -p eth1 # BJ1hk the ethehet Jed - vey usefuJ Wheh suppoted
# 1p J1hk shoW # u1spJay aJJ 1htefaces oh L1hux {s1n1Ja to 1fcohf1g}
# 1p J1hk set ethu up # B1hg dev1ce up {o doWh}. 5ane as "1fcohf1g ethu up"
# 1p add shoW # u1spJay aJJ TP addesses oh L1hux {s1n1Ja to 1fcohf1g}
# 1p he1gh shoW # 51n1Ja to ap -a
OtherOSes
# 1fcohf1g fxpu # Check the "ned1a" f1eJd oh FeeB5u
# ap -a # Check the oute {o host} ARP ehty {aJJ u5}
# p1hg cb.vu # The f1st th1hg to ty...
# taceoute cb.vu # P1ht the oute path to dest1hat1oh
# 1fcohf1g fxpu ned1a 1uubaseTX ned1aopt fuJJ-dupJex # 1uuhb1t fuJJ dupJex {FeeB5u}
# hetstat -s # 5ysten-W1de stat1st1cs fo each hetWok potocoJ
Additionalcommandswhicharenotalwaysinstalledperdefaultbuteasytofind:
# ap1hg 192.1B.1.254 # P1hg oh ethehet Jaye
# tcptaceoute -f 5 cb.vu # uses tcp 1hstead of 1cnp to tace though f1eWaJJs
4.2Routing
Printroutingtable
# oute -h # L1hux o use "1p oute"
# hetstat -h # L1hux, B5u ahd UNTX
# oute p1ht # W1hdoWs
Addanddeletearoute
lreeBSD
# oute add 212.117.u.u71 192.1B.1.1
# oute deJete 212.117.u.u71
# oute add defauJt 192.1B.1.1
Addtheroutepermanentlyin/etc/rc.conf
stat1coutes="nyoute"
outenyoute="-het 212.117.u.u71 192.1B.1.1"
l|nux
# oute add -het 192.1B.2u.u hetnask 255.255.255.u gW 192.1B.1.254
# 1p oute add 192.1B.2u.u724 v1a 192.1B.1.254 # sane as above W1th 1p oute
# oute add -het 192.1B.2u.u hetnask 255.255.255.u dev ethu
# oute add defauJt gW 192.1B.51.254
# 1p oute add defauJt v1a 192.1B.51.254 dev ethu # sane as above W1th 1p oute
# oute deJete -het 192.1B.2u.u hetnask 255.255.255.u
So/ar|s
# oute add -het 192.1B.2u.u -hetnask 255.255.255.u 192.1B.1.254
# oute add defauJt 192.1B.51.254 1 # 1 = hops to the hext gateWay
# oute chahge defauJt 192.1B.5u.254 1
Permanententriesaresetinentryin7etc7defauJtoute.
W|ndows
# Route add 192.1B.5u.u nask 255.255.255.u 192.1B.51.253
# Route add u.u.u.u nask u.u.u.u 192.1B.51.254
Useaddptomaketheroutepersistent.
4.3ConfigureadditionalIPaddresses
Linux
# 1fcohf1g ethu 192.1B.5u.254 hetnask 255.255.255.u # F1st TP
# 1fcohf1g ethu.u 192.1B.51.254 hetnask 255.255.255.u # 5ecohd TP
# 1p add add 192.1B.5u.254724 dev ethu # Equ1vaJeht 1p connahds
# 1p add add 192.1B.51.254724 dev ethu JabeJ ethu.1
FreeBSD
# 1fcohf1g fxpu 1het 192.1B.5u.254724 # F1st TP
# 1fcohf1g fxpu aJ1as 192.1B.51.254 hetnask 255.255.255.u # 5ecohd TP
# 1fcohf1g fxpu -aJ1as 192.1B.51.254 # Renove secohd TP aJ1as
Permanententriesin/etc/rc.conf
1fcohf1gfxpu="1het 192.1B.5u.254 hetnask 255.255.255.u"
1fcohf1gfxpuaJ1asu="192.1B.51.254 hetnask 255.255.255.u"
2/27/12 Uni Toolbo
13/45 cb.vu/unitoolbo.html
Solaris
Checkthesettingswith1fcohf1g -a
# 1fcohf1g hneu pJunb # EhabJe the hetWok cad
# 1fcohf1g hneu 192.1B.5u.254 hetnask 255.255.255.u up # F1st TP
# 1fcohf1g hneu.1 192.1B.51.254 hetnask 255.255.255.u up # 5ecohd TP
4.4ChangeMACaddress
Normallyyouhavetobringtheinterfacedownbeforethechange.Don'ttellmewhyyouwanttochangethe
MACaddress...
# 1fcohf1g ethu doWh
# 1fcohf1g ethu hW ethe uu.u1.u2.u3.u4.u5 # L1hux
# 1fcohf1g fxpu J1hk uu.u1.u2.u3.u4.u5 # FeeB5u
# 1fcohf1g hneu ethe uu.u1.u2.u3.u4.u5 # 5oJa1s
# sudo 1fcohf1g ehu ethe uu.u1.u2.u3.u4.u5 # u5 X T1ge, 5hoW Leopad LAN*
# sudo 1fcohf1g ehu JJadd uu.u1.u2.u3.u4.u5 # u5 X Leopad
*Typicalwirelessinterfaceiseh1andneedsdodisassociatefromanynetworkfirst(osxdailyhowto).
# echo "aJ1as a1pot='75ysten7L1bay7P1vateFaneWoks7AppJeBu211.faneWok7ves1ohs7Cueht7Resouces7a1pot'"`
>> ~7.bashpof1Je # o synJ1hk to 7us7sb1h
# a1pot -z # u1sassoc1ate fon W1eJess hetWoks
# a1pot -T # uet 1hfo fon W1eJess hetWok
Many tools exist for Windows. For example etherchange
http://ntsecurity .nu/toolbox/etherchange
. Or look for "Mac
Makeup","smac".
4.5Portsinuse
Listeningopenports:
# hetstat -ah | gep LT5TEN
# Jsof -1 # L1hux J1st aJJ Thtehet cohhect1ohs
# sockJ1st # L1hux d1spJay J1st of opeh sockets
# sockstat -4 # FeeB5u appJ1cat1oh J1st1hg
# hetstat -ahp --udp --tcp | gep LT5TEN # L1hux
# hetstat -tup # L1st act1ve cohhect1ohs to7fon systen {L1hux}
# hetstat -tupJ # L1st J1steh1hg pots fon systen {L1hux}
# hetstat -aho # W1hdoWs
4.6Firewall
Checkifafirewallisrunning(typicalconfigurationonly):
Linux
# 1ptabJes -L -h -v # Fo status
upeh the 1ptabJes f1eWaJJ
# 1ptabJes -P TNPUT ACCEPT # upeh eveyth1hg
# 1ptabJes -P FuRWARu ACCEPT
# 1ptabJes -P uUTPUT ACCEPT
# 1ptabJes -Z # Zeo the packet ahd byte couhtes 1h aJJ cha1hs
# 1ptabJes -F # FJush aJJ cha1hs
# 1ptabJes -X # ueJete aJJ cha1hs
FreeBSD
# 1pfW shoW # Fo status
# 1pfW J1st 5535 # 1f ahsWe 1s "5535 dehy 1p fon ahy to ahy" the fW 1s d1sabJed
# sysctJ het.1het.1p.fW.ehabJe=u # u1sabJe
# sysctJ het.1het.1p.fW.ehabJe=1 # EhabJe
4.7IPForwardforrouting
Linux
CheckandthenenableIPforwardwith:
# cat 7poc7sys7het71pv471pfoWad # Check TP foWad u=off, 1=oh
# echo 1 > 7poc7sys7het71pv471pfoWad
oredit/etc/sysctl.confwith:
het.1pv4.1pfoWad = 1
FreeBSD
Checkandenablewith:
# sysctJ het.1het.1p.foWad1hg # Check TP foWad u=off, 1=oh
# sysctJ het.1het.1p.foWad1hg=1
# sysctJ het.1het.1p.fastfoWad1hg=1 # Fo ded1cated oute o f1eWaJJ
Penaheht W1th ehty 1h 7etc7c.cohf.
gateWayehabJe="YE5" # 5et to YE5 1f th1s host W1JJ be a gateWay.
2/27/12 Uni Toolbo
14/45 cb.vu/unitoolbo.html
Solaris
# hdd -set 7dev71p 1pfoWad1hg 1 # 5et TP foWad u=off, 1=oh
4.8NATNetworkAddressTranslation
Linux
# 1ptabJes -t hat -A Pu5TRuUTTNu -o ethu - hA5UERAuE # to act1vate NAT
# 1ptabJes -t hat -A PRERuUTTNu -p tcp -d 7B.31.7u.23B --dpot 2uu22 - uNAT `
--to 192.1B.1.44.22 # Pot foWad 2uu22 to 1htehaJ TP pot ssh
# 1ptabJes -t hat -A PRERuUTTNu -p tcp -d 7B.31.7u.23B --dpot 993.995 - uNAT `
--to 192.1B.1.254.993-995 # Pot foWad of ahge 993-995
# 1p oute fJush cache
# 1ptabJes -L -t hat # Check NAT status
DeletetheportforwardwithDinsteadofA.Theprogramnetstatnat
http://tweegy .nl/projects/netstatnat
isveryuseful
totrackconnections(ituses7poc7het71pcohhtackor7poc7het7hfcohhtack).
# hetstat-hat -h # shoW aJJ cohhect1ohs W1th TPs
FreeBSD
# hatd -s -n -u -dyhan1c -f 7etc7hatd.cohf -h fxpu
u ed1t 7etc7c.cohf W1th.
f1eWaJJehabJe="YE5" # 5et to YE5 to ehabJe f1eWaJJ fuhct1ohaJ1ty
f1eWaJJtype="opeh" # F1eWaJJ type {see 7etc7c.f1eWaJJ}
hatdehabJe="YE5" # EhabJe hatd {1f f1eWaJJehabJe == YE5}.
hatd1hteface="tuhu" # PubJ1c 1hteface o TP addess to use.
hatdfJags="-s -n -u -dyhan1c -f 7etc7hatd.cohf"
Portforwardwith:
# cat 7etc7hatd.cohf
sanepots yes
usesockets yes
uheg1steedohJy
# ed1ectpot tcp 1hs1deTP.23uu-2399 33uu-3399 # pot ahge
ed1ectpot udp 192.1B.51.1u3.7777 7777
4.9DNS
On Unix the DNS entries are valid for all interfaces and are stored in /etc/resolv.conf. The domain to which
thehostbelongsisalsostoredinthisfile.Aminimalconfigurationis:
haneseve 7B.31.7u.23B
seach sJeepyoWJ.het 1hteh.Jab
dona1h sJeepyoWJ.het
Checkthesystemdomainnamewith:
# hosthane -d # 5ane as dhsdona1hhane
Windows
On Windows the DNS are configured per interface. To display the configured DNS and to flush the DNS
cacheuse:
# 1pcohf1g 7? # u1spJay heJp
# 1pcohf1g 7aJJ # 5ee aJJ 1hfonat1oh 1hcJud1hg uN5
FlushDNS
FlushtheOSDNScache,someapplicationusingtheirowncache(e.g.Firefox)andwillbeunaffected.
# 7etc71h1t.d7hscd estat # Restat hscd 1f used - L1hux7B5u75oJa1s
# Jookupd -fJushcache # u5 X T1ge
# dscacheut1J -fJushcache # u5 X Leopad ahd heWe
# 1pcohf1g 7fJushdhs # W1hdoWs
Forwardqueries
Dig is you friend to test the DNS settings. For example the public DNS server 213.133.1u5.2 hs.secohd-
hs.decanbeusedfortesting.Seefromwhichservertheclientreceivestheanswer(simplifiedanswer).
# d1g sJeepyoWJ.het
sJeepyoWJ.het. uu TN A 7B.31.7u.23B
5ERvER. 192.1B.51.254#53{192.1B.51.254}
The router 192.168.51.254 answered and the response is the A entry. Any entry can be queried and the
DNSservercanbeselectedwith@:
# d1g hX googJe.con
# d1g 127.u.u.1 N5 suh.con # To test the JocaJ seve
# d1g 2u4.97.212.1u N5 hX he1se.de # uey ah extehaJ seve
# d1g AXFR hs1.xhane.og cb.vu # uet the fuJJ zohe {zohe tahsfe}
Theprogramhostisalsopowerful.
# host -t hX cb.vu # uet the na1J hX ehty
2/27/12 Uni Toolbo
15/45 cb.vu/unitoolbo.html
# host -t N5 -T suh.con # uet the N5 ecod ove a TCP cohhect1oh
# host -a sJeepyoWJ.het # uet eveyth1hg
Reversequeries
FindthenamebelongingtoanIPaddress(inaddr.arpa.).Thiscanbedonewithd1g,hostandhsJookup:
# d1g -x 7B.31.7u.23B
# host 7B.31.7u.23B
# hsJookup 7B.31.7u.23B
/etc/hosts
Singlehostscanbeconfiguredinthefile/etc/hostsinsteadofrunninghanedlocallytoresolvethehostname
queries.Theformatissimple,forexample:
7B.31.7u.23B sJeepyoWJ.het sJeepyoWJ
The priority between hosts and a dns query, that is the name resolution order, can be configured in
7etc7hssW1tch.cohfAND/etc/host.conf.ThefilealsoexistsonWindows,itisusuallyin:
C.`WTNuuW5`5Y5TEh32`uRTvER5`ETC
4.10DHCP
Linux
Somedistributions(SuSE)usedhcpcdasclient.Thedefaultinterfaceiseth0.
# dhcpcd -h ethu # T1gge a eheW {does hot aJWays Wok}
# dhcpcd -k ethu # eJease ahd shutdoWh
Theleasewiththefullinformationisstoredin:
7va7J1b7dhcpcd7dhcpcd-ethu.1hfo
FreeBSD
FreeBSD(andDebian)usesdhclient.Toconfigureaninterface(forexamplebge0)run:
# dhcJ1eht bgeu
Theleasewiththefullinformationisstoredin:
7va7db7dhcJ1eht.Jeases.bgeu
Use
7etc7dhcJ1eht.cohf
toprependoptionsorforcedifferentoptions:
# cat 7etc7dhcJ1eht.cohf
1hteface "Ju" {
pepehd dona1h-hane-seves 127.u.u.1
defauJt dona1h-hane "sJeepyoWJ.het"
supesede dona1h-hane "sJeepyoWJ.het"
}
Windows
Thedhcpleasecanberenewedwith1pcohf1g:
# 1pcohf1g 7eheW # eheW aJJ adaptes
# 1pcohf1g 7eheW LAN # eheW the adapte haned "LAN"
# 1pcohf1g 7eJease WLAN # eJease the adapte haned "WLAN"
Yesitisagoodideatorenameyouadapterwithsimplenames!
4.11Trafficanalysis
Bmon
http://people.suug.ch/~tgr/bmon/
is a small console bandwidth monitor and can display the flow on different
interfaces.
Sniffwithtcpdump
# tcpdunp -hJ -1 bgeu hot pot ssh ahd sc `{192.1B.1.121 o 192.1B.1.54`}
# tcpdunp -h -1 eth1 het 192.1B.1.121 # seJect to7fon a s1hgJe TP
# tcpdunp -h -1 eth1 het 192.1B.1.u724 # seJect taff1c to7fon a hetWok
# tcpdunp -J > dunp 88 ta1J -f dunp # Buffeed output
# tcpdunp -1 Ju -W taff1c.Ju # W1te taff1c heades 1h b1hay f1Je
# tcpdunp -1 Ju -s u -W taff1c.Ju # W1te taff1c + payJoad 1h b1hay f1Je
# tcpdunp - taff1c.Ju # Read fon f1Je {aJso fo etheeaJ
# tcpdunp pot Bu # The tWo cJass1c connahds
# tcpdunp host googJe.con
# tcpdunp -1 ethu -X pot `{11u o 143`} # Check 1f pop o 1nap 1s secue
# tcpdunp -h -1 ethu 1cnp # uhJy catch p1hgs
# tcpdunp -1 ethu -s u -A pot Bu | gep uET # -s u fo fuJJ packet -A fo A5CTT
Additionalimportantoptions:
2/27/12 Uni Toolbo
16/45 cb.vu/unitoolbo.html
-APrinteachpacketsincleartext(withoutheader)
-XPrintpacketsinhexandASCII
-JMakestdoutlinebuffered
-uPrintallinterfacesavailable
OnWindowsusewindumpfromwww.winpcap.org.UsewindumpDtolisttheinterfaces.
Scanwithnmap
Nmap
http://insecure.org/nmap/
isaportscannerwithOSdetection,itisusuallyinstalledonmostdistributionsandis
alsoavailableforWindows.Ifyoudon'tscanyourservers,hackersdoitforyou...
# hnap cb.vu # scahs aJJ eseved TCP pots oh the host
# hnap -sP 192.1B.1.u724 # F1hd out Wh1ch TP ae used ahd by Wh1ch host oh u724
# hnap -s5 -sv -u cb.vu # uo a steaJth 5YN scah W1th ves1oh ahd u5 detect1oh
PuRT 5TATE 5ERvTCE vER5TuN
227tcp opeh ssh upeh55h 3.B.1p1 FeeB5u-2uuu93u {potocoJ 2.u}
257tcp opeh sntp 5ehdna1J sntpd B.13.7B.13.
Bu7tcp opeh http Apache httpd 2.u.59 {{FeeB5u} uAv72 PhP74.
|...
Ruhh1hg. FeeB5u 5.X
Upt1ne 33.12u days {s1hce F1 Aug 31 11.41.u4 2uu7}
Other non standard but useful tools are hp1hg (www.hping.org) an IP packet assembler/analyzer and fp1hg
(fping.sourceforge.net).fpingcancheckmultiplehostsinaroundrobinfashion.
4.12Trafficcontrol(QoS)
Traffic control manages the queuing, policing, scheduling, and other traffic parameters for a network. The
followingexamplesaresimplepracticalusesoftheLinuxandFreeBSDcapabilitiestobetterusetheavailable
bandwidth.
Limitupload
DSLorcablemodemshavealongqueuetoimprovetheuploadthroughput.Howeverfillingthequeuewitha
fastdevice(e.g.ethernet)willdramaticallydecreasetheinteractivity.Itisthereforeusefultolimitthedevice
uploadratetomatchthephysicalcapacityofthemodem,thisshouldgreatlyimprovetheinteractivity.Setto
about90%ofthemodemmaximal(cable)speed.
l|nux
Fora512Kbituploadmodem.
# tc qd1sc add dev ethu oot tbf ate 4Bukb1t Jatehcy 5uns bust 154u
# tc -s qd1sc Js dev ethu # 5tatus
# tc qd1sc deJ dev ethu oot # ueJete the queue
# tc qd1sc chahge dev ethu oot tbf ate 22ukb1t Jatehcy 5uns bust 154u
lreeBSD
FreeBSD uses the dunnyhet traffic shaper which is configured with ipfw. Pipes are used to set limits the
bandwidth in units of [K|M]{bit/s|Byte/s}, 0 means unlimited bandwidth. Using the same pipe number will
reconfigureit.Forexamplelimittheuploadbandwidthto500Kbit.
# kJdJoad dunnyhet # Joad the noduJe 1f hecessay
# 1pfW p1pe 1 cohf1g bW 5uuKb1t7s # ceate a p1pe W1th J1n1ted bahdW1dth
# 1pfW add p1pe 1 1p fon ne to ahy # d1vet the fuJJ upJoad 1hto the p1pe
Qualityofservice
l|nux
Priority queuing with tc to optimize VoIP. See the full example on voipinfo.org or www.howtoforge.com.
Suppose VoIP uses udp on ports 10000:11024 and device eth0 (could also be ppp0 or so). The following
commandsdefinetheQoStothreequeuesandforcetheVoIPtraffictoqueue1withQoSux1e(allbitsset).
Thedefaulttrafficflowsintoqueue3andQoSM|n|m|ze-De/ayflowsintoqueue2.
# tc qd1sc add dev ethu oot hahdJe 1. p1o p1onap 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 u
# tc qd1sc add dev ethu paeht 1.1 hahdJe 1u. sfq
# tc qd1sc add dev ethu paeht 1.2 hahdJe 2u. sfq
# tc qd1sc add dev ethu paeht 1.3 hahdJe 3u. sfq
# tc f1Jte add dev ethu potocoJ 1p paeht 1. p1o 1 u32 `
natch 1p dpot 1uuuu ux3Cuu fJoW1d 1.1 # use seve pot ahge
natch 1p dst 123.23.u.1 fJoW1d 1.1 # o7ahd use seve TP
Statusandremovewith
# tc -s qd1sc Js dev ethu # queue status
# tc qd1sc deJ dev ethu oot # deJete aJJ o5
Ca/cu/ate port range and mask
2/27/12 Uni Toolbo
17/45 cb.vu/unitoolbo.html
The tc filter defines the port range with port and mask which you have to calculate. Find the 2^N end|ng of
theportrange,deducetherangeandconverttoHEX.Thisisyourmask.Examplefor10000>11024,the
rangeis1024.
# 2^13 {B192} < 1uuuu < 2^14 {13B4} # ehd1hg 1s 2^14 = 13B4
# echo "obase=1{2^14}-1u24" | bc # nask 1s ux3Cuu
lreeBSD
Themaxlinkbandwidthis500Kbit/sandwedefine3queueswithpriority100:10:1forVoIP:ssh:alltherest.
# 1pfW p1pe 1 cohf1g bW 5uuKb1t7s
# 1pfW queue 1 cohf1g p1pe 1 We1ght 1uu
# 1pfW queue 2 cohf1g p1pe 1 We1ght 1u
# 1pfW queue 3 cohf1g p1pe 1 We1ght 1
# 1pfW add 1u queue 1 poto udp dst-pot 1uuuu-11u24
# 1pfW add 11 queue 1 poto udp dst-1p 123.23.u.1 # o7ahd use seve TP
# 1pfW add 2u queue 2 dsp-pot ssh
# 1pfW add 3u queue 3 fon ne to ahy # aJJ the est
Statusandremovewith
# 1pfW J1st # uJes status
# 1pfW p1pe J1st # p1pe status
# 1pfW fJush # deJetes aJJ uJes but defauJt
4.13NISDebugging
SomecommandswhichshouldworkonawellconfiguredNISclient:
# ypWh1ch # get the cohhected NT5 seve hane
# dona1hhane # The NT5 dona1h hane as cohf1gued
# ypcat goup # shouJd d1spJay the goup fon the NT5 seve
# cd 7va7yp 88 nake # Rebu1Jd the yp database
# pc1hfo -p sevehane # Repot RPC sev1ces of the seve
Isypbindrunning?
# ps auxWW | gep ypb1hd
7us7sb1h7ypb1hd -s -n -5 sevehane1,sevehane2 # FeeB5u
7us7sb1h7ypb1hd # L1hux
# yppoJJ passWd.byhane
hap passWd.byhane has ode hunbe 119u35u41. hoh 5ep 24 13.57.21 2uu7
The naste seve 1s sevehane.dona1h.het.
Linux
# cat 7etc7yp.cohf
ypseve sevehane
dona1h dona1h.het boadcast
4.14Netcat
Netcat
http://netcat.sourcef orge.net
(nc)isbetterknownasthe"networkSwissArmyKnife",itcanmanipulate,createor
read/writeTCP/IPconnections.Heresomeusefulexamples,therearemanymoreonthenet,forexampleg
loaded.eu[...]
http://www.gloaded.eu/2006/11/06/netcatacoupleof usef ulexamples
and here
http://www.terminally incoherent.com/blog/2007/08/07/f ew
usef ulnetcattricks
.
Youmightneedtousethecommandhetcatinsteadofhc.Alsoseethesimilarcommandsocat.
Filetransfer
Copy a large folder over a raw tcp connection. The transfer is very quick (no protocol overhead) and you
don'tneedtomessupwithNFSorSMBorFTPorso,simplymakethefileavailableontheserver,andgetit
fromtheclient.Here192.168.1.1istheserverIPaddress.
seve# ta -cf - -C vTuEuT5 . | hc -J -p 4444 # 5eve ta foJde oh pot 4444
cJ1eht# hc 192.1B.1.1 4444 | ta xpf - -C vTuEuT5 # PuJJ the f1Je oh pot 4444
seve# cat Jagef1Je | hc -J 57B # 5eve a s1hgJe f1Je
cJ1eht# hc 192.1B.1.1 57B > Jagef1Je # PuJJ the s1hgJe f1Je
seve# dd 1f=7dev7dau | hc -J 4444 # 5eve pat1t1oh 1nage
cJ1eht# hc 192.1B.1.1 4444 | dd of=7dev7dau # PuJJ pat1t1oh to cJohe
cJ1eht# hc 192.1B.1.1 4444 | dd of=dau.1ng # PuJJ pat1t1oh to f1Je
Otherhacks
Speciallyhere,youmustknowwhatyouaredoing.
Pemote she//
OptioneonlyontheWindowsversion?Orusenc1.10.
# hc -Jp 4444 -e 7b1h7bash # Pov1de a enote sheJJ {seve backdoo}
# hc -Jp 4444 -e cnd.exe # enote sheJJ fo W1hdoWs
Fmergency web server
2/27/12 Uni Toolbo
18/45 cb.vu/unitoolbo.html
Serveasinglefileonport80inaloop.
# Wh1Je tue do hc -J -p Bu < uh1xtooJbox.xhtnJ dohe
Chat
AliceandBobcanchatoverasimpleTCPsocket.Thetextistransferredwiththeenterkey.
aJ1ce# hc -Jp 4444
bob # hc 192.1B.1.1 4444
5 SSH SCP
Publickey|Fingerprint|SCP|Tunneling
Seeothertricks25sshcmd
http://blog.urf ix.com/25sshcommandstricks/
5.1Publickeyauthentication
Connecttoahostwithoutpasswordusingpublickeyauthentication.Theideaistoappendyourpublickeyto
theauthorized_keys2fileontheremotehost.Forthisexamplelet'sconnecthostclienttohostserer,the
key is generated on the client. With cygwin you might have to create your home directoy and the .ssh
directorywith# nkd1 -p 7hone7U5ER7.ssh
Use sshkeygen to generate a key pair. ~7.ssh71ddsa is the private key, ~7.ssh71ddsa.pub is the
publickey.
Copy only the public key to the server and append it to the file ~7.ssh7autho1zedkeys2 on your
homeontheserver.
# ssh-keygeh -t dsa -N ''
# cat ~7.ssh71ddsa.pub | ssh youhost-seve "cat - >> ~7.ssh7autho1zedkeys2"
UsingtheWindowsclientfromssh.com
Thenoncommercialversionofthessh.comclientcanbedownloadedthemainftpsite:ftp.ssh.com/pub/ssh/.
Keysgeneratedbythessh.comclientneedtobeconvertedfortheOpenSSHserver.Thiscanbedonewith
thesshkeygencommand.
Createakeypairwiththessh.comclient:SettingsUserAuthenticationGenerateNew....
IuseKeytypeDSAkeylength2048.
Copythepublickeygeneratedbythessh.comclienttotheserverintothe~/.sshfolder.
ThekeysareinC:\DocumentsandSettings\%USERNAME%\ApplicationData\SSH\UserKeys.
Usethesshkeygencommandontheservertoconvertthekey:
# cd ~7.ssh
# ssh-keygeh -1 -f keyf1Jehane.pub >> autho1zedkeys2
Not|ce.WeusedaDSAkey,RSAisalsopossible.Thekeyisnotprotectedbyapassword.
UsingputtyforWindows
Putty
http://www.chiark.greenend.org.uk/~sgtatham/putty /download.html
isasimpleandfreesshclientforWindows.
CreateakeypairwiththepuTTYgenprogram.
Savethepublicandprivatekeys(forexampleintoC:\DocumentsandSettings\%USERNAME%\.ssh).
Copythepublickeytotheserverintothe~/.sshfolder:
# scp .ssh7puttykey.pub oot192.1B.51.254..ssh7
UsethesshkeygencommandontheservertoconvertthekeyforOpenSSH:
# cd ~7.ssh
# ssh-keygeh -1 -f puttykey.pub >> autho1zedkeys2
Pointtheprivatekeylocationintheputtysettings:ConnectionSSHAuth
5.2Checkfingerprint
Atthefirstlogin,sshwillaskiftheunknownhostwiththefingerprinthastobestoredintheknownhosts.To
avoidamaninthemiddleattacktheadministratoroftheservercansendyoutheserverfingerprintwhichis
thencomparedonthefirstlogin.Usessh-keygeh -Jtogetthefingerprint(ontheserver):
# ssh-keygeh -J -f 7etc7ssh7sshhostsakey.pub # Fo R5A key
2u4B 1.33.be.9b.ae.c.3.31.fd.B3.9B.b7.99.2d.9f.cd 7etc7ssh7sshhostsakey.pub
# ssh-keygeh -J -f 7etc7ssh7sshhostdsakey.pub # Fo u5A key {defauJt}
2u4B 14.4a.aa.d9.73.25.4.d.ua.4B.35.c7.f4.1.d4.ee 7etc7ssh7sshhostdsakey.pub
Nowtheclientconnectingtothisservercanverifythatheisconnectingtotherightserver:
2/27/12 Uni Toolbo
19/45 cb.vu/unitoolbo.html
# ssh J1hda
The autheht1c1ty of host 'J1hda {192.1B.1.54}' cah't be estabJ1shed.
u5A key f1hgep1ht 1s 14.4a.aa.d9.73.25.4.d.ua.4B.35.c7.f4.1.d4.ee.
Ae you sue you Waht to coht1hue cohhect1hg {yes7ho}? yes
5.3Securefiletransfer
Somesimplecommands:
# scp f1Je.txt host-tWo.7tnp
# scp oehost-tWo.7WWW7*.htnJ 7WWW7tnp
# scp - oehost-tWo.7WWW 7WWW7tnp
In Konqueror or Midnight Commander it is possible to access a remote file system with the address
fish://user@gate.Howevertheimplementationisveryslow.
FurthermoreitispossibletomountaremotefolderwithsshfsafilesystemclientbasedonSCP.Seefuse
sshfs
http://f use.sourcef orge.net/sshf s.html
.
sshexchahge1deht1f1cat1oh. Cohhect1oh cJosed by enote host
Withthiserrortrythefollowingontheserver:
echo '55hu. ALL' >> 7etc7hosts.aJJoW
7etc71h1t.d7sshd estat
5.4Tunneling
SSHtunnelingallowstoforwardorreverseforwardaportovertheSSHconnection,thussecuringthetraffic
andaccessingportswhichwouldotherwisebeblocked.ThisonlyworkswithTCP.Thegeneralnomenclature
forforwardandreverseis(seealsosshandNATexample):
# ssh -L JocaJpot.desthost.destpot usegate # desthost as seeh fon the gate
# ssh -R destpot.desthost.JocaJpot usegate # foWads you JocaJpot to dest1hat1oh
# desthost.JocaJpot as seeh fon the cJ1eht 1h1t1at1hg the tuhheJ
# ssh -X usegate # To foce X foWad1hg
This will connect to gate and forward the local port to the host desthost:destport. Note desthost is the
destinationhostas seen by the gate,soiftheconnectionistothegate,thendesthostislocalhost.Morethan
oneportforwardispossible.
Directforwardonthegate
LetsaywewanttoaccesstheCVS(port2401)andhttp(port80)whicharerunningonthegate.Thisisthe
simplestexample,desthostisthuslocalhost,andweusetheport8080locallyinsteadof80sowedon'tneed
toberoot.Oncethesshsessionisopen,bothservicesareaccessibleonthelocalports.
# ssh -L 24u1.JocaJhost.24u1 -L BuBu.JocaJhost.Bu usegate
Netbiosandremotedesktopforwardtoasecondserver
LetsayaWindowssmbserverisbehindthegateandisnotrunningssh.Weneedaccesstothesmbshare
andalsoremotedesktoptotheserver.
# ssh -L 139.snbseve.139 -L 33BB.snbseve.33B9 usegate
The smb share can now be accessed with \\127.0.0.1\, but only if the local share is disabled, because the
/oca/ share |s /|sten|ng on port 139.
It is possible to keep the local share enabled, for this we need to create a new virtual device with a new IP
address for the tunnel, the smb share will be connected over this address. Furthermore the /oca/ PDP |s
a/ready /|sten|ng on 3389,sowechoose3388.Forthisexamplelet'suseavirtualIPof10.1.1.1.
WithputtyuseSourceport=10.1.1.1:139.Itispossibletocreatemultipleloopdevicesandtunnel.On
Windows 2000, only putty worked for me. On Windows Vista also forward the port 445 in addition to
the port 139. Also on Vista the patch KB942624 prevents the port 445 to be forwarded, so I had to
uninstallthispathinVista.
With the ssh.com client, disable "Allow local connections only". Since ssh.com will bind to all
addresses,onlyasinglesharecanbeconnected.
NowcreatetheloopbackinterfacewithIP10.1.1.1:
# System>Control Panel>Add Hardware # Yes, Hardware is already connected # Add a new
hardwaredevice(atbottom).
# Install the hardware that I manually select # Network adapters # Microsoft , Microsoft Loopback
Adapter.
ConfiguretheIPaddressofthefakedeviceto10.1.1.1mask255.255.255.0,nogateway.
advanced>WINS,EnableLMHostsLookupDisableNetBIOSoverTCP/IP.
#EnableClientforMicrosoftNetworks.#DisableFileandPrinterSharingforMicrosoftNetworks.
2/27/12 Uni Toolbo
20/45 cb.vu/unitoolbo.html
I HAD to reboot for this to work. Now connect to the smb share with \\10.1.1.1 and remote desktop to
10.1.1.1:3388.
Debug
Ifitisnotworking:
Aretheportsforwarded:netstatan?Lookat0.0.0.0:139or10.1.1.1:139
Doestelnet10.1.1.1139connect?
Youneedthecheckbox"Localportsacceptconnectionsfromotherhosts".
Is"FileandPrinterSharingforMicrosoftNetworks"disabledontheloopbackinterface?
ConnecttwoclientsbehindNAT
Suppose two clients are behind a NAT gateway and client cliadmin has to connect to client cliuser (the
destination),bothcanlogintothegatewithsshandarerunningLinuxwithsshd.Youdon'tneedrootaccess
anywhereaslongastheportsongateareabove1024.Weuse2022ongate.Alsosincethegateisused
locally,theoptionGatewayPortsisnotnecessary.
Onclientcliuser(fromdestinationtogate):
# ssh -R 2u22.JocaJhost.22 usegate # foWads cJ1eht 22 to gate.2u22
Onclientcliadmin(fromhosttogate):
# ssh -L 3u22.JocaJhost.2u22 adn1hgate # foWads cJ1eht 3u22 to gate.2u22
Nowtheadmincanconnectdirectlytotheclientcliuserwith:
# ssh -p 3u22 adn1hJocaJhost # JocaJ.3u22 -> gate.2u22 -> cJ1eht.22
ConnecttoVNCbehindNAT
SupposeaWindowsclientwithVNClisteningonport5900hastobeaccessedfrombehindNAT.Onclient
cliwintogate:
# ssh -R 159uu.JocaJhost.59uu usegate
Onclientcliadmin(fromhosttogate):
# ssh -L 59uu.JocaJhost.159uu adn1hgate
NowtheadmincanconnectdirectlytotheclientVNCwith:
# vhccohhect -d1spJay .u JocaJhost
Digamultihopsshtunnel
Suppose you can not reach a server directly with ssh, but only via multiple intermediate hosts (for example
because of routing issues). Sometimes it is still necessary to get a direct client server connection, for
exampletocopyfileswithscp,orforwardotherportslikesmborvnc.Onewaytodothisistochaintunnels
togethertoforwardaporttotheserveralongthehops.This"carrier"portonlyreachesitsfinaldestination
onthelastconnectiontotheserver.
Supposewewanttoforwardthesshportfromaclienttoaserverovertwohops.Oncethetunnelisbuild,it
ispossibletoconnecttotheserverdirectlyfromtheclient(andalsoaddanotherportforward).
Create tunne/ |n one she//
client>host1>host2>serveranddigtunnel5678
cJ1eht># ssh -L57B.JocaJhost.57B host1 # 57B 1s ah ab1tay pot fo the tuhheJ
host1># ssh -L57B.JocaJhost.57B host2 # cha1h 57B fon host1 to host2
host2># ssh -L57B.JocaJhost.22 seve # ehd the tuhheJ oh pot 22 oh the seve
Use tunne/ w|th an other she//
client>serverusingtunnel5678
# ssh -p 57B JocaJhost # cohhect d1ectJy fon cJ1eht to seve
# scp -P 57B nyf1Je JocaJhost.7tnp7 # o copy a f1Je d1ectJy us1hg the tuhheJ
# syhc -e 'ssh -p 57B' nyf1Je JocaJhost.7tnp7 # o syhc a f1Je d1ectJy to the seve
Autoconnectandkeepalivescript
I use variations of the following script to keep a machine reacheable over a reverse ssh tunnel. The
connectionisautomaticallyrebuiltifclosed.Youcanaddmultiple-Lor-Rtunnelsononeline.
#!7b1h7sh
CuhhANu="ssh -N -f -g -R 3u22.JocaJhost.22 coJ1hcb.vu"
pgep -f -x "$CuhhANu" > 7dev7huJJ 2>81 || $CuhhANu
ex1t u
1 * * * * coJ1h 7hone7coJ1h7potfoWad.sh # cohtab ehty {hee houJy}
6 VPN WI TH SSH
2/27/12 Uni Toolbo
21/45 cb.vu/unitoolbo.html
Asofversion4.3,OpenSSHcanusethetun/tapdevicetoencryptatunnel.ThisisverysimilartootherTLS
basedVPNsolutionslikeOpenVPN.OneadvantagewithSSHisthatthereisnoneedtoinstallandconfigure
additionalsoftware.AdditionallythetunnelusestheSSHauthenticationlikepresharedkeys.Thedrawback
is that the encapsulation is done over TCP which might result in poor performance on a slow link. Also the
tunnelisrelyingonasingle(fragile)TCPconnection.ThistechniqueisveryusefulforaquickIPbasedVPN
setup.ThereisnolimitationaswiththesingleTCPportforward,alllayer3/4protocolslikeICMP,TCP/UDP,
etc.areforwardedovertheVPN.Inanycase,thefollowingoptionsareneededinthesshd_conffile:
Pen1tRootLog1h yes
Pen1tTuhheJ yes
6.1SingleP2Pconnection
Hereweareconnectingtwohosts,hclientandhserverwithapeertopeertunnel.Theconnectionisstarted
lrom hc/|enttohserverandisdoneasroot.Thetunnelendpointsare10.0.1.1(server)and10.0.1.2(client)
andwecreateadevicetun5(thiscouldalsobeanothernumber).Theprocedureisverysimple:
ConnectwithSSHusingthetunneloptionw
ConfiguretheIPaddressesofthetunnel.Onceontheserverandonceontheclient.
Connecttotheserver
Connectionstartedontheclientandcommandsareexecutedontheserver.
Server |s on l|nux
cJ1># ssh -W5.5 oothseve
sv># 1fcohf1g tuh5 1u.u.1.1 hetnask 255.255.255.252 # Executed oh the seve sheJJ
Server |s on lreeBSD
cJ1># ssh -W5.5 oothseve
sv># 1fcohf1g tuh5 1u.u.1.1 1u.u.1.2 # Executed oh the seve sheJJ
Configuretheclient
Commandsexecutedontheclient:
cJ1># 1fcohf1g tuh5 1u.u.1.2 hetnask 255.255.255.252 # CJ1eht 1s oh L1hux
cJ1># 1fcohf1g tuh5 1u.u.1.2 1u.u.1.1 # CJ1eht 1s oh FeeB5u
Thetwohostsarenowconnectedandcantransparentlycommunicatewithanylayer3/4protocolusingthe
tunnelIPaddresses.
6.2Connecttwonetworks
Inadditiontothep2psetupabove,itismoreusefultoconnecttwoprivatenetworkswithanSSHVPNusing
two gates. Suppose for the example, netA is 192.168.51.0/24 and netB 192.168.16.0/24. The procedure is
similarasabove,weonlyneedtoaddtherouting.NATmustbeactivatedontheprivateinterfaceonlyifthe
gatesarenotthesameasthedefaultgatewayoftheirnetwork.
192.168.51.0/24(netA)|gateA<>gateB|192.168.16.0/24(netB)
ConnectwithSSHusingthetunneloptionw.
ConfiguretheIPaddressesofthetunnel.Onceontheserverandonceontheclient.
Addtheroutingforthetwonetworks.
Ifnecessary,activateNATontheprivateinterfaceofthegate.
Thesetupisstarted lrom gateA |n netA.
ConnectfromgateAtogateB
ConnectionisstartedfromgateAandcommandsareexecutedongateB.
gateB |s on l|nux
gateA># ssh -W5.5 ootgateB
gateB># 1fcohf1g tuh5 1u.u.1.1 hetnask 255.255.255.252 # Executed oh the gateB sheJJ
gateB># oute add -het 192.1B.51.u hetnask 255.255.255.u dev tuh5
gateB># echo 1 > 7poc7sys7het71pv471pfoWad # uhJy heeded 1f hot defauJt gW
gateB># 1ptabJes -t hat -A Pu5TRuUTTNu -o ethu - hA5UERAuE
gateB |s on lreeBSD
gateA># ssh -W5.5 ootgateB # Ceates the tuh5 dev1ces
gateB># 1fcohf1g tuh5 1u.u.1.1 1u.u.1.2 # Executed oh the gateB sheJJ
gateB># oute add 192.1B.51.u724 1u.u.1.2
gateB># sysctJ het.1het.1p.foWad1hg=1 # uhJy heeded 1f hot defauJt gW
gateB># hatd -s -n -u -dyhan1c -h fxpu # see NAT
2/27/12 Uni Toolbo
22/45 cb.vu/unitoolbo.html
gateA># sysctJ het.1het.1p.fW.ehabJe=1
ConfiguregateA
CommandsexecutedongateA:
gateA |s on l|nux
gateA># 1fcohf1g tuh5 1u.u.1.2 hetnask 255.255.255.252
gateA># oute add -het 192.1B.1.u hetnask 255.255.255.u dev tuh5
gateA># echo 1 > 7poc7sys7het71pv471pfoWad
gateA># 1ptabJes -t hat -A Pu5TRuUTTNu -o ethu - hA5UERAuE
gateA |s on lreeBSD
gateA># 1fcohf1g tuh5 1u.u.1.2 1u.u.1.1
gateA># oute add 192.1B.1.u724 1u.u.1.2
gateA># sysctJ het.1het.1p.foWad1hg=1
gateA># hatd -s -n -u -dyhan1c -h fxpu # see NAT
gateA># sysctJ het.1het.1p.fW.ehabJe=1
The two private networks are now transparently connected via the SSH VPN. The IP forward and NAT
settingsareonlynecessaryifthegatesarenotthedefaultgateways.Inthiscasetheclientswouldnotknow
wheretoforwardtheresponse,andnatmustbeactivated.
7 RSYNC
Rsynccanalmostcompletelyreplacecpandscp,furthermoreinterruptedtransfersareefficientlyrestarted.
A trailing slash (and the absence thereof) has different meanings, the man page is good... Here some
examples:
Copythedirectorieswithfullcontent:
# syhc -a 7hone7coJ1h7 7backup7coJ1h7 # "ach1ve" node. e.g keep the sane
# syhc -a 7va7 7vabak7
# syhc -aR --deJete-du1hg 7hone7use7 7backup7 # use eJat1ve {see beJoW}
Same as before but over the network and with compression. Rsync uses SSH for the transport per default
andwillusethesshkeyiftheyareset.Use":"aswithSCP.Atypicalremotecopy:
# syhc -ax5Rzv 7hone7use7 useseve.7backup7use7 # Copy to enote
# syhc -a 'useseve.hy` uocunehts' hy` uocunehts # uote ANu escape spaces fo the enote sheJJ
Exclude any directory tmp within /home/user/ and keep the relative folders hierarchy, that is the remote
directorywillhavethestructure/backup/home/user/.Thisistypicallyusedforbackups.
# syhc -azR --excJude=tnp7 7hone7use7 useseve.7backup7
Useport20022forthesshconnection:
# syhc -az -e 'ssh -p 2uu22' 7hone7coJ1h7 useseve.7backup7coJ1h7
Usingthersyncdaemon(usedwith"::")ismuchfaster,butnotencryptedoverssh.Thelocationof/backupis
defined by the configuration in /etc/rsyncd.conf. The variable RSYNC_PASSWORD can be set to avoid the
needtoenterthepasswordmanually.
# syhc -ax5Rz 7hone7 usehosthane..noduJe7backup7
# syhc -ax5Rz usehosthane..noduJe7backup7 7hone7 # To copy back
Someimportantoptions:
-a, --ach1vearchivemodesameasrlptgoD(noH)
-, --ecus1verecurseintodirectories
-R, --eJat1veuserelativepathnames
-h, --had-J1hkspreservehardlinks
-5, --spasehandlesparsefilesefficiently
-x, --ohe-f1Je-systendon'tcrossfilesystemboundaries
--excJude=PATTERNexcludefilesmatchingPATTERN
--deJete-du1hgreceiverdeletesduringxfer,notbefore
--deJete-aftereceiverdeletesaftertransfer,notbefore
7.1RsynconWindows
Rsync is available for Windows through cygwin or as standalone packaged in
cwrsync
http://sourcef orge.net/projects/sereds
. This is very convenient for automated backups. Install one of them (not
both)andaddthepathtotheWindowssystemvariables:#ControlPanel>System>tabAdvanced,button
Environment Variables. Edit the "Path" system variable and add the full path to the installed rsync, e.g.
C:\Program Files\cwRsync\bin or C:\cygwin\bin. This way the commands syhc and ssh are available in a
Windowscommandshell.
2/27/12 Uni Toolbo
23/45 cb.vu/unitoolbo.html
Publickeyauthentication
Rsync is automatically tunneled over SSH and thus uses the SSH authentication on the server. Automatic
backups have to avoid a user interaction, for this the SSH public key authentication can be used and the
rsynccommandwillrunwithoutapassword.
AllthefollowingcommandsareexecutedwithinaWindowsconsole.Inaconsole(Start>Run>cmd)create
and upload the key as described in SSH, change "user" and "server" as appropriate. If the file
authorized_keys2doesnotexistyet,simplycopyid_dsa.pubtoauthorized_keys2anduploadit.
# ssh-keygeh -t dsa -N '' # Ceates a pubJ1c ahd a p1vate key
# syhc useseve..ssh7autho1zedkeys2 . # Copy the f1Je JocaJJy fon the seve
# cat 1ddsa.pub >> autho1zedkeys2 # u use ah ed1to to add the key
# syhc autho1zedkeys2 useseve..ssh7 # Copy the f1Je back to the seve
# deJ autho1zedkeys2 # Renove the JocaJ copy
Nowtestitwith(inoneline):
syhc -v "7cygd1ve7c7uocunehts ahd 5ett1hgs7ZU5ERNAhEZ7hy uocunehts7" `
'useseve.hy` uocunehts7'
Automaticbackup
Useabatchfiletoautomatethebackupandaddthefileinthescheduledtasks(Programs>Accessories>
SystemTools>ScheduledTasks).Forexamplecreatethefilebackup.batandreplaceuser@server.
EChu uFF
REh syhc the d1ectoy hy uocunehts
5ETLuCAL
5ET CWR5YNChuhE=C.`PRuuRAh FTLE5`CWR5YNC
5ET CYuWTN=hohtsec
5ET CWuLuPATh=ZPAThZ
REh uhconneht the hext J1he Wheh us1hg cygW1h
5ET PATh=ZCWR5YNChuhEZ`BTNZPAThZ
echo Pess CohtoJ-C to abot
syhc -av "7cygd1ve7c7uocunehts ahd 5ett1hgs7ZU5ERNAhEZ7hy uocunehts7" `
'useseve.hy` uocunehts7'
pause
8 SUDO
Sudoisastandardwaytogiveuserssomeadministrativerightswithoutgivingouttherootpassword.Sudois
veryusefulinamultiuserenvironmentwithamixofserverandworkstations.Simplycallthecommandwith
sudo:
# sudo 7etc71h1t.d7dhcpd estat # Ruh the c sc1pt as oot
# sudo -u sysadn1h Whoan1 # Ruh cnd as ah othe use
8.1Configuration
Sudo is configured in 7etc7sudoes and must only be edited with v1sudo. The basic syntax is (the lists are
commaseparated):
use hosts = {uhas} connahds # Th 7etc7sudoes
usesoneormoreusersor%group(like%wheel)togaintherights
hostslistofhosts(orALL)
uhaslistofusers(orALL)thatthecommandrulecanberunas.Itisenclosedin()!
connahdslistofcommands(orALL)thatwillberunasrootoras(runas)
Additionallythosekeywordscanbedefinedasalias,theyarecalledUser_Alias,Host_Alias,Runas_Aliasand
Cmnd_Alias.Thisisusefulforlargersetups.Hereasudoersexample:
# cat 7etc7sudoes
# host aJ1ases ae subhets o hosthanes.
hostAJ1as uhZ = 212.11B.B1.4u72B
hostAJ1as uE5KTuP = Wok1, Wok2
# Use aJ1ases ae a J1st of uses Wh1ch cah have the sane 1ghts
UseAJ1as AuhTN5 = coJ1h, Juca, adn1h
UseAJ1as uEvEL = oe, ack, uJ1a
RuhasAJ1as uBA = oacJe,pgsqJ
# Connahd aJ1ases def1he the fuJJ path of a J1st of connahds
CnhdAJ1as 5Y5TEh = 7sb1h7eboot,7us7b1h7k1JJ,7sb1h7haJt,7sb1h7shutdoWh,7etc71h1t.d7
CnhdAJ1as PW = 7us7b1h7passWd |A-z*, !7us7b1h7passWd oot # Not oot pWd!
CnhdAJ1as uEBUu = 7us7sb1h7tcpdunp,7us7b1h7W1eshak,7us7b1h7hnap
# The actuaJ uJes
oot,AuhTN5 ALL = {ALL} NuPA55Wu. ALL # AuhTN5 cah do ahyth1hg W7o a passWod.
uEvEL uE5KTuP = {ALL} NuPA55Wu. ALL # ueveJopes have fuJJ 1ght oh desktops
uEvEL uhZ = {ALL} NuPA55Wu. uEBUu # ueveJopes cah debug the uhZ seves.
# Use sysadn1h cah ness aouhd 1h the uhZ seves W1th sone connahds.
2/27/12 Uni Toolbo
24/45 cb.vu/unitoolbo.html
sysadn1h uhZ = {ALL} NuPA55Wu. 5Y5TEh,PW,uEBUu
sysadn1h ALL,!uhZ = {ALL} NuPA55Wu. ALL # Cah do ahyth1hg outs1de the uhZ.
Zdba ALL = {uBA} ALL # uoup dba cah uh as database use.
# ahyohe cah nouht7uhnouht a cd-on oh the desktop nach1hes
ALL uE5KTuP = NuPA55Wu. 7sb1h7nouht 7cdon,7sb1h7unouht 7cdon
9 ENCRYPT FI LES
9.1OpenSSL
Asinglefile
Encryptanddecrypt:
# opehssJ aes-12B-cbc -saJt -1h f1Je -out f1Je.aes
# opehssJ aes-12B-cbc -d -saJt -1h f1Je.aes -out f1Je
Notethatthefilecanofcoursebeatararchive.
tarandencryptawholedirectory
# ta -cf - d1ectoy | opehssJ aes-12B-cbc -saJt -out d1ectoy.ta.aes # Ehcypt
# opehssJ aes-12B-cbc -d -saJt -1h d1ectoy.ta.aes | ta -x -f - # uecypt
tarzipandencryptawholedirectory
# ta -zcf - d1ectoy | opehssJ aes-12B-cbc -saJt -out d1ectoy.ta.gz.aes # Ehcypt
# opehssJ aes-12B-cbc -d -saJt -1h d1ectoy.ta.gz.aes | ta -xz -f - # uecypt
Usekmysecretpasswordafteraes128cbctoavoidtheinteractivepasswordrequest.Howevernote
thatthisishighlyinsecure.
Useaes256cbcinsteadofaes128cbctogetevenstrongerencryption.ThisusesalsomoreCPU.
9.2GPG
GnuPG is well known to encrypt and sign emails or any data. Furthermore gpg and also provides an
advancedkeymanagementsystem.Thissectiononlycoversfilesencryption,notemailusage,signingorthe
WebOfTrust.
The simplest encryption is with a symmetric cipher. In this case the file is encrypted with a password and
anyonewhoknowsthepasswordcandecryptit,thusthekeysarenotneeded.Gpgaddsanextention".gpg"
totheencryptedfilenames.
# gpg -c f1Je # Ehcypt f1Je W1th passWod
# gpg f1Je.gpg # uecypt f1Je {opt1ohaJJy -o othef1Je}
Usingkeys
For more details see GPG Quick Start
http://www.madboa.com/geek/gpgquickstart
and GPG/PGP
Basics
http://aplawrence.com/Basics/gpg.html
andthegnupgdocumentation
http://gnupg.org/documentation
amongothers.
Theprivateandpublickeysaretheheartofasymmetriccryptography.Whatisimportanttoremember:
Yourpublickeyisusedbyotherstoencryptfilesthatonlyyouasthereceivercandecrypt(noteven
theonewhoencryptedthefilecandecryptit).Thepublickeyisthusmeanttobedistributed.
Yourprivatekeyisencryptedwithyourpassphraseandisusedtodecryptfileswhichwereencrypted
withyourpublickey.Theprivatekeymustbekeptsecure.Alsoifthekeyorpassphraseislost,soare
allthefilesencryptedwithyourpublickey.
Thekeyfilesarecalledkeyringsastheycancontainmorethanonekey.
First generate a key pair. The defaults are fine, however you will have to enter at least your full name and
email and optionally a comment. The comment is useful to create more than one key with the same name
andemail.Alsoyoushouldusea"passphrase",notasimplepassword.
# gpg --geh-key # Th1s cah take a Johg t1ne
Thekeysarestoredin~/.gnupg/onUnix,onWindowstheyaretypicallystoredin
C:/DocumentsandSettings/%USERNAME%/ApplicationData/gnupg/.
~7.ghupg7pub1hg.gpg # Cohta1hs you pubJ1c keys ahd aJJ othes 1npoted
~7.ghupg7sec1hg.gpg # Cah cohta1h noe thah ohe p1vate key
Shortreminderonmostusedoptions:
eencryptdata
ddecryptdata
rNAMEencryptforrecipientNAME(or'FullName'or'email@domain')
acreateasciiarmoredoutputofakey
2/27/12 Uni Toolbo
25/45 cb.vu/unitoolbo.html
ouseasoutputfile
The examples use 'Your Name' and 'Alice' as the keys are referred to by the email or full name or partial
name.ForexampleIcanuse'Colin'or'c@cb.vu'formykey[ColinBarschel(cb.vu)<c@cb.vu>].
Encryptforpersonaluseonly
Noneedtoexport/importanykeyforthis.Youhavebothalready.
# gpg -e - 'You Nane' f1Je # Ehcypt W1th you pubJ1c key
# gpg -o f1Je -d f1Je.gpg # uecypt. Use -o o 1t goes to stdout
EncryptDecryptwithkeys
First you need to export your public key for someone else to use it. And you need to import the public say
from Alice to encrypt a file for her. You can either handle the keys in simple ascii files or use a public key
server.
For example Alice export her public key and you import it, you can then encrypt a file for her. That is only
Alicewillbeabletodecryptit.
# gpg -a -o aJ1cekey.asc --expot 'AJ1ce' # AJ1ce expoted he key 1h asc11 f1Je.
# gpg --sehd-keys --keyseve subkeys.pgp.het KEYTu # AJ1ce put he key oh a seve.
# gpg --1npot aJ1cekey.asc # You 1npot he key 1hto you pub1hg.
# gpg --seach-keys --keyseve subkeys.pgp.het 'AJ1ce' # o get he key fon a seve.
Oncethekeysareimporteditisveryeasytoencryptordecryptafile:
# gpg -e - 'AJ1ce' f1Je # Ehcypt the f1Je fo AJ1ce.
# gpg -d f1Je.gpg -o f1Je # uecypt a f1Je ehcypted by AJ1ce fo you.
Keyadministration
# gpg --J1st-keys # J1st pubJ1c keys ahd see the KEYTu5
The KEYTu foJJoWs the '7' e.g. fo. pub 1u24u7u12B77CE the KEYTu 1s u12B77CE
# gpg --geh-evoke 'You Nane' # geheate evocat1oh cet1f1cate
# gpg --J1st-secet-keys # J1st p1vate keys
# gpg --deJete-keys NAhE # deJete a pubJ1c key fon JocaJ key 1hg
# gpg --deJete-secet-key NAhE # deJete a secet key fon JocaJ key 1hg
# gpg --f1hgep1ht KEYTu # 5hoW the f1hgep1ht of the key
# gpg --ed1t-key KEYTu # Ed1t key {e.g s1gh o add7deJ ena1J}
10 ENCRYPT PARTI TI ONS
LinuxwithLUKS|Linuxdmcryptonly|FreeBSDGELI|FBSDpwdonly|OSXimage
Thereare(many)otheralternativemethodstoencryptdisks,IonlyshowherethemethodsIknowanduse.
Keep in mind that the security is only good as long the OS has not been tempered with. An intruder could
easily record the password from the keyboard events. Furthermore the data is freely accessible when the
partitionisattachedandwillnotpreventanintrudertohaveaccesstoitinthisstate.
10.1Linux
Those instructions use the Linux dn-cypt (devicemapper) facility available on the 2.6 kernel. In this
example,letsencryptthepartition7dev7sdc1,itcouldbehoweveranyotherpartitionordisk,orUSBorafile
based partition created with Josetup. In this case we would use 7dev7Joopu. See file image partition. The
devicemapperuseslabelstoidentifyapartition.Weusesdc1inthisexample,butitcouldbeanystring.
dmcryptwithLUKS
LUKS with dmcrypt has better encryption and makes it possible to have multiple passphrase for the same
partitionortochangethepasswordeasily.TotestifLUKSisavailable,simplytype# cyptsetup --heJp,if
nothingaboutLUKSshowsup,usetheinstructionsbelowWithoutLUKS.Firstcreateapartitionifnecessary:
fd1sk 7dev7sdc.
Create encrypted part|t|on
# dd 1f=7dev7uahdon of=7dev7sdc1 # upt1ohaJ. Fo paaho1ds ohJy {takes days}
# cyptsetup -y JuksFonat 7dev7sdc1 # Th1s destoys ahy data oh sdc1
# cyptsetup Juksupeh 7dev7sdc1 sdc1
# nkfs.ext3 7dev7nappe7sdc1 # ceate ext3 f1Je systen
# nouht -t ext3 7dev7nappe7sdc1 7nht
# unouht 7nht
# cyptsetup JuksCJose sdc1 # uetach the ehcypted pat1t1oh
Attach
# cyptsetup Juksupeh 7dev7sdc1 sdc1
# nouht -t ext3 7dev7nappe7sdc1 7nht
Detach
2/27/12 Uni Toolbo
26/45 cb.vu/unitoolbo.html
# unouht 7nht
# cyptsetup JuksCJose sdc1
dmcryptwithoutLUKS
# cyptsetup -y ceate sdc1 7dev7sdc1 # o ahy othe pat1t1oh J1ke 7dev7Joopu
# dnsetup Js # check 1t, W1JJ d1spJay. sdc1 {254, u}
# nkfs.ext3 7dev7nappe7sdc1 # Th1s 1s dohe ohJy the f1st t1ne!
# nouht -t ext3 7dev7nappe7sdc1 7nht
# unouht 7nht7
# cyptsetup enove sdc1 # uetach the ehcypted pat1t1oh
Do exactly the same (without the mkfs part!) to reattach the partition. If the password is not correct, the
mount command will fail. In this case simply remove the map sdc1 (cyptsetup enove sdc1) and create it
again.
10.2FreeBSD
ThetwopopularFreeBSDdiskencryptionmodulesaregbdeandgeJ1.Inowusegelibecauseitisfasterand
also uses the crypto device for hardware acceleration. See The FreeBSD handbook Chapter
18.6
http://www.f reebsd.org/handbook/disksencry pting.html
forallthedetails.Thegelimodulemustbeloadedorcompiledinto
thekernel:
opt1ohs uEuhELT
dev1ce cypto # o as noduJe.
# echo 'geoneJ1Joad="YE5"' >> 7boot7Joade.cohf # o do. kJdJoad geoneJ1
Usepasswordandkey
Iusethosesettingsforatypicaldiskencryption,itusesapassphraseANDakeytoencryptthemasterkey.
Thatisyouneedboththepasswordandthegeneratedkey7oot7ad1.keytoattachthepartition.Themaster
keyisstoredinsidethepartitionandisnotvisible.SeebelowfortypicalUSBorfilebasedimage.
Create encrypted part|t|on
# dd 1f=7dev7ahdon of=7oot7ad1.key bs=4 couht=1 # th1s key ehcypts the nate key
# geJ1 1h1t -s 4u9 -K 7oot7ad1.key 7dev7ad1 # -s B192 1s aJso uK fo d1sks
# geJ1 attach -k 7oot7ad1.key 7dev7ad1 # uu nake a backup of 7oot7ad1.key
# dd 1f=7dev7ahdon of=7dev7ad1.eJ1 bs=1n # upt1ohaJ ahd takes a Johg t1ne
# heWfs 7dev7ad1.eJ1 # Ceate f1Je systen
# nouht 7dev7ad1.eJ1 7nht
Attach
# geJ1 attach -k 7oot7ad1.key 7dev7ad1
# fsck -hy -t ffs 7dev7ad1.eJ1 # Th doubt check the f1Je systen
# nouht 7dev7ad1.eJ1 7nht
Detach
Thedetachprocedureisdoneautomaticallyonshutdown.
# unouht 7nht
# geJ1 detach 7dev7ad1.eJ1
/etc/lstab
The encrypted partition can be configured to be mounted with /etc/fstab. The password will be prompted
whenbooting.Thefollowingsettingsarerequiredforthisexample:
# gep geJ1 7etc7c.cohf
geJ1dev1ces="ad1"
geJ1ad1fJags="-k 7oot7ad1.key"
# gep geJ1 7etc7fstab
7dev7ad1.eJ1 7hone7p1vate ufs W u u
Usepasswordonly
It is more convenient to encrypt a USB stick or file based image with a passphrase only and no key. In this
case it is not necessary to carry the additional key file around. The procedure is very much the same as
above,simplywithoutthekeyfile.Let'sencryptafilebasedimage7cyptedf1Jeof1GB.
# dd 1f=7dev7zeo of=7cyptedf1Je bs=1h couht=1uuu # 1 uB f1Je
# ndcohf1g -at vhode -f 7cyptedf1Je
# geJ1 1h1t 7dev7ndu # ehcypts W1th passWod ohJy
# geJ1 attach 7dev7ndu
# heWfs -U -n u 7dev7ndu.eJ1
# nouht 7dev7ndu.eJ1 7nht
# unouht 7dev7ndu.eJ1
# geJ1 detach ndu.eJ1
Itisnowpossibletomountthisimageonanothersystemwiththepasswordonly.
# ndcohf1g -at vhode -f 7cyptedf1Je
# geJ1 attach 7dev7ndu
2/27/12 Uni Toolbo
27/45 cb.vu/unitoolbo.html
# nouht 7dev7ndu.eJ1 7nht
10.1OSXEncryptedDiskImage
Don'tknowbycommandlineonly.SeeOSXEncryptedDisk
Image
https://wiki.thay er.dartmouth.edu/display /computing/Creating+a+Mac+OS+X+Encry pted+Disk+Image
andApple
support
http://support.apple.com/kb/ht1578
11 SSL CERTI FI CATES
SocalledSSL/TLScertificatesarecryptographicpublickeycertificatesandarecomposedofapublicanda
privatekey.Thecertificatesareusedtoauthenticatetheendpointsandencryptthedata.Theyareusedfor
exampleonawebserver(https)ormailserver(imaps).
11.1Procedure
We need a certificate authority to sign our certificate. This step is usually provided by a vendor like
Thawte,Verisign,etc.,howeverwecanalsocreateourown.
Create a certificate signing request. This request is like an unsigned certificate (the public part) and
already contains all necessary information. The certificate request is normally sent to the authority
vendorforsigning.Thisstepalsocreatestheprivatekeyonthelocalmachine.
Signthecertificatewiththecertificateauthority.
Ifnecessaryjointhecertificateandthekeyinasinglefiletobeusedbytheapplication(webserver,
mailserveretc.).
11.2ConfigureOpenSSL
We use /usr/local/certs as directory for this example check or edit /etc/ssl/openssl.cnf accordingly to your
settingssoyouknowwherethefileswillbecreated.Herearetherelevantpartofopenssl.cnf:
| CAdefauJt
d1 = 7us7JocaJ7cets7CA # Whee eveyth1hg 1s kept
cets = $d17cets # Whee the 1ssued cets ae kept
cJd1 = $d17cJ # Whee the 1ssued cJ ae kept
database = $d171hdex.txt # database 1hdex f1Je.
Makesurethedirectoriesexistorcreatethem
# nkd1 -p 7us7JocaJ7cets7CA
# cd 7us7JocaJ7cets7CA
# nkd1 cets cJ heWcets p1vate
# echo "u1" > se1aJ # uhJy 1f se1aJ does hot ex1st
# touch 1hdex.txt
Ifyouintendtogetasignedcertificatefromavendor,youonlyneedacertificatesigningrequest(CSR).This
CSRwillthenbesignedbythevendorforalimitedtime(e.g.1year).
11.3Createacertificateauthority
If you do not have a certificate authority from a vendor, you'll have to create your own. This step is not
necessaryifoneintendtouseavendortosigntherequest.Tomakeacertificateauthority(CA):
# opehssJ eq -heW -x5u9 -days 73u -cohf1g 7etc7ssJ7opehssJ.chf `
-keyout CA7p1vate7cakey.pen -out CA7cacet.pen
11.4Createacertificatesigningrequest
Tomakeanewcertificate(formailserverorwebserverforexample),firstcreatearequestcertificatewithits
privatekey.Ifyourapplicationdonotsupportencryptedprivatekey(forexampleUWIMAPdoesnot),then
disableencryptionwith-hodes.
# opehssJ eq -heW -keyout heWkey.pen -out heWeq.pen `
-cohf1g 7etc7ssJ7opehssJ.chf
# opehssJ eq -hodes -heW -keyout heWkey.pen -out heWeq.pen `
-cohf1g 7etc7ssJ7opehssJ.chf # No ehcypt1oh fo the key
KeepthiscreatedCSR(heWeq.pen)asitcanbesignedagainatthenextrenewal,thesignatureonltwilllimit
thevalidityofthecertificate.ThisprocessalsocreatedtheprivatekeyheWkey.pen.
11.5Signthecertificate
ThecertificaterequesthastobesignedbytheCAtobevalid,thisstepisusuallydonebythevendor.Note.
rep/ace "servername" w|th the name ol your server |n the next commands.
# cat heWeq.pen heWkey.pen > heW.pen
# opehssJ ca -poJ1cy poJ1cyahyth1hg -out sevehanecet.pen `
2/27/12 Uni Toolbo
28/45 cb.vu/unitoolbo.html
-cohf1g 7etc7ssJ7opehssJ.chf -1hf1Jes heW.pen
# nv heWkey.pen sevehanekey.pen
Nowservernamekey.pemistheprivatekeyandservernamecert.pemistheservercertificate.
11.6Createunitedcertificate
TheIMAPserverwantstohavebothprivatekeyandservercertificateinthesamefile.Andingeneral,thisis
also easier to handle, but the file has to be kept securely!. Apache also can deal with it well. Create a file
servername.pemcontainingboththecertificateandkey.
Open the private key (servernamekey.pem) with a text editor and copy the private key into the
"servername.pem"file.
Dothesamewiththeservercertificate(servernamecert.pem).
Thefinalservername.pemfileshouldlooklikethis:
-----BEuTN R5A PRTvATE KEY-----
hTTCXTBAAKBguutWy+o7XZ7|...qK5LqgT3c9dUfcR+Wu5saedEuuqBR
-----ENu R5A PRTvATE KEY-----
-----BEuTN CERTTFTCATE-----
hTTERzCCA7CgAWTBAgTBBuANB|...1u9WuBAFAuCBxTELhAkuA1UEBhhCREUx
-----ENu CERTTFTCATE-----
Whatwehavenowinthedirectory/usr/local/certs/:
CA/private/cakey.pem{CA server pr|vate key)
CA/cacert.pem{CA server pub/|c key)
certs/servernamekey.pem{server pr|vate key)
certs/servernamecert.pem{server s|gned cert|l|cate)
certs/servername.pem{server cert|l|cate w|th pr|vate key)
Keeptheprivatekeysecure!
11.7Viewcertificateinformation
Toviewthecertificateinformationsimplydo:
# opehssJ x5u9 -text -1h sevehanecet.pen # v1eW the cet1f1cate 1hfo
# opehssJ eq -hoout -text -1h seve.cs # v1eW the equest 1hfo
# opehssJ scJ1eht -cohhect cb.vu.443 # Check a Web seve cet1f1cate
12 CVS
Serversetup|CVStest|SSHtunneling|CVSusage
12.1Serversetup
InitiatetheCVS
Decidewherethemainrepositorywillrestandcreatearootcvs.Forexample/usr/local/cvs(asroot):
# nkd1 -p 7us7JocaJ7cvs
# setehv Cv5RuuT 7us7JocaJ7cvs # 5et Cv5RuuT to the heW Jocat1oh {JocaJ}
# cvs 1h1t # Ceates aJJ 1htehaJ Cv5 cohf1g f1Jes
# cd 7oot
# cvs checkout Cv5RuuT # Checkout the cohf1g f1Jes to nod1fy then
# cd Cv5RuuT
ed1t cohf1g { f1he as 1t 1s}
# cvs conn1t cohf1g
cat >> W1tes # Ceate a W1tes f1Je {opt1ohaJJy aJso eades}
coJ1h
^u # Use |CohtoJ|u to qu1t the ed1t
# cvs add W1tes # Add the f1Je W1tes 1hto the epos1toy
# cvs ed1t checkoutJ1st
# cat >> checkoutJ1st
W1tes
^u # Use |CohtoJ|u to qu1t the ed1t
# cvs conn1t # Conn1t aJJ the cohf1guat1oh chahges
Add a readers file if you want to differentiate read and write permissions Note. Do not (ever) edit files
directly into the main cvs, but rather checkout the file, modify it and check it in. We did this with the file
writerstodefinethewriteaccess.
There are three popular ways to access the CVS at this point. The first two don't need any further
configuration.SeetheexamplesonCVSROOTbelowforhowtousethem:
Direct local access to the file system. The user(s) need sufficient file permission to access the CS
2/27/12 Uni Toolbo
29/45 cb.vu/unitoolbo.html
directlyandthereisnofurtherauthenticationinadditiontotheOSlogin.Howeverthisisonlyusefulif
therepositoryislocal.
Remote access with ssh with the ext protocol. Any use with an ssh shell account and read/write
permissions on the CVS server can access the CVS directly with ext over ssh without any additional
tunnel. There is no server process running on the CVS for this to work. The ssh login does the
authentication.
Remoteaccesswithpserver(defaultport:2401/tcp).Thisisthepreferreduseforlargeruserbaseas
the users are authenticated by the CVS pserver with a dedicated password database, there is
thereforenoneedforlocalusersaccounts.Thissetupisexplainedbelow.
Networksetupwithinetd
TheCVScanberunlocallyonlyifanetworkaccessisnotneeded.Foraremoteaccess,thedaemoninetd
canstartthepserverwiththefollowinglinein/etc/inetd.conf(/etc/xinetd.d/cvsonSuSE):
cvspseve stean tcp hoWa1t cvs 7us7b1h7cvs cvs `
--aJJoW-oot=7us7JocaJ7cvs pseve
ItisagoodideatoblockthecvsportfromtheInternetwiththefirewallanduseansshtunneltoaccessthe
repositoryremotely.
Separateauthentication
ItispossibletohavecvsuserswhicharenotpartoftheOS(nolocalusers).Thisisactuallyprobablywanted
toofromthesecuritypointofview.Simplyaddafilenamedpasswd(intheCVSROOTdirectory)containing
theusersloginandpasswordinthecryptformat.Thisiscanbedonewiththeapachehtpasswdtool.
Note.ThispasswdfileistheonlyfilewhichhastobeediteddirectlyintheCVSROOTdirectory.Alsoitwon't
becheckedout.Moreinfowithhtpasswdhelp
# htpassWd -cb passWd use1 passWod1 # -c ceates the f1Je
# htpassWd -b passWd use2 passWod2
Nowadd.cvsattheendofeachlinetotellthecvsservertochangetheusertocvs(orwhateveryourcvs
serverisrunningunder).Itlookslikethis:
# cat passWd
use1.xsFhU22uBFuo.cvs
use2.vhefJushhvToh.cvs
12.2Testit
Testtheloginasnormaluser(forexamplehereme)
# cvs -d .pseve.coJ1h192.1B.5u.254.7us7JocaJ7cvs Jog1h
Logg1hg 1h to .pseve.coJ1h192.1B.5u.254.24u17us7JocaJ7cvs
Cv5 passWod.
CVSROOTvariable
Thisisanenvironmentvariableusedtospecifythelocationoftherepositorywe'redoingoperationson.For
localuse,itcanbejustsettothedirectoryoftherepository.Foruseoverthenetwork,thetransportprotocol
must be specified. Set the CVSROOT variable with setehv Cv5RuuT st1hg on a csh, tcsh shell, or with
expot Cv5RuuT=st1hgonash,bashshell.
# setehv Cv5RuuT .pseve.<usehane><host>.7cvsd1ectoy
Foreample:
# setehv Cv5RuuT 7us7JocaJ7cvs # Used JocaJJy ohJy
# setehv Cv5RuuT .JocaJ.7us7JocaJ7cvs # 5ane as above
# setehv Cv5RuuT .ext.usecvsseve.7us7JocaJ7cvs # u1ect access W1th 55h
# setehv Cv5R5h ssh # fo the ext access
# setehv Cv5RuuT .pseve.usecvsseve.254.7us7JocaJ7cvs # hetWok W1th pseve
When the login succeeded one can import a new project into the repository: cd into your project root
directory
cvs 1npot <noduJe hane> <vehdo tag> <1h1t1aJ tag>
cvs -d .pseve.coJ1h192.1B.5u.254.7us7JocaJ7cvs 1npot hyPoect hyConpahy 5TART
WhereMyProjectisthenameofthenewprojectintherepository(usedlatertocheckout).Cvswillimportthe
currentdirectorycontentintothenewproject.
Tocheckout:
# cvs -d .pseve.coJ1h192.1B.5u.254.7us7JocaJ7cvs checkout hyPoect
or
# setehv Cv5RuuT .pseve.coJ1h192.1B.5u.254.7us7JocaJ7cvs
# cvs checkout hyPoect
12.3SSHtunnelingforCVS
2/27/12 Uni Toolbo
30/45 cb.vu/unitoolbo.html
We need 2 shells for this. On the first shell we connect to the cvs server with ssh and portforward the cvs
connection.Onthesecondshellweusethecvsnormallyasifitwhererunninglocally.
onshell1:
# ssh -L24u1.JocaJhost.24u1 coJ1hcvsseve # Cohhect d1ectJy to the Cv5 seve. u.
# ssh -L24u1.cvsseve.24u1 coJ1hgateWay # Use a gateWay to each the Cv5
onshell2:
# setehv Cv5RuuT .pseve.coJ1hJocaJhost.7us7JocaJ7cvs
# cvs Jog1h
Logg1hg 1h to .pseve.coJ1hJocaJhost.24u17us7JocaJ7cvs
Cv5 passWod.
# cvs checkout hyPoect7sc
12.4CVScommandsandusage
Import
Theimportcommandisusedtoaddawholedirectory,itmustberunfromwithinthedirectorytobeimported.
Saythedirectory/devel/containsallfilesandsubdirectoriestobeimported.ThedirectorynameontheCVS
(themodule)willbecalled"myapp".
# cvs 1npot |opt1ohs d1ectoy-hane vehdo-tag eJease-tag
# cd 7deveJ # hust be 1hs1de the poect to 1npot 1t
# cvs 1npot nyapp Conpahy R1u # ReJease tag cah be ahyth1hg 1h ohe Wod
Afterawhileanewdirectory"/devel/tools/"wasaddedandithastobeimportedtoo.
# cd 7deveJ7tooJs
# cvs 1npot nyapp7tooJs Conpahy R1u
Checkoutupdateaddcommit
# cvs co nyapp7tooJs # W1JJ ohJy checkout the d1ectoy tooJs
# cvs co - R11 nyapp # Checkout nyapp at eJease R11 {1s st1cky}
# cvs -q -d update -P # A typ1caJ Cv5 update
# cvs update -A # Reset ahy st1cky tag {o date, opt1oh}
# cvs add heWf1Je # Add a heW f1Je
# cvs add -kb heWf1Je # Add a heW b1hay f1Je
# cvs conn1t f1Je1 f1Je2 # Conn1t the tWo f1Jes ohJy
# cvs conn1t -n "nessage" # Conn1t aJJ chahges dohe W1th a nessage
Createapatch
Itisbesttocreateandapplyapatchfromtheworkingdevelopmentdirectoryrelatedtotheproject,orfrom
withinthesourcedirectory.
# cd 7deveJ7poect
# d1ff -Nau oJdd1 heWd1 > patchf1Je # Ceate a patch fon a d1ectoy o a f1Je
# d1ff -Nau oJdf1Je heWf1Je > patchf1Je
Applyapatch
Sometimesitisnecessarytostripadirectorylevelfromthepatch,dependinghowitwascreated.Incaseof
difficulties,simplylookatthefirstlinesofthepatchandtryp0,p1orp2.
# cd 7deveJ7poect
# patch --dy-uh -pu < patchf1Je # Test the path W1thout appJy1hg 1t
# patch -pu < patchf1Je
# patch -p1 < patchf1Je # st1p off the 1st JeveJ fon the path
13 SVN
Serversetup|SVN+SSH|SVNoverhttp|SVNusage
Subversion (SVN)
http://subv ersion.tigris.org/
is a version control system designed to be the successor of CVS
(ConcurrentVersionsSystem).TheconceptissimilartoCVS,butmanyshortcomingswhereimproved.See
alsotheSVNbook
http://sv nbook.redbean.com/en/1.4/
.
13.1Serversetup
Theinitiationoftherepositoryisfairlysimple(hereforexample7hone7svh7mustexist):
# svhadn1h ceate --fs-type fsfs 7hone7svh7poect1
Nowtheaccesstotherepositoryismadepossiblewith:
f1Je.77 Direct file system access with the svn client with. This requires local permissions on the file
system.
svh.77 or svh+ssh.77 Remote access with the svnserve server (also over SSH). This requires local
permissionsonthefilesystem(defaultport:2690/tcp).
http.77Remoteaccesswithwebdavusingapache.Nolocalusersarenecessaryforthismethod.
2/27/12 Uni Toolbo
31/45 cb.vu/unitoolbo.html
Usingthelocalfilesystem,itisnowpossibletoimportandthencheckoutanexistingproject.UnlikewithCVS
itisnotnecessarytocdintotheprojectdirectory,simplygivethefullpath:
# svh 1npot 7poect17 f1Je.777hone7svh7poect17tuhk -n 'Th1t1aJ 1npot'
# svh checkout f1Je.777hone7svh7poect1
Thenewdirectory"trunk"isonlyaconvention,thisisnotrequired.
Remoteaccesswithssh
Nospecialsetupisrequiredtoaccesstherepositoryviassh,simplyreplacef1Je.77withsvh+ssh7hosthane.
Forexample:
# svh checkout svh+ssh.77hosthane7hone7svh7poect1
As with the local file access, every user needs an ssh access to the server (with a local account) and also
read/write access. This method might be suitable for a small group. All users could belong to a subversion
groupwhichownstherepository,forexample:
# goupadd subves1oh
# goupnod -A use1 subves1oh
# choWh -R oot.subves1oh 7hone7svh
# chnod -R 77u 7hone7svh
Remoteaccesswithhttp(apache)
Remote access over http (https) is the only good solution for a larger user group. This method uses the
apacheauthentication,notthelocalaccounts.Thisisatypicalbutsmallapacheconfiguration:
LoadhoduJe davnoduJe noduJes7noddav.so
LoadhoduJe davsvhnoduJe noduJes7noddavsvh.so
LoadhoduJe authzsvhnoduJe noduJes7nodauthzsvh.so # uhJy fo access cohtoJ
<Locat1oh 7svh>
uAv svh
# ahy "7svh7foo" URL W1JJ nap to a epos1toy 7hone7svh7foo
5vNPaehtPath 7hone7svh
AuthType Bas1c
AuthNane "5ubves1oh epos1toy"
Authz5vNAccessF1Je 7etc7apache27svh.acJ
AuthUseF1Je 7etc7apache27svh-passWd
Requ1e vaJ1d-use
<7Locat1oh>
Theapacheserverneedsfullaccesstotherepository:
# choWh -R WWW.WWW 7hone7svh
Createauserwithhtpasswd2:
# htpassWd -c 7etc7svh-passWd use1 # -c ceates the f1Je
Access contro/ svn.ac/ examp/e
# uefauJt 1t ead access. "* =" WouJd be defauJt ho access
|7
* =
|goups
poect1-deveJopes = oe, ack, ahe
# u1ve W1te access to the deveJopes
|poect1.
poect1-deveJopes = W
13.2SVNcommandsandusage
See also the Subversion Quick Reference Card
http://www.cs.put.poznan.pl/csobaniec/Papers/sv nref card.pdf
. Tortoise
SVN
http://tortoisesv n.tigris.org
isaniceWindowsinterface.
Import
A new project, that is a directory with some files, is imported into the repository with the 1npot command.
Importisalsousedtoaddadirectorywithitscontenttoanexistingproject.
# svh heJp 1npot # uet heJp fo ahy connahd
# Add a heW d1ectoy {W1th cohteht} 1hto the sc d1 oh poect1
# svh 1npot 7poect17heWd1 http.77host.uJ7svh7poect17tuhk7sc -n 'add heWd1'
TypicalSVNcommands
# svh co http.77host.uJ7svh7poect17tuhk # Checkout the nost eceht ves1oh
# Tags ahd bahches ae ceated by copy1hg
# svh nkd1 http.77host.uJ7svh7poect17tags7 # Ceate the tags d1ectoy
# svh copy -n "Tag c1 eJ." http.77host.uJ7svh7poect17tuhk `
http.77host.uJ7svh7poect17tags71.uc1
# svh status |--vebose # Check f1Jes status 1hto Wok1hg d1
# svh add sc7f1Je.h sc7f1Je.cpp # Add tWo f1Jes
# svh conn1t -n 'Added heW cJass f1Je' # Conn1t the chahges W1th a nessage
# svh Js http.77host.uJ7svh7poect17tags7 # L1st aJJ tags
2/27/12 Uni Toolbo
32/45 cb.vu/unitoolbo.html
# svh nove foo.c ba.c # hove {ehane} f1Jes
# svh deJete soneoJdf1Je # ueJete f1Jes
14 USEFUL COMMANDS
less|vi|mail|tar|dd|screen|find|Miscellaneous
14.1less
TheJesscommanddisplaysatextdocumentontheconsole.Itispresentonmostinstallation.
# Jess uh1xtooJbox.xhtnJ
Someimportantcommandsare(^Nstandsfor[control][N]):
hHgoodhelpondisplay
f^F^VSPACEForwardonewindow(orNlines).
b^BESCvBackwardonewindow(orNlines).
FForwardforeverlike"tailf".
/patternSearchforwardfor(Nth)matchingline.
?patternSearchbackwardfor(Nth)matchingline.
nRepeatprevioussearch(forNthoccurrence).
NRepeatprevioussearchinreversedirection.
qquit
14.2vi
Vi is present on ANY Linux/Unix installation (not gentoo?) and it is therefore useful to know some basic
commands. There are two modes: command mode and insertion mode. The commands mode is accessed
with[ESC],theinsertionmodewithi.Use. heJpifyouarelost.
Theeditorshahoandp1coareusuallyavailabletooandareeasier(IMHO)touse.
Quit
:wnewfilenamesavethefiletonewfilename
:wqor:xsaveandquit
:q!quitwithoutsaving
Searchandmove
/stringSearchforwardforstring
?stringSearchbackforstring
nSearchfornextinstanceofstring
NSearchforpreviousinstanceofstring
{Moveaparagraphback
Moveaparagraphforward
1GMovetothefirstlineofthefile
nGMovetothenthlineofthefile
GMovetothelastlineofthefile
:%s/OLD/NEW/gSearchandreplaceeveryoccurrence
Deletecopypastetext
dd(dw)Cutcurrentline(word)
DCuttotheendoftheline
xDelete(cut)character
yy(yw)Copyline(word)aftercursor
PPasteaftercursor
uUndolastmodification
UUndoallchangestocurrentline
14.3mail
Thena1J command is a basic application to read and send email, it is usually installed. To send an email
simplytype"mailuser@domain".Thefirstlineisthesubject,thenthemailcontent.Terminateandsendthe
emailwithasingledot(.)inanewline.Example:
# na1J ccb.vu
5ubect. You text 1s fuJJ of typos
2/27/12 Uni Toolbo
33/45 cb.vu/unitoolbo.html
"Fo a noneht, hoth1hg happehed. Theh, afte a secohd o so,
hoth1hg coht1hued to happeh."
.
EuT
#
Thisisalsoworkingwithapipe:
# echo "Th1s 1s the na1J body" | na1J ccb.vu
Thisisalsoasimplewaytotestthemailserver.
14.4tar
The command ta (tape archive) creates and extracts archives of file and directories. The archive .tar is
uncompressed, a compressed archive has the extension .tgz or .tar.gz (zip) or .tbz (bzip2). Do not use
absolute path when creating an archive, you probably want to unpack it somewhere else. Some typical
commandsare:
Create
# cd 7
# ta -cf hone.ta hone7 # ach1ve the WhoJe 7hone d1ectoy {c fo ceate}
# ta -czf hone.tgz hone7 # sane W1th z1p conpess1oh
# ta -cf hone.tbz hone7 # sane W1th bz1p2 conpess1oh
Only include one (or two) directories from a tree, but keep the relative structure. For example archive
/usr/local/etcand/usr/local/wwwandthefirstdirectoryinthearchiveshouldbelocal/.
# ta -C 7us -czf JocaJ.tgz JocaJ7etc JocaJ7WWW
# ta -C 7us -xzf JocaJ.tgz # To uhta the JocaJ d1 1hto 7us
# cd 7us ta -xzf JocaJ.tgz # Ts the sane as above
Extract
# ta -tzf hone.tgz # Jook 1hs1de the ach1ve W1thout extact1hg {J1st}
# ta -xf hone.ta # extact the ach1ve hee {x fo extact}
# ta -xzf hone.tgz # sane W1th z1p conpess1oh {-xf fo bz1p2 conpess1oh}
# enove Jead1hg path gaJJey2 ahd extact 1hto gaJJey
# ta --st1p-conpohehts 1 -zxvf gaJJey2.tgz -C gaJJey7
# ta -xf hone.tbz hone7coJ1h7f1Je.txt # Restoe a s1hgJe f1Je
Moreadvanced
# ta c d17 | gz1p | ssh useenote 'dd of=d1.tgz' # ach d17 ahd stoe enoteJy.
# ta cvf - `f1hd . -p1ht` > backup.ta # ach the cueht d1ectoy.
# ta -cf - -C 7etc . | ta xpf - -C 7backup7etc # Copy d1ecto1es
# ta -cf - -C 7etc . | ssh useenote ta xpf - -C 7backup7etc # Renote copy.
# ta -czf hone.tgz --excJude '*.o' --excJude 'tnp7' hone7
14.5dd
Theprogramdd (disk dump or destroy disk or see themeaningofdd) is used to copy partitions and disks
andforothercopytricks.Typicalusage:
# dd 1f=<souce> of=<taget> bs=<byte s1ze> cohv=<cohves1oh>
Importantconvoptions:
hotuhcdonottruncatetheoutputfile,allzeroswillbewrittenaszeros.
hoeocontinueafterreaderrors(e.g.badblocks)
syhcpadeveryinputblockwithNullstoibssize
Thedefaultbytesizeis512(oneblock).TheMBR,wherethepartitiontableislocated,isonthefirstblock,
thefirst63blocksofadiskareempty.Largerbytesizesarefastertocopybutrequirealsomorememory.
Backupandrestore
# dd 1f=7dev7hda of=7dev7hdc bs=1u5b # Copy d1sk to d1sk {sane s1ze}
# dd 1f=7dev7sda7 of=7hone7oot.1ng bs=4u9 cohv=hotuhc,hoeo # Backup 7
# dd 1f=7hone7oot.1ng of=7dev7sda7 bs=4u9 cohv=hotuhc,hoeo # Restoe 7
# dd bs=1h 1f=7dev7ad4s3e | gz1p -c > ad4s3e.gz # Z1p the backup
# guhz1p -dc ad4s3e.gz | dd of=7dev7adus3e bs=1h # Restoe the z1p
# dd bs=1h 1f=7dev7ad4s3e | gz1p | ssh eedcobafy 'dd of=ad4s3e.gz' # aJso enote
# guhz1p -dc ad4s3e.gz | ssh eedcobahost 'dd of=7dev7adus3e bs=1h'
# dd 1f=7dev7adu of=7dev7ad2 sk1p=1 seek=1 bs=4k cohv=hoeo # 5k1p hBR
# Th1s 1s hecessay 1f the dest1hat1oh {ad2} 1s snaJJe.
Recover
Thecommandddwillreadevery s|ng/e b/ockofthepartition.Incaseofproblemsitisbettertousetheoption
cohv=syhc,hoeosoddwillskipthebadblockandwritezerosatthedestination.Accordinglyitisimportant
tosettheblocksizeequalorsmallerthanthediskblocksize.A1ksizeseemssafe,setitwithbs=1k.Ifadisk
2/27/12 Uni Toolbo
34/45 cb.vu/unitoolbo.html
hasbadsectorsandthedatashouldberecoveredfromapartition,createanimagefilewithdd,mountthe
image and copy the content to a new disk. With the option hoeo, dd will skip the bad sectors and write
zerosinstead,thusonlythedatacontainedinthebadsectorswillbelost.
# dd 1f=7dev7hda of=7dev7huJJ bs=1n # Check fo bad bJocks
# dd bs=1k 1f=7dev7hda1 cohv=syhc,hoeo,hotuhc | gz1p | ssh ` # 5ehd to enote
ootfy 'dd of=hda1.gz bs=1k'
# dd bs=1k 1f=7dev7hda1 cohv=syhc,hoeo,hotuhc of=hda1.1ng # 5toe 1hto ah 1nage
# nouht -o Joop 7hda1.1ng 7nht # houht the 1nage
# syhc -ax 7nht7 7heWd1sk7 # Copy oh a heW d1sk
# dd 1f=7dev7hda of=7dev7hda # Refesh the naghet1c state
# The above 1s usefuJ to efesh a d1sk. Tt 1s pefectJy safe, but nust be uhnouhted.
Delete
# dd 1f=7dev7zeo of=7dev7hdc # ueJete fuJJ d1sk
# dd 1f=7dev7uahdon of=7dev7hdc # ueJete fuJJ d1sk bette
# k1JJ -U5R1 PTu # v1eW dd pogess {L1hux}
# k1JJ -TNFu PTu # v1eW dd pogess {FeeB5u}
MBRtricks
The MBR contains the boot loader and the partition table and is 512 bytes small. The first 446 are for the
bootloader,thebytes446to512areforthepartitiontable.
# dd 1f=7dev7sda of=7nbsda.bak bs=512 couht=1 # Backup the fuJJ hBR
# dd 1f=7dev7zeo of=7dev7sda bs=512 couht=1 # ueJete hBR ahd pat1t1oh tabJe
# dd 1f=7nbsda.bak of=7dev7sda bs=512 couht=1 # Restoe the fuJJ hBR
# dd 1f=7nbsda.bak of=7dev7sda bs=44 couht=1 # Restoe ohJy the boot Joade
# dd 1f=7nbsda.bak of=7dev7sda bs=1 couht=4 sk1p=44 seek=44 # Restoe pat1t1oh tabJe
14.6screen
Screen(amusthave)hastwomainfunctionalities:
Runmultipleterminalsessionwithinasingleterminal.
A started program is decoupled from the real terminal and can thus run in the background. The real
terminalcanbeclosedandreattachedlater.
Shortstartexample
startscreenwith:
# sceeh
Withinthescreensessionwecanstartalonglastingprogram(liketop).
# top
NowdetachwithCtrlaCtrld.Reattachtheterminalwith:
# sceeh -R -u
Indetailthismeans:Ifasessionisrunning,thenreattach.Ifnecessarydetachandlogoutremotelyfirst.Ifit
wasnotrunningcreateitandnotifytheuser.Or:
# sceeh -x
Attachtoarunningscreeninamultidisplaymode.Theconsoleisthussharedamongmultipleusers.Very
usefulforteamwork/debug!
Screencommands(withinscreen)
AllscreencommandsstartwithCtrla.
Ctrla?helpandsummaryoffunctions
Ctrlaccreateannewwindow(terminal)
CtrlaCtrlnandCtrlaCtrlptoswitchtothenextorpreviouswindowinthelist,bynumber.
CtrlaCtrlNwhereNisanumberfrom0to9,toswitchtothecorrespondingwindow.
Ctrla"togetanavigablelistofrunningwindows
CtrlaatoclearamissedCtrla
CtrlaCtrldtodisconnectandleavethesessionrunninginthebackground
Ctrlaxlockthescreenterminalwithapassword
Ctrla[enterintoscrollbackmode,exitwithesc.
Useecho "defscoJJback 5uuu" > ~7.sceehctoincreasebuffer(defaultis100)
CuScrollsahalfpageup
CbScrollafullpageup
CdScrollahalfpagedown
CfScrollafullpagedown
/Searchforward
2/27/12 Uni Toolbo
35/45 cb.vu/unitoolbo.html
?Searchbackward
Thescreensessionisterminatedwhentheprogramwithintherunningterminalisclosedandyoulogoutfrom
theterminal.
14.7Find
Someimportantoptions:
-x(onBSD)-xdev(onLinux)Stayonthesamefilesystem(devinfstab).
-exec cnd {} `Executethecommandandreplace{}withthefullpath
-1haneLikenamebutiscaseinsensitive
-JsDisplayinformationaboutthefile(likelsla)
-s1ze hnis+n(kMGTP)
-cn1h hFile'sstatuswaslastchangednminutesago.
# f1hd . -type f ! -pen -444 # F1hd f1Jes hot eadabJe by aJJ
# f1hd . -type d ! -pen -111 # F1hd d1s hot access1bJe by aJJ
# f1hd 7hone7use7 -cn1h 1u -p1ht # F1Jes ceated o nod1f1ed 1h the Jast 1u n1h.
# f1hd . -hane '*.|ch' | xags gep -E 'exp' # 5each 'exp' 1h th1s d1 ahd beJoW.
# f1hd 7 -hane "*.coe" | xags n # F1hd coe dunps ahd deJete then {aJso ty coe.*}
# f1hd 7 -hane "*.coe" -p1ht -exec n {} ` # uthe syhtax
# F1hd 1nages ahd ceate ah ach1ve, 1hane 1s hot case sehs1t1ve. - fo appehd
# f1hd . `{ -1hane "*.phg" -o -1hane "*.pg" `} -p1ht -exec ta -f 1nages.ta {} `
# f1hd . -type f -hane "*.txt" ! -hane REAuhE.txt -p1ht # ExcJude REAuhE.txt f1Jes
# f1hd 7va7 -s1ze +1uh -exec Js -Jh {} ` # F1hd Jage f1Jes > 1u hB
# f1hd 7va7 -s1ze +1uh -Js # Th1s 1s s1npJe
# f1hd . -s1ze +1uh -s1ze -5uh -p1ht
# f1hd 7us7pots7 -hane Wok -type d -p1ht -exec n -f {} ` # CJeah the pots
# F1hd f1Jes W1th 5UTu those f1Je ae vuJheabJe ahd nust be kept secue
# f1hd 7 -type f -use oot -pen -4uuu -exec Js -J {} `
Becarefulwithxargorexecasitmightormightnothonorquotingsandcanreturnwrongresultswhenfiles
ordirectoriescontainspaces.Indoubtuse"print0|xargs0"insteadof"|xargs".Theoptionprint0mustbe
thelastinthefindcommand.Seethisniceminitutorialforfind
http://www.hccf l.edu/pollock/Unix/FindCmd.htm
.
# f1hd . -type f | xags Js -J # W1JJ hot Wok W1th spaces 1h hanes
# f1hd . -type f -p1htu | xags -u Js -J # W1JJ Wok W1th spaces 1h hanes
# f1hd . -type f -exec Js -J '{}' ` # u use quotes '{}' W1th -exec
14.8Miscellaneous
# Wh1ch connahd # 5hoW fuJJ path hane of connahd
# t1ne connahd # 5ee hoW Johg a connahd takes to execute
# t1ne cat # Use t1ne as stopWatch. CtJ-c to stop
# set | gep $U5ER # L1st the cueht ehv1ohneht
# caJ -3 # u1spJay a thee nohth caJehda
# date |-u|--utc|--uh1vesaJ |hhuuhhnn||CCYY|.ss
# date 1uu22155 # 5et date ahd t1ne
# What1s gep # u1spJay a shot 1hfo oh the connahd o Wod
# Whee1s ava # 5each path ahd stahdad d1ecto1es fo Wod
# setehv vahane vaJue # 5et ehv. va1abJe vahane to vaJue {csh7tcsh}
# expot vahane="vaJue" # set ehv. va1abJe vahane to vaJue {sh7ksh7bash}
# pWd # P1ht Wok1hg d1ectoy
# nkd1 -p 7path7to7d1 # ho eo 1f ex1st1hg, nake paeht d1s as heeded
# nkd1 -p poect7{b1h,sc,ob,doc7{htnJ,nah,pdf},debug7sone7noe7d1s}
# nd1 7path7to7d1 # Renove d1ectoy
# n -f 7path7to7d1 # Renove d1ectoy ahd 1ts cohteht {foce}
# n -- -badcha.txt # Renove f1Je Wh1tch stats W1th a dash {-}
# cp -Ja 7d11 7d12 # Ach1ve ahd had J1hk f1Jes 1hstead of copy
# cp -JpR 7d11 7d12 # 5ane fo FeeB5u
# cp uh1xtooJbox.xhtnJ{,.bak} # 5hot Way to copy the f1Je W1th a heW extehs1oh
# nv 7d11 7d12 # Rehane a d1ectoy
# Js -1 # J1st ohe f1Je pe J1he
# h1stoy | ta1J -5u # u1spJay the Jast 5u used connahds
# cd - # cd to pev1ous {$uLuPWu} d1ectoy
Checkfilehasheswithopenssl.Thisisanicealternativetothecommandsnd5sunorsha1sun(FreeBSDuses
nd5andsha1)whicharenotalwaysinstalled.
# opehssJ nd5 f1Je.ta.gz # ueheate ah nd5 checksun fon f1Je
# opehssJ sha1 f1Je.ta.gz # ueheate ah sha1 checksun fon f1Je
# opehssJ nd1u f1Je.ta.gz # ueheate a RTPEhu-1u checksun fon f1Je
15 I NSTALL SOFTWARE
Usuallythepackagemanagerusestheproxyvariableforhttp/ftprequests.In.bashrc:
expot httppoxy=http.77poxyseve.312B
expot ftppoxy=http.77poxyseve.312B
2/27/12 Uni Toolbo
36/45 cb.vu/unitoolbo.html
15.1Listinstalledpackages
# pn -qa # L1st 1hstaJJed packages {Rh, 5u5E, RPh based}
# dpkg -J # ueb1ah, Ubuhtu
# pkg1hfo # FeeB5u J1st aJJ 1hstaJJed packages
# pkg1hfo -W snbd # FeeB5u shoW Wh1ch package snbd beJohgs to
# pkg1hfo # 5oJa1s
15.2Add/removesoftware
Frontends:yast2/yastforSuSE,redhatconfigpackagesforRedHat.
# pn -1 pkghane.pn # 1hstaJJ the package {Rh, 5u5E, RPh based}
# pn -e pkghane # Renove package
SuSEzypper(seedocandcheetsheet)
http://en.opensuse.org/Zy pper/Usage
# zyppe efesh # Refesh epos1to1e
# zyppe 1hstaJJ v1n # ThstaJJ the package v1n
# zyppe enove v1n # Renove the package v1n
# zyppe seach v1n # 5each packages W1th v1n
# zyppe update v1n # 5each packages W1th v1n
Debian
# apt-get update # F1st update the package J1sts
# apt-get 1hstaJJ enacs # ThstaJJ the package enacs
# dpkg --enove enacs # Renove the package enacs
# dpkg -5 f1Je # f1hd What package a f1Je beJohgs to
Gentoo
Gentoousesemergeastheheartofits"Portage"packagemanagementsystem.
# enege --syhc # F1st syhc the JocaJ potage tee
# enege -u packagehane # ThstaJJ o upgade a package
# enege -C packagehane # Renove the package
# evdep-ebu1Jd # Repa1 depehdehc1es
Solaris
The<cdrom>pathisusually7cdon7cdonu.
# pkgadd -d <cdon>75oJa1s97Poduct 5UNWgta
# pkgadd -d 5UNWgta # Add doWhJoaded package {buhz1p2 f1st}
# pkgn 5UNWgta # Renove the package
FreeBSD
# pkgadd - syhc # Fetch ahd 1hstaJJ syhc.
# pkgdeJete 7va7db7pkg7syhc-xx # ueJete the syhc package
SetwherethepackagesarefetchedfromwiththePACKAuE5TTEvariable.Forexample:
# expot PACKAuE5TTE=ftp.77ftp.feebsd.og7pub7FeeB5u7pots713B7packages7Latest7
# o ftp.77ftp.feebsd.og7pub7FeeB5u7pots713B7packages--stabJe7Latest7
FreeBSDports
http://www.f reebsd.org/handbook/ports.html
Theporttree7us7pots7isacollectionofsoftwarereadytocompileandinstall(seemanports).Theports
areupdatedwiththeprogrampotshap.
# potshap fetch extact # Ceate the tee Wheh uhh1hg the f1st t1ne
# potshap fetch update # Update the pot tee
# cd 7us7pots7het7syhc7 # 5eJect the package to 1hstaJJ
# nake 1hstaJJ d1stcJeah # ThstaJJ ahd cJeahup {aJso see nah pots}
# nake package # hake a b1hay package of th1s pot
# pkgdb -F # F1x the package eg1sty database
# potscJeah -C -uu # CJeah Wokd1 ahd d1std1 {pat of potupgade}
OSXMacPorts
http://guide.macports.org/
(usesudoforallcommands)
# pot seJfupdate # Update the pot tee {safe}
# pot 1hstaJJed # L1st 1hstaJJed pots
# pot deps apache2 # L1st depehdehc1es fo th1s pot
# pot seach pgep # 5each fo st1hg
# pot 1hstaJJ poctooJs # ThstaJJ th1s package
# pot va1ahts ghostsc1pt # L1st va1ahts of th1s pot
# pot -v 1hstaJJ ghostsc1pt +hox11# -hox11 fo hegat1ve vaJue
# pot cJeah --aJJ ghostsc1pt # CJeah Wokd1 of pot
# pot upgade ghostsc1pt # Upgade th1s pot
# pot uh1hstaJJ ghostsc1pt # Uh1hstaJJ th1s pot
# pot -f uh1hstaJJ 1hstaJJed # Uh1hstaJJ eveyth1hg
15.3Librarypath
Due to complex dependencies and runtime linking, programs are difficult to copy to an other system or
2/27/12 Uni Toolbo
37/45 cb.vu/unitoolbo.html
distribution. However for small programs with little dependencies, the missing libraries can be copied over.
Theruntimelibraries(andthemissingone)arecheckedwithJddandmanagedwithJdcohf1g.
# Jdd 7us7b1h7syhc # L1st aJJ heeded uht1ne J1ba1es
# otooJ -L 7us7b1h7syhc # u5 X equ1vaJeht to Jdd
# Jdcohf1g -h 7path7to7J1bs7 # Add a path to the shaed J1ba1es d1ecto1es
# Jdcohf1g -n 7path7to7J1bs7 # FeeB5u
# LuLTBRARYPATh # The va1abJe set the J1hk J1bay path
16 CONVERT MEDI A
Sometimesonesimplyneedtoconvertavideo,audiofileordocumenttoanotherformat.
16.1Textencoding
Text encoding can get totally wrong, specially when the language requires special characters like . The
command1cohvcanconvertfromoneencodingtoanother.
# 1cohv -f <fonehcod1hg> -t <toehcod1hg> <1hputf1Je>
# 1cohv -f T5uBB59-1 -t UTF-B -o f1Je.1hput > f1JeutfB
# 1cohv -J # L1st khoWh coded chaacte sets
Withoutthefoption,iconvwillusethelocalcharset,whichisusuallyfineifthedocumentdisplayswell.
16.2UnixDOSnewlines
ConvertDOS(CR/LF)toUnix(LF)newlinesandbackwithinaUnixshell.Seealsodos2uh1xanduh1x2dos
ifyouhavethem.
# sed 's7.$77' dosf1Je.txt > uh1xf1Je.txt # uu5 to UNTX
# aWk '{sub{7`$7,""}p1ht}' dosf1Je.txt > uh1xf1Je.txt # uu5 to UNTX
# aWk '{sub{7$7,"`"}p1ht}' uh1xf1Je.txt > dosf1Je.txt # UNTX to uu5
ConvertUnixtoDOSnewlineswithinaWindowsenvironment.Usesedorawkfrommingworcygwin.
# sed -h p uh1xf1Je.txt > dosf1Je.txt
# aWk 1 uh1xf1Je.txt > dosf1Je.txt # UNTX to uu5 {W1th a cygW1h sheJJ}
16.3PDFtoJpegandconcatenatePDFfiles
Convert a PDF document with gs (GhostScript) to jpeg (or png) images for each page. Also much shorter
withcohvetandnog1fy(fromImageMagickorGraphicsMagick).
# gs -dBATCh -dNuPAU5E -suEvTCE=peg -15u -dTextAJphaB1ts=4 -duaph1csAJphaB1ts=4 `
-dhax5t1p51ze=B192 -suutputF1Je=uh1xtooJboxZd.pg uh1xtooJbox.pdf
# cohvet uh1xtooJbox.pdf uh1xtooJbox-Zu3d.phg
# cohvet *.peg 1nages.pdf # Ceate a s1npJe PuF W1th aJJ p1ctues
# cohvet 1nageuuu* -esanpJe 12ux12u -conpess JPEu -quaJ1ty Bu 1nages.pdf
# nog1fy -fonat phg *.ppn # cohvet aJJ ppn 1nages to phg fonat
Ghostscriptcanalsoconcatenatemultiplepdffilesintoasingleone.ThisonlyworkswellifthePDFfilesare
"wellbehaved".
# gs -q -sPAPER5TZE=a4 -dNuPAU5E -dBATCh -suEvTCE=pdfW1te -suutputF1Je=aJJ.pdf `
f1Je1.pdf f1Je2.pdf ... # uh W1hdoWs use '#' 1hstead of '='
16.4Convertvideo
CompresstheCanondigicamvideowithanmpeg4codecandrepairthecrappysound.
# nehcode -o v1deoout.av1 -oac np3Jane -ovc Javc -sate 11u25 `
-chahheJs 1 -af-adv foce=1 -Janeopts peset=ned1un -Javcopts `
vcodec=nsnpeg4v2.vb1tate=uu -nc u v1doe1h.AvT
Seesoxforsoundprocessing.
16.5Copyanaudiocd
The program cdpaaho1a
http://xiph.org/paranoia/
can save the audio tracks (FreeBSD port in audio/cdparanoia/),
oggehccanencodeinOggVorbisformat,Janeconvertstomp3.
# cdpaaho1a -B # Copy the tacks to Wav f1Jes 1h cueht d1
# Jane -b 25 1h.Wav out.np3 # Ehcode 1h np3 25 kb7s
# fo 1 1h *.Wav do Jane -b 25 $1 `basehane $1 .Wav`.np3 dohe
# oggehc 1h.Wav -b 25 out.ogg # Ehcode 1h ugg vob1s 25 kb7s
17 PRI NTI NG
17.1Printwithlpr
# Jp uh1xtooJbox.ps # P1ht oh defauJt p1hte
2/27/12 Uni Toolbo
38/45 cb.vu/unitoolbo.html
# expot PRTNTER=hp4uu # Chahge the defauJt p1hte
# Jp -Php45uu #2 uh1xtooJbox.ps # Use p1hte hp45uu ahd p1ht 2 cop1es
# Jp -o uupJex=uupJexNoTunbJe ... # P1ht dupJex aJohg the Johg s1de
# Jp -o Page51ze=A4,uupJex=uupJexNoTunbJe ...
# Jpq # Check the queue oh defauJt p1hte
# Jpq -J -Php45uu # ueue oh p1hte hp45uu W1th vebose
# Jpn - # Renove aJJ uses obs oh defauJt p1hte
# Jpn -Php45uu 31B # Renove ob 31B. F1hd ob hb W1th Jpq
# Jpc status # L1st aJJ ava1JabJe p1htes
# Jpc status hp45uu # Check 1f p1hte 1s ohJ1he ahd queue Jehgth
Somedevicesarenotpostscriptandwillprintgarbagewhenfedwithapdffile.Thismightbesolvedwith:
# gs -d5AFER -dNuPAU5E -suEvTCE=desket -suutputF1Je=`|Jp f1Je.pdf
PrinttoaPDFfileeveniftheapplicationdoesnotsupportit.UsegsontheprintcommandinsteadofJp.
# gs -q -sPAPER5TZE=a4 -dNuPAU5E -dBATCh -suEvTCE=pdfW1te -suutputF1Je=7path7f1Je.pdf
18 DATABASES
18.1PostgreSQL
Changerootorausernamepassword
# psqJ -d tenpJate1 -U pgsqJ
> aJte use pgsqJ W1th passWod 'pgsqJpassWod' # Use usehane 1hstead of "pgsqJ"
Createuseranddatabase
Thecommandsceateuse,dopuse,ceatedbanddopdbareconvenientshortcutsequivalenttotheSQL
commands.Thenewuserisbobwithdatabasebobdbuseasrootwithpgsqlthedatabasesuperuser:
# ceateuse -U pgsqJ -P bob # -P W1JJ ask fo passWod
# ceatedb -U pgsqJ -u bob bobdb # heW bobdb 1s oWhed by bob
# dopdb bobdb # ueJete database bobdb
# dopuse bob # ueJete use bob
Thegeneraldatabaseauthenticationmechanismisconfiguredinpg_hba.conf
Grantremoteaccess
Thefile$Pu5LuATAu7postgesqJ.cohfspecifiestheaddresstobindto.TypicallyJ1stehaddesses = '*'
forPostgres8.x.
Thefile$Pu5LuATAu7pghba.cohfdefinestheaccesscontrol.Examples:
# TYPE uATABA5E U5ER TP-AuuRE55 TP-hA5K hEThuu
host bobdb bob 212.117.B1.42 255.255.255.255 passWod
host aJJ aJJ u.u.u.u7u passWod
Backupandrestore
Thebackupsandrestorearedonewiththeuserpgsqlorpostgres.Backupandrestoreasingledatabase:
# pgdunp --cJeah dbhane > dbhanesqJ.dunp
# psqJ dbhane < dbhanesqJ.dunp
Backupandrestorealldatabases(includingusers):
# pgdunpaJJ --cJeah > fuJJ.dunp
# psqJ -f fuJJ.dunp postges
Inthiscasetherestoreisstartedwiththedatabasepostgreswhichisbetterwhenreloadinganemptycluster.
18.2MySQL
Changemysqlrootorusernamepassword
Method 1
# 7etc71h1t.d7nysqJ stop
or
# k1JJaJJ nysqJd
# nysqJd --sk1p-gaht-tabJes
# nysqJadn1h -u oot passWod 'heWpassWd'
# 7etc71h1t.d7nysqJ stat
Method 2
# nysqJ -u oot nysqJ
nysqJ> UPuATE U5ER 5ET PA55WuRu=PA55WuRu{"heWpassWod"} Whee use='oot'
nysqJ> FLU5h PRTvTLEuE5 # Use usehane 1hstead of "oot"
nysqJ> qu1t
Createuseranddatabase(seeMySQLdoc
http://dev .my sql.com/doc/ref man/5.1/en/addingusers.html
)
# nysqJ -u oot nysqJ
2/27/12 Uni Toolbo
39/45 cb.vu/unitoolbo.html
nysqJ> CREATE U5ER 'bob''JocaJhost' TuENTTFTEu BY 'pWd' # ceate ohJy a use
nysqJ> CREATE uATABA5E bobdb
nysqJ> uRANT ALL uN *.* Tu 'bob''Z' TuENTTFTEu BY 'pWd' # Use JocaJhost 1hstead of Z
# to est1ct the hetWok access
nysqJ> uRuP uATABA5E bobdb # ueJete database
nysqJ> uRuP U5ER bob # ueJete use
nysqJ> uELETE FRuh nysqJ.use WhERE use='bob ahd host='hosthane' # AJt. connahd
nysqJ> FLU5h PRTvTLEuE5
Grantremoteaccess
Remoteaccessistypicallypermittedforadatabase,andnotalldatabases.Thefile7etc7ny.chfcontainsthe
IP address to bind to. (On FreeBSD ny.chf not created per fedault, copy one .chf file from
7us7JocaJ7shae7nysqJto7us7JocaJ7etc7ny.chf)Typicallycommentthelineb1hd-addess =out.
# nysqJ -u oot nysqJ
nysqJ> uRANT ALL uN bobdb.* Tu bob'xxx.xxx.xxx.xxx' TuENTTFTEu BY 'PA55WuRu'
nysqJ> REvuKE uRANT uPTTuN uN foo.* FRuh ba'xxx.xxx.xxx.xxx'
nysqJ> FLU5h PRTvTLEuE5 # Use 'hosthane' o aJso 'Z' fo fuJJ access
Backupandrestore
Backupandrestoreasingledatabase:
# nysqJdunp -u oot -psecet --add-dop-database dbhane > dbhanesqJ.dunp
# nysqJ -u oot -psecet -u dbhane < dbhanesqJ.dunp
Backupandrestorealldatabases:
# nysqJdunp -u oot -psecet --add-dop-database --aJJ-databases > fuJJ.dunp
# nysqJ -u oot -psecet < fuJJ.dunp
Hereis"secret"themysqlrootpassword,thereisnospaceafterp.Whenthepoptionisusedalone(w/o
password),thepasswordisaskedatthecommandprompt.
18.3SQLite
SQLite
http://www.sqlite.org
isasmallpowerfulselfcontained,serverless,zeroconfigurationSQLdatabase.
Dumpandrestore
ItcanbeusefultodumpandrestoreanSQLitedatabase.Forexampleyoucaneditthedumpfiletochange
acolumnattributeortypeandthenrestorethedatabase.ThisiseasierthanmessingwithSQLcommands.
UsethecommandsqJ1te3fora3.xdatabase.
# sqJ1te database.db .dunp > dunp.sqJ # dunp
# sqJ1te database.db < dunp.sqJ # estoe
Convert2.xto3.xdatabase
sqJ1te databasev2.db .dunp | sqJ1te3 databasev3.db
19 DI SK QUOTA
A disk quota allows to limit the amount of disk space and/or the number of files a user or (or member of
group)canuse.Thequotasareallocatedonaperfilesystembasisandareenforcedbythekernel.
19.1Linuxsetup
Thequotatoolspackageusuallyneedstobeinstalled,itcontainsthecommandlinetools.
Activate the user quota in the fstab and remount the partition. If the partition is busy, either all locked files
mustbeclosed,orthesystemmustberebooted.Addusquotatothefstabmountoptions,forexample:
7dev7sda2 7hone e1sefs W,acJ,usexatt,usquota 1 1
# nouht -o enouht 7hone
# nouht # Check 1f usquota 1s act1ve, otheW1se eboot
Initializethequota.userfilewithquotacheck.
# quotacheck -vun 7hone
# chnod 44 7hone7aquota.use # To Jet the uses check the1 oWh quota
Activatethequotaeitherwiththeprovidedscript(e.g./etc/init.d/quotadonSuSE)orwithquotaoh:
quotaoh -vu 7hone
Checkthatthequotaisactivewith:
quota -v
19.2FreeBSDsetup
The quota tools are part of the base system, however the kernel needs the option quota. If it is not there,
additandrecompilethekernel.
2/27/12 Uni Toolbo
40/45 cb.vu/unitoolbo.html
opt1ohs UuTA
AswithLinux,addthequotatothefstaboptions(userquota,notusrquota):
7dev7adus1d 7hone ufs W,hoat1ne,usequota 2 2
# nouht 7hone # To enouht the pat1t1oh
Enablediskquotasin/etc/rc.confandstartthequota.
# gep quotas 7etc7c.cohf
ehabJequotas="YE5" # tuh oh quotas oh statup {o Nu}.
checkquotas="YE5" # Check quotas oh statup {o Nu}.
# 7etc7c.d7quota stat
19.3Assignquotalimits
Thequotasarenotlimitedperdefault(setto0).Thelimitsaresetwithedquotaforsingleusers.Aquotacan
bealsoduplicatedtomanyusers.Thefilestructureisdifferentbetweenthequotaimplementations,butthe
principle is the same: the values of blocks and inodes can be limited. On/y change the va/ues ol solt and
hard.Ifnotspecified,theblocksare1k.Thegraceperiodissetwithedquota -t.Forexample:
# edquota -u coJ1h
Linux
u1sk quotas fo use coJ1h {u1d 1uu7}.
F1Jesysten bJocks soft had 1hodes soft had
7dev7sdaB 1uB 1uuu 2uuu 1 u u
FreeBSD
uotas fo use coJ1h.
7hone. kbytes 1h use. 5u41B4, J1n1ts {soft = 7uuuuu, had = Buuuuu}
1hodes 1h use. 1792, J1n1ts {soft = u, had = u}
Formanyusers
Thecommandedquota -pisusedtoduplicateaquotatootherusers.Forexampletoduplicateareference
quotatoallusers:
# edquota -p efuse `aWk -F. '$3 > 499 {p1ht $1}' 7etc7passWd`
# edquota -p efuse use1 use2 # uupJ1cate to 2 uses
Checks
Userscanchecktheirquotabysimplytypingquota(thefilequota.usermustbereadable).Rootcancheckall
quotas.
# quota -u coJ1h # Check quota fo a use
# epquota 7hone # FuJJ epot fo the pat1t1oh fo aJJ uses
20 SHELLS
MostLinuxdistributionsusethebashshellwhiletheBSDsusetcsh,thebourneshellisonlyusedforscripts.
Filtersareveryusefulandcanbepiped:
gepPatternmatching
sedSearchandReplacestringsorcharacters
cutPrintspecificcolumnsfromamarker
sotSortalphabeticallyornumerically
uh1qRemoveduplicatelinesfromafile
Forexampleusedallatonce:
# 1fcohf1g | sed 's7 7 7g' | cut -d" " -f1 | uh1q | gep -E "|a-zu-9+" | sot -
# 1fcohf1g | sed '7.*1het add.7!ds777s7 .*77'|sot -t. -k1,1h -k2,2h -k3,3h -k4,4h
Thefirstcharacterinthesedpatternisatab.Towriteatabontheconsole,usectrlvctrltab.
20.1bash
Redirectsandpipesforbashandsh:
# cnd 1> f1Je # Red1ect stdout to f1Je.
# cnd 2> f1Je # Red1ect stde to f1Je.
# cnd 1>> f1Je # Red1ect ahd appehd stdout to f1Je.
# cnd 8> f1Je # Red1ect both stdout ahd stde to f1Je.
# cnd >f1Je 2>81 # Red1ects stde to stdout ahd theh to f1Je.
# cnd1 | cnd2 # p1pe stdout to cnd2
# cnd1 2>81 | cnd2 # p1pe stdout ahd stde to cnd2
Modifyyourconfigurationin~/.bashrc(itcanalsobe~/.bash_profile).Thefollowingentriesareuseful,reload
2/27/12 Uni Toolbo
41/45 cb.vu/unitoolbo.html
with"..bashrc".Withcygwinuse~/.bash_profilewithrxvtpastwithshift+leftclick.
# 1h .bashc
b1hd '"`e|A"'.h1stoy-seach-backWad # Use up ahd doWh aoW to seach
b1hd '"`e|B"'.h1stoy-seach-foWad # the h1stoy. ThvaJuabJe!
set -o enacs # 5et enacs node 1h bash {see beJoW}
set beJJ-styJe v1s1bJe # uo hot beep, 1hvese coJos
# 5et a h1ce ponpt J1ke |usehost7path7tod1>
P51="`|`u33|13un`|`|`u33|134n``u`|`u33|13un`"
P51="$P51`|`u33|u33n``h`|`u33|13un``|`u33|u37n`"
P51="$P51`W`|`u33|13un`>`|`u33|un`"
# To check the cuehtJy act1ve aJ1ases, s1npJy type aJ1as
aJ1as Js='Js -aF' # Appehd 1hd1cato {ohe of *7=>|}
aJ1as JJ='Js -aFJs' # L1st1hg
aJ1as Ja='Js -aJJ'
aJ1as ..='cd ..'
aJ1as ...='cd ..7..'
expot hT5TFTLE5TZE=5uuu # Lage h1stoy
expot CLTCuLuR=1 # Use coJos {1f poss1bJe}
expot L5CuLuR5=ExuxFxdxCxuxuxBxBxExEx
20.2tcsh
Redirectsandpipesfortcshandcsh(simple>and>>arethesameassh):
# cnd >8 f1Je # Red1ect both stdout ahd stde to f1Je.
# cnd >>8 f1Je # Appehd both stdout ahd stde to f1Je.
# cnd1 | cnd2 # p1pe stdout to cnd2
# cnd1 |8 cnd2 # p1pe stdout ahd stde to cnd2
Thesettingsforcsh/tcsharesetin~7.cshc,reloadwith"source.cshrc".Examples:
# 1h .cshc
aJ1as Js 'Js -aF'
aJ1as JJ 'Js -aFJs'
aJ1as Ja 'Js -aJJ'
aJ1as .. 'cd ..'
aJ1as ... 'cd ..7..'
set ponpt = "ZBZhZbZBZnZbZ7> " # J1ke usehost7path7tod1>
set h1stoy = 5uuu
set saveh1st = { uuu nege }
set autoJ1st # Repot poss1bJe conpJet1ohs W1th tab
set v1s1bJebeJJ # uo hot beep, 1hvese coJos
# B1hdkey ahd coJos
b1hdkey -e 5eJect Enacs b1hd1hgs # Use enacs keys to ed1t the connahd ponpt
b1hdkey -k up h1stoy-seach-backWad # Use up ahd doWh aoW to seach
b1hdkey -k doWh h1stoy-seach-foWad
setehv CLTCuLuR 1 # Use coJos {1f poss1bJe}
setehv L5CuLuR5 ExuxFxdxCxuxuxBxBxExEx
The emacs mode enables to use the emacs keys shortcuts to modify the command prompt line. This is
extremelyuseful(notonlyforemacsusers).Themostusedcommandsare:
CaMovecursortobeginningofline
CeMovecursortoendofline
MbMovecursorbackoneword
MfMovecursorforwardoneword
MdCutthenextword
CwCutthelastword
CuCuteverythingbeforethecursor
CkCuteverythingafterthecursor(restoftheline)
CyPastethelastthingtobecut(simplypaste)
C_Undo
Note.C=holdcontrol,M=holdmeta(whichisusuallythealtorescapekey).
21 SCRI PTI NG
Basics|Scriptexample|awk|sed|RegularExpressions|usefulcommands
TheBourneshell(/bin/sh)ispresentonallUnixinstallationsandscriptswritteninthislanguageare(quite)
portablenah 1 shisagoodreference.
21.1Basics
Variablesandarguments
Assignwithvariable=valueandgetcontentwith$variable
hE55AuE="heJJo WoJd" # Ass1gh a st1hg
PT=3.1415 # Ass1gh a dec1naJ hunbe
2/27/12 Uni Toolbo
42/45 cb.vu/unitoolbo.html
N=B
TWuN=`exp $N * 2` # A1thnet1c expess1oh {ohJy 1hteges}
TWuN=${{$N * 2}} # uthe syhtax
TWuPT=`echo "$PT * 2" | bc -J` # Use bc fo fJoat1hg po1ht opeat1ohs
ZERu=`echo "c{$PT74}-sqt{2}72" | bc -J`
Thecommandlineargumentsare
$u, $1, $2, ... # $u 1s the connahd 1tseJf
$# # The hunbe of agunehts
$* # AJJ agunehts {aJso $}
SpecialVariables
$$ # The cueht pocess Tu
$? # ex1t status of Jast connahd
connahd
1f | $? != u theh
echo "connahd fa1Jed"
f1
nypath=`pWd`
nypath=${nypath}7f1Je.txt
echo ${nypath##*7} # u1spJay the f1Jehane ohJy
echo ${nypathZZ.*} # FuJJ path W1thout exteht1oh
va2=${va.=st1hg} # Use va 1f set, otheW1se use st1hg
# ass1gh st1hg to va ahd theh to va2.
Constructs
fo f1Je 1h `Js`
do
echo $f1Je
dohe
couht=u
Wh1Je | $couht -Jt 5 do
echo $couht
sJeep 1
couht=${{$couht + 1}}
dohe
nyfuhct1oh{} {
f1hd . -type f -hane "*.$1" -p1ht # $1 1s f1st aguneht of the fuhct1oh
}
nyfuhct1oh "txt"
Generate a l|/e
hYhuhE=7hone7coJ1h
cat > testhone.sh << EuF
# AJJ of th1s goes 1hto the f1Je testhone.sh
1f | -d "$hYhuhE" theh
echo $hYhuhE ex1sts
eJse
echo $hYhuhE does hot ex1st
f1
EuF
sh testhone.sh
21.2Bournescriptexample
Asasmallexample,thescriptusedtocreateaPDFbookletfromthisxhtmldocument:
#!7b1h7sh
# Th1s sc1pt ceates a book 1h pdf fonat eady to p1ht oh a dupJex p1hte
1f | $# -he 1 theh # Check the aguneht
echo 1>82 "Usage. $u htnJF1Je"
ex1t 1 # hoh zeo ex1t 1f eo
f1
f1Je=$1 # Ass1gh the f1Jehane
fhane=${f1JeZ.*} # uet the hane of the f1Je ohJy
fext=${f1Je#*.} # uet the extehs1oh of the f1Je
p1hce $f1Je -o $fhane.pdf # fon WWW.p1hcexnJ.con
pdftops -pape A4 -hosh1hk $fhane.pdf $fhane.ps # ceate postsc1pt bookJet
cat $fhane.ps |psbook|pshup -Pa4 -2 |pstops -b "2.u,1U{21cn,29.7cn}" > $fhane.book.ps
ps2pdf13 -sPAPER5TZE=a4 -sAutoRotatePages=Nohe $fhane.book.ps $fhane.book.pdf
# use #a4 ahd #Nohe oh W1hdoWs!
ex1t u # ex1t u neahs successfuJ
21.3Someawkcommands
Awk is useful for field stripping, like cut in a more powerful way. Search this document for other examples.
Seeforexamplegnulamp.comandonelinersforawkforsomeniceexamples.
aWk '{ p1ht $2, $1 }' f1Je # P1ht ahd 1hvese f1st tWo coJunhs
aWk '{p1htf{"Z5d . Zs`h", NR,$u}}' f1Je # Add J1he hunbe Jeft aJ1ghed
2/27/12 Uni Toolbo
43/45 cb.vu/unitoolbo.html
aWk '{p1ht FNR "`t" $u}' f1Jes # Add J1he hunbe 1ght aJ1ghed
aWk NF test.txt # enove bJahk J1hes {sane as gep '.'}
aWk 'Jehgth > Bu' # p1ht J1he Johge thah Bu cha}
21.4Somesedcommands
Here is the one liner gold mine
http://student.northpark.edu/pemente/sed/sed1line.txt
. And a good introduction and tutorial to
sed
http://www.gry moire.com/Unix/Sed.html
.
sed 's7st1hg17st1hg27g' # RepJace st1hg1 W1th st1hg2
sed -1 's7Woohg7Wohg7g' *.txt # RepJace a ecu1hg Wod W1th g
sed 's7`{.*`}17`127g' # hod1fy ahyst1hg1 to ahyst1hg2
sed '7<p>7,7<`7p>7d' t.xhtnJ # ueJete J1hes that stat W1th <p>
# ahd ehd W1th <7p>
sed '7 *#7d 7^ *$7d' # Renove connehts ahd bJahk J1hes
sed 's7| `t*$77' # Renove ta1J1hg spaces {use tab as `t}
sed 's7^| `t*77s7| `t*$77' # Renove Jead1hg ahd ta1J1hg spaces
sed 's7|^*7|87' # EhcJose f1st cha W1th | top->|top
sed = f1Je | sed 'Ns7`h7`t7' > f1Je.hun # Nunbe J1hes oh a f1Je
21.5RegularExpressions
Somebasicregularexpressionusefulforsedtoo.SeeBasicRegexSyntax
http://www.regularexpressions.inf o/ref erence.html
foragoodprimer.
|`^$.|?*+{} # spec1aJ chaactes ahy othe W1JJ natch thenseJves
` # escapes spec1aJ chaactes ahd teat as J1teaJ
* # epeat the pev1ous 1ten zeo o noe t1nes
. # s1hgJe chaacte except J1he beak chaactes
.* # natch zeo o noe chaactes
^ # natch at the stat of a J1he7st1hg
$ # natch at the ehd of a J1he7st1hg
.$ # natch a s1hgJe chaacte at the ehd of J1he7st1hg
^ $ # natch J1he W1th a s1hgJe space
|^A-Z # natch ahy J1he beg1hh1hg W1th ahy cha fon A to Z
21.6Someusefulcommands
Thefollowingcommandsareusefultoincludeinascriptorasoneliners.
sot -t. -k1,1h -k2,2h -k3,3h -k4,4h # 5ot TPv4 1p addesses
echo 'Test' | t '|.JoWe.' '|.uppe.' # Case cohves1oh
echo foo.ba | cut -d . -f 1 # Retuhs foo
PTu=${ps | gep sc1pt.sh | gep b1h | aWk '{p1ht $1}'} # PTu of a uhh1hg sc1pt
PTu=${ps axWW | gep |p1hg | aWk '{p1ht $1}'} # PTu of p1hg {W7o gep p1d}
TP=${1fcohf1g $TNTERFACE | sed '7.*1het add.7!ds777s7 .*77'} # L1hux
TP=${1fcohf1g $TNTERFACE | sed '7.*1het 7!ds777s7 .*77'} # FeeB5u
1f | `d1ff f1Je1 f1Je2 | Wc -J` != u theh |... f1 # F1Je chahged?
cat 7etc7naste.passWd | gep -v oot | gep -v `*. | aWk -F"." ` # Ceate http passWd
'{ p1htf{"Zs.Zs`h", $1, $2} }' > 7us7JocaJ7etc7apache27passWd
testuse=${cat 7us7JocaJ7etc7apache27passWd | gep -v ` # Check use 1h passWd
oot | gep -v `*. | aWk -F"." '{ p1htf{"Zs`h", $1} }' | gep ^use$}
.{}{ .|.8 }. # bash fok bonb. W1JJ k1JJ you nach1he
ta1J +2 f1Je > f1Je2 # enove the f1st J1he fon f1Je
Iusethislittletricktochangethefileextensionformanyfilesatonce.Forexamplefrom.cxxto.cpp.Testit
first without the | sh at the end. You can also do this with the command ehane if installed. Or with bash
builtins.
# Js *.cxx | aWk -F. '{p1ht "nv "$u" "$1".cpp"}' | sh
# Js *.c | sed "s7.*7cp 8 8.${date "+ZYZnZd"}7" | sh # e.g. copy *.c to *.c.2uuBu4u1
# ehane .cxx .cpp *.cxx # Rehane aJJ .cxx to cpp
# fo 1 1h *.cxx do nv $1 ${1ZZ.cxx}.cpp dohe # W1th bash bu1Jt1hs
22 PROGRAMMI NG
22.1Cbasics
stcpy{heWst,st} 7* copy st to heWst *7
exp1 ? exp2 . exp3 7* 1f {exp1} exp2 eJse exp3 *7
x = {y > z} ? y . z 7* 1f {y > z} x = y eJse x = z *7
1ht a|={u,1,2} 7* Th1t1aJ1zed aay {o a|3={u,1,2} *7
1ht a|2|3={{1,2,3},{4,5,}} 7* Aay of aay of 1hts *7
1ht 1 = 12345 7* Cohvet 1h 1 to cha st *7
cha st|1u
sp1htf{st, "Zd", 1}
22.2Cexample
Aminimalcprogramsimple.c:
#1hcJude <std1o.h>
na1h{} {
2/27/12 Uni Toolbo
44/45 cb.vu/unitoolbo.html
1ht hunbe=42
p1htf{"The ahsWe 1s Z1`h", hunbe}
}
Compilewith:
# gcc s1npJe.c -o s1npJe
# .7s1npJe
The ahsWe 1s 42
22.3C++basics
*po1hte 77 ubect po1hted to by po1hte
8ob 77 Addess of obect ob
ob.x 77 henbe x of cJass ob {obect ob}
pob->x 77 henbe x of cJass po1hted to by pob
77 {*pob}.x ahd pob->x ae the sane
22.4C++example
AsaslightlymorerealisticprograminC++:aclassinitsownheader(IPv4.h)andimplementation(IPv4.cpp)
andaprogramwhichusestheclassfunctionality.TheclassconvertsanIPaddressinintegerformattothe
knownquadformat.
IPv4class
lPv4.h.
#1fhdef TPv4h
#def1he TPv4h
#1hcJude <st1hg>
hanespace uehe1cUt1Js { 77 ceate a hanespace
cJass TPv4 { 77 cJass def1h1t1oh
pubJ1c.
TPv4{} ~TPv4{}
std..st1hg TP1httoTPquad{uhs1ghed Johg 1p}77 nenbe 1hteface
}
} 77hanespace uehe1cUt1Js
#ehd1f 77 TPv4h
lPv4.cpp.
#1hcJude "TPv4.h"
#1hcJude <st1hg>
#1hcJude <sstean>
us1hg hanespace std 77 use the hanespaces
us1hg hanespace uehe1cUt1Js
TPv4..TPv4{} {} 77 defauJt cohstucto7destucto
TPv4..~TPv4{} {}
st1hg TPv4..TP1httoTPquad{uhs1ghed Johg 1p} { 77 nenbe 1npJenehtat1oh
ost1hgstean 1pst 77 use a st1hgstean
1pst << {{1p 8uxffuuuuuu} >> 24} 77 B1tW1se 1ght sh1ft
<< "." << {{1p 8uxuuffuuuu} >> 1}
<< "." << {{1p 8uxuuuuffuu} >> B}
<< "." << {{1p 8uxuuuuuuff}}
etuh 1pst.st{}
}
Theprogramsimplecpp.cpp
#1hcJude "TPv4.h"
#1hcJude <1ostean>
#1hcJude <st1hg>
us1hg hanespace std
1ht na1h {1ht agc, cha* agv|} {
st1hg 1pst 77 def1he va1abJes
uhs1ghed Johg 1p1ht = 1347B14B 77 The TP 1h 1htege fon
uehe1cUt1Js..TPv4 1put1Js 77 ceate ah obect of the cJass
1pst = 1put1Js.TP1httoTPquad{1p1ht} 77 caJJ the cJass nenbe
cout << 1p1ht << " = " << 1pst << ehdJ 77 p1ht the esuJt
etuh u
}
Compileandexecutewith:
# g++ -c TPv4.cpp s1npJecpp.cpp # Conp1Je 1h obects
# g++ TPv4.o s1npJecpp.o -o s1npJecpp.exe # L1hk the obects to f1haJ executabJe
# .7s1npJecpp.exe
1347B14B = Bu.B.1B7.23B
UseJddtocheckwhichlibrariesareusedbytheexecutableandwheretheyarelocated.Alsousedtocheck
ifasharedlibraryismissingoriftheexecutableisstatic.
# Jdd 7sb1h71fcohf1g # J1st dyhan1c obect depehdehc1es
# a cs stat1cJ1b.a *.o # ceate stat1c ach1ve
2/27/12 Uni Toolbo
45/45 cb.vu/unitoolbo.html
# a t stat1cJ1b.a # p1ht the obects J1st fon the ach1ve
# a x 7us7J1b7J1bc.a ves1oh.o # extact ah obect f1Je fon the ach1ve
# hn ves1oh.o # shoW fuhct1oh nenbes pov1ded by obect
22.5SimpleMakefile
TheminimalMakefileforthemultisourceprogramisshownbelow.Thelineswithinstructionsmust beg|n w|th
a tab!Thebackslash"\"canbeusedtocutlonglines.
CC = g++
CFLAu5 = -u
uBJ5 = TPv4.o s1npJecpp.o
s1npJecpp. ${uBJ5}
${CC} -o s1npJecpp ${CFLAu5} ${uBJ5}
cJeah.
n -f ${TARuET} ${uBJ5}
23 ONLI NE HELP
23.1Documentation
LinuxDocumentation en.tldp.org
LinuxManPages www.linuxmanpages.com
Linuxcommandsdirectory www.oreillynet.com/linux/cmd
Linuxdocmanhowtos linux.die.net
FreeBSDHandbook www.freebsd.org/handbook
FreeBSDManPages www.freebsd.org/cgi/man.cgi
FreeBSDuserwiki www.freebsdwiki.net
SolarisManPages docs.sun.com/app/docs/coll/40.10
23.2OtherUnix/Linuxreferences
RosettaStoneforUnix bhami.com/rosetta.html(aUnixcommandtranslator)
Unixguidecrossreference unixguide.net/unixguide.shtml
Linuxcommandslinelist www.linuxcmd.org
ShortLinuxreference www.pixelbeat.org/cmdline.html
Littlecommandlinegoodies www.shellfu.org
That'sallfolks!
UnixToolboxrevision14.3
The latest version of this document can be found at http://cb.vu/unixtoolbox.xhtml. Replace .xhtml on the link
with.pdf for the PDF version and with .book.pdf for the booklet version. On a duplex printer the booklet will
createasmallbookreadytobind.Seealsotheaboutpage.
Errorreportsandcommentsaremostwelcomec@cb.vuColinBarschel.
This document: "Unix Toolbox revision 14.3" is licensed under a Creative Commons Licence [Attribution
ShareAlike].ColinBarschel20072011.Somerightsreserved.

Das könnte Ihnen auch gefallen