Sie sind auf Seite 1von 14

shell scripting navigating shell mv [options] [source] [destination] -either renames source to destination if destination if a file -or moves

source to destination if destination is a folder cp [options] [source] [destination] -the same except it makes copies ls [options] [directory] -if no directory specified, used working directory - -l for long listing, -a for showing hidden files/folders, -t for sorting by time when a script is executed, a child shell is spawned for the process first line states which shell to use #! /bin/sh, or #! /bin/bash these can in fact point to any program all it does is invoke the program listed with any flags you pass to it, and then appends the script filepath to the argument list basics shell variables must start with ! or a-" or #-$, and can contain ! and alphanumeric -!myvar%%%&'value' -mynum&( dereference using ) *and curly braces optionally+ -)!myvar%%%, ),mynumcommand line arguments are dereferenced with )digit -echo the first arg is ). -echo the tenth arg is ),./-any double digit number must be enclosed in brackets comment with # globbing (don't confuse with regex) 0 & any amount of characters 1 & one of any characters [abc] & one of those characters abc [2abc] & not one of those characters abc 3 3 *backticks, expand as shell command, called command subtitution, same thing as )* ++ 4 4 *single 5uotes, do not expand at all+ ' ' *double 5uotes, only expand backticks, ), and 6+ 77 will run the second command if the first one succeeds *if first one returns /+ 88 will run the second command if the first one fails *if first one doesn4t return /+ special variables )# *num args given to current process+ )9 *command-line args to current process, in ' ', expands to individual arguments+ )0 *same as above, but in ' ', expands to single arguments+ )- *options given to shell on invocation+ )1 *exit status of previous command+ )) *:;< of shell process+ )/ *name of shell program, in other words the path invoked to reach the script+ )=>?@ );AB *defaults to tab, space, newline+ ):#C= ):D< *print working directory+ )E;F@F> *line number of script that Gust ran, as in the one that E;F@F> is on+ ):B. *primary command prompt string, default )+ ):B( *prompt string for line continuation, default H+ ):BI *prompt string for execution tracing with set Jx, default J+ arrays array[./]&/ # initiali"es first value, orK set array[./] # orK array&*one two three+ # orK declare -a array delete an array like thisK unset array dereference with ),array[(]get all elements with ),array[9]-, or ),array[0]-

),#array[9]),array[9]K/K(arithmetic n&( n&3expr )n J .3 let n&nJ. # )**nJ.++ # **n J& .++ # # must prefix

# # # #

gives you length of array, which means how many non-null elements there are you can use this on ordinary variables *Gust exclude the brackets+ to get the number of characters in a string gives you ( elements starting from /

# backtick evaluation # if you4re going to use multiplication, use 404 to avoid globbing no spaces allowed unless you put 5uotes around 'n & n J .' arithmetic expansion carries out the operation, but if you ever want to use this return value you it with )

control structures if [ L -gt . ] then echo 'L is greater than .' elif [ / -gt .] then echo 'certainly not possible' else echo 'not possible' fi if test L -gt . then echo 'L is greater than .' fi case ')variable' in a + echo 'letter a' # don4t forget the double semi-colon [/-%] + echo 'digit' [[KupperK]] + echo 'uppercase' esac M>NFC&O while [ )M>NFC -gt / ] do echo 'Palue of count isK )M>NFC' let M>NFC&M>NFC-. done until [ )M>NFC -e5 L] do # repeat while condition is false echo 'Palue of count is K )M>NFC' let M>NFC&M>NFCJ. done # when parsing a string for tokens, they are separated by the );AB for i in 3ls 0Qtxt3 do echo ')i' done # writes out each word produced by ls temp&3ls3 for f in )temp do echo )f done boolean expressions test/[ ] operationsK stringsK - s. & s( *true if e5ual+ - s. !& s( *true if not e5ual+ - -n s. *true if not null+ - -" s. *true if null+ arithmeticK - exp. -e5 exp( *&&+ - exp. -ne exp( *!&+ - exp. -gt exp( *H+ - exp. -ge exp( *H&+ - exp. -lt exp( *R+ - exp. -le exp( *R&+ - ! exp. *true if false+

fileK logicK * expr + *is true+ ! expr *is false+ expr. -a expr( *and+ expr. -o expr( *or+ -d -e -f -r -w -x file file file file file file *is directory+ *exists+ *is regular file+ *is readable+ *is writeable+ *is executable+

miscellaneous )46n4 will print out the actual escape character, whereas 46n4 will print only 6n return values include / *successful+ . - .(L *unsuccessful, exact meaning varies from command to command+ .(O *command found but not executable+ .(S *command not found+ H.(T *command died due to receiving a signal+ !! in H R HH (H (HH the shell replaces !! with the last command write stdout to file read stdin from file append stedout to file write stderr to file append stderr to file

regex metacharactersK 6 & either turns off special meaning of next character or activate a special meaning 2 & match if succeeding expression is at the beginning of line, egQ 2apple ) & match if preceding expression is at the end of line, egQ apple) 0 & matches / or more of the preceding expression J & matches . or more of the preceding expression 1 & matches / or . of the preceding expression 6,i6- & matches exactly i *between / and (LL+ of the preceding expression -egQ [ab]6,L6- looks for L as and bs in some order 6,i,G6- & matches between i and G, inclusive, of the preceding expression 6,i,6- & matches i or more of the preceding expression all of the six above are greedy they will match as many as possible 8 & matches either the expression before or after Q & matches any character, including newline [list] & matches any character in list -[aeiou] for all vowels, [a-"] for all lowercase characters -[2/-%] for all characters except numbers *2 in lists is the inverse operator+ -to include ], make it the first character *after 2 if necessary+ -to include -, make it the first or last character -to include 2, make it after the first character -every other character is treated literally :>B;U bracket expressions include *it should look like [[KalnumK]/-L]+K [KalnumK], [KalphaK], [KblankK] *space and tab+, [KcntrlK] *control character+, [KdigitK], [KgraphK] *nonspace characters+, [KlowerK], [KprintK] *printable characters+, [KpunctK], [KspaceK] *whitespace characters+, [KupperK], [KxdigitK] *hex digits+ backreference with 6* and 6+ -anything enclosed can be retrieved with 6. through 6%, in order of occurrence in basic regex, 1 J , - 8 * + must be escaped for special meaning in extended regex, they must be escaped for no meaning in basic regex, 2 is special only at the beginning *same line of thought applies to )+ in extended regex, 2 is special everywhere in basic regex, 0 is not special if it4s at the beginning

chmod symbolic modeK chmod [ugoa][J-&][rwxUst] file -u & owner, g & group, o & others, a & all -J & adds to existing bits, - & removes from existing bits, & & adds existing bits and deletes unmentioned ones *basically it sets it+ -r & read, w & write, x & execute, U & execute/search only if directory or some user, s & set user/group id bit already has execute permissions, s & set user/group id on execution, t & restricted deletion flag or sticky bit -egQ chmod a-rw myfile -deletes read and write permissions from all V groups numeric modeK chmod xxxx file -one to four octal digits */ to S+, omitted digits are assumed to be leading "eroes -digit .K set user id *I+, set group id *(+, restricted deletion flag/sticky bit *.+ -digit ( - IK read *I+, write *(+, execute *.+ -digit (K owner, digit VK group, digit IK others user/group id bit means that any user gains the permissions associated with the user group, often used temporarily to 'elevate' a normal user4s permissions cmp cmp [options] file. [file(] -file can be substituted with - for stdin -exit status is / if bytes are e5ual in files, . if different, ( for errors diff diff [options] [files] -first file is original, second file is modified - -u & unified, prints V lines of unified context --- path/to/original!file 44timestamp44 JJJ path/to/modified!file 44timestamp44 99 -line,numEines;n=unk Jline,numEines;n=unk 99 -old stuff Jold stuff unchanged stuff -in the 'hunk header' line, the sign refers to the original and modified -should refer to the same hunk -first number is the line number the hunk begins on -second number is the number of lines in that hunk *considering the changes+ find find [options] [paths] [expression] -expression is made up of operators -numeric arguments specified with Jn, -n, n for greater than, less than, or e5ual to - -amin n last accessed n minutes ago - -atime n last accessed n days ago *fraction ignored, J. searches for ( days or older+ - -cmin n, -ctime n, -mmin n, -mtime n, change/modified versions of above - -empty empty and is either regular file or directory - -exectuable executable files and searchable directories - -name pattern pattern is a shell pattern - -iname pattern case insensitive version - -perm mode file4s permissions are exactly mode *octal or symbolic+ - -perm -mode all the bits set in mode are set in file - -perm /mode any of the bits set in mode are set in file - -readable - -regex pattern pattern is a regex pattern - -si"e n[cwbk?W] file is n bytes, b & L.(-byte blocks *default+, c & bytes, w & two-word bytes, k & kilobytes, ? & megabytes, W & Wigabytes - -type [bcdpfls<] b & block special, c & character special, d & directory, p & named pipe, f & regular file, l & symbolic link, s & socket, < & door *Bolaris+ - -writeable grep prints all lines matching :#CC@XF, which is written in regex grep [options] :#CC@XF [file] -if no files specified or - is the filename, reads from stdin - -@ for extended regex *or use egrep+ - -v/--invert-match to print non-matching lines - -A for fast grep *no regex+ *or use fgrep+

head/tail head [options] [files] -by default, prints - -c&[-]Y - -n&[-]Y tail is the same, but you

first ./ lines of each file to stdout prints first Y bytes, with leading -, prints all but last Y bytes same as above but with lines specify JY for every line after the Yth line

links hard links point to physical data, symbolic links point to a file name -if you change the original file name, symbolic link will no longer function, but a hard link will work Gust fine ln [options] [target] [link name] -defaults to hard link - -s/--symbolic for symbolic links - -f/--force to remove existing destination files *link name+ locale EM!M>EE#C@ & sorting order EM!C;?@ & date format EM!MCZ:@ & character class determination for pattern matching EM!?@BB#W@B & current language for output messages among other thingsK EM!MCZ:@, EM!FN?@X;M, EM!?>F@C#XZ, EM!?@BB#W@B, EM!:#:@X, EM!F#?@, EM!#<<X@BB, EM!C@E@:=>F@, EM!?@#BNX@?@FC, EM!;<@FC;A;M#C;>F, EM!#EE sed stream editor does transformations on an input stream in one pass s/// command is a regex command of interest sed [options] 4s/regexp/replacement/flag4 [input files] -egQ sed 4s/KQ0//4 myAile, prints out each line with everything after a colon deleted -g flag will apply replacements to all matches, not Gust the first -a number flag will apply the replacement only to the nth occurrence - -r will use extended regex instead of basic regex sed [options] 4/regexp/d4 -deletes any lines matching regexp sort sort [options] [file] -write sorted concatenation of all files to stdout - -u & w/o -c, output only the first of an e5ual run *uni5ue values only+ strace strace [options] [command] -prints out system calls to stderr or to output filename time time [options] [command] -realK total time elapsed in real life -userK total time spent executing in user space -sysK total time spent executing in kernel space touch touch [options] [files] -updates access and modification time to current time tr tr [options] set. [set(] -translate, s5uee"e, or delete characters from stdin and print to stdout - -c & complement of set. - -d & delete characters in set., do not translate - -s & s5uee"e repeats into a single occurrence - -t & first truncate set. to length of set( wc wc [options] [files] -prints newline, word, and byte count for each file, and total lines if more than . -no file or - as file means read from stdin - -c, bytes only, -m, chars only, -l, newline only, -E, length of longest line, -w, word only

Makefile # are comments # with no args, first rule is called # this entire thing is a rule targetK prere5uisites commands when calling make, you can specify a specific rule as an argument if you4re compiling, know that -c will tell gcc not to link but Gust to make an obGect file -o will tell it what file to output to declare variables like thisK MAE#WB&-g -;Q -std&cJJ/x -c use variables likeK )*MAE#WB+ Q/configure checks details of machines before installation *like package dependencies+ and then generates the ?akefile make runs ?akefile, which will compile all code and create executables in current directory make install copies executables to system directories

Python obGect-oriented scripting language compiled to bytecode and interpreted basics backticks converts an obGect to a string representation, so for exampleK val & . print 3val3 # prints '.' strings are immutable everything in :ython can be treated as a logical operator -[], /, '', Fone are all examples of false -most other values are true -you can use short circuit logic to easily return value control structures (for loops under data structures) if x R /K QQQ elif x && /K QQQ elseK QQQ while x H /K QQQ tryK f & open*4myfileQtxt4+ s & fQreadline*+ except ;>@rror as eK print ';/> @rror*,/-+K ,.-'Qformat*eQerrno, eQstrerror+ except Palue@rror as eK print 'Mould not convert data into integer' exceptK print 'Nnexpected error' elseK # executed if try does not throw error print 'Buccessful' data structures tuples immutable arrays *though they can contain mutable obGects+ t & ., (, V t[.] # ( u & t, *V, I+ # nested tuples

lists list & [.(V, /, 4dynamic typing4] print t[/] # outputs .(V for i in listK print i # prints out each element4s value for i in range*len*list++K print i # prints out each index of list list[/K(] # all elements / to . *end is exclusive+ list[.K] # all elements . and after list[K(] # all elements up to ( *exclusive+ list[-.] # first element from the end list[K] # essentially copying a list len*list+ list. J list( # concatenation listQappend*L+ listQreverse*+ listQcount*L+ # returns ., only one instance of L listQinsert*/, L+ # index, then obGect del list[/] max*list+ min*list+ list*tuple+ # converts tuple to list strings are actually Gust lists sets # Zou cannot delete from a set list & [., ., (, (] s & set*list+ # contains [., (] sQadd*I+ . in s # returns true V in s # returns false s( & set*[., V]+ # to make all of these actually change the sets, append !update to the function # except for union, that4s Gust the update*+ function s.Qintersection*s(+ # returns set*[.]+, e5uivalent to s. 7 s( s.Qunion*s(+ # returns set*[., (, V, I]+, e5uivalent to s. 8 s( s.Qsymmetric!difference*B(+ # returns set*[(, V, I]+, e5uivalent to s. 2 s( s.Qdifference*s(+ # returns set*[(, I]+, e5uivalent to s. - s( for item in setK print item # prints items in set in no particular order dictionaries a & ,4key.4K ., 4key(4K (, 4keyV4KV- # to make, use curly braces or constructor b & dict*key.&., key(&(, keyV&V+ a && b len*b+ b[4key.4] # . b[4key.4] & I del b[4key.4] key. in b # return false key. not in b # return true, e5uivalent to not key. in b for key in bK print key # prints out each key in no particular order for key, value in bQitems*+K print k, 4corresponds to4, v # iterate over pairs I/O f & open*4path/to/file4, 4w4+ fQread*+ fQreadline*+ # second arg is # and write # optional si"e arg to read at # newline is at the end of the # hence an empty string always mode, r & read, w & write, a & append, rJ & read most n bytes, otherwise reads entire file string unless the file doesn4t end in newline means end of file reached

for line in fK print line, # empty comma means print w/o newline fQclose*+ fQwrite*string+ # must be a string use str*value+ to convert fQseek*offset, from!what & /+ # go to byte in file input*prompt+ # actually attempts to evaluate the expression raw!input*prompt+ usually you want raw!input

:ython V onlyK print*x, y, sep&'6n', end&' '+

# comma separated arguments, can specify separator and end

exceptions by default, the message of an exception is found in its args attribute raise @xception*4something bad happened4+ # construction and raising of exception you can have # multiple args and access them as a tuple would #rithmetic@rror # arising from overflow error, "ero division error, floating point error, etcQ @>A@rror # arising from input*+ or raw!input*+ reading in nothing before reaching @>A ;>@rror # some ;> error, has two args as an errorK errno and strerror ;ndex@rror # se5uence subscript out of range @xception # base class for all exceptions modules import mymodule mymoduleQmyfunction*+ # must call things through module from module import myfunction myfunction*+ # importing specific things, no need for module import string ,/refers to first positional argument ,implicitly refers to the first positional argument ,namereferences keyword argument name ,/Qweight- references weight attribute of first argument ,name[/]references first element of keyword argument name ,/KRleft Gustify *default for most obGects+ ,/KHright Gustify *default for numbers+ ,/K&forces leading /s between sign and digits ,/K2center Gustify ,/KJforces sign to be included for both positive and negative numbers *default is neg only+ ,/K leading space for positive number, minus sign for negative numbers ,/K#valid only for binary, octal, and hex forces leading /b, /o, or /x ,/K,commas for thousands places ,/K(minimum width ( ,/K/(minimum width (, enables "ero padding ,/K./QVminimum width ./, for floats specifies V digits after decimal ,/Ksstring ,/K2TQ(fT characters width min, ( decimal places, floating, center-Gustified other b c d o x U n e e f A g W [ type specifiersK binary character decimal octal hexadecimal, lowercase hexadecimal, uppercase locale aware decimal or float exponential, lowercase exponential, uppercase floating point, lowercase floating point, uppercase chooses between e and f chooses between @ and A multiplies number by .// and displays in f, followed by a [ sign # # # # # strips leading and trailing whitespace, or whatever char you pass in as argument trailing strip leading strip lowercase uppercase

stringQstrip*+ stringQrstrip*+ stringQlstrip*+ stringQlower*+ stringQupper*+

import sys sysQstdin # Qread*+ and Qreadline*+ function Gust as they do in files sysQstdoutQwrite*string+ # you can set stdout and stderr to a file to write to files sysQstderrQwrite*string+ print HH sysQstderr, 4some error4 # if you prefer sysQargv # list with arguments, argv[/] is the program name

import random randomQrandrange*stop+ randomQrandint*a, b+ randomQrandchoice*se5+ randomQshuffle*se5+ randomQrandom*+

# # # # #

pretend the args are Gust like the range function a R& F R& b random choice from a se5uence shuffles se5uence in place random float [/Q/, .Q/+

from optparse import Option arser >ptparse library is a powerful library for parsing command line options -argument & string entered on command line -sysQargv[.K] are the arguments *sysQargv[/] is the program name+ -option & argument that supplies extra information -option argument & argument that is closely associated with an option parser & >ption:arser*+ parserQadd!option*4-f4, 4--file4, dest&4filename4, help&4write report to A;E@4, metavar&4A;E@4+ # default action&4store4, which stores value into destination # if store is specified, you can specify type&4string4, type&4float4, type&4int4 # if dest is unspecified, --foo-bar will store in foo!bar, or -f will store in f # you can also specify action&4store!true4, action&4store!false4 # action&4store!const4, action&4append4, action&4count4, action&4callback4 # default&Crue, default&., etcQ *options, args+ & parserQparse!args*+ # you can pass a custom list, but defaults to sysQargv[.K] optionsQfilename # will contain option argument of -f args[/] # contains positional arguments, which are the 'mandatory' arguments functions :arameters act as they do in \ava primitives are passed by value, obGects are passed by reference def sum*a, b+K # defining and using a function *function pointer shown is optional+pyth return aJb func & sum r & func*L, O+ print r # .. def add*a, b&(+K return aJb # default arguments

you can use the argument name when calling the function to call the args in any order add*b&L, a&V+ ob!ects # every function in a class re5uires self as the first argument class BhapeK def !!init!!*self, x, y+K selfQx & x selfQy & y def x:os*self+K return selfQx class Mircle*Bhape,Bomething@lse+K def !!init!!*self, x, y, rad+K BhapeQ!!init!!*self, x, y+ selfQradius & rad x & Bhape*., (+ # instantiation

git repository & a data structure on the server that contains a set of files and directories and the full history and different versions of a proGect working copy & a local copy of files from a repository check-out & act of creating a working copy, potentially specifying a revision commit & writing one4s changes back to the repository git has I obGect typesK -blobs, which are se5uences of bytes, indexed by hash, stored in Qgit/obGects -trees, which are like directories, and can include other trees and blobs -commits, which are created with git commit, and contains the name of a committer, time of commit, and hash of current tree -tags, which are names to commit obGects, which include tag name, the commit referred

to, the tag message, and tagger info head & reference to a commit obGect, a repository can have many heads =@#< & refers exclusively to the currently active *checked out+ head detached =@#< & commit is not pointed to by a branch -in other words, your =@#< doesn4t point to the tip of a branch -to preserve commits, create new branch branch & head and entire history of ancestor commits preceding that head master & default head name that refers to the default branch created in the repository history, commit, get, log, add, etcQ commands git init, creates new repository git clone, gets a copy of an existing repository git add, adds file to index, run before a commit git commit, changes added to repository - -m 'message' git diff, shows working copy4s changes relative to index -git add adds to index, so git diff won4t show anything once you add a modified file -git diff =@#< will show changes in working version as opposed to last committed -git diff --cached =@#< or git diff --staged =@#< will show changes in the stage as opposed to =@#< *or whatever named branch you chose+ git status, shows list of modified files git checkout, checks out a specific version/branch of the tree -if you specify file as last arg, you get only that file from the version/branch -if you specify -- as the branch, reverts changes in the working directory git reset, moves tree back to a certain specified versions - --force to ignore working changes git revert, reverts a commit, not by deleting but by applying a patch *hence, can be reverted itself+ git branchK git branch [branch name] [reference to commit] -creates a new branch starting at committed -for commit references, you can use 2 to indicate one commit before *egQ =@#<2+ -use git checkout [branch!name] to start working on it git log, show a log of commits git show, shows a certain obGect in repository -on commits, shows log message and diff file -on tags, shows the tag message and the referenced obGects -on trees, shows the names -on blobs, shows the contents git merge, attempts to merge specified branch to current branch -will automatically try to look at changes since the branches4 common ancestor git clean, removes untracked files git tag, assigns a text string to a commit -git tag -a v.Q/ -m 'Persion .Q/' -names commit =@#< as v.Q/ # remote repository # 8 8 2 8 8 8 8 fetch push 8 8 8 8 v 8 8 # local repository # 8 8 2 8 8 8 8 8 commit pull 8 8 8 8 # ;ndex # 8 checkout 2 8 =@#< 8 8 8 add v v 8 # working directory #

C remember that there is no bool, only ints function pointers double *0func!ptr+ *double, double+ func!ptr & pow double result & *0func!ptr+*.QL, (Q/+ result & func!ptr*.QL, (Q/+

// same as above

struct // if you don4t use typedef struct my!struct my!struct, you have to use struct my!struct as // the variable type all the time struct my!struct , int thing "include #stdlib$h% void 0malloc*si"e!t si"e+ // allocates si"e bytes and returns a pointer to allocated memory // use si"eof*type+ 0 n to get the desired number of bytes void 0realloc*void 0ptr, si"e!t+ void free*void 0ptr+ void 5sort*void 0first, si"e!t num!elements, si"e!t element!si"e!in!bytes, int *0compar+*const void 0, const void 0++ // compare must return R/, /, H/ if a is less than, e5ual to, or greater than b // note that 5sort will send you a pointer to the element in other words the arguments of // the compare function are of the same type as the array itself "include #stdio$h% int getchar*+ // returns next char from stdin, @>A if end of file int putchar*int char+ // writes character to current position in stdout, @>A if fail int fprintf*A;E@ 0fp, const char 0format, QQQ+ // fp can be a file, stdin, stdout, stderr int fscanf*A;E@ 0fp, const char 0format, QQQ+ int printf*const char 0format, QQQ+ // defaults to stdout int scanf*const char 0format, QQQ+ // defaults to stdin A;E@ 0fopen*const char 0restrict filename, const char 0restrict mode+ // for mode, r & read, w & write, a & append // returns a FNEE pointer if error int fclose*A;E@ 0fp+ // returns @>A to signal error, / if successful int getc*A;E@ 0fp+ // returns @>A to signal end of file int putc*int c, A;E@ 0fp+ // returns c, or @>A if fail char 0fgets*char 0restrict s, int n, A;E@ 0restrict stream+ // reads at most n-. bytes *terminates if @>A or newline is read and transferred+, and then // terminates with null byte, and then returns s int fputs*const char 0restrict s, A;E@ 0restrict stream+ // does not write in null byte, returns @>A if fail format strings [[flags][width][Qprecision][length]specifier specifiersK [d or [i signed decimal integer [u unsigned decimal integer [o unsigned octal integer [x unsigned hexadecimal integer [U unsigned hexadecimal integer *uppercase+ [f decimal floating point [A decimal floating point *uppercase for things like F#F+ [e scientific notation, lowercase *.Q//eJ.+ [@ scientific notation, uppercase *.Q//@J.+ [g use shorter of [f and [e [W use shorter of [A and [@ [a hexadecimal floating, lowercase */xcQ%/fep-(+ [# hexadecimal floating, uppercase */xMQ/%A@:-(+ [c characters [s string of characters [p pointer address [[ simply writes out [

flagsK J *space+ # / width *number+ 0 Qprecision Qnumber Q0 length hh for h for l for ll for

left-Gustify *right-Gustify is default+ forces preceding the number with J or - *normally only - is used+ blank space written instead of sign for octal or hex numbers, forces preceding the number with /, /x, or /U for other numbers, forces a decimal point to be placed left pads number with /s min number of characters to be printed, never truncated however width specified as an additional integer argument before the number for integers, specifies minimum number of digits to be written if value is shorter, pad with leading /s, never truncated, / precision means no character written for val / see width integers, integers, integers, integers, specifies specifies specifies specifies char as the si"e short int as the si"e long int as the si"e long long int as the si"e

"include #string$h% Dith all the 'n' versions of the functions, you still have to be careful for null termination, as they will not null terminate for youQ char 0strcpy*char 0restrict s., const char 0restrict s(+ // restrict is a keyword Gust to say that there is no aliasing // copies s( up until and including null byte into s. // returns s. // evidently prone to overflows char 0strncpy*char 0restrict s., const char 0restrict s(, si"e!t n+ // only copies in at most n bytes, if s( is less than n then the rest are filled with // null bytes char 0strcat*char 0destination, char 0source+ // appends source to destination, overwriting starting from destination4s null byte char 0strncat*char 0destination, char 0source, si"e!t num+ // appends at most num characters int strcmp*const char 0s., const char 0s(+ int strncmp*const char 0s., const char 0s(, si"e!t num+ // you know the drill "include #pthread$h% a process consists of at least one thread -in a uniprocessor, multiprocessing simply switches between threads and the paralellism is an illusion -in a multiprocessor, multiple cores run the threads each thread gets its own address space for the stack -shares the global data, code, and heap race condition & output depends on order of execution int pthread!create*pthread!t 0tid, const pthread!attr!t 0atr, void *0func+*void0+,void 0arg+ // tid & uni5ue identifier for the thread // attr holds attributes like priority, stack si"e, etcQ, pass FNEE for defaults // func, function that thread will execute once created // arg, single argument that may be passed in *FNEE if no args+, probably want to use // a struct for multiple data // returns / if successful int pthread!Goin*pthread!t tid, void 00status+ // tid is the pthread!t you used in pthread!create // if you don4t pass in FNEE, the exit status from pthread!exit will be stored in // the location pointed to by 0status // the reason we used a double void pointer is so that you can change where yourself // look, not Gust copying the value into void status *who knows what it should // contain1+ // returns / if successful void pthread!exit*void 0value!ptr+ // if you wish to return a value, place it under value!ptr, otherwise use FNEE

"include #unistd$h% ssi"e!t read*int filedes, void 0buf, si"e!t nbyte+ // for filedes, / & stdin, . & stdout, ( & stderr // you can also use BC<;F!A;E@F>, B<>NC!A;E@F>, BC<@XX!A;E@F> // buf should have enough space to hold nbyte bytes // returns / to signal at or after end of filename, otherwise returns bytes read in // returns -. to indicate error ssi"e!t write*int filedes, const void 0buf, si"e!t nbyte+ // returns number of bytes written *may be less than nbyte if out of space+ int fstat*int fildes, struct stat 0buf+ int stat*const char 0restrict path, struct stat 0restrict buf+ stat structure dev!t st!dev // device ;< of device containing filename ino!t st!ino // file serial number mode!t st!mode // mode of file, can be used to determine things such as B!;B<;X*statQst!mode+ B!;BA;A>*m+ // is pipe or A;A> special filename B!;BX@W*m+ // is regular filename B!;BEFY*m+ // is symbolic link nlink!t st!nlink // num hard links to file uid!t st!uid // user ;< gid!t st!gid // group ;< dev!t st!rdev // device ;< if file is character or block special off!t st!si"e // for regular fils, file si"e in bytes, for symbolic links, length in bytes // pathname time!t st!atime // time of last access time!t st!mtime // time of last modification time!t st!ctime // time of last status change

SSH plaintext & actual message ciphertext & encrypted message symmetric key encryption & shared/secret key, same key used to decrypt and encryption asymmetric key encryption & public/private keys, if one is used to decrypt the other must be used to encrypt -private key cannot be derived from public key -never publish the private key ssh username9somehost -on first connect to somehost, will re5uest for host validation -after accepting, public key is saved to ]/Qssh/known!hosts -next time client connects to server, public keys are checked to verify host -to do this, the client encrypts a message with the public key, and if it4s really the host then the host will decrypt it with the corresponding private key after connection, symmetric encryption key *session key+ is used two types of authenticationK password-based, and key-based -password-based is straightforward -key-basedK client generates keypair, gives public key to server *who stores it on ]/Qssh/authori"ed!keys+, and if client can decrypt the server4s encrypted message then they are authenticated -private key can be protected with a passphrase, which makes it inconvenient ssh-agent eliminates the need to type in the passphrase all the time -ssh-add prompts user for the passphrase once and maintains it with ssh-agent U windowing system allows a program to run on one computer but display on another >n server sideK sudo useradd -d /home/username -m NserFame sudo passwd NserFame sudo mkdir /home/username/Qssh // creates the ssh directory for new user sudo chown -X username /home/username/Qssh sudo chmod S// Qssh >n client sideK ssh-keygen generates a keypair ssh-copy-id -i username9server // copies public key to Qssh

ssh-add

// passphrase-less

to digitally sign something, hash the file *called the message digest+, encrypt using your private key, and then attach a certificate *by a trusted Vrd party+ and the encrypted hash to the file to verify something, decrypt the hash with the sender4s public key, hash the file yourself, and compare the hashes -the public key is proven to be the sender4s through the certificate

system calls user mode & restricted access to system resources kernel/supervisor mode & unrestricted access system resources include memory, ;/> devices, M:N hardware contains a mode-bit */ & kernel, . & user+ that sets restrictions on M:N only kernel code is trusted with kernel mode, so applications must go through the kernel to access system resources system calls are part of the kernel, and are used to re5uest a service from the kernel -changes the M:N4s mode to kernel -must verify that the user can do the action when a system call is made, a trap *exception or fault+ switches control to the kernel, who must verify that the user4s operation is valid and execute it getchar, putchar are the library versions of read, write that minimi"e system calls fopen, fclose are likewise for open, close unbuffered & every byte is read/written with a system call buffered & collect as many bytes as possible with one system call, then read/write buffer

buffer overflows args and environment variables *higher addresses+ stack R- stack pointer *points to top of stack+ 8 v unused memory 2 8 heap unitiali"ed data segment *bss+ *uninitiali"ed global variables+ initiali"ed data segment *initiali"ed global variables+ text segment *code to be executed+ *lower addresses+ stack grows downwards as a result of a newly called function heap grows upwards as a result of a malloc stack frame & memory set aside for a function -storage space for all local variables -line number of calling function to return to when the function returns -arguments of the called function -frame pointer points to a fixed location in the frame, and variables are referenced by offsets to the A: when you call a function, previous frame pointer is saved, then stack pointer is copied into the fp to create the new fp sp then advances to reserve space for the local variables in a stack overflow, we put our code in the overflow, and have the overflow overwrite the return address to point to the code from our overflows -we can spawn a shell in the code -fstack-protector option in gcc will gracefully exit the program if stack is ever overflowed -fsaniti"e&address option in gcc will gracefully exit the program if out of bounds memory access occurs heap overflow will probably change the return address of a free*+ function to point to the overflow code

Das könnte Ihnen auch gefallen