unixtoolbox.xhtml 216 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391
  1. <?xml version="1.0" encoding="UTF-8" ?> <!-- -*- coding: utf-8 -*- -->
  2. <!DOCTYPE html PUBLIC
  3. "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN"
  4. "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg-flat.dtd">
  5. <html xmlns="http://www.w3.org/1999/xhtml"
  6. xmlns:svg="http://www.w3.org/2000/svg" xml:lang="en">
  7. <head>
  8. <title>Unix Toolbox</title>
  9. <link rel="icon" href="data:image/x-icon;base64,AAABAAEAEBAAAAAAAABoBQAAFgAAACgAAAAQAAAAIAAAAAEACAAAAAAAQAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAA////AOBfLwBbX14AWxgYABg8RwC/g14AGBgYAL9OJAB8KhgAfHFeAOCDUgC/g0cAGCo7AOCDXgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcJCw4ODg4ODgUHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcLCgcHBwcHBwcHBwcHBwcHBwgOBQcHBwcHBwcHBwcHBwcHBAwNBwcHBwcHBwcHBwcHBwcJCwMHBwcHBwcHBwcHBwcCBg0HBwcHBwcHBwcHBwkLAwcHBwcHBwcHBwcHBwcMDQcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=" />
  10. <meta name="author" content="Colin Barschel c@cb.vu" />
  11. <meta name="copyright" content="Copyright (c) 2007-2016 Colin Barschel. Some rights reserved under Creative Commons [Attribution - Share Alike]" />
  12. <meta name="description" content="A collection of Unix/Linux/BSD commands and tasks which are useful for IT work or for advanced users, a compact and practical reference." />
  13. <meta name="abstract" content="Unix Toolbox a compact and practical reference for sysadmins and advanced users." />
  14. <meta name="subject" content="Unix Toolbox revision 14.5" />
  15. <meta name="keywords" content="Unix Toolbox, Unix tools, Unix, FreeBSD, Linux, commands list, sysadmin, practical guide, advanced reference, common Linux tasks, syntax reminder, howtos, ssh tunnels, rsync, ssl certificates" />
  16. <style type="text/css" >
  17. /* basic CSS common to all media */
  18. html {
  19. margin: 0;
  20. }
  21. body {
  22. padding: 0;
  23. font-family: verdana, arial, sans-serif;
  24. font-size: 90%;
  25. counter-reset: chapter section;
  26. }
  27. div.title {
  28. text-transform: uppercase;
  29. padding: 1em 0;
  30. text-align: center;
  31. font-size: 220%;
  32. font-weight: bold;
  33. letter-spacing: .22em;
  34. }
  35. h1, h2, h3 div.title {
  36. font-family: verdana, sans-serif;
  37. }
  38. h1 {
  39. text-transform: uppercase;
  40. font-size: 150%;
  41. letter-spacing: .15em;
  42. counter-reset: section;
  43. string-set: chaptertitle content();
  44. }
  45. h2 {
  46. font-size: 120%;
  47. letter-spacing: .10em;
  48. }
  49. h3, h4 {
  50. font-size: 100%;
  51. line-height:1em;
  52. letter-spacing: .07em;
  53. }
  54. h4 {
  55. font-style: italic;
  56. font-weight: normal;
  57. margin: 1em 0 0.5em 0;
  58. }
  59. pre {
  60. padding: 0.1em 0em 0.1em 1em;
  61. }
  62. div.menu a {
  63. font-weight: normal;
  64. text-decoration: none;
  65. }
  66. h1:before {
  67. content: counter(chapter) " ";
  68. counter-increment: chapter;
  69. }
  70. h2:before {
  71. counter-increment: section;
  72. content: counter(chapter) "." counter(section) " ";
  73. }
  74. /* Not implemented in browsers yet */
  75. a.xref:after {
  76. content: " " target-counter(attr(href, url), chapter) "."
  77. target-counter(attr(href, url), section);
  78. }
  79. div.changestyle {
  80. padding-top: 1em;
  81. }
  82. @media screen, handheld {
  83. /* Menu on the right for screen media */
  84. /* including some IE6 hacks */
  85. body {
  86. padding: 0;
  87. margin: 1em 13em 0em 1.5em;
  88. }
  89. html>body {
  90. margin: 1em 13em 0em 1.5em;
  91. }
  92. body>div.menu {
  93. position: fixed;
  94. }
  95. body>div.changestyle {
  96. position: fixed;
  97. }
  98. div.menu {
  99. position: absolute;
  100. z-index: 2;
  101. width: 10.7em; height: auto;
  102. top: 0.4em; right: 0.5em; bottom: 0.8em; left: auto;
  103. }
  104. div.changestyle {
  105. font-size: 80%;
  106. font-weight: normal;
  107. position: absolute;
  108. z-index: 2;
  109. width: 10.7em; height: auto;
  110. bottom: 0;
  111. }
  112. ol.toc, ol.toc li {
  113. margin: 0;
  114. list-style-type: none;
  115. padding: 0.13em 0;
  116. text-indent: 0;
  117. text-align: left;
  118. line-height: 1.1em;
  119. }
  120. p.last {
  121. padding-top: 5em;
  122. }
  123. .fn {
  124. display: none;
  125. counter-increment: footnote
  126. }
  127. }
  128. @media print {
  129. /* layout */
  130. /* Menu as TOC for print */
  131. body {
  132. font-size: 88%;
  133. }
  134. div.title {
  135. padding: 0.5em 0 2em 0;
  136. }
  137. div {
  138. text-align: justify;
  139. }
  140. h2 {
  141. margin-bottom: 0.5em;
  142. }
  143. h3 {
  144. margin-bottom: 0.3em;
  145. }
  146. h4 {
  147. margin-bottom: 0.3em;
  148. }
  149. pre {
  150. font-size: 90%;
  151. margin: 0.3em 0 0.3em 0;
  152. padding: 0.2em 0 0.2em 0.4em;
  153. text-align: left;
  154. line-height: 115%;
  155. letter-spacing:-0.03em
  156. }
  157. a {
  158. text-decoration: none;
  159. }
  160. p.xrefp { /* links below h1 headers */
  161. padding-top: 0;
  162. margin: -1em 0 1.3em 0;
  163. page-break-inside: avoid;
  164. page-break-after: avoid;
  165. }
  166. a.xrefp {
  167. font-weight: normal;
  168. text-decoration: none;
  169. }
  170. ol.toc li {
  171. list-style-type: decimal;
  172. margin: 0;
  173. padding: 0.25em 0;
  174. }
  175. ol.toc {
  176. margin: 0 0 0 2.2em;
  177. list-style-position: outside;
  178. font-weight: normal;
  179. list-style-type: decimal;
  180. padding: 4em 0;
  181. }
  182. ol.toc a::after {
  183. content: leader(' . ') target-counter(attr(href), page);
  184. }
  185. /*
  186. a.xref:after {
  187. content: " [" target-counter(attr(href, url), chapter) "."
  188. target-counter(attr(href, url), section) " page "
  189. target-counter(attr(href, url), page) "]";
  190. }
  191. */
  192. a.xref:after {
  193. content: " (page " target-counter(attr(href, url), page) ")";
  194. }
  195. a.xrefp:after {
  196. content: " (p"target-counter(attr(href, url), page)")";
  197. }
  198. h1, h2, h3, h4, h5 {
  199. page-break-after: avoid;
  200. }
  201. div.footerfirst, div.footerlast {
  202. position: absolute;
  203. bottom: 0;
  204. }
  205. div.main {
  206. page-break-before: always;
  207. }
  208. div.pb {
  209. page-break-after: always;
  210. }
  211. div.changestyle, p.copyright, span.web {
  212. display: none;
  213. }
  214. div#sysinfo {
  215. margin-top: -1.5em;
  216. }
  217. p.last {
  218. padding-top: 2em;
  219. }
  220. .fn {
  221. display: prince-footnote;
  222. counter-increment: footnote;
  223. font: caption;
  224. font-stretch: normal;
  225. letter-spacing: normal;
  226. font-size: xx-small;
  227. font-style: normal;
  228. font-weight: normal;
  229. text-decoration: none;
  230. vertical-align: super;
  231. }
  232. .fn::footnote-call {
  233. content: counter(footnote);
  234. font-size: 80%;
  235. font-style: normal;
  236. font-weight: normal;
  237. text-decoration: none;
  238. vertical-align: super;
  239. line-height: none
  240. }
  241. .fn::footnote-marker {
  242. list-style-position: inside;
  243. }
  244. }
  245. @page {
  246. size: A4 portrait;
  247. margin: 15mm 12mm 14mm 12mm;
  248. padding: 0mm 0 5mm 0;
  249. @footnotes {
  250. border-top: solid #000040 thin;
  251. padding-top: 0.22em;
  252. padding-left: 1.2em;
  253. font-family: verdana, sans-serif;
  254. }
  255. @bottom-center {
  256. padding: 0 0 5mm 0;
  257. content: counter(page);
  258. font-family: verdana, sans-serif;
  259. font-size: 88%;
  260. }
  261. @top {
  262. padding-top: 5mm;
  263. content: "&#8212; " string(chaptertitle) " &#8212;";
  264. font-family: verdana, sans-serif;
  265. }
  266. }
  267. @page :first {
  268. padding: 0;
  269. @bottom-center {
  270. content: normal;
  271. }
  272. @top {
  273. content: normal;
  274. }
  275. }
  276. </style>
  277. <style type="text/css" title="default" >
  278. @media screen, handheld, print {
  279. /* Colors only */
  280. html {
  281. background-color: white;
  282. color: black;
  283. }
  284. h1 {
  285. background-color: #000040;
  286. color: white;
  287. }
  288. h3, h4, div.title, h2, a:link, a:visited, .cmt {
  289. background-color: transparent;
  290. color: #000040;
  291. }
  292. pre {
  293. background-color: #F6F6FC;
  294. }
  295. pre, code {
  296. color: #003300;
  297. }
  298. a:hover, .pp {
  299. color: #D55500;
  300. }
  301. a:active {
  302. color: green;
  303. }
  304. .keyword {
  305. color:#0000FF;
  306. }
  307. }
  308. @media print {
  309. /* print only colors */
  310. pre, code {
  311. color: #000;
  312. }
  313. a:link, a:visited, .cmt {
  314. background-color: transparent;
  315. color: #000060;
  316. }
  317. }
  318. </style>
  319. <style type="text/css" title="inverse" >
  320. @media screen, handheld {
  321. /* Colors only */
  322. html {
  323. background-color: black;
  324. color: Gainsboro;
  325. }
  326. h1 {
  327. background-color: #ffffcd;
  328. color: black;
  329. }
  330. h3, h4, div.title, h2, a:link, a:visited, .cmt {
  331. background-color: transparent;
  332. color: #ffffcd;
  333. }
  334. pre {
  335. background-color: #090903;
  336. }
  337. pre, code {
  338. color: #ffc3ff;
  339. }
  340. a:hover, .pp {
  341. color: #2aaaff;
  342. }
  343. a:active {
  344. color: orange;
  345. }
  346. .keyword {
  347. color:#ff0000;
  348. }
  349. }
  350. </style>
  351. <!-- Script to change the color of the site via the above two styles and
  352. save the selection into a cookie. The cookie is only generated when
  353. either the link "white" or "black" is clicked -->
  354. <!-- This does not word on Safari and Konqueror. Can someone fix it? -->
  355. <script type="text/javascript" >
  356. /*<![CDATA[*/
  357. function initCSS() {
  358. var cookie = readCookie("style");
  359. var title = cookie ? cookie : "default";
  360. setActiveStyle(title);
  361. }
  362. function setActiveStyle(title) {
  363. var j = document.getElementsByTagName("style");
  364. for(var i=1; i < j.length; i++) { // bypass the first (main) style
  365. j[i].disabled = true;
  366. if(j[i].getAttribute("title") == title) {
  367. j[i].disabled = false;
  368. }
  369. }
  370. }
  371. /* Only create a cookie when the link is clicked */
  372. function setActiveStyleLink(title) {
  373. setActiveStyle(title)
  374. createCookie("style", title, 365);
  375. }
  376. function createCookie(name,value,days) {
  377. if (days) {
  378. var date = new Date();
  379. date.setTime(date.getTime()+(days*24*60*60*1000));
  380. var expires = "; expires="+date.toGMTString();
  381. }
  382. else expires = "";
  383. document.cookie = name+"="+value+expires+"; path=/";
  384. }
  385. function readCookie(name) {
  386. var nameEQ = name + "=";
  387. var ca = document.cookie.split(';');
  388. for(var i=0;i < ca.length;i++) {
  389. var c = ca[i];
  390. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  391. if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  392. }
  393. return null;
  394. }
  395. window.onload = initCSS();
  396. /*]]>*/
  397. </script>
  398. </head>
  399. <body>
  400. <div class="title">Unix Toolbox</div>
  401. <div class="abstract">
  402. This document is a collection of Unix/Linux/BSD commands and tasks which are useful for IT work or for advanced users. This is a practical guide with concise explanations, however the reader is supposed to know what s/he is doing.<br /><br />
  403. </div>
  404. <div class="footerfirst">
  405. Unix Toolbox revision 14.5<br />
  406. The latest version of this document can be found at <a href="http://cb.vu/unixtoolbox.xhtml">http://cb.vu/unixtoolbox.xhtml</a>. Replace .xhtml on the link with <a href="http://cb.vu/unixtoolbox.pdf">.pdf</a> for the PDF version and with <a href="http://cb.vu/unixtoolbox.book.pdf">.book.pdf</a> for the booklet version. On a duplex printer the booklet will create a small book ready to bind. <span class="web">This XHTML page can be converted into a nice PDF document with a CSS3 compliant application (see the <a class="xref" href="#bourneexample">script example</a>).</span> See also the <a href="http://cb.vu/unixtoolbox">about page</a>.<br />
  407. Error reports and comments are most welcome - <a href="mailto:c\at\cb.vu">c@cb.vu</a> Colin Barschel.
  408. <p class="copyright">&#169; <a href="mailto:c_at_cb.vu">Colin Barschel</a> 2007-2016. <a rel="license" href="http://creativecommons.org/licenses/by-sa/3.0/">Some rights reserved under Creative Commons</a>.
  409. </p>
  410. </div>
  411. <!-- The table of content is displayed as a fixed vertical right menu
  412. when viewed in a browser. When printed TOC is displayed on the front
  413. page as a classical table of content with page numbers -->
  414. <div class="menu">
  415. <ol class="toc">
  416. <li><a href="#sysinfo">System</a></li>
  417. <li><a href="#processes">Processes</a></li>
  418. <li><a href="#filesystem">File System</a></li>
  419. <li><a href="#network">Network</a></li>
  420. <li><a href="#ssh">SSH SCP</a></li>
  421. <li><a href="#vpn">VPN with SSH</a></li>
  422. <li><a href="#rsync">RSYNC</a></li>
  423. <li><a href="#sudo">SUDO</a></li>
  424. <li><a href="#crypt">Encrypt Files</a></li>
  425. <li><a href="#cryptpart">Encrypt Partitions</a></li>
  426. <li><a href="#certs">SSL Certificates</a></li>
  427. <li><a href="#cvs">CVS</a></li>
  428. <li><a href="#svn">SVN</a></li>
  429. <li><a href="#other">Useful Commands</a></li>
  430. <li><a href="#software">Install Software</a></li>
  431. <li><a href="#convert">Convert Media</a></li>
  432. <li><a href="#printing">Printing</a></li>
  433. <li><a href="#databases">Databases</a></li>
  434. <li><a href="#quota">Disk Quota</a></li>
  435. <li><a href="#shells">Shells</a></li>
  436. <li><a href="#scripting">Scripting</a></li>
  437. <li><a href="#programming">Programming</a></li>
  438. <li><a href="#onlinehelp">Online Help</a></li>
  439. </ol>
  440. <br />
  441. <div class="changestyle"> <!-- small icons for black and white view. SVG is embedded -->
  442. <a href="#" onclick="setActiveStyleLink('default'); return false;">
  443. <svg:svg width="15" height="10" viewBox="0 0 310 210">
  444. <svg:rect x="5" y="5" width="300" height="200" style="stroke:black;stroke-width:7;fill:white" />
  445. <svg:line x1="25" y1="55" x2="280" y2="55" style="stroke:black;stroke-width:7;" />
  446. <svg:line x1="25" y1="100" x2="280" y2="100" style="stroke:black;stroke-width:7;" />
  447. <svg:line x1="25" y1="148" x2="280" y2="148" style="stroke:black;stroke-width:7;" />
  448. </svg:svg> white
  449. </a>
  450. <a href="#" onclick="setActiveStyleLink('inverse'); return false;">
  451. <svg:svg width="15" height="10" viewBox="0 0 310 210">
  452. <svg:rect x="5" y="5" width="300" height="200" style="stroke:white;stroke-width:7;fill:black" />
  453. <svg:line x1="25" y1="55" x2="280" y2="55" style="stroke:white;stroke-width:10;" />
  454. <svg:line x1="25" y1="100" x2="280" y2="100" style="stroke:white;stroke-width:10;" />
  455. <svg:line x1="25" y1="148" x2="280" y2="148" style="stroke:white;stroke-width:10;" />
  456. </svg:svg> black
  457. </a>
  458. </div> <!-- end change style links -->
  459. </div> <!-- end menu -->
  460. <div class="pb" />
  461. <!-- <div class="main"> Every chapter is inside a div block for easy XML parsing -->
  462. <div id="sysinfo"><h1><a>System</a></h1>
  463. <p class="xrefp"><a class="xrefp" href="#hardwareinfo">Hardware</a> | <a class="xrefp" href="#loadstats">Statistics</a> | <a class="xrefp" href="#users">Users</a> | <a class="xrefp" href="#limits">Limits</a> | <a class="xrefp" href="#runlevels">Runlevels</a> | <a class="xrefp" href="#resetpasswd">root password</a> | <a class="xrefp" href="#compilekernel">Compile kernel</a> | <a class="xrefp" href="#grub">Repair grub</a> | <a class="xrefp" href="#sysmisc">Misc</a></p>
  464. Running kernel and system information
  465. <pre># uname -a <span class="cmt"># Get the kernel version (and BSD version)</span>
  466. # lsb_release -a <span class="cmt"># Full release info of any LSB distribution</span>
  467. # cat /etc/SuSE-release <span class="cmt"># Get SuSE version</span>
  468. # cat /etc/debian_version <span class="cmt"># Get Debian version</span>
  469. </pre>
  470. Use /etc/<code>DISTR</code>-release with <code>DISTR=</code> lsb (Ubuntu), redhat, gentoo, mandrake, sun (Solaris), and so on. See also <code>/etc/issue</code>.
  471. <pre># uptime <span class="cmt"># Show how long the system has been running + load</span>
  472. # hostname <span class="cmt"># system's host name</span>
  473. # hostname -i <span class="cmt"># Display the IP address of the host. (Linux only)</span>
  474. # man hier <span class="cmt"># Description of the file system hierarchy</span>
  475. # last reboot <span class="cmt"># Show system reboot history</span>
  476. </pre>
  477. <h2 id="hardwareinfo">Hardware Informations</h2>
  478. Kernel detected hardware
  479. <pre># dmesg <span class="cmt"># Detected hardware and boot messages</span>
  480. # lsdev <span class="cmt"># information about installed hardware</span>
  481. # dd if=/dev/mem bs=1k skip=768 count=256 2>/dev/null | strings -n 8 <span class="cmt"># Read BIOS</span>
  482. </pre>
  483. <h3>Linux</h3>
  484. <pre># cat /proc/cpuinfo <span class="cmt"># CPU model</span>
  485. # cat /proc/meminfo <span class="cmt"># Hardware memory</span>
  486. # grep MemTotal /proc/meminfo <span class="cmt"># Display the physical memory</span>
  487. # watch -n1 'cat /proc/interrupts' <span class="cmt"># Watch changeable interrupts continuously</span>
  488. # free -m <span class="cmt"># Used and free memory (-m for MB)</span>
  489. # cat /proc/devices <span class="cmt"># Configured devices</span>
  490. # lspci -tv <span class="cmt"># Show PCI devices</span>
  491. # lsusb -tv <span class="cmt"># Show USB devices</span>
  492. # lshal <span class="cmt"># Show a list of all devices with their properties</span>
  493. # dmidecode <span class="cmt"># Show DMI/SMBIOS: hw info from the BIOS</span>
  494. </pre>
  495. <h3>FreeBSD</h3>
  496. <pre># sysctl hw.model <span class="cmt"># CPU model</span>
  497. # sysctl hw <span class="cmt"># Gives a lot of hardware information</span>
  498. # sysctl hw.ncpu <span class="cmt"># number of active CPUs installed</span>
  499. # sysctl vm <span class="cmt"># Memory usage</span>
  500. # sysctl hw.realmem <span class="cmt"># Hardware memory</span>
  501. # sysctl -a | grep mem <span class="cmt"># Kernel memory settings and info</span>
  502. # sysctl dev <span class="cmt"># Configured devices</span>
  503. # pciconf -l -cv <span class="cmt"># Show PCI devices</span>
  504. # usbdevs -v <span class="cmt"># Show USB devices</span>
  505. # atacontrol list <span class="cmt"># Show ATA devices</span>
  506. # camcontrol devlist -v <span class="cmt"># Show SCSI devices</span>
  507. </pre>
  508. <h2 id="loadstats">Load, statistics and messages</h2>
  509. The following commands are useful to find out what is going on on the system.
  510. <pre># top <span class="cmt"># display and update the top cpu processes</span>
  511. # mpstat 1 <span class="cmt"># display processors related statistics</span>
  512. # vmstat 2 <span class="cmt"># display virtual memory statistics</span>
  513. # iostat 2 <span class="cmt"># display I/O statistics (2 s intervals)</span>
  514. # systat -vmstat 1 <span class="cmt"># BSD summary of system statistics (1 s intervals)</span>
  515. # systat -tcp 1 <span class="cmt"># BSD tcp connections (try also -ip)</span>
  516. # systat -netstat 1 <span class="cmt"># BSD active network connections</span>
  517. # systat -ifstat 1 <span class="cmt"># BSD network traffic through active interfaces</span>
  518. # systat -iostat 1 <span class="cmt"># BSD CPU and and disk throughput</span>
  519. # ipcs -a <span class="cmt"># information on System V interprocess</span>
  520. # tail -n 500 /var/log/messages <span class="cmt"># Last 500 kernel/syslog messages</span>
  521. # tail /var/log/warn <span class="cmt"># System warnings messages see syslog.conf</span>
  522. </pre>
  523. <h2 id="users">Users</h2>
  524. <pre># id <span class="cmt"># Show the active user id with login and group</span>
  525. # last <span class="cmt"># Show last logins on the system</span>
  526. # who <span class="cmt"># Show who is logged on the system</span>
  527. # groupadd admin <span class="cmt"># Add group "admin" and user colin (Linux/Solaris)</span>
  528. # useradd -c "Colin Barschel" -g admin -m colin
  529. # usermod -a -G &lt;group&gt; &lt;user&gt; <span class="cmt"># Add existing user to group (Debian)</span>
  530. # groupmod -A &lt;user&gt; &lt;group&gt; <span class="cmt"># Add existing user to group (SuSE)</span>
  531. # userdel colin <span class="cmt"># Delete user colin (Linux/Solaris)</span>
  532. # adduser joe <span class="cmt"># FreeBSD add user joe (interactive)</span>
  533. # rmuser joe <span class="cmt"># FreeBSD delete user joe (interactive)</span>
  534. # pw groupadd admin <span class="cmt"># Use pw on FreeBSD</span>
  535. # pw groupmod admin -m newmember <span class="cmt"># Add a new member to a group</span>
  536. # pw useradd colin -c "Colin Barschel" -g admin -m -s /bin/tcsh
  537. # pw userdel colin; pw groupdel admin
  538. </pre>
  539. Encrypted passwords are stored in /etc/shadow for Linux and Solaris and /etc/master.passwd on FreeBSD. If the master.passwd is modified manually (say to delete a password), run <code># pwd_mkdb -p master.passwd</code> to rebuild the database.<br /><br />
  540. To temporarily prevent logins system wide (for all users but root) use nologin. The message in nologin will be displayed (might not work with ssh pre-shared keys).
  541. <pre># echo "Sorry no login now" > /etc/nologin <span class="cmt"># (Linux)</span>
  542. # echo "Sorry no login now" > /var/run/nologin <span class="cmt"># (FreeBSD)</span>
  543. </pre>
  544. <h2 id="limits">Limits</h2>
  545. Some application require higher limits on open files and sockets (like a proxy
  546. web server, database). The default limits are usually too low.
  547. <h3>Linux</h3>
  548. <h4>Per shell/script</h4>
  549. The shell limits are governed by <code>ulimit</code>. The status is checked
  550. with <code>ulimit -a</code>. For example to change the open files limit from
  551. 1024 to 10240 do:
  552. <pre># ulimit -n 10240 <span class="cmt"># This is only valid within the shell</span>
  553. </pre>
  554. The <code>ulimit</code> command can be used in a script to change the limits for the script only.
  555. <h4>Per user/process</h4>
  556. Login users and applications can be configured in <code>/etc/security/limits.conf</code>. For example:
  557. <pre># cat /etc/security/limits.conf
  558. * hard nproc 250 <span class="cmt"># Limit user processes</span>
  559. asterisk hard nofile 409600 <span class="cmt"># Limit application open files</span>
  560. </pre>
  561. <h4>System wide</h4>
  562. Kernel limits are set with sysctl. Permanent limits are set in <code>/etc/sysctl.conf</code>.
  563. <pre># sysctl -a <span class="cmt"># View all system limits</span>
  564. # sysctl fs.file-max <span class="cmt"># View max open files limit</span>
  565. # sysctl fs.file-max=102400 <span class="cmt"># Change max open files limit</span>
  566. # echo "1024 50000" > /proc/sys/net/ipv4/ip_local_port_range <span class="cmt"># port range</span>
  567. # cat /etc/sysctl.conf
  568. fs.file-max=102400 <span class="cmt"># Permanent entry in sysctl.conf</span>
  569. # cat /proc/sys/fs/file-nr <span class="cmt"># How many file descriptors are in use</span>
  570. </pre>
  571. <h3>FreeBSD</h3>
  572. <h4>Per shell/script</h4>
  573. Use the command <code>limits</code> in csh or tcsh or as in Linux, use <code>ulimit</code> in an sh or bash shell.
  574. <h4>Per user/process</h4>
  575. The default limits on login are set in <code>/etc/login.conf</code>. An unlimited value is still limited by the system maximal value.
  576. <h4>System wide</h4>
  577. Kernel limits are also set with sysctl. Permanent limits are set in <code>/etc/sysctl.conf</code> or <code>/boot/loader.conf</code>. The syntax is the same as Linux but the keys are different.
  578. <pre># sysctl -a <span class="cmt"># View all system limits</span>
  579. # sysctl kern.maxfiles=XXXX <span class="cmt"># maximum number of file descriptors</span>
  580. kern.ipc.nmbclusters=32768 <span class="cmt"># Permanent entry in /etc/sysctl.conf</span>
  581. kern.maxfiles=65536 <span class="cmt"># Typical values for Squid</span>
  582. kern.maxfilesperproc=32768
  583. kern.ipc.somaxconn=8192 <span class="cmt"># TCP queue. Better for apache/sendmail</span>
  584. # sysctl kern.openfiles <span class="cmt"># How many file descriptors are in use</span>
  585. # sysctl kern.ipc.numopensockets <span class="cmt"># How many open sockets are in use</span>
  586. # sysctl net.inet.ip.portrange.last=50000 <span class="cmt"># Default is 1024-5000</span>
  587. # netstat -m <span class="cmt"># network memory buffers statistics</span>
  588. </pre>
  589. See The <a href="http://www.freebsd.org/doc/en_US.ISO8859-1/books/handbook/configtuning-kernel-limits.html">FreeBSD handbook Chapter 11</a><span class="fn">http://www.freebsd.org/handbook/configtuning-kernel-limits.html</span> for details. And also <a href="http://serverfault.com/questions/64356/freebsd-performance-tuning-sysctls-loader-conf-kernel">FreeBSD performance tuning</a><span class="fn">http://serverfault.com/questions/64356/freebsd-performance-tuning-sysctls-loader-conf-kernel</span>
  590. <h3>Solaris</h3>
  591. The following values in <code>/etc/system</code> will increase the maximum file descriptors per proc:
  592. <pre>set rlim_fd_max = 4096 <span class="cmt"># Hard limit on file descriptors for a single proc</span>
  593. set rlim_fd_cur = 1024 <span class="cmt"># Soft limit on file descriptors for a single proc</span>
  594. </pre>
  595. <h2 id="runlevels">Runlevels</h2>
  596. <h3>Linux</h3>
  597. Once booted, the kernel starts <code>init</code> which then starts <code>rc</code> which starts all scripts belonging to a runlevel. The scripts are stored in /etc/init.d and are linked into /etc/rc.d/rcN.d with N the runlevel number.<br />
  598. The default runlevel is configured in /etc/inittab. It is usually 3 or 5:
  599. <pre># grep default: /etc/inittab
  600. id:3:initdefault:
  601. </pre>
  602. The actual runlevel can be changed with <code>init</code>. For example to go from 3 to 5:
  603. <pre># init 5 <span class="cmt"># Enters runlevel 5</span></pre>
  604. <ul style="list-style-type:none; page-break-inside:avoid;">
  605. <li>0 &#160; &#160; &#160; Shutdown and halt</li>
  606. <li>1 &#160; &#160; &#160; Single-User mode (also S)</li>
  607. <li>2 &#160; &#160; &#160; Multi-user without network</li>
  608. <li>3 &#160; &#160; &#160; Multi-user with network</li>
  609. <li>5 &#160; &#160; &#160; Multi-user with X</li>
  610. <li>6 &#160; &#160; &#160; Reboot</li>
  611. </ul>
  612. Use <code>chkconfig</code> to configure the programs that will be started at boot in a runlevel.
  613. <pre># chkconfig --list <span class="cmt"># List all init scripts</span>
  614. # chkconfig --list sshd <span class="cmt"># Report the status of sshd</span>
  615. # chkconfig sshd --level 35 on <span class="cmt"># Configure sshd for levels 3 and 5</span>
  616. # chkconfig sshd off <span class="cmt"># Disable sshd for all runlevels</span>
  617. </pre>
  618. Debian and Debian based distributions like Ubuntu or Knoppix use the command <code>update-rc.d</code> to manage the runlevels scripts. Default is to start in 2,3,4 and 5 and shutdown in 0,1 and 6.
  619. <pre># update-rc.d sshd defaults <span class="cmt"># Activate sshd with the default runlevels</span>
  620. # update-rc.d sshd start 20 2 3 4 5 . stop 20 0 1 6 . <span class="cmt"># With explicit arguments</span>
  621. # update-rc.d -f sshd remove <span class="cmt"># Disable sshd for all runlevels</span>
  622. # shutdown -h now (or # poweroff) <span class="cmt"># Shutdown and halt the system</span>
  623. </pre>
  624. <h3>FreeBSD</h3>
  625. The BSD boot approach is different from the SysV, there are no runlevels. The final boot state (single user, with or without X) is configured in <code>/etc/ttys</code>. All OS scripts are located in <code>/etc/rc.d/</code> and in <code>/usr/local/etc/rc.d/</code> for third-party applications. The activation of the service is configured in <code>/etc/rc.conf</code> and <code>/etc/rc.conf.local</code>. The default behavior is configured in <code>/etc/defaults/rc.conf</code>. The scripts responds at least to start|stop|status.
  626. <pre># /etc/rc.d/sshd status
  627. sshd is running as pid 552.
  628. # shutdown now <span class="cmt"># Go into single-user mode</span>
  629. # exit <span class="cmt"># Go back to multi-user mode</span>
  630. # shutdown -p now <span class="cmt"># Shutdown and halt the system</span>
  631. # shutdown -r now <span class="cmt"># Reboot</span>
  632. </pre>
  633. The process <code>init</code> can also be used to reach one of the following states level. For example <code># init 6</code> for reboot.
  634. <ul style="list-style-type:none; page-break-inside:avoid;">
  635. <li>0 &#160; &#160; &#160; Halt and turn the power off (signal <code>USR2</code>)</li>
  636. <li>1 &#160; &#160; &#160; Go to single-user mode (signal <code>TERM</code>)</li>
  637. <li>6 &#160; &#160; &#160; Reboot the machine (signal <code>INT</code>)</li>
  638. <li>c &#160; &#160; &#160; Block further logins (signal <code>TSTP</code>)</li>
  639. <li>q &#160; &#160; &#160; Rescan the ttys(5) file (signal <code>HUP</code>)</li>
  640. </ul>
  641. <h3>Windows</h3>
  642. Start and stop a service with either the <code>service name</code> or <code>"service description"</code> (shown in the Services Control Panel) as follows:
  643. <pre>net stop WSearch
  644. net start WSearch <span class="cmt"># start search service</span>
  645. net stop "Windows Search"
  646. net start "Windows Search" <span class="cmt"># same as above using descr.</span>
  647. </pre>
  648. <h2 id="resetpasswd">Reset root password</h2>
  649. <h3>Linux method 1</h3>
  650. At the boot loader (lilo or grub), enter the following boot option:
  651. <pre>init=/bin/sh</pre>
  652. The kernel will mount the root partition and <code>init</code> will start the bourne shell
  653. instead of <code>rc</code> and then a runlevel. Use the command <code>passwd</code> at the prompt to change the password and then reboot. Forget the single user mode as you need the password for that.<br />
  654. If, after booting, the root partition is mounted read only, remount it rw:
  655. <pre># mount -o remount,rw /
  656. # passwd <span class="cmt"># or delete the root password (/etc/shadow)</span>
  657. # sync; mount -o remount,ro / <span class="cmt"># sync before to remount read only</span>
  658. # reboot
  659. </pre>
  660. <h3>FreeBSD method 1</h3>
  661. On FreeBSD, boot in single user mode, remount / rw and use passwd. You can select the single user mode on the boot menu (option 4) which is displayed for 10 seconds at startup. The single user mode will give you a root shell on the / partition.
  662. <pre># mount -u /; mount -a <span class="cmt"># will mount / rw</span>
  663. # passwd
  664. # reboot
  665. </pre>
  666. <h3>Unixes and FreeBSD and Linux method 2</h3>
  667. Other Unixes might not let you go away with the simple init trick. The solution is to mount the root partition from an other OS (like a rescue CD) and change the password on the disk.
  668. <ul>
  669. <li>Boot a live CD or installation CD into a rescue mode which will give you a shell.</li>
  670. <li>Find the root partition with fdisk e.g. fdisk /dev/sda</li>
  671. <li>Mount it and use chroot:</li>
  672. </ul>
  673. <pre># mount -o rw /dev/ad4s3a /mnt
  674. # chroot /mnt <span class="cmt"># chroot into /mnt</span>
  675. # passwd
  676. # reboot
  677. </pre>
  678. <h2 id="kernelmodules">Kernel modules</h2>
  679. <h3>Linux</h3>
  680. <pre># lsmod <span class="cmt"># List all modules loaded in the kernel</span>
  681. # modprobe isdn <span class="cmt"># To load a module (here isdn)</span>
  682. </pre>
  683. <h3>FreeBSD</h3>
  684. <pre># kldstat <span class="cmt"># List all modules loaded in the kernel</span>
  685. # kldload crypto <span class="cmt"># To load a module (here crypto)</span>
  686. </pre>
  687. <h2 id="compilekernel">Compile Kernel</h2>
  688. <h3>Linux</h3>
  689. <pre># cd /usr/src/linux
  690. # make mrproper <span class="cmt"># Clean everything, including config files</span>
  691. # make oldconfig <span class="cmt"># Reuse the old .config if existent</span>
  692. # make menuconfig <span class="cmt"># or xconfig (Qt) or gconfig (GTK)</span>
  693. # make <span class="cmt"># Create a compressed kernel image</span>
  694. # make modules <span class="cmt"># Compile the modules</span>
  695. # make modules_install <span class="cmt"># Install the modules</span>
  696. # make install <span class="cmt"># Install the kernel</span>
  697. # reboot
  698. </pre>
  699. <h3>FreeBSD</h3>
  700. Optionally update the source tree (in <code>/usr/src</code>) with csup (as of FreeBSD 6.2 or later):
  701. <pre># csup &lt;supfile&gt;</pre>
  702. I use the following supfile:
  703. <pre>*default host=cvsup5.FreeBSD.org # www.freebsd.org/handbook/cvsup.html#CVSUP-MIRRORS
  704. *default prefix=/usr
  705. *default base=/var/db
  706. *default release=cvs delete tag=RELENG_7
  707. src-all
  708. </pre>
  709. 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 <code>GENERIC</code> directly). To restart the build after an interruption, add the option <code>NO_CLEAN=YES</code> to the make command to avoid cleaning the objects already build.
  710. <pre># cd /usr/src/sys/i386/conf/
  711. # cp GENERIC MYKERNEL
  712. # cd /usr/src
  713. # make buildkernel KERNCONF=MYKERNEL
  714. # make installkernel KERNCONF=MYKERNEL
  715. </pre>
  716. To rebuild the full OS:
  717. <pre># make buildworld <span class="cmt"># Build the full OS but not the kernel</span>
  718. # make buildkernel <span class="cmt"># Use KERNCONF as above if appropriate</span>
  719. # make installkernel
  720. # reboot
  721. # mergemaster -p <span class="cmt"># Compares only files known to be essential</span>
  722. # make installworld
  723. # mergemaster -i -U <span class="cmt"># Update all configurations and other files</span>
  724. # reboot
  725. </pre>
  726. For small changes in the source you can use NO_CLEAN=yes to avoid rebuilding the whole tree.
  727. <pre># make buildworld NO_CLEAN=yes <span class="cmt"># Don't delete the old objects</span>
  728. # make buildkernel KERNCONF=MYKERNEL NO_CLEAN=yes
  729. </pre>
  730. <h2 id="grub">Repair grub</h2>
  731. So you broke grub? Boot from a live cd, [find your linux partition under <code>/dev</code> and use <code>fdisk</code> to find the linux partion] mount the linux partition, add /proc and /dev and use <code>grub-install /dev/xyz</code>. Suppose linux lies on <code>/dev/sda6</code>:
  732. <pre># mount /dev/sda6 /mnt <span class="cmt"># mount the linux partition on /mnt</span>
  733. # mount --bind /proc /mnt/proc <span class="cmt"># mount the proc subsystem into /mnt</span>
  734. # mount --bind /dev /mnt/dev <span class="cmt"># mount the devices into /mnt</span>
  735. # chroot /mnt <span class="cmt"># change root to the linux partition</span>
  736. # grub-install /dev/sda <span class="cmt"># reinstall grub with your old settings</span>
  737. </pre>
  738. <h2 id="sysmisc">Misc</h2>
  739. Disable OSX virtual memory (repeat with <code>load</code> to re-enable). Faster system, but a little risky.
  740. <pre># sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.dynamic_pager.plist
  741. # sleep 3600; pmset sleepnow <span class="cmt"># go to standby in one hour (OSX)</span>
  742. # defaults write -g com.apple.mouse.scaling -float 8
  743. <span class="cmt"># OSX mouse acceleration (use -1 to reverse)</span>
  744. </pre>
  745. </div>
  746. <div id="processes"><h1><a>Processes</a></h1>
  747. <p class="xrefp"><a class="xrefp" href="#ps">Listing</a> | <a class="xrefp" href="#nice">Priority</a> | <a class="xrefp" href="#bgfg">Background/Foreground</a> | <a class="xrefp" href="#top">Top</a> | <a class="xrefp" href="#kill">Kill</a></p>
  748. <h2 id="ps">Listing and PIDs</h2>
  749. Each process has a unique number, the PID. A list of all running process is retrieved with <code>ps</code>.
  750. <pre># ps -auxefw <span class="cmt"># Extensive list of all running process</span></pre>
  751. However more typical usage is with a pipe or with <code>pgrep</code> (for OS X install <code>proctools</code> from <a class="xref" href="#macports">MacPorts</a>):
  752. <pre># ps axww | grep cron
  753. 586 ?? Is 0:01.48 /usr/sbin/cron -s
  754. # ps axjf <span class="cmt"># All processes in a tree format (Linux)</span>
  755. # ps aux | grep 'ss[h]' <span class="cmt"># Find all ssh pids without the grep pid</span>
  756. # pgrep -l sshd <span class="cmt"># Find the PIDs of processes by (part of) name</span>
  757. # echo $$ <span class="cmt"># The PID of your shell</span>
  758. # fuser -va 22/tcp <span class="cmt"># List processes using port 22 (Linux)</span>
  759. # pmap PID <span class="cmt"># Memory map of process (hunt memory leaks) (Linux)</span>
  760. # fuser -va /home <span class="cmt"># List processes accessing the /home partition</span>
  761. # strace df <span class="cmt"># Trace system calls and signals</span>
  762. # truss df <span class="cmt"># same as above on FreeBSD/Solaris/Unixware</span>
  763. </pre>
  764. <h2 id="nice">Priority</h2>
  765. Change the priority of a running process with <code>renice</code>. <b>Negative numbers have a higher priority</b>, the lowest is -20 and "nice" have a positive value.
  766. <pre># renice -5 586 <span class="cmt"># Stronger priority</span>
  767. 586: old priority 0, new priority -5
  768. </pre>
  769. Start the process with a defined priority with <code>nice</code>. Positive is "nice" or weak, negative is strong scheduling priority. Make sure you know if <code>/usr/bin/nice</code> or the shell built-in is used (check with <code># which nice</code>).
  770. <pre># nice -n -5 top <span class="cmt"># Stronger priority (/usr/bin/nice)</span>
  771. # nice -n 5 top <span class="cmt"># Weaker priority (/usr/bin/nice)</span>
  772. # nice +5 top <span class="cmt"># tcsh builtin nice (same as above!)</span>
  773. </pre>
  774. While nice changes the CPU scheduler, an other useful command <code>ionice</code> will schedule the disk IO. This is very useful for intensive IO application (e.g. compiling). You can select a class (idle - best effort - real time), the man page is short and well explained.
  775. <pre># ionice c3 -p123 <span class="cmt"># set idle class for pid 123 (Linux only)</span>
  776. # ionice -c2 -n0 firefox <span class="cmt"># Run firefox with best effort and high priority</span>
  777. # ionice -c3 -p$$ <span class="cmt"># Set the actual shell to idle priority</span>
  778. </pre>
  779. The last command is very useful to compile (or debug) a large project. Every command launched from this shell will have a lover priority. <code>$$</code> is your shell pid (try echo $$).<br/>
  780. FreeBSD uses <code>idprio/rtprio</code> (0 = max priority, 31 = most idle):
  781. <pre># idprio 31 make <span class="cmt"># compile in the lowest priority</span>
  782. # idprio 31 -1234 <span class="cmt"># set PID 1234 with lowest priority</span>
  783. # idprio -t -1234 <span class="cmt"># -t removes any real time/idle priority</span>
  784. </pre>
  785. <h2 id="bgfg">Background/Foreground</h2>
  786. When started from a shell, processes can be brought in the background and back to the foreground with [Ctrl]-[Z] (^Z), <code>bg</code> and <code>fg</code>. List the processes with <code>jobs</code>. When needed detach from the terminal with <code>disown</code>.
  787. <pre># ping cb.vu > ping.log
  788. ^Z <span class="cmt"># ping is suspended (stopped) with [Ctrl]-[Z]</span>
  789. # bg <span class="cmt"># put in background and continues running</span>
  790. # jobs -l <span class="cmt"># List processes in background</span>
  791. [1] - 36232 Running ping cb.vu > ping.log
  792. [2] + 36233 Suspended (tty output) top
  793. # fg %2 <span class="cmt"># Bring process 2 back in foreground</span>
  794. </pre>
  795. <pre># make <span class="cmt"># start a long compile job but need to leave the terminal</span>
  796. ^Z <span class="cmt"># suspended (stopped) with [Ctrl]-[Z]</span>
  797. # bg <span class="cmt"># put in background and continues running</span>
  798. # disown -h %1 <span class="cmt"># detatch process from terminal, won't be killed at logout</span>
  799. </pre>
  800. No straight forward way to re-attach the process to a new terminal, try <a href="https://github.com/nelhage/reptyr">reptyr</a> (Linux).<br />
  801. Use <code>nohup</code> to start a process which has to keep running when the shell is closed (immune to hangups).
  802. <pre># nohup ping -i 60 > ping.log &amp;
  803. </pre>
  804. <h2 id="top">Top</h2>
  805. The program <code>top</code> displays running information of processes. See also the program <code>htop</code> from htop.sourceforge.net (a more powerful version of top) which runs on Linux and FreeBSD (<code>ports/sysutils/htop/</code>). While top is running press the key h for a help overview. Useful keys are:
  806. <ul>
  807. <li><b>u [user name]</b> To display only the processes belonging to the user. Use + or blank to see all users</li>
  808. <li><b>k [pid]</b> Kill the process with pid.</li>
  809. <li><b>1</b> To display all processors statistics (Linux only)</li>
  810. <li><b>R</b> Toggle normal/reverse sort.</li>
  811. </ul>
  812. <h2 id="kill">Signals/Kill</h2>
  813. Terminate or send a signal with <code>kill</code> or <code>killall</code>.
  814. <pre># ping -i 60 cb.vu > ping.log &amp;
  815. [1] 4712
  816. # kill -s TERM 4712 <span class="cmt"># same as kill -15 4712</span>
  817. # killall -1 httpd <span class="cmt"># Kill HUP processes by exact name</span>
  818. # pkill -9 http <span class="cmt"># Kill TERM processes by (part of) name</span>
  819. # pkill -TERM -u www <span class="cmt"># Kill TERM processes owned by www</span>
  820. # fuser -k -TERM -m /home <span class="cmt"># Kill every process accessing /home (to umount)</span>
  821. </pre>
  822. Important signals are:
  823. <ul style="list-style-type: none;">
  824. <li>1 &#160; &#160; &#160; <code>HUP</code> (hang up)</li>
  825. <li>2 &#160; &#160; &#160; <code>INT</code> (interrupt)</li>
  826. <li>3 &#160; &#160; &#160; <code>QUIT</code> (quit)</li>
  827. <li>9 &#160; &#160; &#160; <code>KILL</code> (non-catchable, non-ignorable kill)</li>
  828. <li>15 &#160; &#160; <code>TERM</code> (software termination signal)</li>
  829. </ul>
  830. </div>
  831. <div id="filesystem"><h1><a>File System</a></h1>
  832. <p class="xrefp"><a class="xrefp" href="#diskinfo">Disk info</a> | <a class="xrefp" href="#fsboot">Boot</a> | <a class="xrefp" href="#mountpoints">Disk usage</a> | <a class="xrefp" href="#filesstat">Opened files</a> | <a class="xrefp" href="#mountcd">Mount/remount</a> | <a class="xrefp" href="#mountsmb">Mount SMB</a> | <a class="xrefp" href="#mountimg">Mount image</a> | <a class="xrefp" href="#burniso">Burn ISO</a> | <a class="xrefp" href="#createimg">Create image</a> | <a class="xrefp" href="#creatememdisk">Memory disk</a> | <a class="xrefp" href="#diskperf">Disk performance</a></p>
  833. <h2 id="permissions">Permissions</h2>
  834. Change permission and ownership with <code>chmod</code> and <code>chown</code>. The default umask can be changed for all users in /etc/profile for Linux or /etc/login.conf for FreeBSD. The default umask is usually 022. The umask is subtracted from 777, thus umask 022 results in a permission 0f 755.
  835. <pre>1 --x execute <span class="cmt"># Mode 764 = exec/read/write | read/write | read</span>
  836. 2 -w- write <span class="cmt"># For: |-- Owner --| |- Group-| |Oth|</span>
  837. 4 r-- read
  838. ugo=a <span class="cmt">u=user, g=group, o=others, a=everyone</span>
  839. </pre>
  840. <pre># chmod [OPTION] MODE[,MODE] FILE <span class="cmt"># MODE is of the form [ugoa]*([-+=]([rwxXst]))</span>
  841. # chmod 640 /var/log/maillog <span class="cmt"># Restrict the log -rw-r-----</span>
  842. # chmod u=rw,g=r,o= /var/log/maillog <span class="cmt"># Same as above</span>
  843. # chmod -R o-r /home/* <span class="cmt"># Recursive remove other readable for all users</span>
  844. # chmod u+s /path/to/prog <span class="cmt"># Set SUID bit on executable (know what you do!)</span>
  845. # find / -perm -u+s -print <span class="cmt"># Find all programs with the SUID bit</span>
  846. # chown user:group /path/to/file <span class="cmt"># Change the user and group ownership of a file</span>
  847. # chgrp group /path/to/file <span class="cmt"># Change the group ownership of a file</span>
  848. # chmod 640 `find ./ -type f -print` <span class="cmt"># Change permissions to 640 for all files</span>
  849. # chmod 751 `find ./ -type d -print` <span class="cmt"># Change permissions to 751 for all directories</span>
  850. </pre>
  851. <h2 id="diskinfo">Disk information</h2>
  852. <pre># diskinfo -v /dev/ad2 <span class="cmt"># information about disk (sector/size) FreeBSD</span>
  853. # hdparm -I /dev/sda <span class="cmt"># information about the IDE/ATA disk (Linux)</span>
  854. # fdisk /dev/ad2 <span class="cmt"># Display and manipulate the partition table</span>
  855. # smartctl -a /dev/ad2 <span class="cmt"># Display the disk SMART info</span>
  856. </pre>
  857. <h2 id="fsboot">Boot</h2>
  858. <h3>FreeBSD</h3>
  859. To boot an old kernel if the new kernel doesn't boot, stop the boot at during the count down.
  860. <pre># unload
  861. # load kernel.old
  862. # boot
  863. </pre>
  864. <h2 id="mountpoints">System mount points/Disk usage</h2>
  865. <pre># mount | column -t <span class="cmt"># Show mounted file-systems on the system</span>
  866. # df <span class="cmt"># display free disk space and mounted devices</span>
  867. # cat /proc/partitions <span class="cmt"># Show all registered partitions (Linux)</span>
  868. </pre>
  869. <h3 id="diskusage">Disk usage</h3>
  870. <pre># du -sh * <span class="cmt"># Directory sizes as listing</span>
  871. # du -csh <span class="cmt"># Total directory size of the current directory</span>
  872. # du -ks * | sort -n -r <span class="cmt"># Sort everything by size in kilobytes</span>
  873. # ls -lSr <span class="cmt"># Show files, biggest last</span>
  874. </pre>
  875. <h2 id="filesstat">Who has which files opened</h2>
  876. This is useful to find out which file is blocking a partition which has to be unmounted and gives a typical error of:
  877. <pre># umount /home/
  878. umount: unmount of /home <span class="cmt"># umount impossible because a file is locking home</span>
  879. failed: Device busy
  880. </pre>
  881. <h3>FreeBSD and most Unixes</h3>
  882. <pre># fstat -f /home <span class="cmt"># for a mount point</span>
  883. # fstat -p PID <span class="cmt"># for an application with PID</span>
  884. # fstat -u user <span class="cmt"># for a user name</span>
  885. </pre>
  886. Find opened log file (or other opened files), say for Xorg:
  887. <pre># ps ax | grep Xorg | awk '{print $1}'
  888. 1252
  889. # fstat -p 1252
  890. USER CMD PID FD MOUNT INUM MODE SZ|DV R/W
  891. root Xorg 1252 root / 2 drwxr-xr-x 512 r
  892. root Xorg 1252 text /usr 216016 -rws--x--x 1679848 r
  893. root Xorg 1252 0 /var 212042 -rw-r--r-- 56987 w
  894. </pre>
  895. The file with inum 212042 is the only file in /var:
  896. <pre># find -x /var -inum 212042
  897. /var/log/Xorg.0.log
  898. </pre>
  899. <h3>Linux</h3>
  900. Find opened files on a mount point with <code>fuser</code> or <code>lsof</code>:
  901. <pre># fuser -m /home <span class="cmt"># List processes accessing /home</span>
  902. # lsof /home
  903. COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
  904. tcsh 29029 eedcoba cwd DIR 0,18 12288 1048587 /home/eedcoba (guam:/home)
  905. lsof 29140 eedcoba cwd DIR 0,18 12288 1048587 /home/eedcoba (guam:/home)
  906. </pre>
  907. About an application:
  908. <pre>ps ax | grep Xorg | awk '{print $1}'
  909. 3324
  910. # lsof -p 3324
  911. COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
  912. Xorg 3324 root 0w REG 8,6 56296 12492 /var/log/Xorg.0.log
  913. </pre>
  914. About a single file:
  915. <pre># lsof /var/log/Xorg.0.log
  916. COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
  917. Xorg 3324 root 0w REG 8,6 56296 12492 /var/log/Xorg.0.log
  918. </pre>
  919. <h2 id="mountcd">Mount/remount a file system</h2>
  920. For example the cdrom. If listed in /etc/fstab:
  921. <pre># mount /cdrom</pre>
  922. Or find the device in /dev/ or with dmesg
  923. <h3>FreeBSD</h3>
  924. <pre># mount -v -t cd9660 /dev/cd0c /mnt <span class="cmt"># cdrom</span>
  925. # mount_cd9660 /dev/wcd0c /cdrom <span class="cmt"># other method</span>
  926. # mount -v -t msdos /dev/fd0c /mnt <span class="cmt"># floppy</span>
  927. </pre>
  928. Entry in /etc/fstab:
  929. <pre># Device Mountpoint FStype Options Dump Pass#
  930. /dev/acd0 /cdrom cd9660 ro,noauto 0 0
  931. </pre>
  932. To let users do it:
  933. <pre># sysctl vfs.usermount=1 <span class="cmt"># Or insert the line "vfs.usermount=1" in /etc/sysctl.conf</span>
  934. </pre>
  935. <h3>Linux</h3>
  936. <pre># mount -t auto /dev/cdrom /mnt/cdrom <span class="cmt"># typical cdrom mount command</span>
  937. # mount /dev/hdc -t iso9660 -r /cdrom <span class="cmt"># typical IDE</span>
  938. # mount /dev/scd0 -t iso9660 -r /cdrom <span class="cmt"># typical SCSI cdrom</span>
  939. # mount /dev/sdc0 -t ntfs-3g /windows <span class="cmt"># typical SCSI</span>
  940. </pre>
  941. Entry in /etc/fstab:
  942. <pre>/dev/cdrom /media/cdrom subfs noauto,fs=cdfss,ro,procuid,nosuid,nodev,exec 0 0</pre>
  943. <h4>Mount a FreeBSD partition with Linux</h4>
  944. Find the partition number containing with fdisk, this is usually the root partition, but it could be an other BSD slice too. If the FreeBSD has many slices, they are the one not listed in the fdisk table, but visible in /dev/sda* or /dev/hda*.
  945. <pre># fdisk /dev/sda <span class="cmt"># Find the FreeBSD partition</span>
  946. /dev/sda3 * 5357 7905 20474842+ a5 FreeBSD
  947. # mount -t ufs -o ufstype=ufs2,ro /dev/sda3 /mnt
  948. /dev/sda10 = /tmp; /dev/sda11 /usr <span class="cmt"># The other slices</span>
  949. </pre>
  950. <h3 id="remount">Remount</h3>
  951. Remount a device without unmounting it. Necessary for fsck for example
  952. <pre># mount -o remount,ro / <span class="cmt"># Linux</span>
  953. # mount -o ro -u / <span class="cmt"># FreeBSD</span>
  954. </pre>
  955. Copy the raw data from a cdrom into an iso image (default 512 blocksize might cause problems):
  956. <pre># dd if=/dev/cd0c of=file.iso bs=2048</pre>
  957. <h3 id="virtualbox">Virtualbox</h3>
  958. Allow a share on the host:
  959. <pre># VBoxManage sharedfolder add "GuestName" --name "share" --hostpath "C:\hostshare"</pre>
  960. Mount share on guest (linux, FreeBSD)
  961. <pre># sudo mount -t vboxsf share /home/vboxshare <span class="cmt"># -o uid=1000,gid=1000 (as appropriate)</span>
  962. share /home/colin/share vboxsf defaults,uid=colin 0 0 <span class="cmt"># fstab entry</span>
  963. </pre>
  964. <h3 id="osxdisk">OSX</h3>
  965. <pre># diskutil list <span class="cmt"># List the partitions of a disk</span>
  966. # diskutil unmountDisk /dev/disk1 <span class="cmt"># Unmount an entire disk (all volumes)</span>
  967. # chflags hidden ~/Documents/folder <span class="cmt"># Hide folder (reverse with unhidden)</span>
  968. </pre>
  969. <h2 id="addswap">Add swap on-the-fly</h2>
  970. Suppose you need more swap (right now), say a 2GB file /swap2gb (Linux only).
  971. <pre># dd if=/dev/zero of=/swap2gb bs=1024k count=2000
  972. # mkswap /swap2gb <span class="cmt"># create the swap area</span>
  973. # swapon /swap2gb <span class="cmt"># activate the swap. It now in use</span>
  974. # swapoff /swap2gb <span class="cmt"># when done deactivate the swap</span>
  975. # rm /swap2gb
  976. </pre>
  977. <h2 id="mountsmb">Mount an SMB share</h2>
  978. Suppose we want to access the SMB share myshare on the computer smbserver, the address as typed on a Windows PC is \\smbserver\myshare\. We mount on /mnt/smbshare. Warning> cifs wants an IP or DNS name, not a Windows name.
  979. <h3>Linux/OSX</h3>
  980. <pre># smbclient -U user -I 192.168.16.229 -L //smbshare/ <span class="cmt"># List the shares</span>
  981. # mount -t smbfs -o username=winuser //smbserver/myshare /mnt/smbshare
  982. # mount -t cifs -o username=winuser,password=winpwd //192.168.16.229/myshare /mnt/share
  983. </pre>
  984. Mount Samba share through ssh tunnel
  985. <pre># ssh -C -f -N -p 20022 -L 445:127.0.0.1:445 me@server <span class="cmt"># connect on 20022, tunnel 445</span>
  986. # mount -t smbfs //colin@localhost/colin ~/mnt
  987. # mount_smbfs //colin:mypassword@127.0.0.1/private /Volumes/private <span class="cmt"># I use this on OSX + ssh</span>
  988. </pre>
  989. Additionally with the package mount.cifs it is possible to store the credentials in a file, for example <code>/home/user/.smb</code>:
  990. <pre>username=winuser
  991. password=winpwd
  992. </pre>
  993. And mount as follow:
  994. <pre># mount -t cifs -o credentials=/home/user/.smb //192.168.16.229/myshare /mnt/smbshare</pre>
  995. <h3>FreeBSD</h3>
  996. Use -I to give the IP (or DNS name); smbserver is the Windows name.
  997. <pre># smbutil view -I 192.168.16.229 //winuser@smbserver <span class="cmt"># List the shares</span>
  998. # mount_smbfs -I 192.168.16.229 //winuser@smbserver/myshare /mnt/smbshare
  999. </pre>
  1000. <h2 id="mountimg">Mount an image</h2>
  1001. <pre># hdiutil mount image.iso <span class="cmt"># OS X</span></pre>
  1002. <h3>Linux loop-back</h3>
  1003. <pre># mount -t iso9660 -o loop file.iso /mnt <span class="cmt"># Mount a CD image</span>
  1004. # mount -t ext3 -o loop file.img /mnt <span class="cmt"># Mount an image with ext3 fs</span>
  1005. </pre>
  1006. <h3>FreeBSD</h3>
  1007. With memory device (do # kldload md.ko if necessary):
  1008. <pre># mdconfig -a -t vnode -f file.iso -u 0
  1009. # mount -t cd9660 /dev/md0 /mnt
  1010. # umount /mnt; mdconfig -d -u 0 <span class="cmt"># Cleanup the md device</span>
  1011. </pre>
  1012. Or with virtual node:
  1013. <pre># vnconfig /dev/vn0c file.iso; mount -t cd9660 /dev/vn0c /mnt
  1014. # umount /mnt; vnconfig -u /dev/vn0c <span class="cmt"># Cleanup the vn device</span>
  1015. </pre>
  1016. <h3>Solaris and FreeBSD</h3>
  1017. with loop-back file interface or lofi:
  1018. <pre># lofiadm -a file.iso
  1019. # mount -F hsfs -o ro /dev/lofi/1 /mnt
  1020. # umount /mnt; lofiadm -d /dev/lofi/1 <span class="cmt"># Cleanup the lofi device</span>
  1021. </pre>
  1022. <h2 id="burniso">Create and burn an ISO image</h2>
  1023. This will copy the cd or DVD sector for sector. Without <code>conv=notrunc</code>, the image will be smaller if there is less content on the cd. See below and the <a class="xref" href="#dd">dd examples</a>.
  1024. <pre># dd if=/dev/hdc of=/tmp/mycd.iso bs=2048 conv=notrunc</pre>
  1025. Use mkisofs to create a CD/DVD image from files in a directory. To overcome the file names restrictions: -r enables the Rock Ridge extensions common to UNIX systems, -J enables Joliet extensions used by Microsoft systems. -L allows ISO9660 filenames to begin with a period.
  1026. <pre># mkisofs -J -L -r -V TITLE -o imagefile.iso /path/to/dir
  1027. # hdiutil makehybrid -iso -joliet -o dir.iso dir/ <span class="cmt"># OS X</span></pre>
  1028. On FreeBSD, mkisofs is found in the ports in sysutils/cdrtools.
  1029. <h3>Burn a CD/DVD ISO image</h3>
  1030. <h4>FreeBSD</h4>
  1031. FreeBSD does not enable DMA on ATAPI drives by default. DMA is enabled with the sysctl command and the arguments below, or with /boot/loader.conf with the following entries:
  1032. <pre>hw.ata.ata_dma="1"
  1033. hw.ata.atapi_dma="1"
  1034. </pre>
  1035. Use <code>burncd</code> with an ATAPI device (<code>burncd</code> is part of the base system) and <code>cdrecord</code> (in sysutils/cdrtools) with a SCSI drive.
  1036. <pre># burncd -f /dev/acd0 data imagefile.iso fixate <span class="cmt"># For ATAPI drive</span>
  1037. # cdrecord -scanbus <span class="cmt"># To find the burner device (like 1,0,0)</span>
  1038. # cdrecord dev=1,0,0 imagefile.iso
  1039. </pre>
  1040. <h4>Linux</h4>
  1041. Also use <code>cdrecord</code> with Linux as described above. Additionally it is possible to use the native ATAPI interface which is found with:
  1042. <pre># cdrecord dev=ATAPI -scanbus</pre>
  1043. And burn the CD/DVD as above.
  1044. <h4>dvd+rw-tools</h4>
  1045. The <a href="http://fy.chalmers.se/~appro/linux/DVD+RW/">dvd+rw-tools</a> package (FreeBSD: ports/sysutils/dvd+rw-tools) can do it all and includes <code>growisofs</code> to burn CDs or DVDs. The examples refer to the dvd device as <code>/dev/dvd</code> which could be a symlink to <code>/dev/scd0</code> (typical scsi on Linux) or <code>/dev/cd0</code> (typical FreeBSD) or <code>/dev/rcd0c</code> (typical NetBSD/OpenBSD character SCSI) or <code>/dev/rdsk/c0t1d0s2</code> (Solaris example of a character SCSI/ATAPI CD-ROM device). There is a nice documentation with examples on the <a href="http://www.freebsd.org/handbook/creating-dvds.html">FreeBSD handbook chapter 18.7</a><span class="fn">http://www.freebsd.org/handbook/creating-dvds.html</span>.
  1046. <pre> <span class="cmt"># -dvd-compat closes the disk</span>
  1047. # growisofs -dvd-compat -Z /dev/dvd=imagefile.iso <span class="cmt"># Burn existing iso image</span>
  1048. # growisofs -dvd-compat -Z /dev/dvd -J -R /p/to/data <span class="cmt"># Burn directly</span>
  1049. </pre>
  1050. <h3>Convert a Nero .nrg file to .iso</h3>
  1051. Nero simply adds a 300Kb header to a normal iso image. This can be trimmed with dd.
  1052. <pre># dd bs=1k if=imagefile.nrg of=imagefile.iso skip=300</pre>
  1053. <h3>Convert a bin/cue image to .iso</h3>
  1054. The little <a href="http://freshmeat.net/projects/bchunk/"><code>bchunk</code> program</a><span class="fn">http://freshmeat.net/projects/bchunk/</span> can do this. It is in the FreeBSD ports in sysutils/bchunk.
  1055. <pre># bchunk imagefile.bin imagefile.cue imagefile.iso
  1056. </pre>
  1057. <h2 id="createimg">Create a file based image</h2>
  1058. For example a partition of 1GB using the file /usr/vdisk.img. Here we use the vnode 0, but it could also be 1.
  1059. <h3>FreeBSD</h3>
  1060. <pre># dd if=/dev/random of=/usr/vdisk.img bs=1K count=1M
  1061. # mdconfig -a -t vnode -f /usr/vdisk.img -u 0 <span class="cmt"># Creates device /dev/md1</span>
  1062. # bsdlabel -w /dev/md0
  1063. # newfs /dev/md0c
  1064. # mount /dev/md0c /mnt
  1065. # umount /mnt; mdconfig -d -u 0; rm /usr/vdisk.img <span class="cmt"># Cleanup the md device</span>
  1066. </pre>
  1067. The file based image can be automatically mounted during boot with an entry in /etc/rc.conf and /etc/fstab. Test your setup with <code># /etc/rc.d/mdconfig start</code> (first delete the md0 device with <code># mdconfig -d -u 0</code>).<br />
  1068. Note however that this automatic setup will only work if the file image is NOT on the root partition. The reason is that the /etc/rc.d/mdconfig script is executed very early during boot and the root partition is still read-only. Images located outside the root partition will be mounted later with the script /etc/rc.d/mdconfig2.<br />
  1069. /boot/loader.conf:
  1070. <pre>md_load="YES"</pre>
  1071. /etc/rc.conf:
  1072. <pre># mdconfig_md0="-t vnode -f /usr/vdisk.img" <span class="cmt"># /usr is not on the root partition</span></pre>
  1073. /etc/fstab: (The 0 0 at the end is important, it tell fsck to ignore this device, as is does not exist yet)
  1074. <pre>/dev/md0 /usr/vdisk ufs rw 0 0</pre>
  1075. It is also possible to increase the size of the image afterward, say for example 300 MB larger.
  1076. <pre># umount /mnt; mdconfig -d -u 0
  1077. # dd if=/dev/zero bs=1m count=300 >> /usr/vdisk.img
  1078. # mdconfig -a -t vnode -f /usr/vdisk.img -u 0
  1079. # growfs /dev/md0
  1080. # mount /dev/md0c /mnt <span class="cmt"># File partition is now 300 MB larger</span>
  1081. </pre>
  1082. <h3>Linux</h3>
  1083. <pre># dd if=/dev/zero of=/usr/vdisk.img bs=1024k count=1024
  1084. # mkfs.ext3 /usr/vdisk.img
  1085. # mount -o loop /usr/vdisk.img /mnt
  1086. # umount /mnt; rm /usr/vdisk.img <span class="cmt"># Cleanup</span>
  1087. </pre>
  1088. <h3 id="losetup">Linux with losetup</h3>
  1089. <code>/dev/zero</code> is much faster than <code>urandom</code>, but less secure for encryption.
  1090. <pre># dd if=/dev/urandom of=/usr/vdisk.img bs=1024k count=1024
  1091. # losetup /dev/loop0 /usr/vdisk.img <span class="cmt"># Creates and associates /dev/loop0</span>
  1092. # mkfs.ext3 /dev/loop0
  1093. # mount /dev/loop0 /mnt
  1094. # losetup -a <span class="cmt"># Check used loops</span>
  1095. # umount /mnt
  1096. # losetup -d /dev/loop0 <span class="cmt"># Detach</span>
  1097. # rm /usr/vdisk.img
  1098. </pre>
  1099. <h2 id="creatememdisk">Create a memory file system</h2>
  1100. A memory based file system is very fast for heavy IO application. How to create a 64 MB partition mounted on /memdisk:
  1101. <h3>FreeBSD</h3>
  1102. <pre># mount_mfs -o rw -s 64M md /memdisk
  1103. # umount /memdisk; mdconfig -d -u 0 <span class="cmt"># Cleanup the md device</span>
  1104. md /memdisk mfs rw,-s64M 0 0 <span class="cmt"># /etc/fstab entry</span>
  1105. </pre>
  1106. <h3>Linux</h3>
  1107. <pre># mount -t tmpfs -osize=64m tmpfs /memdisk
  1108. </pre>
  1109. <h2 id="diskperf">Disk performance</h2>
  1110. Read and write a 1 GB file on partition ad4s3c (/home)
  1111. <pre># time dd if=/dev/ad4s3c of=/dev/null bs=1024k count=1000
  1112. # time dd if=/dev/zero bs=1024k count=1000 of=/home/1Gb.file
  1113. # hdparm -tT /dev/hda <span class="cmt"># Linux only</span>
  1114. </pre>
  1115. </div>
  1116. <div id="network"><h1><a>Network</a></h1>
  1117. <p class="xrefp"><a class="xrefp" href="#routing">Routing</a> | <a class="xrefp" href="#secondip">Additional IP</a> | <a class="xrefp" href="#changemac">Change MAC</a> | <a class="xrefp" href="#ports">Ports</a> | <a class="xrefp" href="#firewall">Firewall</a> | <a class="xrefp" href="#ipforward">IP Forward</a> | <a class="xrefp" href="#nat">NAT</a> | <a class="xrefp" href="#dns">DNS</a> | <a class="xrefp" href="#dhcp">DHCP</a> | <a class="xrefp" href="#traffic">Traffic</a> | <a class="xrefp" href="#trafficctrl">QoS</a> | <a class="xrefp" href="#nis">NIS</a> | <a class="xrefp" href="#netcat">Netcat</a></p>
  1118. <h2 id="netdebug">Debugging (See also <a class="xref" href="#traffic">Traffic analysis)</a></h2>
  1119. <h3>Linux</h3>
  1120. <pre># ethtool eth0 <span class="cmt"># Show the ethernet status (replaces mii-diag)</span>
  1121. # ethtool -s eth0 speed 100 duplex full <span class="cmt"># Force 100Mbit Full duplex</span>
  1122. # ethtool -s eth0 autoneg off <span class="cmt"># Disable auto negotiation</span>
  1123. # ethtool -p eth1 <span class="cmt"># Blink the ethernet led - very useful when supported</span>
  1124. # ip link show <span class="cmt"># Display all interfaces on Linux (similar to ifconfig)</span>
  1125. # ip link set eth0 up <span class="cmt"># Bring device up (or down). Same as "ifconfig eth0 up"</span>
  1126. # ip addr show <span class="cmt"># Display all IP addresses on Linux (similar to ifconfig)</span>
  1127. # ip neigh show <span class="cmt"># Similar to arp -a</span>
  1128. </pre>
  1129. <h3>Other OSes</h3>
  1130. <pre># ifconfig fxp0 <span class="cmt"># Check the "media" field on FreeBSD</span>
  1131. # arp -a <span class="cmt"># Check the router (or host) ARP entry (all OS)</span>
  1132. # ping cb.vu <span class="cmt"># The first thing to try...</span>
  1133. # traceroute cb.vu <span class="cmt"># Print the route path to destination</span>
  1134. # ifconfig fxp0 media 100baseTX mediaopt full-duplex <span class="cmt"># 100Mbit full duplex (FreeBSD)</span>
  1135. # netstat -s <span class="cmt"># System-wide statistics for each network protocol</span>
  1136. </pre>
  1137. Additional commands which are not always installed per default but easy to find:
  1138. <pre># arping 192.168.16.254 <span class="cmt"># Ping on ethernet layer</span>
  1139. # tcptraceroute -f 5 cb.vu <span class="cmt"># uses tcp instead of icmp to trace through firewalls</span>
  1140. </pre>
  1141. <h2 id="routing">Routing</h2>
  1142. <h3>Print routing table</h3>
  1143. <pre># route -n <span class="cmt"># Linux or use "ip route"</span>
  1144. # netstat -rn <span class="cmt"># Linux, BSD and UNIX</span>
  1145. # route print <span class="cmt"># Windows</span>
  1146. </pre>
  1147. <h3 id="addroute">Add and delete a route</h3>
  1148. <h4>FreeBSD</h4>
  1149. <pre># route add 212.117.0.0/16 192.168.1.1
  1150. # route delete 212.117.0.0/16
  1151. # route add default 192.168.1.1
  1152. </pre>
  1153. Add the route permanently in /etc/rc.conf
  1154. <pre>static_routes="myroute"
  1155. route_myroute="-net 212.117.0.0/16 192.168.1.1"
  1156. </pre>
  1157. <h4>OS X</h4>
  1158. <pre># sudo route -n add 192.168.0.0/27 192.168.0.62 <span class="cmt"># add a route</span>
  1159. # netstat -nr <span class="cmt"># routing table</span>
  1160. </pre>
  1161. <h4>Linux</h4>
  1162. <pre># route add -net 192.168.20.0 netmask 255.255.255.0 gw 192.168.16.254
  1163. # ip route add 192.168.20.0/24 via 192.168.16.254 <span class="cmt"># same as above with ip route</span>
  1164. # route add -net 192.168.20.0 netmask 255.255.255.0 dev eth0
  1165. # route add default gw 192.168.51.254
  1166. # ip route add default via 192.168.51.254 dev eth0 <span class="cmt"># same as above with ip route</span>
  1167. # route delete -net 192.168.20.0 netmask 255.255.255.0
  1168. </pre>
  1169. <h4>Solaris</h4>
  1170. <pre># route add -net 192.168.20.0 -netmask 255.255.255.0 192.168.16.254
  1171. # route add default 192.168.51.254 1 <span class="cmt"># 1 = hops to the next gateway</span>
  1172. # route change default 192.168.50.254 1
  1173. </pre>
  1174. Permanent entries are set in entry in <code>/etc/defaultrouter</code>.
  1175. <h4>Windows</h4>
  1176. <pre># Route add 192.168.50.0 mask 255.255.255.0 192.168.51.253
  1177. # Route add 0.0.0.0 mask 0.0.0.0 192.168.51.254</pre>
  1178. Use add -p to make the route persistent.
  1179. <h2 id="secondip">Configure additional IP addresses</h2>
  1180. <h3>Linux</h3>
  1181. <pre># ifconfig eth0 192.168.50.254 netmask 255.255.255.0 <span class="cmt"># First IP</span>
  1182. # ifconfig eth0:0 192.168.51.254 netmask 255.255.255.0 <span class="cmt"># Second IP</span>
  1183. # ip addr add 192.168.50.254/24 dev eth0 <span class="cmt"># Equivalent ip commands</span>
  1184. # ip link set dev eth0 up <span class="cmt"># Activate eth0 network interface</span>
  1185. # ip addr add 192.168.51.254/24 dev eth0 label eth0:1
  1186. # ip link ls dev eth0 <span class="cmt"># Get info on eth0</span>
  1187. # ip addr del 1.2.3.4/32 dev eth0 <span class="cmt"># Remove an IP</span>
  1188. # ip addr flush dev eth0 <span class="cmt"># Remove all addresses</span>
  1189. </pre>
  1190. <h3>FreeBSD</h3>
  1191. <pre># ifconfig fxp0 inet 192.168.50.254/24 <span class="cmt"># First IP</span>
  1192. # ifconfig fxp0 alias 192.168.51.254 netmask 255.255.255.0 <span class="cmt"># Second IP</span>
  1193. # ifconfig fxp0 -alias 192.168.51.254 <span class="cmt"># Remove second IP alias</span>
  1194. </pre>Permanent entries in /etc/rc.conf
  1195. <pre>ifconfig_fxp0="inet 192.168.50.254 netmask 255.255.255.0"
  1196. ifconfig_fxp0_alias0="192.168.51.254 netmask 255.255.255.0"
  1197. </pre>
  1198. <h3>OS X</h3>
  1199. <pre># sudo ifconfig en3 10.10.10.201/24 <span class="cmt"># First IP</span>
  1200. # ifconfig en3 delete 10.10.10.201 <span class="cmt"># Delete IP</span>
  1201. # sudo ifconfig en1 down ; sudo ifconfig en1 up
  1202. # ipconfig getifaddr en1 <span class="cmt"># current IP address</span>
  1203. </pre>
  1204. <h3>Solaris</h3>
  1205. Check the settings with <code>ifconfig -a</code>
  1206. <pre># ifconfig hme0 plumb <span class="cmt"># Enable the network card</span>
  1207. # ifconfig hme0 192.168.50.254 netmask 255.255.255.0 up <span class="cmt"># First IP</span>
  1208. # ifconfig hme0:1 192.168.51.254 netmask 255.255.255.0 up <span class="cmt"># Second IP</span>
  1209. </pre>
  1210. <h2 id="changemac">Change MAC address</h2>
  1211. Normally you have to bring the interface down before the change. Don't tell me why you want to change the MAC address...
  1212. <pre># ifconfig eth0 down
  1213. # ifconfig eth0 hw ether 00:01:02:03:04:05 <span class="cmt"># Linux</span>
  1214. # ifconfig fxp0 link 00:01:02:03:04:05 <span class="cmt"># FreeBSD</span>
  1215. # ifconfig hme0 ether 00:01:02:03:04:05 <span class="cmt"># Solaris</span>
  1216. # sudo ifconfig en0 ether 00:01:02:03:04:05 <span class="cmt"># OS X Tiger, Snow Leopard LAN*</span>
  1217. # sudo ifconfig en0 lladdr 00:01:02:03:04:05 <span class="cmt"># OS X Leopard</span>
  1218. </pre>
  1219. *Typical wireless interface is <code>en1</code> and needs do disassociate from
  1220. any network first (<a href="http://osxdaily.com/2008/01/17/how-to-spoof-your-mac-address-in-mac-os-x/">osxdaily howto</a>).
  1221. <pre># echo "alias airport='/System/Library/PrivateFrameworks/Apple80211.framework/Versions/Current/Resources/airport'"\
  1222. >> ~/.bash_profile <span class="cmt"># or symlink to /usr/sbin</span>
  1223. # airport -z <span class="cmt"># Disassociate from wireless networks</span>
  1224. # airport -I <span class="cmt"># Get info from wireless network</span></pre>
  1225. Many tools exist for Windows. For example <a href="http://ntsecurity.nu/toolbox/etherchange/">etherchange</a><span class="fn">http://ntsecurity.nu/toolbox/etherchange</span>. Or look for "Mac Makeup", "smac".
  1226. <h2 id="ports">Ports in use</h2>
  1227. Listening open ports:
  1228. <pre># netstat -an | grep LISTEN
  1229. # lsof -i <span class="cmt"># Linux list all Internet connections</span>
  1230. # socklist <span class="cmt"># Linux display list of open sockets</span>
  1231. # sockstat -4 <span class="cmt"># FreeBSD application listing</span>
  1232. # netstat -anp --udp --tcp | grep LISTEN <span class="cmt"># Linux</span>
  1233. # netstat -tup <span class="cmt"># List active connections to/from system (Linux)</span>
  1234. # netstat -tupl <span class="cmt"># List listening ports from system (Linux)</span>
  1235. # netstat -ano <span class="cmt"># Windows</span>
  1236. </pre>
  1237. <h2 id="firewall">Firewall</h2>
  1238. Check if a firewall is running (typical configuration only):
  1239. <h3>Linux</h3>
  1240. <pre># iptables -L -n -v <span class="cmt"># For status</span>
  1241. Open the iptables firewall
  1242. # iptables -P INPUT ACCEPT <span class="cmt"># Open everything</span>
  1243. # iptables -P FORWARD ACCEPT
  1244. # iptables -P OUTPUT ACCEPT
  1245. # iptables -Z <span class="cmt"># Zero the packet and byte counters in all chains</span>
  1246. # iptables -F <span class="cmt"># Flush all chains</span>
  1247. # iptables -X <span class="cmt"># Delete all chains</span>
  1248. </pre>
  1249. <h3>FreeBSD</h3>
  1250. <pre># ipfw show <span class="cmt"># For status</span>
  1251. # ipfw list 65535 <span class="cmt"># if answer is "65535 deny ip from any to any" the fw is disabled</span>
  1252. # sysctl net.inet.ip.fw.enable=0 <span class="cmt"># Disable</span>
  1253. # sysctl net.inet.ip.fw.enable=1 <span class="cmt"># Enable</span>
  1254. </pre>
  1255. <h2 id="ipforward">IP Forward for routing</h2>
  1256. <h3>Linux</h3>
  1257. Check and then enable IP forward with:
  1258. <pre># cat /proc/sys/net/ipv4/ip_forward <span class="cmt"># Check IP forward 0=off, 1=on</span>
  1259. # echo 1 > /proc/sys/net/ipv4/ip_forward
  1260. </pre>
  1261. or edit /etc/sysctl.conf with:
  1262. <pre>net.ipv4.ip_forward = 1</pre>
  1263. <h3>FreeBSD</h3>
  1264. Check and enable with:
  1265. <pre># sysctl net.inet.ip.forwarding <span class="cmt"># Check IP forward 0=off, 1=on</span>
  1266. # sysctl net.inet.ip.forwarding=1
  1267. # sysctl net.inet.ip.fastforwarding=1 <span class="cmt"># For dedicated router or firewall</span>
  1268. Permanent with entry in /etc/rc.conf:
  1269. gateway_enable="YES" <span class="cmt"># Set to YES if this host will be a gateway.</span>
  1270. </pre>
  1271. <h3>Solaris</h3>
  1272. <pre># ndd -set /dev/ip ip_forwarding 1 <span class="cmt"># Set IP forward 0=off, 1=on</span>
  1273. </pre>
  1274. <h2 id="nat">NAT Network Address Translation</h2>
  1275. <h3>Linux</h3>
  1276. <pre># iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE <span class="cmt"># to activate NAT</span>
  1277. # iptables -t nat -A PREROUTING -p tcp -d 78.31.70.238 --dport 20022 -j DNAT \
  1278. --to 192.168.16.44:22 <span class="cmt"># Port forward 20022 to internal IP port ssh</span>
  1279. # iptables -t nat -A PREROUTING -p tcp -d 78.31.70.238 --dport 993:995 -j DNAT \
  1280. --to 192.168.16.254:993-995 <span class="cmt"># Port forward of range 993-995</span>
  1281. # ip route flush cache
  1282. # iptables -L -t nat <span class="cmt"># Check NAT status</span>
  1283. </pre>
  1284. Delete the port forward with -D instead of -A. The program <a href="http://tweegy.nl/projects/netstat-nat/">netstat-nat</a><span class="fn">http://tweegy.nl/projects/netstat-nat</span> is very useful to track connections (it uses <code>/proc/net/ip_conntrack</code> or <code>/proc/net/nf_conntrack</code>).
  1285. <pre># netstat-nat -n <span class="cmt"># show all connections with IPs</span></pre>
  1286. <h3>FreeBSD</h3>
  1287. <pre># natd -s -m -u -dynamic -f /etc/natd.conf -n fxp0
  1288. Or edit /etc/rc.conf with:
  1289. firewall_enable="YES" <span class="cmt"># Set to YES to enable firewall functionality</span>
  1290. firewall_type="open" <span class="cmt"># Firewall type (see /etc/rc.firewall)</span>
  1291. natd_enable="YES" <span class="cmt"># Enable natd (if firewall_enable == YES).</span>
  1292. natd_interface="tun0" <span class="cmt"># Public interface or IP address to use.</span>
  1293. natd_flags="-s -m -u -dynamic -f /etc/natd.conf"
  1294. </pre>
  1295. Port forward with:
  1296. <pre># cat /etc/natd.conf
  1297. same_ports yes
  1298. use_sockets yes
  1299. unregistered_only
  1300. # redirect_port tcp insideIP:2300-2399 3300-3399 <span class="cmt"># port range</span>
  1301. redirect_port udp 192.168.51.103:7777 7777
  1302. </pre>
  1303. <h2 id="dns">DNS</h2>
  1304. On Unix the DNS entries are valid for all interfaces and are stored in /etc/resolv.conf. The domain to which the host belongs is also stored in this file. A minimal configuration is:
  1305. <pre>nameserver 78.31.70.238
  1306. search sleepyowl.net intern.lab
  1307. domain sleepyowl.net
  1308. </pre>
  1309. Check the system domain name with:
  1310. <pre># hostname -d <span class="cmt"># Same as dnsdomainname</span></pre>
  1311. <h3>Windows</h3>
  1312. On Windows the DNS are configured per interface. To display the configured DNS and to flush the DNS cache use:
  1313. <pre># ipconfig /? <span class="cmt"># Display help</span>
  1314. # ipconfig /all <span class="cmt"># See all information including DNS</span>
  1315. </pre>
  1316. <h3>Flush DNS</h3>
  1317. Flush the OS DNS cache, some application using their own cache (e.g. Firefox) and will be unaffected.
  1318. <pre># /etc/init.d/nscd restart <span class="cmt"># Restart nscd if used - Linux/BSD/Solaris</span>
  1319. # lookupd -flushcache <span class="cmt"># OS X Tiger</span>
  1320. # dscacheutil -flushcache <span class="cmt"># OS X Leopard and newer</span>
  1321. # ipconfig /flushdns <span class="cmt"># Windows</span>
  1322. </pre>
  1323. <h3>Forward queries</h3>
  1324. Dig is you friend to test the DNS settings. For example the public DNS server <code>213.133.105.2 ns.second-ns.de</code> can be used for testing. See from which server the client receives the answer (simplified answer).
  1325. <pre># dig sleepyowl.net
  1326. sleepyowl.net. 600 IN A 78.31.70.238
  1327. ;; SERVER: 192.168.51.254#53(192.168.51.254)
  1328. </pre>
  1329. The router 192.168.51.254 answered and the response is the A entry. Any entry can be queried and the DNS server can be selected with @:
  1330. <pre># dig MX google.com
  1331. # dig @127.0.0.1 NS sun.com <span class="cmt"># To test the local server</span>
  1332. # dig @204.97.212.10 NS MX heise.de <span class="cmt"># Query an external server</span>
  1333. # dig AXFR @ns1.xname.org cb.vu <span class="cmt"># Get the full zone (zone transfer)</span>
  1334. </pre>
  1335. The program host is also powerful.
  1336. <pre># host -t MX cb.vu <span class="cmt"># Get the mail MX entry</span>
  1337. # host -t NS -T sun.com <span class="cmt"># Get the NS record over a TCP connection</span>
  1338. # host -a sleepyowl.net <span class="cmt"># Get everything</span>
  1339. </pre>
  1340. <h3>Reverse queries</h3>
  1341. Find the name belonging to an IP address (in-addr.arpa.). This can be done with <code>dig</code>, <code>host</code> and <code>nslookup</code>:
  1342. <pre># dig -x 78.31.70.238
  1343. # host 78.31.70.238
  1344. # nslookup 78.31.70.238
  1345. </pre>
  1346. <h3>/etc/hosts</h3>
  1347. Single hosts can be configured in the file /etc/hosts instead of running <code>named</code> locally to resolve the hostname queries. The format is simple, for example:
  1348. <pre>78.31.70.238 sleepyowl.net sleepyowl</pre>
  1349. The priority between hosts and a dns query, that is the name resolution order, can be configured in <code>/etc/nsswitch.conf</code> AND /etc/host.conf. The file also exists on Windows, it is usually in:
  1350. <pre>C:\WINDOWS\SYSTEM32\DRIVERS\ETC</pre>
  1351. <h2 id="dhcp">DHCP</h2>
  1352. <h3>Linux</h3>
  1353. Some distributions (SuSE) use dhcpcd as client. The default interface is eth0.
  1354. <pre># dhcpcd -n eth0 <span class="cmt"># Trigger a renew (does not always work)</span>
  1355. # dhcpcd -k eth0 <span class="cmt"># release and shutdown</span>
  1356. </pre>
  1357. The lease with the full information is stored in:
  1358. <pre>/var/lib/dhcpcd/dhcpcd-eth0.info</pre>
  1359. <h3>FreeBSD</h3>
  1360. FreeBSD (and Debian) uses dhclient. To configure an interface (for example bge0) run:
  1361. <pre># dhclient bge0</pre>
  1362. The lease with the full information is stored in:
  1363. <pre>/var/db/dhclient.leases.bge0</pre>
  1364. Use <pre>/etc/dhclient.conf</pre> to prepend options or force different options:
  1365. <pre># cat /etc/dhclient.conf
  1366. interface "rl0" {
  1367. prepend domain-name-servers 127.0.0.1;
  1368. default domain-name "sleepyowl.net";
  1369. supersede domain-name "sleepyowl.net";
  1370. }
  1371. </pre>
  1372. <h3>Windows</h3>
  1373. The dhcp lease can be renewed with <code>ipconfig</code>:
  1374. <pre># ipconfig /renew <span class="cmt"># renew all adapters</span>
  1375. # ipconfig /renew LAN <span class="cmt"># renew the adapter named "LAN"</span>
  1376. # ipconfig /release WLAN <span class="cmt"># release the adapter named "WLAN"</span>
  1377. </pre>
  1378. Yes it is a good idea to rename you adapter with simple names!
  1379. <h2 id="traffic">Traffic analysis</h2>
  1380. <a href="http://people.suug.ch/~tgr/bmon/">Bmon</a><span class="fn">http://people.suug.ch/~tgr/bmon/</span> is a small console bandwidth monitor and can display the flow on different interfaces.
  1381. <h3>Sniff with tcpdump</h3>
  1382. <pre># tcpdump -nl -i bge0 not port ssh and src \(192.168.16.121 or 192.168.16.54\)
  1383. # tcpdump -n -i eth1 net 192.168.16.121 <span class="cmt"># select to/from a single IP</span>
  1384. # tcpdump -n -i eth1 net 192.168.16.0/24 <span class="cmt"># select traffic to/from a network</span>
  1385. # tcpdump -l > dump &amp;&amp; tail -f dump <span class="cmt"># Buffered output</span>
  1386. # tcpdump -i rl0 -w traffic.rl0 <span class="cmt"># Write traffic headers in binary file</span>
  1387. # tcpdump -i rl0 -s 0 -w traffic.rl0 <span class="cmt"># Write traffic + payload in binary file</span>
  1388. # tcpdump -r traffic.rl0 <span class="cmt"># Read from file (also for ethereal</span>
  1389. # tcpdump port 80 <span class="cmt"># The two classic commands</span>
  1390. # tcpdump host google.com
  1391. # tcpdump -i eth0 -X port \(110 or 143\) <span class="cmt"># Check if pop or imap is secure</span>
  1392. # tcpdump -n -i eth0 icmp <span class="cmt"># Only catch pings</span>
  1393. # tcpdump -i eth0 -s 0 -A port 80 | grep GET <span class="cmt"># -s 0 for full packet -A for ASCII</span>
  1394. </pre>
  1395. Additional important options:
  1396. <ul style="list-style-type: none;">
  1397. <li><code>-A</code> &#160; &#160; Print each packets in clear text (without header)</li>
  1398. <li><code>-X</code> &#160; &#160; Print packets in hex and ASCII</li>
  1399. <li><code>-l</code> &#160; &#160; Make stdout line buffered</li>
  1400. <li><code>-D</code> &#160; &#160; Print all interfaces available</li>
  1401. </ul>
  1402. On Windows use windump from <a rel="nofollow" href="http://www.winpcap.org/">www.winpcap.org</a>. Use windump -D to list the interfaces.
  1403. <h3>Scan with nmap</h3>
  1404. <a rel="nofollow" href="http://insecure.org/nmap/">Nmap</a><span class="fn">http://insecure.org/nmap/</span> is a port scanner with OS detection, it is usually installed on most distributions and is also available for Windows. If you don't scan your servers, hackers do it for you...
  1405. <pre># nmap cb.vu <span class="cmt"># scans all reserved TCP ports on the host</span>
  1406. # nmap -sP 192.168.16.0/24 <span class="cmt"># Find out which IP are used and by which host on 0/24</span>
  1407. # nmap -sS -sV -O cb.vu <span class="cmt"># Do a stealth SYN scan with version and OS detection</span>
  1408. PORT STATE SERVICE VERSION
  1409. 22/tcp open ssh OpenSSH 3.8.1p1 FreeBSD-20060930 (protocol 2.0)
  1410. 25/tcp open smtp Sendmail smtpd 8.13.6/8.13.6
  1411. 80/tcp open http Apache httpd 2.0.59 ((FreeBSD) DAV/2 PHP/4.
  1412. [...]
  1413. Running: FreeBSD 5.X
  1414. Uptime 33.120 days (since Fri Aug 31 11:41:04 2007)
  1415. </pre>
  1416. Other non standard but useful tools are <code>hping</code> (www.hping.org) an IP packet assembler/analyzer and <code>fping</code> (fping.sourceforge.net). fping can check multiple hosts in a round-robin fashion.
  1417. <h2 id="trafficctrl">Traffic control (QoS)</h2>
  1418. Traffic control manages the queuing, policing, scheduling, and other traffic parameters for a network. The following examples are simple practical uses of the Linux and FreeBSD capabilities to better use the available bandwidth.
  1419. <h3>Limit upload</h3>
  1420. DSL or cable modems have a long queue to improve the upload throughput. However filling the queue with a fast device (e.g. ethernet) will dramatically decrease the interactivity. It is therefore useful to limit the device upload rate to match the physical capacity of the modem, this should greatly improve the interactivity. Set to about 90% of the modem maximal (cable) speed.
  1421. <h4>Linux</h4>
  1422. For a 512 Kbit upload modem.
  1423. <pre># tc qdisc add dev eth0 root tbf rate 480kbit latency 50ms burst 1540
  1424. # tc -s qdisc ls dev eth0 <span class="cmt"># Status</span>
  1425. # tc qdisc del dev eth0 root <span class="cmt"># Delete the queue</span>
  1426. # tc qdisc change dev eth0 root tbf rate 220kbit latency 50ms burst 1540
  1427. </pre>
  1428. <h4>FreeBSD</h4>
  1429. FreeBSD uses the <code>dummynet</code> 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 reconfigure it. For example limit the upload bandwidth to 500 Kbit.
  1430. <pre>
  1431. # kldload dummynet <span class="cmt"># load the module if necessary</span>
  1432. # ipfw pipe 1 config bw 500Kbit/s <span class="cmt"># create a pipe with limited bandwidth</span>
  1433. # ipfw add pipe 1 ip from me to any <span class="cmt"># divert the full upload into the pipe</span>
  1434. </pre>
  1435. <h3>Quality of service</h3>
  1436. <h4>Linux</h4>
  1437. Priority queuing with <code>tc</code> to optimize VoIP. See the full example on <a rel="nofollow" href="http://www.voip-info.org/wiki-QoS+Linux+with+HFS">voip-info.org</a> or <a rel="nofollow" href="http://www.howtoforge.com/voip_qos_traffic_shaping_iproute2_asterisk">www.howtoforge.com</a>. Suppose VoIP uses udp on ports 10000:11024 and device eth0 (could also be ppp0 or so). The following commands define the QoS to three queues and force the VoIP traffic to queue 1 with QoS <code>0x1e</code> (all bits set). The default traffic flows into queue 3 and QoS <i>Minimize-Delay</i> flows into queue 2.
  1438. <pre># tc qdisc add dev eth0 root handle 1: prio priomap 2 2 2 2 2 2 2 2 1 1 1 1 1 1 1 0
  1439. # tc qdisc add dev eth0 parent 1:1 handle 10: sfq
  1440. # tc qdisc add dev eth0 parent 1:2 handle 20: sfq
  1441. # tc qdisc add dev eth0 parent 1:3 handle 30: sfq
  1442. # tc filter add dev eth0 protocol ip parent 1: prio 1 u32 \
  1443. match ip dport 10000 0x3C00 flowid 1:1 <span class="cmt"># use server port range</span>
  1444. match ip dst 123.23.0.1 flowid 1:1 <span class="cmt"># or/and use server IP</span>
  1445. </pre>
  1446. Status and remove with
  1447. <pre># tc -s qdisc ls dev eth0 <span class="cmt"># queue status</span>
  1448. # tc qdisc del dev eth0 root <span class="cmt"># delete all QoS</span>
  1449. </pre>
  1450. <h4>Calculate port range and mask</h4>
  1451. The tc filter defines the port range with port and mask which you have to calculate. Find the 2^N <i>ending</i> of the port range, deduce the range and convert to HEX. This is your mask. Example for 10000 -&gt; 11024, the range is 1024.
  1452. <pre># 2^13 (8192) &lt; 10000 &lt; 2^14 (16384) <span class="cmt"># ending is 2^14 = 16384</span>
  1453. # echo "obase=16;(2^14)-1024" | bc <span class="cmt"># mask is 0x3C00</span>
  1454. </pre>
  1455. <h4>FreeBSD</h4>
  1456. The max link bandwidth is 500Kbit/s and we define 3 queues with priority 100:10:1 for VoIP:ssh:all the rest.
  1457. <pre># ipfw pipe 1 config bw 500Kbit/s
  1458. # ipfw queue 1 config pipe 1 weight 100
  1459. # ipfw queue 2 config pipe 1 weight 10
  1460. # ipfw queue 3 config pipe 1 weight 1
  1461. # ipfw add 10 queue 1 proto udp dst-port 10000-11024
  1462. # ipfw add 11 queue 1 proto udp dst-ip 123.23.0.1 <span class="cmt"># or/and use server IP</span>
  1463. # ipfw add 20 queue 2 dsp-port ssh
  1464. # ipfw add 30 queue 3 from me to any <span class="cmt"># all the rest</span>
  1465. </pre>
  1466. Status and remove with
  1467. <pre># ipfw list <span class="cmt"># rules status</span>
  1468. # ipfw pipe list <span class="cmt"># pipe status</span>
  1469. # ipfw flush <span class="cmt"># deletes all rules but default</span>
  1470. </pre>
  1471. <h2 id="nis">NIS Debugging</h2>
  1472. Some commands which should work on a well configured NIS client:
  1473. <pre># ypwhich <span class="cmt"># get the connected NIS server name</span>
  1474. # domainname <span class="cmt"># The NIS domain name as configured</span>
  1475. # ypcat group <span class="cmt"># should display the group from the NIS server</span>
  1476. # cd /var/yp &amp;&amp; make <span class="cmt"># Rebuild the yp database</span>
  1477. # rpcinfo -p servername <span class="cmt"># Report RPC services of the server</span>
  1478. </pre>
  1479. Is ypbind running?
  1480. <pre># ps auxww | grep ypbind
  1481. /usr/sbin/ypbind -s -m -S servername1,servername2 <span class="cmt"># FreeBSD</span>
  1482. /usr/sbin/ypbind <span class="cmt"># Linux</span>
  1483. # yppoll passwd.byname
  1484. Map passwd.byname has order number 1190635041. Mon Sep 24 13:57:21 2007
  1485. The master server is servername.domain.net.
  1486. </pre>
  1487. <h3>Linux</h3>
  1488. <pre># cat /etc/yp.conf
  1489. ypserver servername
  1490. domain domain.net broadcast
  1491. </pre>
  1492. <h2 id="netcat">Netcat</h2>
  1493. <a rel="nofollow" href="http://netcat.sourceforge.net/">Netcat</a><span class="fn">http://netcat.sourceforge.net</span> (nc) is better known as the "network Swiss Army Knife", it can manipulate, create or read/write TCP/IP connections. Here some useful examples, there are many more on the net, for example <a rel="nofollow" href="http://www.g-loaded.eu/2006/11/06/netcat-a-couple-of-useful-examples">g-loaded.eu[...]</a><span class="fn">http://www.g-loaded.eu/2006/11/06/netcat-a-couple-of-useful-examples</span> and <a rel="nofollow" href="http://www.terminally-incoherent.com/blog/2007/08/07/few-useful-netcat-tricks">here</a><span class="fn">http://www.terminally-incoherent.com/blog/2007/08/07/few-useful-netcat-tricks</span>.<br /> You might need to use the command <code>netcat</code> instead of <code>nc</code>. Also see the similar command <a rel="nofollow" href="http://www.dest-unreach.org/socat">socat</a>.
  1494. <h3>File transfer</h3>
  1495. Copy a large folder over a raw tcp connection. The transfer is very quick (no protocol overhead) and you don't need to mess up with NFS or SMB or FTP or so, simply make the file available on the server, and get it from the client. Here 192.168.1.1 is the server IP address.
  1496. <pre><span class="cmt">server#</span> tar -cf - -C VIDEO_TS . | nc -l -p 4444 <span class="cmt"># Serve tar folder on port 4444</span>
  1497. <span class="cmt">client#</span> nc 192.168.1.1 4444 | tar xpf - -C VIDEO_TS <span class="cmt"># Pull the file on port 4444</span>
  1498. <span class="cmt">server#</span> cat largefile | nc -l 5678 <span class="cmt"># Server a single file</span>
  1499. <span class="cmt">client#</span> nc 192.168.1.1 5678 > largefile <span class="cmt"># Pull the single file</span>
  1500. <span class="cmt">server#</span> dd if=/dev/da0 | nc -l 4444 <span class="cmt"># Server partition image</span>
  1501. <span class="cmt">client#</span> nc 192.168.1.1 4444 | dd of=/dev/da0 <span class="cmt"># Pull partition to clone</span>
  1502. <span class="cmt">client#</span> nc 192.168.1.1 4444 | dd of=da0.img <span class="cmt"># Pull partition to file</span>
  1503. </pre>
  1504. <h3>Other hacks</h3>
  1505. Specially here, you must know what you are doing.
  1506. <h4>Remote shell</h4>
  1507. Option -e only on the Windows version? Or use <a rel="nofollow" href="http://download.insecure.org/stf/nc110.tgz">nc 1.10</a>.
  1508. <pre># nc -lp 4444 -e /bin/bash <span class="cmt"># Provide a remote shell (server backdoor)</span>
  1509. # nc -lp 4444 -e cmd.exe <span class="cmt"># remote shell for Windows</span>
  1510. </pre>
  1511. <h4>Emergency web server</h4>
  1512. Serve a single file on port 80 in a loop.
  1513. <pre># while true; do nc -l -p 80 &lt; unixtoolbox.xhtml; done
  1514. </pre>
  1515. <h4>Chat</h4>
  1516. Alice and Bob can chat over a simple TCP socket. The text is transferred with the enter key.
  1517. <pre><span class="cmt">alice#</span> nc -lp 4444
  1518. <span class="cmt">bob #</span> nc 192.168.1.1 4444
  1519. </pre>
  1520. </div>
  1521. <div id="ssh"><h1><a>SSH SCP</a></h1>
  1522. <p class="xrefp"><a class="xrefp" href="#publickey">Public key</a> | <a class="xrefp" href="#sshfingerprint">Fingerprint</a> | <a class="xrefp" href="#scp">SCP</a> | <a class="xrefp" href="#sshtunnel">Tunneling</a> | <a class="xrefp" href="#sshfs">SSHFS</a></p>
  1523. See other tricks <a href="http://blog.urfix.com/25-ssh-commands-tricks/">25 ssh cmd</a><span class="fn">http://blog.urfix.com/25-ssh-commands-tricks/</span>
  1524. <h2 id="publickey">Public key authentication</h2>
  1525. Connect to a host without password using public key authentication. The idea is to append your public key to the authorized_keys2 file on the remote host. For this example let's <b>connect <i>host-client</i> to <i>host-server</i></b>, the key is generated on the client. With cygwin you might have to create your home directoy and the .ssh directory with <code># mkdir -p /home/USER/.ssh</code>
  1526. <ul>
  1527. <li>Use ssh-keygen to generate a key pair. <code>~/.ssh/id_dsa</code> is the private key, <code>~/.ssh/id_dsa.pub</code> is the public key.</li>
  1528. <li>Copy only the public key to the server and append it to the file <code>~/.ssh/authorized_keys2</code> on your home on the server.</li>
  1529. </ul>
  1530. <pre># ssh-keygen -t dsa -N ''
  1531. # cat ~/.ssh/id_dsa.pub | ssh you@host-server "cat - >> ~/.ssh/authorized_keys2"
  1532. </pre>
  1533. <h3>Using the Windows client from ssh.com</h3>
  1534. The non commercial version of the ssh.com client can be downloaded the main ftp site: <a rel="nofollow" href="http://ftp.ssh.com/pub/ssh/">ftp.ssh.com/pub/ssh/</a>. Keys generated by the ssh.com client need to be converted for the OpenSSH server. This can be done with the ssh-keygen command.
  1535. <ul>
  1536. <li>Create a key pair with the ssh.com client: Settings - User Authentication - Generate New....</li>
  1537. <li>I use Key type DSA; key length 2048.</li>
  1538. <li>Copy the public key generated by the ssh.com client to the server into the ~/.ssh folder.</li>
  1539. <li>The keys are in C:\Documents and Settings\%USERNAME%\Application Data\SSH\UserKeys.</li>
  1540. <li>Use the ssh-keygen command on the server to convert the key:
  1541. <pre># cd ~/.ssh
  1542. # ssh-keygen -i -f keyfilename.pub >> authorized_keys2
  1543. </pre></li>
  1544. </ul>
  1545. <i>Notice:</i> We used a DSA key, RSA is also possible. The key is not protected by a password.
  1546. <h3>Using putty for Windows</h3>
  1547. <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html">Putty</a><span class="fn">http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html</span> is a simple and free ssh client for Windows.
  1548. <ul>
  1549. <li>Create a key pair with the puTTYgen program.</li>
  1550. <li>Save the public and private keys (for example into C:\Documents and Settings\%USERNAME%\.ssh).</li>
  1551. <li>Copy the public key to the server into the ~/.ssh folder:
  1552. <pre># scp .ssh/puttykey.pub root@192.168.51.254:.ssh/</pre></li>
  1553. <li>Use the ssh-keygen command on the server to convert the key for OpenSSH:
  1554. <pre># cd ~/.ssh
  1555. # ssh-keygen -i -f puttykey.pub >> authorized_keys2
  1556. </pre></li>
  1557. <li>Point the private key location in the putty settings: Connection - SSH - Auth</li>
  1558. </ul>
  1559. <h2 id="sshfingerprint">Check fingerprint</h2>
  1560. At the first login, ssh will ask if the unknown host with the fingerprint has to be stored in the known hosts. To avoid a man-in-the-middle attack the administrator of the server can send you the server fingerprint which is then compared on the first login. Use <code>ssh-keygen -l</code> to get the fingerprint (on the server):
  1561. <pre># ssh-keygen -l -f /etc/ssh/ssh_host_rsa_key.pub <span class="cmt"># For RSA key</span>
  1562. 2048 61:33:be:9b:ae:6c:36:31:fd:83:98:b7:99:2d:9f:cd /etc/ssh/ssh_host_rsa_key.pub
  1563. # ssh-keygen -l -f /etc/ssh/ssh_host_dsa_key.pub <span class="cmt"># For DSA key (default)</span>
  1564. 2048 14:4a:aa:d9:73:25:46:6d:0a:48:35:c7:f4:16:d4:ee /etc/ssh/ssh_host_dsa_key.pub
  1565. </pre>
  1566. Now the client connecting to this server can verify that he is connecting to the right server:
  1567. <pre># ssh linda
  1568. The authenticity of host 'linda (192.168.16.54)' can't be established.
  1569. DSA key fingerprint is 14:4a:aa:d9:73:25:46:6d:0a:48:35:c7:f4:16:d4:ee.
  1570. Are you sure you want to continue connecting (yes/no)? yes
  1571. </pre>
  1572. <h2 id="scp">Secure file transfer</h2>
  1573. Some simple commands:<br />
  1574. <pre># scp file.txt host-two:/tmp
  1575. # scp joe@host-two:/www/*.html /www/tmp
  1576. # scp -r joe@host-two:/www /www/tmp
  1577. # scp -P 20022 cb@cb.vu:unixtoolbox.xhtml . <span class="cmt"># connect on port 20022</span>
  1578. </pre>
  1579. In Konqueror or Midnight Commander it is possible to access a remote file system with the address <strong>fish://user@gate</strong>. However the implementation is very slow.<br />
  1580. Furthermore it is possible to mount a remote folder with <strong>sshfs</strong> a file system client based on SCP. <a href="http://fuse.sourceforge.net/sshfs.html">See fuse sshfs</a><span class="fn">http://fuse.sourceforge.net/sshfs.html</span>.
  1581. <pre>ssh_exchange_identification: Connection closed by remote host</pre>
  1582. With this error try the following on the server:
  1583. <pre>echo 'SSHD: ALL' >> /etc/hosts.allow
  1584. /etc/init.d/sshd restart</pre>
  1585. <h2 id="sshtunnel">Tunneling</h2>
  1586. SSH tunneling allows to forward or reverse forward a port over the SSH connection, thus securing the traffic and accessing ports which would otherwise be blocked. This only works with TCP. The general nomenclature for forward and reverse is (see also <a href="#sshnat">ssh and NAT example</a>):
  1587. <pre># ssh -L localport:desthost:destport user@gate <span class="cmt"># desthost as seen from the gate</span>
  1588. # ssh -R destport:desthost:localport user@gate <span class="cmt"># forwards your localport to destination</span>
  1589. <span class="cmt"># desthost:localport as seen from the client initiating the tunnel</span>
  1590. # ssh -X user@gate <span class="cmt"># To force X forwarding</span>
  1591. </pre>
  1592. This will connect to gate and forward the local port to the host desthost:destport. Note desthost is the destination host <i>as seen by the gate</i>, so if the connection is to the gate, then desthost is localhost. More than one port forward is possible.
  1593. <h3>Direct forward on the gate</h3>
  1594. Let say we want to access the CVS (port 2401) and http (port 80) which are running on the gate. This is the simplest example, desthost is thus localhost, and we use the port 8080 locally instead of 80 so we don't need to be root. Once the ssh session is open, both services are accessible on the local ports.
  1595. <pre># ssh -L 2401:localhost:2401 -L 8080:localhost:80 user@gate</pre>
  1596. <h3>Netbios and remote desktop forward to a second server</h3>
  1597. Let say a Windows smb server is behind the gate and is not running ssh. We need access to the smb share and also remote desktop to the server.
  1598. <pre># ssh -L 139:smbserver:139 -L 3388:smbserver:3389 user@gate</pre>
  1599. The smb share can now be accessed with \\127.0.0.1\, but only if the local share is disabled, because <i>the local share is listening on port 139</i>.<br />
  1600. 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 <i>the local RDP is already listening on 3389</i>, so we choose 3388. For this example let's use a virtual IP of 10.1.1.1.<br />
  1601. <ul>
  1602. <li>With putty use Source port=10.1.1.1:139. It is possible to create multiple loop devices and tunnel. 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 uninstall this path in Vista.</li>
  1603. <li>With the ssh.com client, disable "Allow local connections only". Since ssh.com will bind to all addresses, only a single share can be connected.</li>
  1604. </ul>
  1605. Now create the loopback interface with IP 10.1.1.1:
  1606. <ul>
  1607. <li># System->Control Panel->Add Hardware # Yes, Hardware is already connected
  1608. # Add a new hardware device (at bottom).</li>
  1609. <li># Install the hardware that I manually select # Network adapters # Microsoft , Microsoft Loopback Adapter.</li>
  1610. <li>Configure the IP address of the fake device to 10.1.1.1 mask 255.255.255.0, no gateway.</li>
  1611. <li>advanced->WINS, Enable LMHosts Lookup; Disable NetBIOS over TCP/IP.</li>
  1612. <li># Enable Client for Microsoft Networks. # Disable File and Printer Sharing for Microsoft Networks.</li>
  1613. </ul>
  1614. 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.
  1615. <h4>Debug</h4>
  1616. If it is not working:
  1617. <ul>
  1618. <li>Are the ports forwarded: netstat -an? Look at 0.0.0.0:139 or 10.1.1.1:139</li>
  1619. <li>Does telnet 10.1.1.1 139 connect?</li>
  1620. <li>You need the checkbox "Local ports accept connections from other hosts".</li>
  1621. <li>Is "File and Printer Sharing for Microsoft Networks" disabled on the loopback interface?</li>
  1622. </ul>
  1623. <h3 id="sshnat">Connect two clients behind NAT</h3>
  1624. Suppose two clients are behind a NAT gateway and client cliadmin has to connect to client cliuser (the destination), both can login to the gate with ssh and are running Linux with sshd. You don't need root access anywhere as long as the ports on gate are above 1024. We use 2022 on gate. Also since the gate is used locally, the option GatewayPorts is not necessary.<br />
  1625. On client cliuser (from destination to gate):
  1626. <pre># ssh -R 2022:localhost:22 user@gate <span class="cmt"># forwards client 22 to gate:2022</span></pre>
  1627. On client cliadmin (from host to gate):
  1628. <pre># ssh -L 3022:localhost:2022 admin@gate <span class="cmt"># forwards client 3022 to gate:2022</span></pre>
  1629. Now the admin can connect directly to the client cliuser with:
  1630. <pre># ssh -p 3022 admin@localhost <span class="cmt"># local:3022 -&gt; gate:2022 -&gt; client:22</span></pre>
  1631. <h3>Connect to VNC behind NAT</h3>
  1632. Suppose a Windows client with VNC listening on port 5900 has to be accessed from behind NAT.
  1633. On client cliwin to gate:
  1634. <pre># ssh -R 15900:localhost:5900 user@gate</pre>
  1635. On client cliadmin (from host to gate):
  1636. <pre># ssh -L 5900:localhost:15900 admin@gate</pre>
  1637. Now the admin can connect directly to the client VNC with:
  1638. <pre># vncconnect -display :0 localhost</pre>
  1639. <h3 id="sshmultihop">Dig a multi-hop ssh tunnel</h3>
  1640. 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 example to copy files with scp, or forward other ports like smb or vnc. One way to do this is to chain tunnels together to forward a port to the server along the hops. This "carrier" port only reaches its final destination on the last connection to the server.<br />
  1641. Suppose we want to forward the ssh port from a client to a server over two hops. Once the tunnel is build, it is possible to connect to the server directly from the client (and also add an other port forward).
  1642. <h4>Create tunnel in one shell</h4>
  1643. client -&gt; host1 -&gt; host2 -&gt; server and dig tunnel 5678
  1644. <pre><span class="cmt">client&gt;</span># ssh -L5678:localhost:5678 host1 <span class="cmt"># 5678 is an arbitrary port for the tunnel</span>
  1645. <span class="cmt">host_1&gt;</span># ssh -L5678:localhost:5678 host2 <span class="cmt"># chain 5678 from host1 to host2</span>
  1646. <span class="cmt">host_2&gt;</span># ssh -L5678:localhost:22 server <span class="cmt"># end the tunnel on port 22 on the server</span>
  1647. </pre>
  1648. <h4>Use tunnel with an other shell</h4>
  1649. client -&gt; server using tunnel 5678
  1650. <pre># ssh -p 5678 localhost <span class="cmt"># connect directly from client to server</span>
  1651. # scp -P 5678 myfile localhost:/tmp/ <span class="cmt"># or copy a file directly using the tunnel</span>
  1652. # rsync -e 'ssh -p 5678' myfile localhost:/tmp/ <span class="cmt"># or rsync a file directly to the server</span>
  1653. </pre>
  1654. <h3>Autoconnect and keep alive script</h3>
  1655. I use variations of the following script to keep a machine reacheable over a reverse ssh tunnel. The connection is automatically rebuilt if closed. You can add multiple <code>-L</code> or <code>-R</code> tunnels on one line.
  1656. <pre>#!/bin/sh
  1657. COMMAND="ssh -N -f -g -R 3022:localhost:22 colin@cb.vu"
  1658. pgrep -f -x "$COMMAND" &gt; /dev/null 2&gt;&amp;1 || $COMMAND
  1659. exit 0
  1660. </pre>
  1661. <pre>1 * * * * colin /home/colin/port_forward.sh <span class="cmt"># crontab entry (here hourly)</span></pre>
  1662. </div>
  1663. <h2 id="sshfs">sshfs</h2>
  1664. Mount a filesystem with ssh.
  1665. <pre># sshfs cb@cb.vu:/ /Users/barschel/cbvu -oauto_cache,reconnect,defer_permissions \
  1666. ,noappledouble,negative_vncache,volname=cbvu
  1667. </pre>
  1668. Or via a two hops tunnel
  1669. <pre># ssh -Y -A -t -L20022:127.0.0.1:20022 cbarsche@lbgw ssh -Y -A -t -L20022:127.0.0.1:22 rootbgv@bgvctrl
  1670. # sshfs -p 20022 cb@cb.vu:/ /Users/barschel/cbvu -oauto_cache,reconnect,defer_permissions \
  1671. ,noappledouble,negative_vncache,volname=cbvu
  1672. </pre>
  1673. <div id="vpn"><h1><a>VPN with SSH</a></h1>
  1674. As of version 4.3, OpenSSH can use the tun/tap device to encrypt a tunnel. This is very similar to other TLS based VPN solutions like OpenVPN. One advantage with SSH is that there is no need to install and configure additional software. Additionally the tunnel uses the SSH authentication like pre shared keys. The drawback is that the encapsulation is done over TCP which might result in poor performance on a slow link. Also the tunnel is relying on a single (fragile) TCP connection. This technique is very useful for a quick IP based VPN setup. There is no limitation as with the single TCP port forward, all layer 3/4 protocols like ICMP, TCP/UDP, etc. are forwarded over the VPN. In any case, the following options are needed in the sshd_conf file:
  1675. <pre>PermitRootLogin yes
  1676. PermitTunnel yes
  1677. </pre>
  1678. <h2 id="sshp2p">Single P2P connection</h2>
  1679. Here we are connecting two hosts, hclient and hserver with a peer to peer tunnel. The connection is <i>started from hclient</i> to hserver and is done as root. The tunnel end points are 10.0.1.1 (server) and 10.0.1.2 (client) and we create a device tun5 (this could also be an other number). The procedure is very simple:
  1680. <ul>
  1681. <li>Connect with SSH using the tunnel option -w</li>
  1682. <li>Configure the IP addresses of the tunnel. Once on the server and once on the client.</li>
  1683. </ul>
  1684. <h3>Connect to the server</h3>
  1685. Connection started on the client and commands are executed on the server.
  1686. <h4>Server is on Linux</h4>
  1687. <pre><span class="cmt">cli&gt;#</span> ssh -w5:5 root@hserver
  1688. <span class="cmt">srv&gt;#</span> ifconfig tun5 10.0.1.1 netmask 255.255.255.252 <span class="cmt"># Executed on the server shell</span>
  1689. </pre>
  1690. <h4>Server is on FreeBSD</h4>
  1691. <pre><span class="cmt">cli&gt;#</span> ssh -w5:5 root@hserver
  1692. <span class="cmt">srv&gt;#</span> ifconfig tun5 10.0.1.1 10.0.1.2 <span class="cmt"># Executed on the server shell</span>
  1693. </pre>
  1694. <h3>Configure the client</h3>
  1695. Commands executed on the client:
  1696. <pre><span class="cmt">cli&gt;#</span> ifconfig tun5 10.0.1.2 netmask 255.255.255.252 <span class="cmt"># Client is on Linux</span>
  1697. <span class="cmt">cli&gt;#</span> ifconfig tun5 10.0.1.2 10.0.1.1 <span class="cmt"># Client is on FreeBSD</span>
  1698. </pre>
  1699. The two hosts are now connected and can transparently communicate with any layer 3/4 protocol using the tunnel IP addresses.
  1700. <h2 id="sshg2g">Connect two networks</h2>
  1701. In addition to the p2p setup above, it is more useful to connect two private networks with an SSH VPN using two gates. Suppose for the example, netA is 192.168.51.0/24 and netB 192.168.16.0/24. The procedure is similar as above, we only need to add the routing. NAT must be activated on the private interface only if the gates are not the same as the default gateway of their network.<br />
  1702. 192.168.51.0/24 (netA)|gateA &lt;-&gt; gateB|192.168.16.0/24 (netB)<br />
  1703. <ul>
  1704. <li>Connect with SSH using the tunnel option -w.</li>
  1705. <li>Configure the IP addresses of the tunnel. Once on the server and once on the client.</li>
  1706. <li>Add the routing for the two networks.</li>
  1707. <li>If necessary, activate NAT on the private interface of the gate.</li>
  1708. </ul>
  1709. The setup is <i>started from gateA in netA</i>.
  1710. <h3>Connect from gateA to gateB</h3>
  1711. Connection is started from gateA and commands are executed on gateB.
  1712. <h4>gateB is on Linux</h4>
  1713. <pre><span class="cmt">gateA&gt;#</span> ssh -w5:5 root@gateB
  1714. <span class="cmt">gateB&gt;#</span> ifconfig tun5 10.0.1.1 netmask 255.255.255.252 <span class="cmt"># Executed on the gateB shell</span>
  1715. <span class="cmt">gateB&gt;#</span> route add -net 192.168.51.0 netmask 255.255.255.0 dev tun5
  1716. <span class="cmt">gateB&gt;#</span> echo 1 &gt; /proc/sys/net/ipv4/ip_forward <span class="cmt"># Only needed if not default gw</span>
  1717. <span class="cmt">gateB&gt;#</span> iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
  1718. </pre>
  1719. <h4>gateB is on FreeBSD</h4>
  1720. <pre><span class="cmt">gateA&gt;#</span> ssh -w5:5 root@gateB <span class="cmt"># Creates the tun5 devices</span>
  1721. <span class="cmt">gateB&gt;#</span> ifconfig tun5 10.0.1.1 10.0.1.2 <span class="cmt"># Executed on the gateB shell</span>
  1722. <span class="cmt">gateB&gt;#</span> route add 192.168.51.0/24 10.0.1.2
  1723. <span class="cmt">gateB&gt;#</span> sysctl net.inet.ip.forwarding=1 <span class="cmt"># Only needed if not default gw</span>
  1724. <span class="cmt">gateB&gt;#</span> natd -s -m -u -dynamic -n fxp0 <span class="cmt"># see <a class="xref" href="#nat">NAT</a></span>
  1725. <span class="cmt">gateA&gt;#</span> sysctl net.inet.ip.fw.enable=1
  1726. </pre>
  1727. <h3>Configure gateA</h3>
  1728. Commands executed on gateA:
  1729. <h4>gateA is on Linux</h4>
  1730. <pre><span class="cmt">gateA&gt;#</span> ifconfig tun5 10.0.1.2 netmask 255.255.255.252
  1731. <span class="cmt">gateA&gt;#</span> route add -net 192.168.16.0 netmask 255.255.255.0 dev tun5
  1732. <span class="cmt">gateA&gt;#</span> echo 1 &gt; /proc/sys/net/ipv4/ip_forward
  1733. <span class="cmt">gateA&gt;#</span> iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
  1734. </pre>
  1735. <h4>gateA is on FreeBSD</h4>
  1736. <pre><span class="cmt">gateA&gt;#</span> ifconfig tun5 10.0.1.2 10.0.1.1
  1737. <span class="cmt">gateA&gt;#</span> route add 192.168.16.0/24 10.0.1.2
  1738. <span class="cmt">gateA&gt;#</span> sysctl net.inet.ip.forwarding=1
  1739. <span class="cmt">gateA&gt;#</span> natd -s -m -u -dynamic -n fxp0 <span class="cmt"># see <a class="xref" href="#nat">NAT</a></span>
  1740. <span class="cmt">gateA&gt;#</span> sysctl net.inet.ip.fw.enable=1
  1741. </pre>
  1742. The two private networks are now transparently connected via the SSH VPN. The IP forward and NAT settings are only necessary if the gates are not the default gateways. In this case the clients would not know where to forward the response, and nat must be activated.
  1743. </div>
  1744. <div id="rsync"><h1><a>RSYNC</a></h1>
  1745. Rsync can almost completely replace cp and scp, furthermore interrupted transfers are efficiently restarted. A trailing slash (and the absence thereof) has different meanings, the man page is good... Here some examples:<br />
  1746. Copy the directories with full content:
  1747. <pre># rsync -a /home/colin/ /backup/colin/ <span class="cmt"># "archive" mode. e.g keep the same</span>
  1748. # rsync -a /var/ /var_bak/
  1749. # rsync -aR --delete-during /home/user/ /backup/ <span class="cmt"># use relative (see below)</span>
  1750. # /opt/local/bin/rsync -azv --iconv=UTF-8-MAC,UTF-8 ~/Music/flac/ me@server:/dst/
  1751. <span class="cmt"># convert filenames OSX UTF8 to Windows UTF8</span>
  1752. </pre>
  1753. Same as before but over the network and with compression. Rsync uses SSH for the transport per default and will use the ssh key if they are set. Use ":" as with SCP. A typical remote copy:
  1754. <pre># rsync -axSRzv /home/user/ user@server:/backup/user/ <span class="cmt"># Copy to remote</span>
  1755. # rsync -a 'user@server:My\ Documents' My\ Documents <span class="cmt"># Quote AND escape spaces for the remote shell</span></pre>
  1756. Exclude any directory tmp within /home/user/ and keep the relative folders hierarchy, that is the remote directory will have the structure /backup/home/user/. This is typically used for backups.
  1757. <pre># rsync -azR --exclude=tmp/ /home/user/ user@server:/backup/</pre>
  1758. Use port 20022 for the ssh connection:
  1759. <pre># rsync -az -e 'ssh -p 20022' /home/colin/ user@server:/backup/colin/</pre>
  1760. Using the rsync daemon (used with "::") is much faster, but not encrypted over ssh. The location of /backup is defined by the configuration in /etc/rsyncd.conf. The variable RSYNC_PASSWORD can be set to avoid the need to enter the password manually.
  1761. <pre># rsync -axSRz /home/ ruser@hostname::rmodule/backup/
  1762. # rsync -axSRz ruser@hostname::rmodule/backup/ /home/ <span class="cmt"># To copy back</span>
  1763. </pre>
  1764. Some important options:
  1765. <ul style="list-style-type: none;">
  1766. <li><code>-a, --archive</code> &#160; &#160; &#160; archive mode; same as -rlptgoD (no -H)</li>
  1767. <li><code>-r, --recursive</code> &#160; &#160; &#160; recurse into directories</li>
  1768. <li><code>-R, --relative</code> &#160; &#160; &#160; use relative path names</li>
  1769. <li><code>-H, --hard-links</code> &#160; &#160; &#160; preserve hard links</li>
  1770. <li><code>-S, --sparse</code> &#160; &#160; &#160; handle sparse files efficiently</li>
  1771. <li><code>-x, --one-file-system</code> &#160; &#160; &#160; don't cross file system boundaries</li>
  1772. <li><code> --exclude=PATTERN</code> &#160; &#160; &#160; exclude files matching PATTERN</li>
  1773. <li><code> --delete-during</code> &#160; &#160; &#160; receiver deletes during xfer, not before</li>
  1774. <li><code> --delete-after</code> &#160; &#160; &#160; receiver deletes after transfer, not before</li>
  1775. </ul>
  1776. <h2 id="winrsync">Rsync on Windows</h2>
  1777. Rsync is available for Windows through cygwin or as stand-alone packaged in <a href="http://sourceforge.net/projects/sereds/">cwrsync</a><span class="fn">http://sourceforge.net/projects/sereds</span>. This is very convenient for automated backups. Install one of them (<i>not both</i>) and add the path to the Windows system variables: # Control Panel -&gt; System -&gt; tab Advanced, 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 <code>rsync</code> and <code>ssh</code> are available in a Windows command shell.
  1778. <h3>Public key authentication</h3>
  1779. 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 rsync command will run without a password.<br />
  1780. All the following commands are executed within a Windows console. In a console (Start -&gt; Run -&gt; cmd) create and upload the key as described in <a href="#ssh">SSH</a>, change "user" and "server" as appropriate. If the file authorized_keys2 does not exist yet, simply copy id_dsa.pub to authorized_keys2 and upload it.
  1781. <pre># ssh-keygen -t dsa -N '' <span class="cmt"># Creates a public and a private key</span>
  1782. # rsync user@server:.ssh/authorized_keys2 . <span class="cmt"># Copy the file locally from the server</span>
  1783. # cat id_dsa.pub >> authorized_keys2 <span class="cmt"># Or use an editor to add the key</span>
  1784. # rsync authorized_keys2 user@server:.ssh/ <span class="cmt"># Copy the file back to the server</span>
  1785. # del authorized_keys2 <span class="cmt"># Remove the local copy</span>
  1786. </pre>
  1787. Now test it with (in one line):
  1788. <pre>rsync -rv "/cygdrive/c/Documents and Settings/%USERNAME%/My Documents/" \
  1789. 'user@server:My\ Documents/'
  1790. </pre>
  1791. <h3>Automatic backup</h3>
  1792. Use a batch file to automate the backup and add the file in the scheduled tasks (Programs -&gt; Accessories -&gt; System Tools -&gt; Scheduled Tasks). For example create the file backup.bat and replace user@server.
  1793. <pre>@ECHO OFF
  1794. REM rsync the directory My Documents
  1795. SETLOCAL
  1796. SET CWRSYNCHOME=C:\PROGRAM FILES\CWRSYNC
  1797. SET CYGWIN=nontsec
  1798. SET CWOLDPATH=%PATH%
  1799. REM uncomment the next line when using cygwin
  1800. SET PATH=%CWRSYNCHOME%\BIN;%PATH%
  1801. echo Press Control-C to abort
  1802. rsync -av "/cygdrive/c/Documents and Settings/%USERNAME%/My Documents/" \
  1803. 'user@server:My\ Documents/'
  1804. pause
  1805. </pre>
  1806. </div>
  1807. <div id="sudo"><h1><a>SUDO</a></h1>
  1808. Sudo is a standard way to give users some administrative rights without giving out the root password. Sudo is very useful in a multi user environment with a mix of server and workstations. Simply call the command with sudo:
  1809. <pre># sudo /etc/init.d/dhcpd restart <span class="cmt"># Run the rc script as root</span>
  1810. # sudo -u sysadmin whoami <span class="cmt"># Run cmd as an other user</span>
  1811. </pre>
  1812. <h2>Configuration</h2>
  1813. Sudo is configured in <code>/etc/sudoers</code> and must only be edited with <code>visudo</code>. The basic syntax is (the lists are comma separated):
  1814. <pre>user hosts = (runas) commands <span class="cmt"># In /etc/sudoers</span></pre>
  1815. <ul style="list-style-type:none; page-break-inside:avoid;">
  1816. <li><code>users</code> one or more users or %group (like %wheel) to gain the rights</li>
  1817. <li><code>hosts</code> list of hosts (or ALL)</li>
  1818. <li><code>runas</code> list of users (or ALL) that the command rule can be run as. It is enclosed in ( )!</li>
  1819. <li><code>commands</code> list of commands (or ALL) that will be run as root or as (runas)</li>
  1820. </ul>
  1821. Additionally those keywords can be defined as alias, they are called User_Alias, Host_Alias, Runas_Alias and Cmnd_Alias. This is useful for larger setups. Here a sudoers example:
  1822. <pre># cat /etc/sudoers
  1823. <span class="cmt"># Host aliases are subnets or hostnames.</span>
  1824. Host_Alias DMZ = 212.118.81.40/28
  1825. Host_Alias DESKTOP = work1, work2
  1826. <span class="cmt"># User aliases are a list of users which can have the same rights</span>
  1827. User_Alias ADMINS = colin, luca, admin
  1828. User_Alias DEVEL = joe, jack, julia
  1829. Runas_Alias DBA = oracle,pgsql
  1830. <span class="cmt"># Command aliases define the full path of a list of commands</span>
  1831. Cmnd_Alias SYSTEM = /sbin/reboot,/usr/bin/kill,/sbin/halt,/sbin/shutdown,/etc/init.d/
  1832. Cmnd_Alias PW = /usr/bin/passwd [A-z]*, !/usr/bin/passwd root <span class="cmt"># Not root pwd!</span>
  1833. Cmnd_Alias DEBUG = /usr/sbin/tcpdump,/usr/bin/wireshark,/usr/bin/nmap
  1834. </pre><pre><span class="cmt"># The actual rules</span>
  1835. root,ADMINS ALL = (ALL) NOPASSWD: ALL <span class="cmt"># ADMINS can do anything w/o a password.</span>
  1836. DEVEL DESKTOP = (ALL) NOPASSWD: ALL <span class="cmt"># Developers have full right on desktops</span>
  1837. DEVEL DMZ = (ALL) NOPASSWD: DEBUG <span class="cmt"># Developers can debug the DMZ servers.</span>
  1838. <span class="cmt"># User sysadmin can mess around in the DMZ servers with some commands.</span>
  1839. sysadmin DMZ = (ALL) NOPASSWD: SYSTEM,PW,DEBUG
  1840. sysadmin ALL,!DMZ = (ALL) NOPASSWD: ALL <span class="cmt"># Can do anything outside the DMZ.</span>
  1841. %dba ALL = (DBA) ALL <span class="cmt"># Group dba can run as database user.</span>
  1842. <span class="cmt"># anyone can mount/unmount a cd-rom on the desktop machines</span>
  1843. ALL DESKTOP = NOPASSWD: /sbin/mount /cdrom,/sbin/umount /cdrom
  1844. </pre>
  1845. </div>
  1846. <div id="crypt"><h1><a>Encrypt Files</a></h1>
  1847. <h2>OpenSSL</h2>
  1848. <h3>A single file</h3>
  1849. Encrypt and decrypt:
  1850. <pre># openssl aes-128-cbc -salt -in file -out file.aes
  1851. # openssl aes-128-cbc -d -salt -in file.aes -out file
  1852. </pre>
  1853. Note that the file can of course be a tar archive.
  1854. <h3>tar and encrypt a whole directory</h3>
  1855. <pre># tar -cf - directory | openssl aes-128-cbc -salt -out directory.tar.aes <span class="cmt"># Encrypt</span>
  1856. # openssl aes-128-cbc -d -salt -in directory.tar.aes | tar -x -f - <span class="cmt"># Decrypt</span>
  1857. </pre>
  1858. <h3>tar zip and encrypt a whole directory</h3>
  1859. <pre># tar -zcf - directory | openssl aes-128-cbc -salt -out directory.tar.gz.aes <span class="cmt"># Encrypt</span>
  1860. # openssl aes-128-cbc -d -salt -in directory.tar.gz.aes | tar -xz -f - <span class="cmt"># Decrypt</span>
  1861. </pre>
  1862. <ul>
  1863. <li>Use -k mysecretpassword after aes-128-cbc to avoid the interactive password request. However note that this is highly insecure.</li>
  1864. <li>Use <strong>aes-256-cbc</strong> instead of <strong>aes-128-cbc</strong> to get even stronger encryption. This uses also more CPU.</li>
  1865. </ul>
  1866. <h2>GPG</h2>
  1867. <a href="http://gnupg.org/">GnuPG</a> is well known to encrypt and sign emails or any data. Furthermore gpg and also provides an advanced key management system. This section only covers files encryption, not email usage, signing or the Web-Of-Trust.<br />
  1868. The simplest encryption is with a symmetric cipher. In this case the file is encrypted with a password and anyone who knows the password can decrypt it, thus the keys are not needed. Gpg adds an extention ".gpg" to the encrypted file names.
  1869. <pre># gpg -c file <span class="cmt"># Encrypt file with password</span>
  1870. # gpg file.gpg <span class="cmt"># Decrypt file (optionally -o otherfile)</span>
  1871. </pre>
  1872. <h3>Using keys</h3>
  1873. For more details see <a href="http://www.madboa.com/geek/gpg-quickstart">GPG Quick Start</a><span class="fn">http://www.madboa.com/geek/gpg-quickstart</span> and <a href="http://aplawrence.com/Basics/gpg.html">GPG/PGP Basics</a><span class="fn">http://aplawrence.com/Basics/gpg.html</span> and the <a href="http://gnupg.org/documentation">gnupg documentation</a><span class="fn">http://gnupg.org/documentation</span> among others.<br />
  1874. The private and public keys are the heart of asymmetric cryptography. What is important to remember:
  1875. <ul>
  1876. <li>Your public key is used by <i>others</i> to encrypt files that only you as the receiver can decrypt (not even the one who encrypted the file can decrypt it). The public key is thus meant to be distributed.</li>
  1877. <li>Your private key is encrypted with your passphrase and is used to decrypt files which were encrypted with <i>your</i> public key. The private key must be kept <b>secure</b>. Also if the key or passphrase is lost, so are all the files encrypted with your public key.</li>
  1878. <li>The key files are called keyrings as they can contain more than one key.</li>
  1879. </ul>
  1880. 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 and email. Also you should use a "passphrase", not a simple password.
  1881. <pre># gpg --gen-key <span class="cmt"># This can take a long time</span></pre>
  1882. The keys are stored in ~/.gnupg/ on Unix, on Windows they are typically stored in<br />
  1883. C:/Documents and Settings/%USERNAME%/Application Data/gnupg/.
  1884. <pre>~/.gnupg/pubring.gpg <span class="cmt"># Contains your public keys and all others imported</span>
  1885. ~/.gnupg/secring.gpg <span class="cmt"># Can contain more than one private key</span>
  1886. </pre>
  1887. Short reminder on most used options:
  1888. <ul style="list-style-type:none; page-break-inside:avoid;">
  1889. <li><b>-e</b> encrypt data</li>
  1890. <li><b>-d</b> decrypt data</li>
  1891. <li><b>-r</b> NAME encrypt for recipient NAME (or 'Full Name' or 'email@domain')</li>
  1892. <li><b>-a</b> create ascii armored output of a key</li>
  1893. <li><b>-o</b> use as output file</li>
  1894. </ul>
  1895. The examples use 'Your Name' and 'Alice' as the keys are referred to by the email or full name or partial name. For example I can use 'Colin' or 'c@cb.vu' for my key [Colin Barschel (cb.vu) &lt;c@cb.vu&gt;].
  1896. <h3>Encrypt for personal use only</h3>
  1897. No need to export/import any key for this. You have both already.
  1898. <pre># gpg -e -r 'Your Name' file <span class="cmt"># Encrypt with your public key</span>
  1899. # gpg -o file -d file.gpg <span class="cmt"># Decrypt. Use -o or it goes to stdout</span>
  1900. </pre>
  1901. <h3>Encrypt - Decrypt with keys</h3>
  1902. 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.<br />
  1903. For example Alice export her public key and you import it, you can then encrypt a file for her. That is only Alice will be able to decrypt it.
  1904. <pre># gpg -a -o alicekey.asc --export 'Alice' <span class="cmt"># Alice exported her key in ascii file.</span>
  1905. # gpg --send-keys --keyserver subkeys.pgp.net KEYID <span class="cmt"># Alice put her key on a server.</span>
  1906. # gpg --import alicekey.asc <span class="cmt"># You import her key into your pubring.</span>
  1907. # gpg --search-keys --keyserver subkeys.pgp.net 'Alice' <span class="cmt"># or get her key from a server.</span>
  1908. </pre>
  1909. Once the keys are imported it is very easy to encrypt or decrypt a file:
  1910. <pre># gpg -e -r 'Alice' file <span class="cmt"># Encrypt the file for Alice.</span>
  1911. # gpg -d file.gpg -o file <span class="cmt"># Decrypt a file encrypted by Alice for you.</span>
  1912. </pre>
  1913. <h3>Key administration</h3>
  1914. <pre># gpg --list-keys <span class="cmt"># list public keys and see the KEYIDS</span>
  1915. <span class="cmt">The KEYID follows the '/' e.g. for: pub 1024D/D12B77CE the KEYID is D12B77CE</span>
  1916. # gpg --gen-revoke 'Your Name' <span class="cmt"># generate revocation certificate</span>
  1917. # gpg --list-secret-keys <span class="cmt"># list private keys</span>
  1918. # gpg --delete-keys NAME <span class="cmt"># delete a public key from local key ring</span>
  1919. # gpg --delete-secret-key NAME <span class="cmt"># delete a secret key from local key ring</span>
  1920. # gpg --fingerprint KEYID <span class="cmt"># Show the fingerprint of the key</span>
  1921. # gpg --edit-key KEYID <span class="cmt"># Edit key (e.g sign or add/del email)</span>
  1922. </pre>
  1923. </div>
  1924. <div id="cryptpart"><h1><a>Encrypt Partitions</a></h1>
  1925. <p class="xrefp"><a class="xrefp" href="#wluks">Linux with LUKS</a> | <a class="xrefp" href="#woluks">Linux dm-crypt only</a> | <a class="xrefp" href="#bsdgeli">FreeBSD GELI</a> | <a class="xrefp" href="#bsdpwd">FBSD pwd only</a> | <a class="xrefp" href="#osxcrypt">OS X image</a></p>
  1926. There are (many) other alternative methods to encrypt disks, I only show here the methods I know and use. 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 partition is <i>attached</i> and will not prevent an intruder to have access to it in this state.
  1927. <h2 id="dm-crypt">Linux</h2>
  1928. Those instructions use the Linux <code>dm-crypt</code> (device-mapper) facility available on the 2.6 kernel. In this example, lets encrypt the partition <code>/dev/sdc1</code>, it could be however any other partition or disk, or USB or a file based partition created with <code>losetup</code>. In this case we would use <code>/dev/loop0</code>. See <a href="#losetup">file image partition</a>. The device mapper uses labels to identify a partition. We use <code>sdc1</code> in this example, but it could be any string.
  1929. <h3 id="wluks">dm-crypt with LUKS</h3>
  1930. LUKS with dm-crypt has better encryption and makes it possible to have multiple passphrase for the same partition or to change the password easily. To test if LUKS is available, simply type <code># cryptsetup --help</code>, if nothing about LUKS shows up, use the instructions below <a href="#woluks">Without LUKS</a>. First create a partition if necessary: <code>fdisk /dev/sdc</code>.
  1931. <h4>Create encrypted partition</h4>
  1932. <pre># dd if=/dev/urandom of=/dev/sdc1 <span class="cmt"># Optional. For paranoids only (takes days)</span>
  1933. # cryptsetup -y luksFormat /dev/sdc1 <span class="cmt"># This destroys any data on sdc1</span>
  1934. # cryptsetup luksOpen /dev/sdc1 sdc1
  1935. # mkfs.ext3 /dev/mapper/sdc1 <span class="cmt"># create ext3 file system</span>
  1936. # mount -t ext3 /dev/mapper/sdc1 /mnt
  1937. # umount /mnt
  1938. # cryptsetup luksClose sdc1 <span class="cmt"># Detach the encrypted partition</span></pre>
  1939. <h4>Attach</h4>
  1940. <pre># cryptsetup luksOpen /dev/sdc1 sdc1
  1941. # mount -t ext3 /dev/mapper/sdc1 /mnt</pre>
  1942. <h4>Detach</h4>
  1943. <pre># umount /mnt
  1944. # cryptsetup luksClose sdc1
  1945. </pre>
  1946. <h3 id="woluks">dm-crypt without LUKS</h3>
  1947. <pre># cryptsetup -y create sdc1 /dev/sdc1 <span class="cmt"># or any other partition like /dev/loop0</span>
  1948. # dmsetup ls <span class="cmt"># check it, will display: sdc1 (254, 0)</span>
  1949. # mkfs.ext3 /dev/mapper/sdc1 <span class="cmt"># This is done only the first time!</span>
  1950. # mount -t ext3 /dev/mapper/sdc1 /mnt
  1951. # umount /mnt/
  1952. # cryptsetup remove sdc1 <span class="cmt"># Detach the encrypted partition</span>
  1953. </pre>
  1954. Do exactly the same (without the mkfs part!) to re-attach the partition. If the password is not correct, the mount command will fail. In this case simply remove the map sdc1 (<code>cryptsetup remove sdc1</code>) and create it again.
  1955. <h2 id="bsdgeli">FreeBSD</h2>
  1956. The two popular FreeBSD disk encryption modules are <code>gbde</code> and <code>geli</code>. I now use geli because it is faster and also uses the crypto device for hardware acceleration. See The <a href="http://www.freebsd.org/handbook/disks-encrypting.html">FreeBSD handbook Chapter 18.6</a><span class="fn">http://www.freebsd.org/handbook/disks-encrypting.html</span> for all the details. The geli module must be loaded or compiled into the kernel:
  1957. <pre>options GEOM_ELI
  1958. device crypto <span class="cmt"># or as module:</span>
  1959. # echo 'geom_eli_load="YES"' >> /boot/loader.conf <span class="cmt"># or do: kldload geom_eli</span>
  1960. </pre>
  1961. <h3>Use password and key</h3>
  1962. I use those settings for a typical disk encryption, it uses a passphrase AND a key to encrypt the master key. That is you need both the password and the generated key <code>/root/ad1.key</code> to attach the partition. The master key is stored inside the partition and is not visible. See below for typical USB or file based image.
  1963. <h4>Create encrypted partition</h4>
  1964. <pre>
  1965. # dd if=/dev/random of=/root/ad1.key bs=64 count=1 <span class="cmt"># this key encrypts the mater key</span>
  1966. # geli init -s 4096 -K /root/ad1.key /dev/ad1 <span class="cmt"># -s 8192 is also OK for disks</span>
  1967. # geli attach -k /root/ad1.key /dev/ad1 <span class="cmt"># DO make a backup of /root/ad1.key</span>
  1968. # dd if=/dev/random of=/dev/ad1.eli bs=1m <span class="cmt"># Optional and takes a long time</span>
  1969. # newfs /dev/ad1.eli <span class="cmt"># Create file system</span>
  1970. # mount /dev/ad1.eli /mnt
  1971. </pre>
  1972. <h4>Attach</h4>
  1973. <pre># geli attach -k /root/ad1.key /dev/ad1
  1974. # fsck -ny -t ffs /dev/ad1.eli <span class="cmt"># In doubt check the file system</span>
  1975. # mount /dev/ad1.eli /mnt
  1976. </pre>
  1977. <h4>Detach</h4>
  1978. The detach procedure is done automatically on shutdown.
  1979. <pre># umount /mnt
  1980. # geli detach /dev/ad1.eli
  1981. </pre>
  1982. <h4>/etc/fstab</h4>
  1983. The encrypted partition can be configured to be mounted with /etc/fstab. The password will be prompted when booting. The following settings are required for this example:
  1984. <pre># grep geli /etc/rc.conf
  1985. geli_devices="ad1"
  1986. geli_ad1_flags="-k /root/ad1.key"
  1987. # grep geli /etc/fstab
  1988. /dev/ad1.eli /home/private ufs rw 0 0
  1989. </pre>
  1990. <h3 id="bsdpwd">Use password only</h3>
  1991. 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, simply without the key file. Let's encrypt a file based image <code>/cryptedfile</code> of 1 GB.
  1992. <pre># dd if=/dev/zero of=/cryptedfile bs=1M count=1000 <span class="cmt"># 1 GB file</span>
  1993. # mdconfig -at vnode -f /cryptedfile
  1994. # geli init /dev/md0 <span class="cmt"># encrypts with password only</span>
  1995. # geli attach /dev/md0
  1996. # newfs -U -m 0 /dev/md0.eli
  1997. # mount /dev/md0.eli /mnt
  1998. # umount /dev/md0.eli
  1999. # geli detach md0.eli
  2000. </pre>
  2001. It is now possible to mount this image on an other system with the password only.
  2002. <pre># mdconfig -at vnode -f /cryptedfile
  2003. # geli attach /dev/md0
  2004. # mount /dev/md0.eli /mnt
  2005. </pre>
  2006. </div>
  2007. <h2 id="osxcrypt">OS X Encrypted Disk Image</h2>
  2008. Don't know by command line only. See <a href="https://wiki.thayer.dartmouth.edu/display/computing/Creating+a+Mac+OS+X+Encrypted+Disk+Image">OS X Encrypted Disk Image</a><span class="fn">https://wiki.thayer.dartmouth.edu/display/computing/Creating+a+Mac+OS+X+Encrypted+Disk+Image</span> and <a href="http://support.apple.com/kb/ht1578">Apple support</a><span class="fn">http://support.apple.com/kb/ht1578</span>
  2009. <div id="certs"><h1><a>SSL Certificates</a></h1>
  2010. So called SSL/TLS certificates are cryptographic public key certificates and are composed of a public and a private key. The certificates are used to authenticate the endpoints and encrypt the data. They are used for example on a web server (https) or mail server (imaps).
  2011. <h2>Procedure</h2>
  2012. <ul>
  2013. <li>We need a certificate authority to sign our certificate. This step is
  2014. usually provided by a vendor like Thawte, Verisign, etc., however we can also create our own.</li>
  2015. <li>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 vendor for signing. This step also creates the private key on the local machine.</li>
  2016. <li>Sign the certificate with the certificate authority.</li>
  2017. <li>If necessary join the certificate and the key in a single file to be used by the application (web server, mail server etc.).</li>
  2018. </ul>
  2019. <h2>Configure OpenSSL</h2>
  2020. We use /usr/local/certs as directory for this example check or edit /etc/ssl/openssl.cnf accordingly to your settings so you know where the files will be created. Here are the relevant part of openssl.cnf:
  2021. <pre>[ CA_default ]
  2022. dir = /usr/local/certs/CA <span class="cmt"># Where everything is kept</span>
  2023. certs = $dir/certs <span class="cmt"># Where the issued certs are kept</span>
  2024. crl_dir = $dir/crl <span class="cmt"># Where the issued crl are kept</span>
  2025. database = $dir/index.txt <span class="cmt"># database index file.</span>
  2026. </pre>
  2027. Make sure the directories exist or create them
  2028. <pre># mkdir -p /usr/local/certs/CA
  2029. # cd /usr/local/certs/CA
  2030. # mkdir certs crl newcerts private
  2031. # echo "01" > serial <span class="cmt"># Only if serial does not exist</span>
  2032. # touch index.txt
  2033. </pre>
  2034. If you intend to get a signed certificate from a vendor, you only need a certificate signing request (CSR). This CSR will then be signed by the vendor for a limited time (e.g. 1 year).
  2035. <h2 id="createca">Create a certificate authority</h2>
  2036. If you do not have a certificate authority from a vendor, you'll have to create your own. This step is not necessary if one intend to use a vendor to sign the request. To make a certificate authority (CA):
  2037. <pre># openssl req -new -x509 -days 730 -config /etc/ssl/openssl.cnf \
  2038. -keyout CA/private/cakey.pem -out CA/cacert.pem
  2039. </pre>
  2040. <h2 id="createreq">Create a certificate signing request</h2>
  2041. To make a new certificate (for mail server or web server for example), first create a request certificate with its private key. If your application do not support encrypted private key (for example UW-IMAP does not), then disable encryption with <code>-nodes</code>.
  2042. <pre># openssl req -new -keyout newkey.pem -out newreq.pem \
  2043. -config /etc/ssl/openssl.cnf
  2044. # openssl req -nodes -new -keyout newkey.pem -out newreq.pem \
  2045. -config /etc/ssl/openssl.cnf <span class="cmt"># No encryption for the key</span>
  2046. </pre>
  2047. Keep this created CSR (<code>newreq.pem</code>) as it can be signed again at the next renewal, the signature onlt will limit the validity of the certificate. This process also created the private key <code>newkey.pem</code>.
  2048. <h2 id="signcert">Sign the certificate</h2>
  2049. The certificate request has to be signed by the CA to be valid, this step is usually done by the vendor. <i>Note: replace "servername" with the name of your server in the next commands</i>.
  2050. <pre># cat newreq.pem newkey.pem > new.pem
  2051. # openssl ca -policy policy_anything -out servernamecert.pem \
  2052. -config /etc/ssl/openssl.cnf -infiles new.pem
  2053. # mv newkey.pem servernamekey.pem
  2054. </pre>
  2055. Now servernamekey.pem is the private key and servernamecert.pem is the server certificate.
  2056. <h2>Create united certificate</h2>
  2057. The IMAP server wants to have both private key and server certificate in the same file. And in general, this is also easier to handle, but the file has to be kept securely!. Apache also can deal with it well. Create a file servername.pem containing both the certificate and key.
  2058. <ul>
  2059. <li>Open the private key (servernamekey.pem) with a text editor and copy the private key into the "servername.pem" file.</li>
  2060. <li>Do the same with the server certificate (servernamecert.pem).</li>
  2061. </ul>
  2062. The final servername.pem file should look like this:<br/><br/>
  2063. <pre>-----BEGIN RSA PRIVATE KEY-----
  2064. MIICXQIBAAKBgQDutWy+o/XZ/[...]qK5LqQgT3c9dU6fcR+WuSs6aejdEDDqBRQ
  2065. -----END RSA PRIVATE KEY-----
  2066. -----BEGIN CERTIFICATE-----
  2067. MIIERzCCA7CgAwIBAgIBBDANB[...]iG9w0BAQQFADCBxTELMAkGA1UEBhMCREUx
  2068. -----END CERTIFICATE-----
  2069. </pre>
  2070. What we have now in the directory /usr/local/certs/:
  2071. <ul style="list-style-type: none;">
  2072. <li>CA/private/cakey.pem <i>(CA server private key)</i></li>
  2073. <li>CA/cacert.pem <i>(CA server public key)</i></li>
  2074. <li>certs/servernamekey.pem <i>(server private key)</i></li>
  2075. <li>certs/servernamecert.pem <i>(server signed certificate)</i></li>
  2076. <li>certs/servername.pem <i>(server certificate with private key)</i></li>
  2077. </ul>
  2078. Keep the private key secure!
  2079. <h2 id="viewcert">View certificate information</h2>
  2080. To view the certificate information simply do:
  2081. <pre># openssl x509 -text -in servernamecert.pem <span class="cmt"># View the certificate info</span>
  2082. # openssl req -noout -text -in server.csr <span class="cmt"># View the request info</span>
  2083. # openssl s_client -connect cb.vu:443 <span class="cmt"># Check a web server certificate</span>
  2084. </pre>
  2085. </div>
  2086. <div id="cvs"><h1><a>CVS</a></h1>
  2087. <p class="xrefp"><a class="xrefp" href="#cvssetup">Server setup</a> | <a class="xrefp" href="#cvstest">CVS test</a> | <a class="xrefp" href="#cvsssh">SSH tunneling</a> | <a class="xrefp" href="#cvsusage">CVS usage</a></p>
  2088. <h2 id="cvssetup">Server setup</h2>
  2089. <h3>Initiate the CVS</h3>
  2090. Decide where the main repository will rest and create a root cvs. For example /usr/local/cvs (as root):
  2091. <pre># mkdir -p /usr/local/cvs
  2092. # setenv CVSROOT /usr/local/cvs <span class="cmt"># Set CVSROOT to the new location (local)</span>
  2093. # cvs init <span class="cmt"># Creates all internal CVS config files</span>
  2094. # cd /root
  2095. # cvs checkout CVSROOT <span class="cmt"># Checkout the config files to modify them</span>
  2096. # cd CVSROOT
  2097. edit config ( fine as it is)
  2098. # cvs commit config
  2099. cat >> writers <span class="cmt"># Create a writers file (optionally also readers)</span>
  2100. colin
  2101. ^D <span class="cmt"># Use [Control][D] to quit the edit</span>
  2102. # cvs add writers <span class="cmt"># Add the file writers into the repository</span>
  2103. # cvs edit checkoutlist
  2104. # cat >> checkoutlist
  2105. writers
  2106. ^D <span class="cmt"># Use [Control][D] to quit the edit</span>
  2107. # cvs commit <span class="cmt"># Commit all the configuration changes</span>
  2108. </pre>
  2109. Add a <strong>readers</strong> file if you want to differentiate read and write permissions <i>Note:</i> 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 <strong>writers</strong> to define the write access.<br />
  2110. There are three popular ways to access the CVS at this point. The first two don't need any further configuration. See the examples on <a href="#cvsroot">CVSROOT</a> below for how to use them:
  2111. <ul>
  2112. <li>Direct local access to the file system. The user(s) need sufficient file permission to access the CS directly and there is no further authentication in addition to the OS login. However this is only useful if the repository is local.</li>
  2113. <li>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.</li>
  2114. <li>Remote access with pserver (default port: 2401/tcp). This is the preferred use for larger user base as the users are authenticated by the CVS pserver with a dedicated password database, there is therefore no need for local users accounts. This setup is explained below.</li>
  2115. </ul>
  2116. <h3>Network setup with inetd</h3>
  2117. The CVS can be run locally only if a network access is not needed. For a remote access, the daemon inetd can start the pserver with the following line in /etc/inetd.conf (/etc/xinetd.d/cvs on SuSE):
  2118. <pre>cvspserver stream tcp nowait cvs /usr/bin/cvs cvs \
  2119. --allow-root=/usr/local/cvs pserver
  2120. </pre>
  2121. It is a good idea to block the cvs port from the Internet with the firewall and use an ssh tunnel to access the repository remotely.
  2122. <h3>Separate authentication</h3>
  2123. It is possible to have cvs users which are not part of the OS (no local users). This is actually probably wanted too from the security point of view. Simply add a file named <strong>passwd</strong> (in the CVSROOT directory) containing the users login and password in the crypt format. This is can be done with the apache htpasswd tool.<br/>
  2124. <i>Note:</i> This passwd file is the only file which has to be edited directly in the CVSROOT directory. Also it won't be checked out. More info with htpasswd --help
  2125. <pre># htpasswd -cb passwd user1 password1 <span class="cmt"># -c creates the file</span>
  2126. # htpasswd -b passwd user2 password2
  2127. </pre>
  2128. Now add <code>:cvs</code> at the end of each line to tell the cvs server to change the user to cvs (or whatever your cvs server is running under). It looks like this:
  2129. <pre># cat passwd
  2130. user1:xsFjhU22u8Fuo:cvs
  2131. user2:vnefJOsnnvToM:cvs
  2132. </pre>
  2133. <h2 id="cvstest">Test it</h2>
  2134. Test the login as normal user (for example here me)
  2135. <pre># cvs -d :pserver:colin@192.168.50.254:/usr/local/cvs login
  2136. Logging in to :pserver:colin@192.168.50.254:2401/usr/local/cvs
  2137. CVS password:
  2138. </pre>
  2139. <h3 id="cvsroot">CVSROOT variable</h3>
  2140. This is an environment variable used to specify the location of the repository we're doing operations on. For local use, it can be just set to the directory of the repository. For use over the network, the transport protocol must be specified. Set the CVSROOT variable with <code>setenv CVSROOT string</code> on a csh, tcsh shell, or with <code>export CVSROOT=string</code> on a sh, bash shell.
  2141. <pre># setenv CVSROOT :pserver:&lt;username&gt;@&lt;host&gt;:/cvsdirectory
  2142. <i><span class="cmt">For example:</span></i>
  2143. # setenv CVSROOT /usr/local/cvs <span class="cmt"># Used locally only</span>
  2144. # setenv CVSROOT :local:/usr/local/cvs <span class="cmt"># Same as above</span>
  2145. # setenv CVSROOT :ext:user@cvsserver:/usr/local/cvs <span class="cmt"># Direct access with SSH</span>
  2146. # setenv CVS_RSH ssh <span class="cmt"># for the ext access</span>
  2147. # setenv CVSROOT :pserver:user@cvsserver.254:/usr/local/cvs <span class="cmt"># network with pserver</span>
  2148. </pre>
  2149. When the login succeeded one can import a new project into the repository:
  2150. <strong>cd into</strong> your project root directory
  2151. <pre>cvs import &lt;module name&gt; &lt;vendor tag&gt; &lt;initial tag&gt;
  2152. cvs -d :pserver:colin@192.168.50.254:/usr/local/cvs import MyProject MyCompany START
  2153. </pre>
  2154. Where MyProject is the name of the new project in the repository (used later to checkout). Cvs will import the current directory content into the new project.<br/><br/>
  2155. To checkout:
  2156. <pre># cvs -d :pserver:colin@192.168.50.254:/usr/local/cvs checkout MyProject
  2157. <i><span class="cmt">or</span></i>
  2158. # setenv CVSROOT :pserver:colin@192.168.50.254:/usr/local/cvs
  2159. # cvs checkout MyProject
  2160. </pre>
  2161. <h2 id="cvsssh">SSH tunneling for CVS</h2>
  2162. We need 2 shells for this. On the first shell we connect to the cvs server with ssh and port-forward the cvs connection. On the second shell we use the cvs normally as if it where running locally.
  2163. <br/>
  2164. on shell 1:
  2165. <pre># ssh -L2401:localhost:2401 colin@cvs_server <span class="cmt"># Connect directly to the CVS server. Or:</span>
  2166. # ssh -L2401:cvs_server:2401 colin@gateway <span class="cmt"># Use a gateway to reach the CVS</span></pre>
  2167. on shell 2:
  2168. <pre># setenv CVSROOT :pserver:colin@localhost:/usr/local/cvs
  2169. # cvs login
  2170. Logging in to :pserver:colin@localhost:2401/usr/local/cvs
  2171. CVS password:
  2172. # cvs checkout MyProject/src
  2173. </pre>
  2174. <h2 id="cvsusage">CVS commands and usage</h2>
  2175. <h3>Import</h3>
  2176. The import command is used to add a whole directory, it must be run from within the directory to be imported. Say the directory /devel/ contains all files and subdirectories to be imported. The directory name on the CVS (the module) will be called "myapp".
  2177. <pre># cvs import [options] directory-name vendor-tag release-tag
  2178. # cd /devel <span class="cmt"># Must be inside the project to import it</span>
  2179. # cvs import myapp Company R1_0 <span class="cmt"># Release tag can be anything in one word</span>
  2180. </pre>
  2181. After a while a new directory "/devel/tools/" was added and it has to be imported too.
  2182. <pre># cd /devel/tools
  2183. # cvs import myapp/tools Company R1_0
  2184. </pre>
  2185. <h3>Checkout update add commit</h3>
  2186. <pre># cvs co myapp/tools <span class="cmt"># Will only checkout the directory tools</span>
  2187. # cvs co -r R1_1 myapp <span class="cmt"># Checkout myapp at release R1_1 (is sticky)</span>
  2188. # cvs -q -d update -P <span class="cmt"># A typical CVS update</span>
  2189. # cvs update -A <span class="cmt"># Reset any sticky tag (or date, option)</span>
  2190. # cvs add newfile <span class="cmt"># Add a new file</span>
  2191. # cvs add -kb newfile <span class="cmt"># Add a new binary file</span>
  2192. # cvs commit file1 file2 <span class="cmt"># Commit the two files only</span>
  2193. # cvs commit -m "message" <span class="cmt"># Commit all changes done with a message</span>
  2194. </pre>
  2195. <h3>Create a patch</h3>
  2196. It is best to create and apply a patch from the working development directory related to the project, or from within the source directory.
  2197. <pre># cd /devel/project
  2198. # diff -Naur olddir newdir &gt; patchfile <span class="cmt"># Create a patch from a directory or a file</span>
  2199. # diff -Naur oldfile newfile &gt; patchfile
  2200. </pre>
  2201. <h3>Apply a patch</h3>
  2202. Sometimes it is necessary to strip a directory level from the patch, depending how it was created. In case of difficulties, simply look at the first lines of the patch and try -p0, -p1 or -p2.
  2203. <pre># cd /devel/project
  2204. # patch --dry-run -p0 &lt; patchfile <span class="cmt"># Test the path without applying it</span>
  2205. # patch -p0 &lt; patchfile
  2206. # patch -p1 &lt; patchfile <span class="cmt"># strip off the 1st level from the path</span>
  2207. </pre>
  2208. </div>
  2209. <div id="svn"><h1><a>SVN</a></h1>
  2210. <p class="xrefp"><a class="xrefp" href="#svnsetup">Server setup</a> | <a class="xrefp" href="#svnssh">SVN+SSH</a> | <a class="xrefp" href="#svnhttp">SVN over http</a> | <a class="xrefp" href="#svnusage">SVN usage</a></p>
  2211. <a href="http://subversion.tigris.org/">Subversion (SVN)</a><span class="fn">http://subversion.tigris.org/</span> is a version control system designed to be the successor of CVS (Concurrent Versions System). The concept is similar to CVS, but many shortcomings where improved. See also the <a href="http://svnbook.red-bean.com/en/1.4/">SVN book</a><span class="fn">http://svnbook.red-bean.com/en/1.4/</span>.
  2212. <h2 id="svnsetup">Server setup</h2>
  2213. The initiation of the repository is fairly simple (here for example <code>/home/svn/</code> must exist):
  2214. <pre># svnadmin create --fs-type fsfs /home/svn/project1</pre>
  2215. Now the access to the repository is made possible with:
  2216. <ul>
  2217. <li><code>file://</code> Direct file system access with the svn client with. This requires local permissions on the file system.</li>
  2218. <li><code>svn://</code> or <code>svn+ssh://</code> Remote access with the svnserve server (also over SSH). This requires local permissions on the file system (default port: 2690/tcp).</li>
  2219. <li><code>http://</code> Remote access with webdav using apache. No local users are necessary for this method.</li>
  2220. </ul>
  2221. Using the local file system, it is now possible to import and then check out an existing project. Unlike with CVS it is not necessary to cd into the project directory, simply give the full path:
  2222. <pre># svn import /project1/ file:///home/svn/project1/trunk -m 'Initial import'
  2223. # svn checkout file:///home/svn/project1
  2224. </pre>
  2225. The new directory "trunk" is only a convention, this is not required.
  2226. <h3 id="svnssh">Remote access with ssh</h3>
  2227. No special setup is required to access the repository via ssh, simply replace <code>file://</code> with <code>svn+ssh/hostname</code>. For example:
  2228. <pre># svn checkout svn+ssh://hostname/home/svn/project1</pre>
  2229. 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 group which owns the repository, for example:
  2230. <pre># groupadd subversion
  2231. # groupmod -A user1 subversion
  2232. # chown -R root:subversion /home/svn
  2233. # chmod -R 770 /home/svn
  2234. </pre>
  2235. <h3 id="svnhttp">Remote access with http (apache)</h3>
  2236. Remote access over http (https) is the only good solution for a larger user group. This method uses the apache authentication, not the local accounts. This is a typical but small apache configuration:
  2237. <pre>LoadModule dav_module modules/mod_dav.so
  2238. LoadModule dav_svn_module modules/mod_dav_svn.so
  2239. LoadModule authz_svn_module modules/mod_authz_svn.so <span class="cmt"> # Only for access control</span>
  2240. </pre><pre style="page-break-inside:avoid;">&lt;Location /svn&gt;
  2241. DAV svn
  2242. <span class="cmt"># any "/svn/foo" URL will map to a repository /home/svn/foo</span>
  2243. SVNParentPath /home/svn
  2244. AuthType Basic
  2245. AuthName "Subversion repository"
  2246. AuthzSVNAccessFile /etc/apache2/svn.acl
  2247. AuthUserFile /etc/apache2/svn-passwd
  2248. Require valid-user
  2249. &lt;/Location&gt;
  2250. </pre>
  2251. The apache server needs full access to the repository:
  2252. <pre># chown -R www:www /home/svn</pre>
  2253. Create a user with htpasswd2:
  2254. <pre># htpasswd -c /etc/svn-passwd user1 <span class="cmt"> # -c creates the file</span></pre>
  2255. <h4>Access control svn.acl example</h4>
  2256. <pre><span class="cmt"># Default it read access. "* =" would be default no access</span>
  2257. [/]
  2258. * = r
  2259. [groups]
  2260. project1-developers = joe, jack, jane
  2261. <span class="cmt"># Give write access to the developers</span>
  2262. [project1:]
  2263. @project1-developers = rw
  2264. </pre>
  2265. <h2 id="svnusage">SVN commands and usage</h2>
  2266. See also the <a rel="nofollow" href="http://www.cs.put.poznan.pl/csobaniec/Papers/svn-refcard.pdf">Subversion Quick Reference Card</a><span class="fn">http://www.cs.put.poznan.pl/csobaniec/Papers/svn-refcard.pdf</span>. <a href="http://tortoisesvn.tigris.org">Tortoise SVN</a><span class="fn">http://tortoisesvn.tigris.org</span> is a nice Windows interface.
  2267. <h3 id="svnimport">Import</h3>
  2268. A new project, that is a directory with some files, is imported into the repository with the <code>import</code> command. Import is also used to add a directory with its content to an existing project.
  2269. <pre># svn help import <span class="cmt"> # Get help for any command</span>
  2270. <span class="cmt"> # Add a new directory (with content) into the src dir on project1</span>
  2271. # svn import /project1/newdir http://host.url/svn/project1/trunk/src -m 'add newdir'
  2272. </pre>
  2273. <h3 id="svntypical">Typical SVN commands</h3>
  2274. <pre># svn co http://host.url/svn/project1/trunk <span class="cmt"> # Checkout the most recent version</span>
  2275. <span class="cmt"> # Tags and branches are created by copying</span>
  2276. # svn mkdir http://host.url/svn/project1/tags/ <span class="cmt"> # Create the tags directory</span>
  2277. # svn copy -m "Tag rc1 rel." http://host.url/svn/project1/trunk \
  2278. http://host.url/svn/project1/tags/1.0rc1
  2279. # svn status [--verbose] <span class="cmt"> # Check files status into working dir</span>
  2280. # svn add src/file.h src/file.cpp <span class="cmt"> # Add two files</span>
  2281. # svn commit -m 'Added new class file' <span class="cmt"> # Commit the changes with a message</span>
  2282. # svn ls http://host.url/svn/project1/tags/ <span class="cmt"> # List all tags</span>
  2283. # svn move foo.c bar.c <span class="cmt"> # Move (rename) files</span>
  2284. # svn delete some_old_file <span class="cmt"> # Delete files</span>
  2285. </pre>
  2286. </div>
  2287. <div id="other"><h1><a>Useful Commands</a></h1>
  2288. <p class="xrefp"><a class="xrefp" href="#less">less</a> | <a class="xrefp" href="#vi">vi</a> | <a class="xrefp" href="#mail">mail</a> | <a class="xrefp" href="#tar">tar</a> | <a class="xrefp" href="#zip">zip</a> | <a class="xrefp" href="#dd">dd</a> | <a class="xrefp" href="#screen">screen</a> | <a class="xrefp" href="#find">find</a> | <a class="xrefp" href="#misccmd">Miscellaneous</a></p>
  2289. <h2 id="less">less</h2>
  2290. The <code>less</code> command displays a text document on the console. It is present on most installation.
  2291. <pre># less unixtoolbox.xhtml</pre>
  2292. Some important commands are (^N stands for [control]-[N]):
  2293. <ul style="list-style-type: none;">
  2294. <li><strong>h H</strong> &#160; &#160; &#160; good help on display</li>
  2295. <li><strong>f ^F ^V SPACE</strong> &#160; &#160; &#160; Forward one window (or N lines).</li>
  2296. <li><strong>b ^B ESC-v</strong> &#160; &#160; &#160; Backward one window (or N lines).</li>
  2297. <li><strong>F</strong> &#160; &#160; &#160; Forward forever; like "tail -f".</li>
  2298. <li><strong>/pattern</strong> &#160; &#160; &#160; Search forward for (N-th) matching line.</li>
  2299. <li><strong>?pattern</strong> &#160; &#160; &#160; Search backward for (N-th) matching line.</li>
  2300. <li><strong>n</strong> &#160; &#160; &#160; Repeat previous search (for N-th occurrence).</li>
  2301. <li><strong>N</strong> &#160; &#160; &#160; Repeat previous search in reverse direction.</li>
  2302. <li><strong>q</strong> &#160; &#160; &#160; quit</li>
  2303. </ul>
  2304. <h2 id="vi">vi</h2>
  2305. 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 <strong>[ESC]</strong>, the insertion mode with <strong>i</strong>. Use <code>: help</code> if you are lost.<br />
  2306. The editors <code>nano</code> and <code>pico</code> are usually available too and are easier (IMHO) to use.
  2307. <h3>Quit</h3>
  2308. <ul style="list-style-type: none;">
  2309. <li><strong>:w</strong> newfilename &#160; &#160; &#160; save the file to newfilename</li>
  2310. <li><strong>:wq or :x</strong> &#160; &#160; &#160; save and quit</li>
  2311. <li><strong>:q!</strong> &#160; &#160; &#160; quit without saving</li>
  2312. </ul>
  2313. <h3>Search and move</h3>
  2314. <ul style="list-style-type: none;">
  2315. <li><strong>/string</strong> &#160; &#160; &#160; Search forward for string</li>
  2316. <li><strong>?string</strong> &#160; &#160; &#160; Search back for string</li>
  2317. <li><strong>n</strong> &#160; &#160; &#160; Search for next instance of string</li>
  2318. <li><strong>N</strong> &#160; &#160; &#160; Search for previous instance of string</li>
  2319. <li><strong>{</strong> &#160; &#160; &#160; Move a paragraph back</li>
  2320. <li><strong>}</strong> &#160; &#160; &#160; Move a paragraph forward</li>
  2321. <li><strong>1G</strong> &#160; &#160; &#160; Move to the first line of the file</li>
  2322. <li><strong>nG</strong> &#160; &#160; &#160; Move to the n th line of the file</li>
  2323. <li><strong>G</strong> &#160; &#160; &#160; Move to the last line of the file</li>
  2324. <li><strong>:%s/OLD/NEW/g</strong> &#160; &#160; &#160; Search and replace every occurrence</li>
  2325. </ul>
  2326. <h3>Delete copy paste text</h3>
  2327. <ul style="list-style-type: none;">
  2328. <li><strong>dd (dw)</strong> &#160; &#160; &#160; Cut current line (word)</li>
  2329. <li><strong>D</strong> &#160; &#160; &#160; Cut to the end of the line</li>
  2330. <li><strong>x</strong> &#160; &#160; &#160; Delete (cut) character</li>
  2331. <li><strong>yy (yw)</strong> &#160; &#160; &#160; Copy line (word) after cursor</li>
  2332. <li><strong>P</strong> &#160; &#160; &#160; Paste after cursor</li>
  2333. <li><strong>u</strong> &#160; &#160; &#160; Undo last modification</li>
  2334. <li><strong>U</strong> &#160; &#160; &#160; Undo all changes to current line</li>
  2335. </ul>
  2336. <h2 id="mail">mail</h2>
  2337. The <code>mail</code> command is a basic application to read and send email, it is usually installed. To send an email simply type "mail user@domain". The first line is the subject, then the mail content. Terminate and send the email with a single dot (.) in a new line. Example:
  2338. <pre># mail c@cb.vu
  2339. Subject: Your text is full of typos
  2340. "For a moment, nothing happened. Then, after a second or so,
  2341. nothing continued to happen."
  2342. .
  2343. EOT
  2344. #
  2345. </pre>
  2346. This is also working with a pipe:
  2347. <pre># echo "This is the mail body" | mail c@cb.vu</pre>
  2348. This is also a simple way to test the mail server.
  2349. <h2 id="tar">tar</h2>
  2350. The command <code>tar</code> (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 commands are:
  2351. <h3>Create</h3>
  2352. <pre># cd /
  2353. # tar -cf home.tar home/ <span class="cmt"># archive the whole /home directory (c for create)</span>
  2354. # tar -czf home.tgz home/ <span class="cmt"># same with zip compression</span>
  2355. # tar -cjf home.tbz home/ <span class="cmt"># same with bzip2 compression</span>
  2356. </pre>
  2357. Only include one (or two) directories from a tree, but keep the relative structure. For example archive /usr/local/etc and /usr/local/www and the first directory in the archive should be local/.
  2358. <pre># tar -C /usr -czf local.tgz local/etc local/www
  2359. # tar -C /usr -xzf local.tgz <span class="cmt"># To untar the local dir into /usr</span>
  2360. # cd /usr; tar -xzf local.tgz <span class="cmt"># Is the same as above</span>
  2361. </pre>
  2362. <h3>Extract</h3>
  2363. <pre># tar -tzf home.tgz <span class="cmt"># look inside the archive without extracting (list)</span>
  2364. # tar -xf home.tar <span class="cmt"># extract the archive here (x for extract)</span>
  2365. # tar -xzf home.tgz <span class="cmt"># same with zip compression (-xjf for bzip2 compression)</span>
  2366. <span class="cmt"># remove leading path gallery2 and extract into gallery</span>
  2367. # tar --strip-components 1 -zxvf gallery2.tgz -C gallery/
  2368. # tar -xjf home.tbz home/colin/file.txt <span class="cmt"># Restore a single file</span>
  2369. # tar -xOf home.tbz home/colin/file.txt <span class="cmt"># Print file to stdout (no extraction)</span>
  2370. </pre>
  2371. <h3>More advanced</h3>
  2372. <pre># tar c dir/ | gzip | ssh user@remote 'dd of=dir.tgz' <span class="cmt"># arch dir/ and store remotely.</span>
  2373. # tar cvf - `find . -print` > backup.tar <span class="cmt"># arch the current directory.</span>
  2374. # tar -cf - -C /etc . | tar xpf - -C /backup/etc <span class="cmt"># Copy directories</span>
  2375. # tar -cf - -C /etc . | ssh user@remote tar xpf - -C /backup/etc <span class="cmt"># Remote copy.</span>
  2376. # tar -czf home.tgz --exclude '*.o' --exclude 'tmp/' home/
  2377. </pre>
  2378. <h2 id="zip">zip/unzip</h2>
  2379. Zip files can be easier to share with Windows.
  2380. <pre># zip -r fileName.zip /path/to/dir <span class="cmt"># zip dir into file fileName.zip</span>
  2381. # unzip fileName.zip <span class="cmt"># uncompress zip file</span>
  2382. # unzip -l fileName.zip <span class="cmt"># list files inside archive</span>
  2383. # unzip -c fileName.zip fileinside.txt <span class="cmt"># print one file to stdout (no extraction)</span>
  2384. # unzip fileName.zip fileinside.txt <span class="cmt"># extract one file only</span>
  2385. </pre>
  2386. <h2 id="dd">dd</h2>
  2387. The program <code>dd</code> (disk dump or destroy disk or see <a href="http://roesler-ac.de/wolfram/acro/credits.htm">the meaning of dd</a>) is used to copy partitions and disks and for other copy tricks. Typical usage:
  2388. <pre># dd if=&lt;source&gt; of=&lt;target&gt; bs=&lt;byte size&gt; conv=&lt;conversion&gt;
  2389. # kill -INFO PID <span class="cmt"># View dd progress (FreeBSD, OSX)</span>
  2390. </pre>
  2391. Important conv options:
  2392. <ul style="list-style-type: none;">
  2393. <li><code>notrunc</code> &#160; &#160; &#160; do not truncate the output file, all zeros will be written as zeros.</li>
  2394. <li><code>noerror</code> &#160; &#160; &#160; continue after read errors (e.g. bad blocks)</li>
  2395. <li><code>sync</code> &#160; &#160; &#160; pad every input block with Nulls to ibs-size</li>
  2396. </ul>
  2397. The default byte size is 512 (one block). The MBR, where the partition table is located, is on the first block, the first 63 blocks of a disk are empty. Larger byte sizes are faster to copy but require also more memory.
  2398. <h3>Backup and restore</h3>
  2399. <pre># dd if=/dev/hda of=/dev/hdc bs=16065b <span class="cmt"># Copy disk to disk (same size)</span>
  2400. # dd if=/dev/sda7 of=/home/root.img bs=4096 conv=notrunc,noerror <span class="cmt"># Backup /</span>
  2401. # dd if=/home/root.img of=/dev/sda7 bs=4096 conv=notrunc,noerror <span class="cmt"># Restore /</span>
  2402. # dd bs=1M if=/dev/ad4s3e | gzip -c &gt; ad4s3e.gz <span class="cmt"># Zip the backup</span>
  2403. # gunzip -dc ad4s3e.gz | dd of=/dev/ad0s3e bs=1M <span class="cmt"># Restore the zip</span>
  2404. # dd bs=1M if=/dev/ad4s3e | gzip | ssh eedcoba@fry 'dd of=ad4s3e.gz' <span class="cmt"># also remote</span>
  2405. # gunzip -dc ad4s3e.gz | ssh eedcoba@host 'dd of=/dev/ad0s3e bs=1M'
  2406. # dd if=/dev/ad0 of=/dev/ad2 skip=1 seek=1 bs=4k conv=noerror <span class="cmt"># Skip MBR</span>
  2407. <span class="cmt"># This is necessary if the destination (ad2) is smaller.</span>
  2408. # dd if=/vm/FreeBSD-8.2-RELEASE-amd64-memstick.img of=/dev/disk1 bs=10240 conv=sync
  2409. <span class="cmt"># Copy FreeBSD image to USB memory stick</span>
  2410. </pre>
  2411. <h3>Recover</h3>
  2412. The command <code>dd</code> will read <i>every single block</i> of the partition. In case of problems it is better to use the option <code>conv=sync,noerror</code> so dd will skip the bad block and write zeros at the destination. Accordingly it is important to set the block size equal or smaller than the disk block size. A 1k size seems safe, set it with <code>bs=1k</code>. If a disk has bad sectors and the data should be recovered from a partition, create an image file with dd, mount the image and copy the content to a new disk. With the option <code>noerror</code>, dd will skip the bad sectors and write zeros instead, thus only the data contained in the bad sectors will be lost.
  2413. <pre># dd if=/dev/hda of=/dev/null bs=1m <span class="cmt"># Check for bad blocks</span>
  2414. # dd bs=1k if=/dev/hda1 conv=sync,noerror,notrunc | gzip | ssh \ <span class="cmt"># Send to remote</span>
  2415. root@fry 'dd of=hda1.gz bs=1k'
  2416. # dd bs=1k if=/dev/hda1 conv=sync,noerror,notrunc of=hda1.img <span class="cmt"># Store into an image</span>
  2417. # mount -o loop /hda1.img /mnt <span class="cmt"># <a class="xref" href="#createimg">Mount the image</a></span>
  2418. # rsync -ax /mnt/ /newdisk/ <span class="cmt"># Copy on a new disk</span>
  2419. # dd if=/dev/hda of=/dev/hda <span class="cmt"># Refresh the magnetic state</span>
  2420. <span class="cmt"># The above is useful to refresh a disk. It is perfectly safe, but must be unmounted.</span>
  2421. </pre>
  2422. <h3>Delete</h3>
  2423. <pre># dd if=/dev/zero of=/dev/hdc <span class="cmt"># Delete full disk</span>
  2424. # dd if=/dev/urandom of=/dev/hdc <span class="cmt"># Delete full disk better</span>
  2425. # kill -USR1 PID <span class="cmt"># View dd progress (Linux)</span>
  2426. # kill -INFO PID <span class="cmt"># View dd progress (FreeBSD)</span>
  2427. </pre>
  2428. <h3>MBR tricks</h3>
  2429. The MBR contains the boot loader and the partition table and is 512 bytes small. The first 446 are for the boot loader, the bytes 446 to 512 are for the partition table.
  2430. <pre># dd if=/dev/sda of=/mbr_sda.bak bs=512 count=1 <span class="cmt"># Backup the full MBR</span>
  2431. # dd if=/dev/zero of=/dev/sda bs=512 count=1 <span class="cmt"># Delete MBR and partition table</span>
  2432. # dd if=/mbr_sda.bak of=/dev/sda bs=512 count=1 <span class="cmt"># Restore the full MBR</span>
  2433. # dd if=/mbr_sda.bak of=/dev/sda bs=446 count=1 <span class="cmt"># Restore only the boot loader</span>
  2434. # dd if=/mbr_sda.bak of=/dev/sda bs=1 count=64 skip=446 seek=446 <span class="cmt"># Restore partition table</span>
  2435. </pre>
  2436. <h2 id="screen">screen</h2>
  2437. Screen (a must have) has two main functionalities:
  2438. <ul>
  2439. <li>Run multiple terminal session within a single terminal.</li>
  2440. <li>A started program is decoupled from the real terminal and can thus run in the background. The real terminal can be closed and reattached later.</li>
  2441. </ul>
  2442. <h3>Short start example</h3>
  2443. start screen with:
  2444. <pre># screen</pre>
  2445. Within the screen session we can start a long lasting program (like top).
  2446. <pre># top</pre>
  2447. Now detach with <strong>Ctrl-a Ctrl-d</strong>. Reattach the terminal with:
  2448. <pre># screen -R -D</pre>
  2449. In detail this means: If a session is running, then reattach. If necessary detach and logout remotely first. If it was not running create it and notify the user. Or:
  2450. <pre># screen -x</pre>
  2451. Attach to a running screen in a multi display mode. The console is thus shared among multiple users. Very useful for team work/debug!
  2452. <h3>Screen commands (within screen)</h3>
  2453. All screen commands start with <strong>Ctrl-a</strong>.
  2454. <ul>
  2455. <li><strong>Ctrl-a ?</strong> help and summary of functions</li>
  2456. <li><strong>Ctrl-a c</strong> create an new window (terminal)</li>
  2457. <li><strong>Ctrl-a Ctrl-n and Ctrl-a Ctrl-p</strong> to switch to the next or previous
  2458. window in the list, by number.</li>
  2459. <li><strong>Ctrl-a Ctrl-N</strong> where N is a number from 0 to 9, to switch to the corresponding window.</li>
  2460. <li><strong>Ctrl-a &quot;</strong> to get a navigable list of running windows</li>
  2461. <li><strong>Ctrl-a a</strong> to clear a missed Ctrl-a</li>
  2462. <li><strong>Ctrl-a Ctrl-d</strong> to disconnect and leave the session running in the background</li>
  2463. <li><strong>Ctrl-a x</strong> lock the screen terminal with a password</li>
  2464. <li><strong>Ctrl-a [</strong> enter into <strong>scrollback</strong> mode, exit with <strong>esc</strong>.<br />
  2465. Use <code>echo "defscrollback 5000" > ~/.screenrc</code> to increase buffer (default is 100)</li>
  2466. <ul>
  2467. <li><strong>C-u</strong> Scrolls a half page up</li>
  2468. <li><strong>C-b</strong> Scroll a full page up</li>
  2469. <li><strong>C-d</strong> Scroll a half page down</li>
  2470. <li><strong>C-f</strong> Scroll a full page down</li>
  2471. <li><strong>/</strong> Search forward</li>
  2472. <li><strong>?</strong> Search backward</li>
  2473. </ul>
  2474. </ul>
  2475. Configuration in ~/.screenrc:
  2476. <pre>defscrollback 100000 <span class="cmt"># increase scrollback buffer (default is 100)</span>
  2477. termcapinfo xterm* ti@:te@ <span class="cmt"># avoid alternate text buffer to allow scrolling</span>
  2478. </pre>
  2479. The screen session is terminated when the program within the running terminal is closed and you logout from the terminal.
  2480. <h2 id="find">Find</h2>
  2481. Some important options:
  2482. <ul style="list-style-type: none;">
  2483. <li><code>-x</code> (on BSD) <code>-xdev</code> (on Linux) &#160; &#160; &#160; Stay on the same file system (dev in fstab).</li>
  2484. <li><code>-exec cmd {} \;</code> &#160; &#160; &#160; Execute the command and replace {} with the full path</li>
  2485. <li><code>-iname</code> &#160; &#160; &#160; Like -name but is case insensitive</li>
  2486. <li><code>-ls</code> &#160; &#160; &#160; Display information about the file (like ls -la)</li>
  2487. <li><code>-size n</code> &#160; &#160; &#160; n is +-n (k M G T P)</li>
  2488. <li><code>-cmin n</code> &#160; &#160; &#160; File's status was last changed n minutes ago.</li>
  2489. </ul>
  2490. <pre># find . -type f ! -perm -444 <span class="cmt"># Find files not readable by all</span>
  2491. # find . -type d ! -perm -111 <span class="cmt"># Find dirs not accessible by all</span>
  2492. # find /home/user/ -cmin 10 -print <span class="cmt"># Files created or modified in the last 10 min.</span>
  2493. # find . -name '*.[ch]' | xargs grep -E 'expr' <span class="cmt"># Search 'expr' in this dir and below.</span>
  2494. # find / -name "*.core" | xargs rm <span class="cmt"># Find core dumps and delete them (also try core.*)</span>
  2495. # find / -name "*.core" -print -exec rm {} \; <span class="cmt"># Other syntax</span>
  2496. <span class="cmt"># Find images and create an archive, iname is not case sensitive. -r for append</span>
  2497. # find . \( -iname "*.png" -o -iname "*.jpg" \) -print -exec tar -rf images.tar {} \;
  2498. # find . -type f -name "*.txt" ! -name README.txt -print <span class="cmt"># Exclude README.txt files</span>
  2499. # find /var/ -size +10M -exec ls -lh {} \; <span class="cmt"># Find large files &gt; 10 MB</span>
  2500. # find /var/ -size +10M -ls <span class="cmt"># This is simpler</span>
  2501. # find . -size +10M -size -50M -print
  2502. # find /usr/ports/ -name work -type d -print -exec rm -rf {} \; <span class="cmt"># Clean the ports</span>
  2503. <span class="cmt"># Find files with SUID; those file are vulnerable and must be kept secure</span>
  2504. # find / -type f -user root -perm -4000 -exec ls -l {} \;
  2505. # find flac/ -iname *.flac -print -size +500k -exec /Applications/Fluke.app/Contents/MacOS/Fluke {} \;
  2506. <span class="cmt"># I use above to add flac files to iTunes on OSX</span>
  2507. </pre>
  2508. Be careful with xarg or exec as it might or might not honor quotings and can return wrong results when files or directories contain spaces. In doubt use "-print0 | xargs -0" instead of "| xargs". The option -print0 must be the last in the find command. See this nice <a href="http://www.hccfl.edu/pollock/Unix/FindCmd.htm">mini tutorial for find</a><span class="fn">http://www.hccfl.edu/pollock/Unix/FindCmd.htm</span>.
  2509. <pre># find . -type f | xargs ls -l <span class="cmt"># Will not work with spaces in names</span>
  2510. # find . -type f -print0 | xargs -0 ls -l <span class="cmt"># Will work with spaces in names</span>
  2511. # find . -type f -exec ls -l '{}' \; <span class="cmt"># Or use quotes '{}' with -exec</span>
  2512. </pre>
  2513. Duplicate directory tree:
  2514. <pre># find . -type d -exec mkdir -p /tmp/new_dest/{} \;</pre>
  2515. <h2 id="misccmd">Miscellaneous</h2>
  2516. <pre># which command <span class="cmt"># Show full path name of command</span>
  2517. # time command <span class="cmt"># See how long a command takes to execute</span>
  2518. # time cat <span class="cmt"># Use time as stopwatch. Ctrl-c to stop</span>
  2519. # set | grep $USER <span class="cmt"># List the current environment</span>
  2520. # cal -3 <span class="cmt"># Display a three month calendar</span>
  2521. # date [-u|--utc|--universal] [MMDDhhmm[[CC]YY][.ss]]
  2522. # date 10022155 <span class="cmt"># Set date and time</span>
  2523. # whatis grep <span class="cmt"># Display a short info on the command or word</span>
  2524. # whereis java <span class="cmt"># Search path and standard directories for word</span>
  2525. # setenv varname value <span class="cmt"># Set env. variable varname to value (csh/tcsh)</span>
  2526. # export varname="value" <span class="cmt"># set env. variable varname to value (sh/ksh/bash)</span>
  2527. # pwd <span class="cmt"># Print working directory</span>
  2528. # mkdir -p /path/to/dir <span class="cmt"># no error if existing, make parent dirs as needed</span>
  2529. # mkdir -p project/{bin,src,obj,doc/{html,man,pdf},debug/some/more/dirs}
  2530. # rmdir /path/to/dir <span class="cmt"># Remove directory</span>
  2531. # rm -rf /path/to/dir <span class="cmt"># Remove directory and its content (force)</span>
  2532. # rm -- -badchar.txt <span class="cmt"># Remove file whitch starts with a dash (-)</span>
  2533. # cp -la /dir1 /dir2 <span class="cmt"># Archive and hard link files instead of copy</span>
  2534. # cp -lpR /dir1 /dir2 <span class="cmt"># Same for FreeBSD</span>
  2535. # cp unixtoolbox.xhtml{,.bak} <span class="cmt"># Short way to copy the file with a new extension</span>
  2536. # mv /dir1 /dir2 <span class="cmt"># Rename a directory</span>
  2537. # ls -1 <span class="cmt"># list one file per line</span>
  2538. # history | tail -50 <span class="cmt"># Display the last 50 used commands</span>
  2539. # cd - <span class="cmt"># cd to previous ($OLDPWD) directory</span>
  2540. # /bin/ls| grep -v .py | xargs rm -r <span class="cmt"># pipe file names to rm with xargs</span>
  2541. </pre>
  2542. Check file hashes with openssl. This is a nice alternative to the commands <code>md5sum</code> or <code>sha1sum</code> (FreeBSD uses <code>md5</code> and <code>sha1</code>) which are not always installed.
  2543. <pre># openssl md5 file.tar.gz <span class="cmt"># Generate an md5 checksum from file</span>
  2544. # openssl sha1 file.tar.gz <span class="cmt"># Generate an sha1 checksum from file</span>
  2545. # openssl rmd160 file.tar.gz <span class="cmt"># Generate a RIPEMD-160 checksum from file</span>
  2546. </pre>
  2547. </div>
  2548. <div id="software"><h1><a>Install Software</a></h1>
  2549. Usually the package manager uses the proxy variable for http/ftp requests. In .bashrc:
  2550. <pre>export http_proxy=http://proxy_server:3128
  2551. export ftp_proxy=http://proxy_server:3128
  2552. </pre>
  2553. <h2 id="softwarelist">List installed packages</h2>
  2554. <pre># rpm -qa <span class="cmt"># List installed packages (RH, SuSE, RPM based)</span>
  2555. # dpkg -l <span class="cmt"># Debian, Ubuntu</span>
  2556. # pkg_info <span class="cmt"># FreeBSD list all installed packages</span>
  2557. # pkg_info -W smbd <span class="cmt"># FreeBSD show which package smbd belongs to</span>
  2558. # pkginfo <span class="cmt"># Solaris</span>
  2559. </pre>
  2560. More on RPM:
  2561. <pre># rpm -ql package-name <span class="cmt"># list the files for INSTALLED package</span>
  2562. # rpm -qlp package.rpm <span class="cmt"># list the files inside package</span>
  2563. </pre>
  2564. <h2 id="softwareadd">Add/remove software</h2>
  2565. Front ends: yast2/yast for SuSE, redhat-config-packages for Red Hat.
  2566. <pre># rpm -i pkgname.rpm <span class="cmt"># install the package (RH, SuSE, RPM based)</span>
  2567. # rpm -e pkgname <span class="cmt"># Remove package</span>
  2568. </pre>
  2569. <h3>SuSE zypper <a href="http://en.opensuse.org/SDB:Zypper_usage">(see doc and cheet sheet)</a><span class="fn">http://en.opensuse.org/SDB:Zypper_usage</span></h3>
  2570. <pre># zypper refresh <span class="cmt"># Refresh repositorie</span>
  2571. # zypper install vim <span class="cmt"># Install the package vim</span>
  2572. # zypper remove vim <span class="cmt"># Remove the package vim</span>
  2573. # zypper search vim <span class="cmt"># Search packages with vim</span>
  2574. # zypper update vim <span class="cmt"># Search packages with vim</span>
  2575. </pre>
  2576. <h3>Debian</h3>
  2577. <pre># apt-get update <span class="cmt"># First update the package lists</span>
  2578. # apt-get install emacs <span class="cmt"># Install the package emacs</span>
  2579. # dpkg --remove emacs <span class="cmt"># Remove the package emacs</span>
  2580. # dpkg -S file <span class="cmt"># find what package a file belongs to</span>
  2581. </pre>
  2582. <h3>Gentoo</h3>
  2583. Gentoo uses emerge as the heart of its "Portage" package management system.
  2584. <pre># emerge --sync <span class="cmt"># First sync the local portage tree</span>
  2585. # emerge -u packagename <span class="cmt"># Install or upgrade a package</span>
  2586. # emerge -C packagename <span class="cmt"># Remove the package</span>
  2587. # revdep-rebuild <span class="cmt"># Repair dependencies</span>
  2588. </pre>
  2589. <h3>Solaris</h3>
  2590. The &lt;cdrom&gt; path is usually <code>/cdrom/cdrom0</code>.
  2591. <pre># pkgadd -d &lt;cdrom&gt;/Solaris_9/Product SUNWgtar
  2592. # pkgadd -d SUNWgtar <span class="cmt"># Add downloaded package (bunzip2 first)</span>
  2593. # pkgrm SUNWgtar <span class="cmt"># Remove the package</span>
  2594. </pre>
  2595. <h3>FreeBSD</h3>
  2596. <pre># pkg_add -r rsync <span class="cmt"># Fetch and install rsync.</span>
  2597. # pkg_delete /var/db/pkg/rsync-xx <span class="cmt"># Delete the rsync package</span>
  2598. </pre>
  2599. Set where the packages are fetched from with the <code>PACKAGESITE</code> variable. For example:
  2600. <pre># export PACKAGESITE=ftp://ftp.freebsd.org/pub/FreeBSD/ports/i386/packages/Latest/
  2601. # or ftp://ftp.freebsd.org/pub/FreeBSD/ports/i386/packages-6-stable/Latest/
  2602. </pre>
  2603. <h3>FreeBSD <a href="http://www.freebsd.org/handbook/ports.html">ports</a><span class="fn">http://www.freebsd.org/handbook/ports.html</span></h3>
  2604. The port tree <code>/usr/ports/</code> is a collection of software ready to compile and install (see man ports). The ports are updated with the program <code>portsnap</code>.
  2605. <pre># portsnap fetch extract <span class="cmt"># Create the tree when running the first time</span>
  2606. # portsnap fetch update <span class="cmt"># Update the port tree</span>
  2607. # cd /usr/ports/net/rsync/ <span class="cmt"># Select the package to install</span>
  2608. # make install distclean <span class="cmt"># Install and cleanup (also see man ports)</span>
  2609. # make package <span class="cmt"># Make a binary package of this port</span>
  2610. # pkgdb -F <span class="cmt"># Fix the package registry database</span>
  2611. # portsclean -C -DD <span class="cmt"># Clean workdir and distdir (part of portupgrade)</span>
  2612. </pre>
  2613. <h3 id="macports">OS X <a href="http://guide.macports.org/">MacPorts</a><span class="fn">http://guide.macports.org/</span> (use sudo for all commands)</h3>
  2614. <pre># port selfupdate <span class="cmt"># Update the port tree (safe)</span>
  2615. # port installed <span class="cmt"># List installed ports</span>
  2616. # port deps apache2 <span class="cmt"># List dependencies for this port</span>
  2617. # port search pgrep <span class="cmt"># Search for string</span>
  2618. # port install proctools <span class="cmt"># Install this package</span>
  2619. # port variants ghostscript <span class="cmt"># List variants of this port</span>
  2620. # port -v install ghostscript +no_x11<span class="cmt"># -no_x11 for negative value</span>
  2621. # port clean --all ghostscript <span class="cmt"># Clean workdir of port</span>
  2622. # port upgrade ghostscript <span class="cmt"># Upgrade this port</span>
  2623. # port uninstall ghostscript <span class="cmt"># Uninstall this port</span>
  2624. # port -f uninstall installed <span class="cmt"># Uninstall everything</span>
  2625. </pre>
  2626. <h2 id="librarypath">Library path</h2>
  2627. Due to complex dependencies and runtime linking, programs are difficult to copy to an other system or distribution. However for small programs with little dependencies, the missing libraries can be copied over. The runtime libraries (and the missing one) are checked with <code>ldd</code> and managed with <code>ldconfig</code>.
  2628. <pre># ldd /usr/bin/rsync <span class="cmt"># List all needed runtime libraries</span>
  2629. # otool -L /usr/bin/rsync <span class="cmt"># OS X equivalent to ldd</span>
  2630. # ldconfig -n /path/to/libs/ <span class="cmt"># Add a path to the shared libraries directories</span>
  2631. # ldconfig -m /path/to/libs/ <span class="cmt"># FreeBSD</span>
  2632. # LD_LIBRARY_PATH <span class="cmt"># The variable set the link library path</span>
  2633. </pre>
  2634. </div>
  2635. <div id="convert"><h1><a>Convert Media</a></h1>
  2636. Sometimes one simply need to convert a video, audio file or document to another format.
  2637. <h2 id="encoding">Text encoding</h2>
  2638. Text encoding can get totally wrong, specially when the language requires
  2639. special characters like àäç. The command <code>iconv</code> can convert from
  2640. one encoding to an other.
  2641. <pre># iconv -f &lt;from_encoding&gt; -t &lt;to_encoding&gt; &lt;input_file&gt;
  2642. # iconv -f ISO8859-1 -t UTF-8 -o file.input > file_utf8
  2643. # iconv -l <span class="cmt"># List known coded character sets</span>
  2644. </pre>
  2645. Without the -f option, iconv will use the local char-set, which is usually fine
  2646. if the document displays well.<br />
  2647. Convert filenames from one encoding to another (not file content). Works also if only some files are already utf8
  2648. <pre># convmv -r -f utf8 --nfd -t utf8 --nfc /dir/* --notest</pre>
  2649. <h2 id="newlines">Unix - DOS newlines</h2>
  2650. Convert DOS (CR/LF) to Unix (LF) newlines and back <b>within a Unix shell</b>. See also <code>dos2unix</code> and <code>unix2dos</code> if you have them.
  2651. <pre># sed 's/.$//' dosfile.txt > unixfile.txt <span class="cmt"># DOS to UNIX</span>
  2652. # awk '{sub(/\r$/,"");print}' dosfile.txt > unixfile.txt <span class="cmt"># DOS to UNIX</span>
  2653. # awk '{sub(/$/,"\r");print}' unixfile.txt > dosfile.txt <span class="cmt"># UNIX to DOS</span>
  2654. </pre>
  2655. Convert Unix to DOS newlines <b>within a Windows environment</b>. Use sed or awk from mingw or cygwin.
  2656. <pre># sed -n p unixfile.txt > dosfile.txt
  2657. # awk 1 unixfile.txt > dosfile.txt <span class="cmt"># UNIX to DOS (with a cygwin shell)</span>
  2658. </pre>
  2659. Remove <code>^M</code> mac newline and replace with unix new line. To get a <code>^M</code> use CTL-V then CTL-M
  2660. <pre># tr '^M' '\n' &lt; macfile.txt
  2661. </pre>
  2662. <h2>PDF images and concatenate PDF files</h2>
  2663. Convert a PDF document with <code>gs</code> (GhostScript) to jpeg (or png) images for each page. Also much shorter with <code>convert</code> and <code>mogrify</code> (from ImageMagick or GraphicsMagick).
  2664. <pre># gs -dBATCH -dNOPAUSE -sDEVICE=jpeg -r150 -dTextAlphaBits=4 -dGraphicsAlphaBits=4 \
  2665. -dMaxStripSize=8192 -sOutputFile=unixtoolbox_%d.jpg unixtoolbox.pdf
  2666. # convert unixtoolbox.pdf unixtoolbox-%03d.png
  2667. # convert *.jpeg images.pdf <span class="cmt"># Create a simple PDF with all pictures</span>
  2668. # convert image000* -resample 120x120 -compress JPEG -quality 80 images.pdf
  2669. # mogrify -format png *.ppm <span class="cmt"># convert all ppm images to png format</span>
  2670. </pre>
  2671. Ghostscript can also concatenate multiple pdf files into a single one. This only works well if the PDF files are "well behaved".
  2672. <pre># gs -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=all.pdf \
  2673. file1.pdf file2.pdf ... <span class="cmt"># On Windows use '#' instead of '='</span>
  2674. </pre>
  2675. Create PDF file from images
  2676. <pre># convert 20140416-DSCF1915.jpg 20140416-DSCF1920.jpg all.pdf
  2677. convert 20140416-DSCF1915.jpg 20140416-DSCF1920.jpg -resize 1240x1753 -units PixelsPerInch \
  2678. -density 150x150 all.pdf <span class="cmt"># force A4</span>
  2679. </pre>
  2680. Extract images from pdf document using <code>pdfimages</code> from poppler or <a href="http://foolabs.com/xpdf/download.html"><code>xpdf</code></a><span class="fn">http://foolabs.com/xpdf/download.html</span>
  2681. <pre># pdfimages document.pdf dst/ <span class="cmt"># extract all images and put in dst</span>
  2682. # yum install poppler-utils <span class="cmt"># install poppler-utils if needed. or:</span>
  2683. # apt-get install poppler-utils
  2684. </pre>
  2685. <h2>Convert video</h2>
  2686. Compress the Canon digicam video with an mpeg4 codec and repair the crappy sound.
  2687. <pre># mencoder -o videoout.avi -oac mp3lame -ovc lavc -srate 11025 \
  2688. -channels 1 -af-adv force=1 -lameopts preset=medium -lavcopts \
  2689. vcodec=msmpeg4v2:vbitrate=600 -mc 0 vidoein.AVI
  2690. </pre>
  2691. See <a href="http://sox.sourceforge.net/">sox</a> for sound processing.
  2692. <h2>Copy an audio cd</h2>
  2693. The program <a rel="nofollow" href="http://xiph.org/paranoia/"><code>cdparanoia</code></a><span class="fn">http://xiph.org/paranoia/</span> can save the audio tracks (FreeBSD port in audio/cdparanoia/), <code>oggenc</code> can encode in Ogg Vorbis format, <code>lame</code> converts to mp3.
  2694. <pre># cdparanoia -B <span class="cmt"># Copy the tracks to wav files in current dir</span>
  2695. # lame -b 256 in.wav out.mp3 <span class="cmt"># Encode in mp3 256 kb/s</span>
  2696. # for i in *.wav; do lame -b 256 $i `basename $i .wav`.mp3; done
  2697. # oggenc in.wav -b 256 out.ogg <span class="cmt"># Encode in Ogg Vorbis 256 kb/s</span>
  2698. </pre>
  2699. </div>
  2700. <div id="printing"><h1><a>Printing</a></h1>
  2701. <h2>Print with lpr</h2>
  2702. <pre style="page-break-inside:avoid;"># lpr unixtoolbox.ps <span class="cmt"># Print on default printer</span>
  2703. # export PRINTER=hp4600 <span class="cmt"># Change the default printer</span>
  2704. # lpr -Php4500 #2 unixtoolbox.ps <span class="cmt"># Use printer hp4500 and print 2 copies</span>
  2705. # lpr -o Duplex=DuplexNoTumble ... <span class="cmt"># Print duplex along the long side</span>
  2706. # lpr -o PageSize=A4,Duplex=DuplexNoTumble ...
  2707. </pre>
  2708. <pre># lpq <span class="cmt"># Check the queue on default printer</span>
  2709. # lpq -l -Php4500 <span class="cmt"># Queue on printer hp4500 with verbose</span>
  2710. # lprm - <span class="cmt"># Remove all users jobs on default printer</span>
  2711. # lprm -Php4500 3186 <span class="cmt"># Remove job 3186. Find job nbr with lpq</span>
  2712. # lpc status <span class="cmt"># List all available printers</span>
  2713. # lpc status hp4500 <span class="cmt"># Check if printer is online and queue length</span>
  2714. </pre>
  2715. Some devices are not postscript and will print garbage when fed with a pdf file. This might be solved with:
  2716. <pre># gs -dSAFER -dNOPAUSE -sDEVICE=deskjet -sOutputFile=\|lpr file.pdf</pre>
  2717. Print to a PDF file even if the application does not support it. Use <code>gs</code> on the print command instead of <code>lpr</code>.
  2718. <pre># gs -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=/path/file.pdf</pre>
  2719. </div>
  2720. <div id="databases"><h1><a>Databases</a></h1>
  2721. <h2 id="pgsql">PostgreSQL</h2>
  2722. <h3>Change root or a username password</h3>
  2723. <pre># psql -d template1 -U pgsql
  2724. &gt; alter user pgsql with password 'pgsql_password'; <span class="cmt"># Use username instead of "pgsql"</span>
  2725. </pre>
  2726. <h3>Create user and database</h3>
  2727. The commands <code>createuser</code>, <code>dropuser</code>, <code>createdb</code> and <code>dropdb</code> are convenient shortcuts equivalent to the SQL commands. The new user is bob with database bobdb ; use as root with pgsql the database super user:
  2728. <pre># createuser -U pgsql -P bob <span class="cmt"># -P will ask for password</span>
  2729. # createdb -U pgsql -O bob bobdb <span class="cmt"># new bobdb is owned by bob</span>
  2730. # dropdb bobdb <span class="cmt"># Delete database bobdb</span>
  2731. # dropuser bob <span class="cmt"># Delete user bob</span>
  2732. </pre>
  2733. The general database authentication mechanism is configured in pg_hba.conf
  2734. <h3>Grant remote access</h3>
  2735. The file <code>$PGSQL_DATA_D/postgresql.conf</code> specifies the address to bind to. Typically <code>listen_addresses = '*'</code> for Postgres 8.x.<br />
  2736. The file <code>$PGSQL_DATA_D/pg_hba.conf</code> defines the access control. Examples:
  2737. <pre># TYPE DATABASE USER IP-ADDRESS IP-MASK METHOD
  2738. host bobdb bob 212.117.81.42 255.255.255.255 password
  2739. host all all 0.0.0.0/0 password
  2740. </pre>
  2741. <h3>Backup and restore</h3>
  2742. The backups and restore are done with the user pgsql or postgres. Backup and restore a single database:
  2743. <pre># pg_dump --clean dbname &gt; dbname_sql.dump
  2744. # psql dbname &lt; dbname_sql.dump
  2745. </pre>
  2746. Backup and restore all databases (including users):
  2747. <pre># pg_dumpall --clean &gt; full.dump
  2748. # psql -f full.dump postgres
  2749. </pre>
  2750. In this case the restore is started with the database postgres which is better when reloading an empty cluster.
  2751. <h2 id="mysql">MySQL</h2>
  2752. <h3>Change mysql root or username password</h3>
  2753. <h4>Method 1</h4>
  2754. <pre># /etc/init.d/mysql stop
  2755. <i><span class="cmt">or</span></i>
  2756. # killall mysqld
  2757. # mysqld --skip-grant-tables
  2758. # mysqladmin -u root password 'newpasswd'
  2759. # /etc/init.d/mysql start
  2760. </pre>
  2761. <h4>Method 2</h4>
  2762. <pre># mysql -u root mysql
  2763. <span class="cmt">mysql></span> UPDATE USER SET PASSWORD=PASSWORD("newpassword") where user='root';
  2764. <span class="cmt">mysql></span> FLUSH PRIVILEGES; <span class="cmt"># Use username instead of "root"</span>
  2765. <span class="cmt">mysql></span> quit
  2766. </pre>
  2767. <h3>Create user and database (see <a href="http://dev.mysql.com/doc/refman/5.1/en/adding-users.html">MySQL doc</a><span class="fn">http://dev.mysql.com/doc/refman/5.1/en/adding-users.html</span>)</h3>
  2768. <pre># mysql -u root mysql
  2769. <span class="cmt">mysql></span> CREATE USER 'bob'@'localhost' IDENTIFIED BY 'pwd'; <span class="cmt"># create only a user</span>
  2770. <span class="cmt">mysql></span> CREATE DATABASE bobdb;
  2771. <span class="cmt">mysql></span> GRANT ALL ON *.* TO 'bob'@'%' IDENTIFIED BY 'pwd'; <span class="cmt"># Use localhost instead of %</span>
  2772. <span class="cmt"># to restrict the network access</span>
  2773. <span class="cmt">mysql></span> DROP DATABASE bobdb; <span class="cmt"># Delete database</span>
  2774. <span class="cmt">mysql></span> DROP USER bob; <span class="cmt"># Delete user</span>
  2775. <span class="cmt">mysql></span> DELETE FROM mysql.user WHERE user='bob and host='hostname'; <span class="cmt"># Alt. command</span>
  2776. <span class="cmt">mysql></span> FLUSH PRIVILEGES;
  2777. </pre>
  2778. <h3>Grant remote access</h3>
  2779. Remote access is typically permitted for a database, and not all databases. The file <code>/etc/my.cnf</code> contains the IP address to bind to. (On FreeBSD <code>my.cnf</code> not created per fedault, copy one <code>.cnf</code> file from <code>/usr/local/share/mysql</code> to <code>/usr/local/etc/my.cnf</code>) Typically comment the line <code>bind-address =</code> out.
  2780. <pre># mysql -u root mysql
  2781. <span class="cmt">mysql></span> GRANT ALL ON bobdb.* TO bob@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'PASSWORD';
  2782. <span class="cmt">mysql></span> REVOKE GRANT OPTION ON foo.* FROM bar@'xxx.xxx.xxx.xxx';
  2783. <span class="cmt">mysql></span> FLUSH PRIVILEGES; <span class="cmt"># Use 'hostname' or also '%' for full access</span>
  2784. </pre>
  2785. <h3>Backup and restore</h3>
  2786. Backup and restore a single database:
  2787. <pre># mysqldump -u root -psecret --add-drop-database dbname &gt; dbname_sql.dump
  2788. # mysql -u root -psecret -D dbname &lt; dbname_sql.dump
  2789. </pre>
  2790. Backup and restore all databases:
  2791. <pre># mysqldump -u root -psecret --add-drop-database --all-databases &gt; full.dump
  2792. # mysql -u root -psecret &lt; full.dump
  2793. </pre>
  2794. Here is "secret" the mysql root password, there is no space after -p. When the -p option is used alone (w/o password), the password is asked at the command prompt.
  2795. <h2 id="sqlite">SQLite</h2>
  2796. <a href="http://www.sqlite.org">SQLite</a><span class="fn">http://www.sqlite.org</span> is a small powerful self-contained, serverless, zero-configuration SQL database.
  2797. <h3>Dump and restore</h3>
  2798. It can be useful to dump and restore an SQLite database. For example you can edit the dump file to change a column attribute or type and then restore the database. This is easier than messing with SQL commands. Use the command <code>sqlite3</code> for a 3.x database.
  2799. <pre># sqlite database.db .dump &gt; dump.sql <span class="cmt"># dump</span>
  2800. # sqlite database.db &lt; dump.sql <span class="cmt"># restore</span>
  2801. </pre>
  2802. <h3>Convert 2.x to 3.x database</h3>
  2803. <pre>sqlite database_v2.db .dump | sqlite3 database_v3.db</pre>
  2804. </div>
  2805. <div id="quota"><h1><a>Disk Quota</a></h1>
  2806. A disk quota allows to limit the amount of disk space and/or the number of files a user or (or member of group) can use. The quotas are allocated on a per-file system basis and are enforced by the kernel.
  2807. <h2>Linux setup</h2>
  2808. The quota tools package usually needs to be installed, it contains the command line tools.<br />
  2809. Activate the user quota in the fstab and remount the partition. If the partition is busy, either all locked files must be closed, or the system must be rebooted. Add <code>usrquota</code> to the fstab mount options, for example:
  2810. <pre>/dev/sda2 /home reiserfs rw,acl,user_xattr,usrquota 1 1
  2811. # mount -o remount /home
  2812. # mount <span class="cmt"># Check if usrquota is active, otherwise reboot</span>
  2813. </pre>
  2814. Initialize the quota.user file with <code>quotacheck</code>.
  2815. <pre># quotacheck -vum /home
  2816. # chmod 644 /home/aquota.user <span class="cmt"># To let the users check their own quota</span>
  2817. </pre>
  2818. Activate the quota either with the provided script (e.g. /etc/init.d/quotad on SuSE) or with <code>quotaon</code>:
  2819. <pre>quotaon -vu /home</pre>
  2820. Check that the quota is active with:
  2821. <pre>quota -v</pre>
  2822. <h2>FreeBSD setup</h2>
  2823. The quota tools are part of the base system, however the kernel needs the option quota. If it is not there, add it and <a href="#compilekernel">recompile</a> the kernel.
  2824. <pre>options QUOTA</pre>
  2825. As with Linux, add the quota to the fstab options (userquota, not usrquota):
  2826. <pre>/dev/ad0s1d /home ufs rw,noatime,userquota 2 2
  2827. # mount /home <span class="cmt"># To remount the partition</span>
  2828. </pre>
  2829. Enable disk quotas in /etc/rc.conf and start the quota.
  2830. <pre># grep quotas /etc/rc.conf
  2831. enable_quotas="YES" <span class="cmt"># turn on quotas on startup (or NO).</span>
  2832. check_quotas="YES" <span class="cmt"># Check quotas on startup (or NO).</span>
  2833. # /etc/rc.d/quota start
  2834. </pre>
  2835. <h2 id="assignquota">Assign quota limits</h2>
  2836. The quotas are not limited per default (set to 0). The limits are set with <code>edquota</code> for single users. A quota can be also duplicated to many users. The file structure is different between the quota implementations, but the principle is the same: the values of blocks and inodes can be limited. <i>Only change the values of soft and hard</i>. If not specified, the blocks are 1k. The grace period is set with <code>edquota -t</code>. For example:
  2837. <pre># edquota -u colin</pre>
  2838. <h3>Linux</h3>
  2839. <pre>Disk quotas for user colin (uid 1007):
  2840. Filesystem blocks soft hard inodes soft hard
  2841. /dev/sda8 108 1000 2000 1 0 0
  2842. </pre>
  2843. <h3>FreeBSD</h3>
  2844. <pre>Quotas for user colin:
  2845. /home: kbytes in use: 504184, limits (soft = 700000, hard = 800000)
  2846. inodes in use: 1792, limits (soft = 0, hard = 0)
  2847. </pre>
  2848. <h3>For many users</h3>
  2849. The command <code>edquota -p</code> is used to duplicate a quota to other users. For example to duplicate a reference quota to all users:
  2850. <pre># edquota -p refuser `awk -F: '$3 > 499 {print $1}' /etc/passwd`
  2851. # edquota -p refuser user1 user2 <span class="cmt"># Duplicate to 2 users</span>
  2852. </pre>
  2853. <h3>Checks</h3>
  2854. Users can check their quota by simply typing <code>quota</code> (the file quota.user must be readable). Root can check all quotas.
  2855. <pre># quota -u colin <span class="cmt"># Check quota for a user</span>
  2856. # repquota /home <span class="cmt"># Full report for the partition for all users</span>
  2857. </pre>
  2858. </div>
  2859. <div id="shells"><h1><a>Shells</a></h1>
  2860. Most Linux distributions use the bash shell while the BSDs use tcsh, the bourne shell is only used for scripts. Filters are very useful and can be piped:
  2861. <ul style="list-style-type:none;">
  2862. <li><code>grep</code> &#160; Pattern matching</li>
  2863. <li><code>sed</code> &#160; Search and Replace strings or characters</li>
  2864. <li><code>cut</code> &#160; Print specific columns from a marker</li>
  2865. <li><code>sort</code> &#160; Sort alphabetically or numerically</li>
  2866. <li><code>uniq</code> &#160; Remove duplicate lines from a file</li>
  2867. </ul>
  2868. For example used all at once:
  2869. <pre># ifconfig | sed 's/ / /g' | cut -d" " -f1 | uniq | grep -E "[a-z0-9]+" | sort -r
  2870. # ifconfig | sed '/.*inet addr:/!d;s///;s/ .*//'|sort -t. -k1,1n -k2,2n -k3,3n -k4,4n
  2871. </pre>
  2872. The first character in the sed pattern is a tab. To write a tab on the console, use ctrl-v ctrl-tab.
  2873. <h2 id="bash">bash</h2>
  2874. Redirects and pipes for bash and sh:
  2875. <pre># cmd 1&gt; file <span class="cmt"># Redirect stdout to file.</span>
  2876. # cmd 2&gt; file <span class="cmt"># Redirect stderr to file.</span>
  2877. # cmd 1&gt;&gt; file <span class="cmt"># Redirect and append stdout to file.</span>
  2878. # cmd &amp;&gt; file <span class="cmt"># Redirect both stdout and stderr to file.</span>
  2879. # cmd &gt;file 2&gt;&amp;1 <span class="cmt"># Redirects stderr to stdout and then to file.</span>
  2880. # cmd1 | cmd2 <span class="cmt"># pipe stdout to cmd2</span>
  2881. # cmd1 2&gt;&amp;1 | cmd2 <span class="cmt"># pipe stdout and stderr to cmd2</span>
  2882. </pre>
  2883. Modify your configuration in ~/.bashrc (it can also be ~/.bash_profile). The following entries are useful, reload with ". .bashrc". With cygwin use ~/.bash_profile; with rxvt past with shift + left-click.
  2884. <pre style="page-break-inside:avoid;"># in .bashrc
  2885. bind '"\e[A"':history-search-backward <span class="cmt"># Use up and down arrow to search</span>
  2886. bind '"\e[B"':history-search-forward <span class="cmt"># the history. Invaluable!</span>
  2887. set -o emacs <span class="cmt"># Set emacs mode in bash (see below)</span>
  2888. set bell-style visible <span class="cmt"># Do not beep, inverse colors</span>
  2889. <span class="cmt"># Set a nice prompt like [user@host]/path/todir&gt;</span>
  2890. PS1="\[\033[1;30m\][\[\033[1;34m\]\u\[\033[1;30m\]"
  2891. PS1="$PS1@\[\033[0;33m\]\h\[\033[1;30m\]]\[\033[0;37m\]"
  2892. PS1="$PS1\w\[\033[1;30m\]&gt;\[\033[0m\]"
  2893. </pre><pre><span class="cmt"># To check the currently active aliases, simply type alias</span>
  2894. alias ls='ls -aF' <span class="cmt"># Append indicator (one of */=&gt;@|)</span>
  2895. alias ll='ls -aFls' <span class="cmt"># Listing</span>
  2896. alias la='ls -all'
  2897. alias ..='cd ..'
  2898. alias ...='cd ../..'
  2899. export HISTFILESIZE=5000 <span class="cmt"># Larger history</span>
  2900. export CLICOLOR=1 <span class="cmt"># Use colors (if possible)</span>
  2901. export LSCOLORS=ExGxFxdxCxDxDxBxBxExEx
  2902. </pre>
  2903. <h2 id="tcsh">tcsh</h2>
  2904. Redirects and pipes for tcsh and csh (simple &gt; and &gt;&gt; are the same as sh):
  2905. <pre># cmd &gt;&amp; file <span class="cmt"># Redirect both stdout and stderr to file.</span>
  2906. # cmd &gt;&gt;&amp; file <span class="cmt"># Append both stdout and stderr to file.</span>
  2907. # cmd1 | cmd2 <span class="cmt"># pipe stdout to cmd2</span>
  2908. # cmd1 |&amp; cmd2 <span class="cmt"># pipe stdout and stderr to cmd2</span>
  2909. </pre>
  2910. The settings for csh/tcsh are set in <code>~/.cshrc</code>, reload with "source .cshrc". Examples:
  2911. <pre style="page-break-inside:avoid;"># in .cshrc
  2912. alias ls 'ls -aF'
  2913. alias ll 'ls -aFls'
  2914. alias la 'ls -all'
  2915. alias .. 'cd ..'
  2916. alias ... 'cd ../..'
  2917. set prompt = "%B%n%b@%B%m%b%/> " <span class="cmt"># like user@host/path/todir></span>
  2918. set history = 5000
  2919. set savehist = ( 6000 merge )
  2920. set autolist <span class="cmt"># Report possible completions with tab</span>
  2921. set visiblebell <span class="cmt"># Do not beep, inverse colors</span>
  2922. </pre><pre><span class="cmt"># Bindkey and colors</span>
  2923. bindkey -e Select Emacs bindings <span class="cmt"># Use emacs keys to edit the command prompt</span>
  2924. bindkey -k up history-search-backward <span class="cmt"># Use up and down arrow to search</span>
  2925. bindkey -k down history-search-forward
  2926. setenv CLICOLOR 1 <span class="cmt"># Use colors (if possible)</span>
  2927. setenv LSCOLORS ExGxFxdxCxDxDxBxBxExEx
  2928. </pre>
  2929. The emacs mode enables to use the emacs keys shortcuts to modify the command prompt line. This is extremely useful (not only for emacs users). The most used commands are:
  2930. <ul style="list-style-type:none;">
  2931. <li>C-a &#160; &#160; &#160; Move cursor to beginning of line</li>
  2932. <li>C-e &#160; &#160; &#160; Move cursor to end of line</li>
  2933. <li>M-b &#160; &#160; &#160; Move cursor back one word</li>
  2934. <li>M-f &#160; &#160; &#160; Move cursor forward one word</li>
  2935. <li>M-d &#160; &#160; &#160; Cut the next word</li>
  2936. <li>C-w &#160; &#160; &#160; Cut the last word</li>
  2937. <li>C-u &#160; &#160; &#160; Cut everything before the cursor</li>
  2938. <li>C-k &#160; &#160; &#160; Cut everything after the cursor (rest of the line)</li>
  2939. <li>C-y &#160; &#160; &#160; Paste the last thing to be cut (simply paste)</li>
  2940. <li>C-_ &#160; &#160; &#160; Undo</li>
  2941. </ul>
  2942. <i>Note:</i> C- = hold control, M- = hold meta (which is usually the alt or escape key).
  2943. </div>
  2944. <div id="scripting"><h1><a>Scripting</a></h1>
  2945. <p class="xrefp"><a class="xrefp" href="#bournebasics">Basics</a> | <a class="xrefp" href="#bourneexample">Script example</a> | <a class="xrefp" href="#awk">awk</a> | <a class="xrefp" href="#sed">sed</a> | <a class="xrefp" href="#regex">Regular Expressions</a> | <a class="xrefp" href="#shcmd">useful commands</a></p>
  2946. The Bourne shell (/bin/sh) is present on all Unix installations and scripts written in this language are (quite) portable; <code>man 1 sh</code> is a good reference.
  2947. <h2 id="bournebasics">Basics</h2>
  2948. <h3>Variables and arguments</h3>
  2949. Assign with variable=value and get content with $variable
  2950. <pre>MESSAGE="Hello World" <span class="cmt"># Assign a string</span>
  2951. PI=3.1415 <span class="cmt"># Assign a decimal number</span>
  2952. N=8
  2953. TWON=`expr $N * 2` <span class="cmt"># Arithmetic expression (only integers)</span>
  2954. TWON=$(($N * 2)) <span class="cmt"># Other syntax</span>
  2955. TWOPI=`echo "$PI * 2" | bc -l` <span class="cmt"># Use bc for floating point operations</span>
  2956. ZERO=`echo "c($PI/4)-sqrt(2)/2" | bc -l`
  2957. </pre>
  2958. The command line arguments are
  2959. <pre>$0, $1, $2, ... <span class="cmt"># $0 is the command itself</span>
  2960. $# <span class="cmt"># The number of arguments</span>
  2961. $* <span class="cmt"># All arguments (also $@)</span>
  2962. </pre>
  2963. <h3>Special Variables</h3>
  2964. <pre>$$ <span class="cmt"># The current process ID</span>
  2965. $? <span class="cmt"># exit status of last command</span>
  2966. command
  2967. <span class="keyword">if</span> [ $<span class="pp">?</span> != 0 ]; <span class="keyword">then</span>
  2968. echo "command failed"
  2969. <span class="keyword">fi</span>
  2970. <span class="pp">mypath</span>=`pwd`
  2971. <span class="pp">mypath</span>=${<span class="pp">mypath</span>}/file.txt
  2972. echo ${<span class="pp">mypath</span>##*/} <span class="cmt"># Display the filename only</span>
  2973. echo ${<span class="pp">mypath</span>%%.*} <span class="cmt"># Full path without extention</span>
  2974. foo=/tmp/my.dir/filename.tar.gz
  2975. path = ${foo%/*} <span class="cmt"># Full path without extention</span>
  2976. <span class="pp">var2</span>=${<span class="pp">var</span>:=string} <span class="cmt"># Use var if set, otherwise use string
  2977. # assign string to var and then to var2.</span>
  2978. size=$(stat -c%s "$file") <span class="cmt"># get file size in bourne script</span>
  2979. filesize=${size:=-1}
  2980. </pre>
  2981. <h3>Constructs</h3>
  2982. <pre><span class="keyword">for</span> <span class="pp">file</span> in `ls`
  2983. <span class="keyword">do</span>
  2984. echo $<span class="pp">file</span>
  2985. <span class="keyword">done</span>
  2986. <span class="pp">count</span>=0
  2987. <span class="keyword">while</span> [ $<span class="pp">count</span> -lt 5 ]; <span class="keyword">do</span>
  2988. echo $<span class="pp">count</span>
  2989. sleep 1
  2990. <span class="pp">count</span>=$(($<span class="pp">count</span> + 1))
  2991. <span class="keyword">done</span>
  2992. myfunction() {
  2993. find . -type f -name "*.$<span class="pp">1</span>" -print <span class="cmt"># $1 is first argument of the function</span>
  2994. }
  2995. myfunction "txt"
  2996. </pre>
  2997. <h4>Generate a file</h4>
  2998. <pre><span class="pp">MYHOME</span>=/home/colin
  2999. cat &gt; testhome.sh &lt;&lt; _EOF
  3000. <span class="cmt"># All of this goes into the file testhome.sh</span>
  3001. <span class="keyword">if</span> [ -d "$<span class="pp">MYHOME</span>" ] ; <span class="keyword">then</span>
  3002. echo $<span class="pp">MYHOME</span> exists
  3003. <span class="keyword">else</span>
  3004. echo $<span class="pp">MYHOME</span> does not exist
  3005. <span class="keyword">fi</span>
  3006. _EOF
  3007. sh testhome.sh
  3008. </pre>
  3009. <h2 id="bourneexample">Bourne script example</h2>
  3010. As a small example, the script used to create a PDF booklet from this xhtml document:
  3011. <pre style="page-break-inside:avoid;"><span class="pp">#!/bin/sh</span>
  3012. <span class="cmt"># This script creates a book in pdf format ready to print on a duplex printer</span>
  3013. <span class="keyword">if</span> [ $<span class="pp">#</span> <span class="keyword">-ne</span> 1 ]; <span class="keyword">then</span> <span class="cmt"># Check the argument</span>
  3014. echo 1&gt;&amp;2 "Usage: $0 HtmlFile"
  3015. <span class="keyword">exit</span> 1 <span class="cmt"># non zero exit if error</span>
  3016. <span class="keyword">fi</span>
  3017. <span class="pp">file</span>=$<span class="pp">1</span> <span class="cmt"># Assign the filename</span>
  3018. <span class="pp">fname</span>=${<span class="pp">file</span>%.*} <span class="cmt"># Get the name of the file only</span>
  3019. <span class="pp">fext</span>=${<span class="pp">file</span>#*.} <span class="cmt"># Get the extension of the file</span>
  3020. prince $<span class="pp">file</span> -o $<span class="pp">fname</span>.pdf <span class="cmt"># from www.princexml.com</span>
  3021. pdftops -paper A4 -noshrink $<span class="pp">fname</span>.pdf $<span class="pp">fname</span>.ps <span class="cmt"># create postscript booklet</span>
  3022. cat $<span class="pp">fname</span>.ps |psbook|psnup -Pa4 -2 |pstops -b "2:0,1U(21cm,29.7cm)" > $<span class="pp">fname</span>.book.ps
  3023. ps2pdf13 -sPAPERSIZE=a4 -sAutoRotatePages=None $<span class="pp">fname</span>.book.ps $<span class="pp">fname</span>.book.pdf
  3024. <span class="cmt"># use #a4 and #None on Windows!</span>
  3025. <span class="keyword">exit</span> 0 <span class="cmt"># exit 0 means successful</span>
  3026. </pre>
  3027. <h2 id="awk">Some awk commands</h2>
  3028. Awk is useful for field stripping, like cut in a more powerful way. Search this document for other examples. See for example <a href="http://www.gnulamp.com/awk.html">gnulamp.com</a> and <a href="http://student.northpark.edu/pemente/awk/awk1line.txt">one-liners for awk</a> for some nice examples.
  3029. <pre>awk '{ print $2, $1 }' file <span class="cmt"># Print and inverse first two columns</span>
  3030. awk '{printf("%5d : %s\n", NR,$0)}' file <span class="cmt"># Add line number left aligned</span>
  3031. awk '{print FNR "\t" $0}' files <span class="cmt"># Add line number right aligned</span>
  3032. awk NF test.txt <span class="cmt"># remove blank lines (same as grep '.')</span>
  3033. awk 'length > 80' <span class="cmt"># print line longer than 80 char)</span>
  3034. </pre>
  3035. <h2 id="sed">Some sed commands</h2>
  3036. Here is <a href="http://student.northpark.edu/pemente/sed/sed1line.txt">the one liner gold mine</a><span class="fn">http://student.northpark.edu/pemente/sed/sed1line.txt</span>. And a good <a href="http://www.grymoire.com/Unix/Sed.html">introduction and tutorial to sed</a><span class="fn">http://www.grymoire.com/Unix/Sed.html</span>.
  3037. <pre>sed 's/string1/string2/g' <span class="cmt"># Replace string1 with string2</span>
  3038. sed -i 's/wroong/wrong/g' *.txt <span class="cmt"># Replace a recurring word with g</span>
  3039. sed 's/\(.*\)1/\12/g' <span class="cmt"># Modify anystring1 to anystring2</span>
  3040. sed '/&lt;p&gt;/,/&lt;\/p&gt;/d' t.xhtml <span class="cmt"># Delete lines that start with &lt;p&gt;</span>
  3041. <span class="cmt"># and end with &lt;/p&gt;</span>
  3042. sed '/ *#/d; /^ *$/d' <span class="cmt"># Remove comments and blank lines</span>
  3043. sed 's/[ \t]*$//' <span class="cmt"># Remove trailing spaces (use tab as \t)</span>
  3044. sed 's/^[ \t]*//;s/[ \t]*$//' <span class="cmt"># Remove leading and trailing spaces</span>
  3045. sed 's/[^*]/[&amp;]/' <span class="cmt"># Enclose first char with [] top-&gt;[t]op</span>
  3046. sed = file | sed 'N;s/\n/\t/' > file.num <span class="cmt"># Number lines on a file</span>
  3047. </pre>
  3048. <h2 id="regex">Regular Expressions</h2>
  3049. Some basic regular expression useful for sed too. See <a href="http://www.regular-expressions.info/reference.html">Basic Regex Syntax</a><span class="fn">http://www.regular-expressions.info/reference.html</span> for a good primer.
  3050. <pre>[\^$.|?*+() <span class="cmt"># special characters any other will match themselves</span>
  3051. \ <span class="cmt"># escapes special characters and treat as literal</span>
  3052. * <span class="cmt"># repeat the previous item zero or more times</span>
  3053. . <span class="cmt"># single character except line break characters</span>
  3054. .* <span class="cmt"># match zero or more characters</span>
  3055. ^ <span class="cmt"># match at the start of a line/string</span>
  3056. $ <span class="cmt"># match at the end of a line/string</span>
  3057. .$ <span class="cmt"># match a single character at the end of line/string</span>
  3058. ^ $ <span class="cmt"># match line with a single space</span>
  3059. ^[A-Z] <span class="cmt"># match any line beginning with any char from A to Z</span>
  3060. </pre>
  3061. <h2 id="shcmd">Some useful commands</h2>
  3062. The following commands are useful to include in a script or as one liners.
  3063. <pre>sort -t. -k1,1n -k2,2n -k3,3n -k4,4n <span class="cmt"># Sort IPv4 ip addresses</span>
  3064. echo 'Test' | tr '[:lower:]' '[:upper:]' <span class="cmt"># Case conversion</span>
  3065. echo foo.bar | cut -d . -f 1 <span class="cmt"># Returns foo</span>
  3066. PID=$(ps | grep script.sh | grep bin | awk '{print $1}') <span class="cmt"># PID of a running script</span>
  3067. PID=$(ps axww | grep [p]ing | awk '{print $1}') <span class="cmt"># PID of ping (w/o grep pid)</span>
  3068. IP=$(ifconfig $INTERFACE | sed '/.*inet addr:/!d;s///;s/ .*//') <span class="cmt"># Linux</span>
  3069. IP=$(ifconfig $INTERFACE | sed '/.*inet /!d;s///;s/ .*//') <span class="cmt"># FreeBSD</span>
  3070. if [ `diff file1 file2 | wc -l` != 0 ]; then [...] fi <span class="cmt"># File changed?</span>
  3071. cat /etc/master.passwd | grep -v root | grep -v \*: | awk -F":" \ <span class="cmt"># Create http passwd</span>
  3072. '{ printf("%s:%s\n", $1, $2) }' > /usr/local/etc/apache2/passwd
  3073. testuser=$(cat /usr/local/etc/apache2/passwd | grep -v \ <span class="cmt"># Check user in passwd</span>
  3074. root | grep -v \*: | awk -F":" '{ printf("%s\n", $1) }' | grep ^user$)
  3075. :(){ :|:&amp; };: <span class="cmt"># bash fork bomb. Will kill your machine</span>
  3076. tail +2 file > file2 <span class="cmt"># remove the first line from file</span>
  3077. </pre>
  3078. I use this little trick to change the file extension for many files at once. For example from .cxx to .cpp. Test it first without the <code>| sh</code> at the end. You can also do this with the command <code>rename</code> if installed. Or with bash builtins.
  3079. <pre># ls *.cxx | awk -F. '{print "mv "$0" "$1".cpp"}' | sh
  3080. # ls *.c | sed "s/.*/cp &amp; &amp;.$(date "+%Y%m%d")/" | sh <span class="cmt"># e.g. copy *.c to *.c.20080401</span>
  3081. # rename .cxx .cpp *.cxx <span class="cmt"># Rename all .cxx to cpp</span>
  3082. # for i in *.cxx; do mv $i ${i%%.cxx}.cpp; done <span class="cmt"># with bash builtins</span>
  3083. </pre>
  3084. </div>
  3085. <div id="programming"><h1><a>Programming</a></h1>
  3086. <h2 id="cbasics">C basics</h2>
  3087. <pre>strcpy(newstr,str) <span class="cmt">/* copy str to newstr */</span>
  3088. expr1 ? expr2 : expr3 <span class="cmt">/* if (expr1) expr2 else expr3 */</span>
  3089. x = (y > z) ? y : z; <span class="cmt">/* if (y > z) x = y; else x = z; */</span>
  3090. int a[]={0,1,2}; <span class="cmt">/* Initialized array (or a[3]={0,1,2}; */</span>
  3091. int a[2][3]={{1,2,3},{4,5,6}}; <span class="cmt">/* Array of array of ints */</span>
  3092. int i = 12345; <span class="cmt">/* Convert in i to char str */</span>
  3093. char str[10];
  3094. sprintf(str, "%d", i);
  3095. </pre>
  3096. <h2>C example</h2>
  3097. A minimal c program simple.c:
  3098. <pre><span class="pp">#include</span> &lt;stdio.h&gt;
  3099. main() {
  3100. <span class="keyword">int</span> number=42;
  3101. printf(&quot;The answer is %i\n&quot;, number);
  3102. }
  3103. </pre>
  3104. Compile with:
  3105. <pre># gcc simple.c -o simple
  3106. # ./simple
  3107. The answer is 42
  3108. </pre>
  3109. <h2 id="cppbasics">C++ basics</h2>
  3110. <pre>*pointer <span class="cmt">// Object pointed to by pointer</span>
  3111. &amp;obj <span class="cmt">// Address of object obj</span>
  3112. obj.x <span class="cmt">// Member x of class obj (object obj)</span>
  3113. pobj-&gt;x <span class="cmt">// Member x of class pointed to by pobj</span>
  3114. <span class="cmt">// (*pobj).x and pobj->x are the same</span>
  3115. </pre>
  3116. <h2>C++ example</h2>
  3117. As a slightly more realistic program in C++: a class in its own header (IPv4.h) and implementation (IPv4.cpp) and a program which uses the class functionality. The class converts an IP address in integer format to the known quad format.
  3118. <h3>IPv4 class</h3>
  3119. <h4>IPv4.h:</h4>
  3120. <pre style="page-break-inside:avoid;"><span class="pp">#ifndef</span> IPV4_H
  3121. <span class="pp">#define</span> IPV4_H
  3122. <span class="pp">#include</span> &lt;string&gt;
  3123. <span class="keyword">namespace</span> GenericUtils { <span class="cmt">// create a namespace
  3124. </span><span class="keyword">class</span> IPv4 { <span class="cmt">// class definition
  3125. </span><span class="keyword">public</span>:
  3126. IPv4(); ~IPv4();
  3127. std::string IPint_to_IPquad(<span class="keyword">unsigned</span> <span class="keyword">long</span> ip);<span class="cmt">// member interface
  3128. </span>};
  3129. } <span class="cmt">//namespace GenericUtils</span>
  3130. <span class="pp">#endif</span> <span class="cmt">// IPV4_H
  3131. </span></pre>
  3132. <h4>IPv4.cpp:</h4>
  3133. <pre style="page-break-inside:avoid;"><span class="pp">#include</span> &quot;IPv4.h&quot;
  3134. <span class="pp">#include</span> &lt;string&gt;
  3135. <span class="pp">#include</span> &lt;sstream&gt;
  3136. <span class="keyword">using</span> <span class="keyword">namespace</span> std; <span class="cmt">// use the namespaces
  3137. </span><span class="keyword">using</span> <span class="keyword">namespace</span> GenericUtils;
  3138. IPv4::IPv4() {} <span class="cmt">// default constructor/destructor
  3139. </span>IPv4::~IPv4() {}
  3140. string IPv4::IPint_to_IPquad(<span class="keyword">unsigned</span> <span class="keyword">long</span> ip) { <span class="cmt">// member implementation
  3141. </span> ostringstream ipstr; <span class="cmt">// use a stringstream
  3142. </span> ipstr &lt;&lt; ((ip &amp;0xff000000) &gt;&gt; 24) <span class="cmt">// Bitwise right shift
  3143. </span> &lt;&lt; &quot;.&quot; &lt;&lt; ((ip &amp;0x00ff0000) &gt;&gt; 16)
  3144. &lt;&lt; &quot;.&quot; &lt;&lt; ((ip &amp;0x0000ff00) &gt;&gt; 8)
  3145. &lt;&lt; &quot;.&quot; &lt;&lt; ((ip &amp;0x000000ff));
  3146. <span class="keyword">return</span> ipstr.str();
  3147. }
  3148. </pre>
  3149. <h3>The program simplecpp.cpp</h3>
  3150. <pre style="page-break-inside:avoid;"><span class="pp">#include</span> &quot;IPv4.h&quot;
  3151. <span class="pp">#include</span> &lt;iostream&gt;
  3152. <span class="pp">#include</span> &lt;string&gt;
  3153. <span class="keyword">using</span> <span class="keyword">namespace</span> std;
  3154. <span class="keyword">int</span> main (<span class="keyword">int</span> argc, <span class="keyword">char</span>* argv[]) {
  3155. string ipstr; <span class="cmt">// define variables
  3156. </span> <span class="keyword">unsigned</span> <span class="keyword">long</span> ipint = 1347861486; <span class="cmt">// The IP in integer form</span>
  3157. GenericUtils::IPv4 iputils; <span class="cmt">// create an object of the class
  3158. </span> ipstr = iputils.IPint_to_IPquad(ipint); <span class="cmt">// call the class member
  3159. </span> cout &lt;&lt; ipint &lt;&lt; &quot; = &quot; &lt;&lt; ipstr &lt;&lt; endl; <span class="cmt">// print the result</span>
  3160. <span class="keyword">return</span> 0;
  3161. }
  3162. </pre>
  3163. Compile and execute with:
  3164. <pre style="page-break-before:avoid;"># g++ -c IPv4.cpp simplecpp.cpp <span class="cmt"># Compile in objects</span>
  3165. # g++ IPv4.o simplecpp.o -o simplecpp.exe <span class="cmt"># Link the objects to final executable</span>
  3166. # ./simplecpp.exe
  3167. 1347861486 = 80.86.187.238
  3168. </pre>
  3169. Use <code>ldd</code> to check which libraries are used by the executable and where they are located. Also used to check if a shared library is missing or if the executable is static.
  3170. <pre># ldd /sbin/ifconfig <span class="cmt"># list dynamic object dependencies</span>
  3171. # ar rcs staticlib.a *.o <span class="cmt"># create static archive</span>
  3172. # ar t staticlib.a <span class="cmt"># print the objects list from the archive</span>
  3173. # ar x /usr/lib/libc.a version.o <span class="cmt"># extract an object file from the archive</span>
  3174. # nm version.o <span class="cmt"># show function members provided by object</span>
  3175. </pre>
  3176. <h2 id="makefile">Simple Makefile</h2>
  3177. The minimal Makefile for the multi-source program is shown below. The lines with instructions <i>must begin with a tab</i>! The back slash "\" can be used to cut long lines.
  3178. <pre style="page-break-inside:avoid;"><span class="pp">CC</span> = g++
  3179. <span class="pp">CFLAGS</span> = -O
  3180. <span class="pp">OBJS</span> = IPv4.o simplecpp.o
  3181. <span class="keyword">simplecpp</span>: ${OBJS}
  3182. ${CC} -o simplecpp ${CFLAGS} ${OBJS}
  3183. <span class="keyword">clean</span>:
  3184. rm -f ${TARGET} ${OBJS}
  3185. </pre>
  3186. </div>
  3187. <div id="onlinehelp"><h1><a>Online Help</a></h1>
  3188. <h2 id="documentation">Documentation</h2>
  3189. <table>
  3190. <tr><td><a href="http://en.tldp.org/">Linux Documentation</a> </td><td>en.tldp.org</td></tr>
  3191. <tr><td><a href="http://www.linuxmanpages.com/">Linux Man Pages</a> </td><td>www.linuxmanpages.com</td></tr>
  3192. <tr><td><a href="http://www.oreillynet.com/linux/cmd/">Linux commands directory</a> </td><td>www.oreillynet.com/linux/cmd</td></tr>
  3193. <tr><td><a href="http://linux.die.net/">Linux doc man howtos</a> </td><td>linux.die.net</td></tr>
  3194. <tr><td><a href="http://www.freebsd.org/handbook/">FreeBSD Handbook</a> </td><td>www.freebsd.org/handbook</td></tr>
  3195. <tr><td><a href="http://www.freebsd.org/cgi/man.cgi">FreeBSD Man Pages</a> </td><td>www.freebsd.org/cgi/man.cgi</td></tr>
  3196. <tr><td><a href="http://www.freebsdwiki.net">FreeBSD user wiki</a> </td><td>www.freebsdwiki.net</td></tr>
  3197. <tr><td><a href="http://docs.sun.com/app/docs/coll/40.10">Solaris Man Pages</a> </td><td>docs.sun.com/app/docs/coll/40.10</td></tr>
  3198. </table>
  3199. <h2 id="crossref">Other Unix/Linux references</h2>
  3200. <table>
  3201. <tr><td><a href="http://bhami.com/rosetta.html">Rosetta Stone for Unix</a> </td><td>bhami.com/rosetta.html (a Unix command translator)</td></tr>
  3202. <tr><td><a href="http://unixguide.net/unixguide.shtml">Unix guide cross reference</a> </td><td>unixguide.net/unixguide.shtml</td></tr>
  3203. <tr><td><a rel="nofollow" href="http://www.linuxcmd.org">Linux commands line list</a> </td><td>www.linuxcmd.org</td></tr>
  3204. <tr><td><a rel="nofollow" href="http://www.pixelbeat.org/cmdline.html">Short Linux reference</a> </td><td>www.pixelbeat.org/cmdline.html</td></tr>
  3205. <tr><td><a href="http://www.shell-fu.org">Little command line goodies</a> </td><td>www.shell-fu.org</td></tr>
  3206. </table>
  3207. </div>
  3208. <p class="last">That's all folks!</p>
  3209. <!-- page break -->
  3210. <!-- <div class="pb" /> -->
  3211. <div class="footerlast">
  3212. This document: "Unix Toolbox revision 14.4" is licensed under a <a rel="nofollow" href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Licence [Attribution - Share Alike]</a>. &#169; <a href="mailto:c_at_cb.vu">Colin Barschel</a> 2007-2012. Some rights reserved.
  3213. </div>
  3214. </body>
  3215. </html>