-->

The Essentials : Linux Basics

The Essentials : Linux Basics

This post lists essential commands too concepts which would live helpful to a Linux user. We would comprehend tools required for programming (Vi, git), organisation direction (Bash configuration files, Updating Debian Linux System, Adding/ Deleting/ Modifying Users/ Groups, Changing Group/ Owner/ Permission, Mounting/ Unmounting, Linux Directories, Runlevels too Kernel Configurations). Also, furnish some useful tips, tricks too TODO which would assistance you lot larn too practice.

Vi : Powerful Editor

Open file alongside vi

vi <filename>               - Open a file to edit inwards Vi editor. 

Vi Modes

Two modes - Command too Insert Mode. All commands below are inwards command mode.
h,l,j,k                     - Move left, right, down, upwards w                           - Move to the start of the adjacent word. e                           - Move to the terminate of the word. b                           - Move to the starting fourth dimension of the word. 3w                          - 3w is similar to pressing w 3 times, moves to the start of the tertiary word. 30i-'EscKey'                - 30<insert>-<EscapeKey> : Inserts thirty - at once. f                           - detect too motility to the adjacent (or previous) occurrence of a character. fo detect adjacent o. 3fo                         - detect tertiary occurrence of o %                           - In text that is structured alongside parentheses or brackets, ( or { or [, utilisation % to jump to the matching parenthesis or bracket. 0 (Zero)                    - Reach starting fourth dimension of the line of piece of job $                           - Reach terminate of the line. *                           - Find the adjacent occurrence of the give-and-take nether cursor #                           - Find the previous occurrence of the give-and-take nether cursor gg                          - Reach starting fourth dimension of the file G                           - Reach terminate of the file 30G                         - Reach the 30th line of piece of job inwards the file /<text>                     - Search for the text. Utilize n, due north for adjacent too previous occurrences. o                           - Insert a novel line of piece of job below the cursor O                           - Insert a novel line of piece of job higher upwards the cursor x                           - Delete the grapheme r                           - supersede the grapheme alongside the adjacent fundamental pressed. dw                          - Delete the electrical flow word. dd                          - Delete the electrical flow line. d$                          - Delete the text from where your cursor is to the terminate of the line. dnd                         - Delete n lines. .                           - Repeat the concluding command :q                          - Quit. :wq                         - Save too close. :syntax on                  - Turn on Syntax highlighting for C programming too other languages. :history                    - Shows the history of the commands executed :set number                 - Turn on the line of piece of job numbers. :set nonumber               - Turn off the line of piece of job numbers. :set spell spelllang=en_us  - Turn spell checking on alongside spell linguistic communication every bit "en_us" :set nospell                - Turn spell checking off :set listing                   - If 'list' is on, whitespace characters are made visible. The default displays "^I" for each tab, too "$" at each EOL (end of line, so trailing whitespace tin give notice live seen) :u                          - Undo i change. z=                          - If the cursor is on the give-and-take ( which is highlighted alongside spell check), Vim volition advise a listing of alternatives that it thinks may live correct. yy                          - Yank or re-create electrical flow line. y$, yny                     - Similar to delete lines. p                           - Paste the line of piece of job inwards the buffer inwards to text after the currentline. :%!xxd                      - to plough it into a hexeditor. :%!xxd -r                   - to move out dorsum to normal trend (from hexedit mode) 

Vi Configuration Files

Two configurations files which are important:

.vimrc

Contains optional runtime configuration settings to initialize Vim when it starts. Example: If you lot desire Vim to stimulate got syntax on too line of piece of job numbers on, whenever you lot opened upwards vi, move inwards syntax on too laid number inwards this file.
##Sample contents of .vimrc  syntax on laid number 
H5N1 practiced details well-nigh diverse options which tin give notice live laid inwards vimrc tin give notice live constitute at A Good Vimrc

.viminfo

Viminfo file stores command-line, search string, input-line history too other stuff. Useful if you lot desire to detect out what user has been doing inwards vi.
Tip
Both files are introduce inwards user habitation directory.

Replace text inwards Vi

:s/test/learn     - would supersede essay to larn inwards electrical flow line of piece of job but alone foremost instance. :s/test/learn/g   - would supersede essay to larn inwards electrical flow line of piece of job all the instance. :s/test/learn/gi  - would supersede essay (all cases) to larn inwards electrical flow line of piece of job all the instance. :%s/test/learn/gi - would supersede essay to larn inwards the file (all lines) 

Other Info

  • Vim Awesome provides Awesome VIM plugins from across the universe. Few practiced i are
  • The NERD tree : Tree explorer plugin for vim
  • Syntastic : Syntax checking hacks for vim
  • Youcompleteme : Code-completion engine for Vim

Bash configuration files - For Debian/Ubuntu based Systems

Important Files

  • /.bash_profile - Stores user environs variables.
  • /.bash_history - contains all the history of the commands.
  • /.bash_logout - contains the command which are executed when bash is exited.
  • /.bashrc - setting of variables for bash.
  • /etc/profile - Global organisation configuration for bash which controls the environmental variables too programs that are to live run when bash is executed. Setting of PATH variable too PS1.
  • /etc/bashrc - Global organisation configuration for bash which controls the aliases too functions to live run when bash is executed

Important variables

  • HISTSIZE - Controls the number of commands to recall inwards the history command. The default value is 500.
  • HISTFILE - Defines the file inwards which all commands volition live logged to. Normally the value for this variable is laid to /.bash_history. This way that whatever you lot type inwards bash volition live stored into the value of HISTFILE. It is advisable to leave of absence it undefined, or pipage the output to /dev/null (For privacy reasons).
  • HISTFILESIZE - Defines the maximum number of commands inwards /.bash_history.

System Administration

Updating Debian Linux System

Using apt-get

apt-get update                 - Sync alongside Repositories. apt-get upgrade                - Upgrade installed packages. apt-get dist-upgrade           - Upgrade distribution packages. apt-get install "Package Name" - Install the package. apt-get take away  "Package Name" - Uninstall the package. apt-get purge   "Package Name" - Removes the bundle every bit good every bit the configuration files. apt-cache demo  "Package name" - Shows what bundle is used for. apt-cache search "Keywords"    - Search bundle call based on keywords. 
Tip
As mostly, updating takes time, you lot tin give notice monastic tell all the commands similar “apt-get update && apt-get upgrade && apt-get dist-upgrade && poweroff”. poweroff would shutdown the organisation after everything is updated.

Using Debian Package Manager dpkg

dpkg -i <Package>.deb          - Install package. dpkg -r <Package>              - Removes everything except configuration files. dpkg -P <Package>              - Removes configurations files too. dpkg -l                        - Shows the listing of all installed packages. dpkg -L "Package name"         - Shows a listing of files installed past times specific packages. dpkg -S "File path"            - Shows the bundle to which a file belong to. 

Adding/Deleting/Modifying Users/Groups

adduser <username> : Add a user.  --gecos GECOS     : adduser won't inquire for finger information.  --system          : Create a organisation user.  --quiet           : Suppress informational messages, alone demo warnings too errors.  --disabled-login  : Do non run passwd to laid the password. deluser <username> : Delete a user.  --remove-home     : Remove the habitation directory of the user too its mailspool.  --remove-all-files: Remove all files from the organisation owned past times this user.  --backup          : Backup all files contained inwards the userhome too the mailspool-file to a file named /$user.tar.bz2 or /$user.tar.gz. usermod            : Modify a user account.  -e EXPIREDATE     : The engagement on which the user concern human relationship volition live disabled. The engagement is specified inwards the format YYYY-MM-DD.  -L, --lock        : Lock a user's password.  -U, --unlock      : Unlock a user's password groupadd           : Create a novel group. groupdel           : Delete a group. groupmod           : Modify a grouping definition on the system. 

Changing Group/Owner/Permission

chown              : Change file possessor too group.  -reference=RFILE  : utilisation RFILE's possessor too grouping rather than specifying OWNER:GROUP values.  -R, --recursive   : operate on files too directories recursively. chmod              : alter file trend bits. chgrp              : alter grouping ownership. SUID flake           : SetUID flake specifies that an executable should run every bit its possessor instead of the user executing it.                    : SUID is generally commonly used to run an executable every bit root, allowing users to perform tasks such every bit changing their passwords.                    : If in that location is a flaw inwards a SUID root executable, you lot tin give notice run arbitrary code every bit root. 

Mounting/ Unmounting

mount <device> <dir> : Mount a filesystem.    -r, --read-only   : Mount the filesystem read-only. unmount {dir|device} : Unmount file systems. 

Mounting Windows percentage on Linux

mount -t cifs -o username=<share user>,password=<share password>,domain=example.com //WIN_PC_IP/<share name> /mnt 

Linux Directories

/home                             : users habitation directories. /etc                              : system-wide configuration files. /bin, /usr/bin, /usr/local/bin    : directories alongside executable files. /lib, /usr/lib, /usr/local/lib    : shared libraries needed to upport the applications. /sbin, /usr/sbin, /usr/local/sbin : directories alongside executables supposed to live run past times the Superuser. /tmp, /var/tmp                    : temporary directories, sentinel out every bit /tmp is, past times default, cleaned out on each reboot. /usr/share/doc, /usr/share/man    : consummate organisation documentation. /dev                              : organisation device files. In Unix, hardware devices are represented every bit files. /proc                             : "virtual" directory containing files through which you lot tin give notice query or melody Linux nub settings. 

Runlevels too Kernel Configurations

Linux Boot Process

1. BIOS start the kick loader. 2. Boot loader loads the nub into memory. 3. The Kernel mounts disks/partitions too starts the init daemon. 4. The init daemon starts services based on the runlevel. 
Linux has 6 runlevels 0-6. Scripts are contained inwards /etc/rc[0-6,S].d/. Each folder contains the scripts which are followed past times either K or S. If the foremost missive of the alphabet is K that script is non executed. If S, that script is executed. /etc/inittab contains the default run level.
ID Name Description
0 Halt Shuts downward the system.
1 Single-user Mode Mode for administrative tasks.
2 Multi-user Mode Does non configure network interfaces too does non export networks services
3 Multi-user Mode alongside Networking Starts the organisation normally.
4 Not used/User-definable For exceptional purposes.
5 Start organisation usually alongside display manager (with GUI). Same every bit runlevel 3 + display manager
6 Reboot Reboot the system

Sysctl - configure nub parameters

/etc/sysctl.conf                : Contains the variables for nub parameters. sysctl -a                       : Display all the nub parameters sysctl -w <kernel parameter>    : Change a sysctl setting. 
Note
To brand permanent changes to the kernel, edit the /etc/sysctl.conf file.

Kernel Modules

Kernel modules are contained inwards /lib/modules/$(uname -r)/
lsmod      : listing all loaded modules modprobe   : charge nub modules lspci      : listing all pci devices lsusb      : listing all usb devices hal-device : listing all the Hardware Abstraction layer devices 

Manage Runlevels

Debian GNU provides a convenient tool to contend runlevels (to command when services are started too closed down);
  • update-rc.d too in that location are 2 commonly used invocation methods:
update-rc.d -f <service name> take away : Disabling a service. update-rc.d <service name> defaults  : Insert links using defaults, start inwards runlevel 2-5 too halt inwards runlevels 0,1 too 6. 
  • Systemctl : Control the systemd organisation too service manager. systemctl may live used to introspect too command the set down of the “systemd” organisation too service manager.
systemctl : Present a detailed output well-nigh the dissimilar services running.  e.g.  systemctl status <service_name> - Status of the service. systemctl start <service_name>  - Start the service 

Screen Multiplexer

tmux

tmux novel -s myname            : start novel alongside session name: tmux list-sessions            : demo sessions tmux ls                       : demo sessions tmux list-windows             : demo windows tmux attach-session -t myname : Attach to session named "myname" tmux a -t myname              : Attach to session named "myname" (Prefix) + d                  : detach 
Windows (Tabs)
(Prefix Key) + c  create window w  listing windows n  adjacent window p  previous window f  detect window ,  call window &  kill window 
tmux.conf
# Enable mouse trend (tmux 2.1 too above) laid -g mouse on 
Reloading tmux config
If nosotros stimulate got made changes to tmux configuration file inwards the /.tmux.conf file, it shouldn’t live necessary to start the server upwards over again from scratch alongside kill-server. Instead, nosotros tin give notice prompt the electrical flow tmux session to reload the configuration alongside the source-file command. This tin give notice live done either from within tmux, past times pressing Ctrl+B or Prefix fundamental too and so : to convey upwards a command prompt, too typing:
:source-file  /.tmux.conf 
Or only from a shell:
$ tmux source-file  /.tmux.conf 
This should apply your changes to the running tmux server without affecting the sessions or windows within them.
Copy Paste
For copying, Press the Shift key; i.e., Shift-MouseHighlight properly selects text too - all the same belongings downward the shift key
  • we tin give notice right-click too acquire the criterion bash context card alongside Copy, Paste, etc.
  • or Ctrl-Shift-C too Ctrl-Shift-V does piece of job to re-create too glue text.

Programming

GIT

Version Control System, genuinely useful for tracking your changes.
Todo
try.github.com xv mins tutorial.

cc - GNU Compile Collection

To Compile: gcc -Wall -pedantic -g <C source file> -o <Executable file> -Wall -pedantic : to cheque for all the warnings too errors if any. -g              : to create the symbol file to live used past times gdb -o              : to create the executable file. 

GDB: GNU debugger

gdb -tui <Program name>  tui               : for listing the source patch debugging <linenumber>      : to laid the interruption dot p <variable name> : to impress the value of the variable bt                : to impress the stack call, mainly useful to detect segmentation fault when multiple functions are called. 

Gathering Information

From Files

/etc/issue     : Contains the message which is displayed on terminal earlier login. /etc/motd      : Contains the message which is displayed on terminal after login. /proc/cpuinfo  : provides data well-nigh CPU. /proc/meminfo  : provides data well-nigh memory/ RAM. /proc/version  : provides data well-nigh the version of your system. 

From Commands

last      : shows all the login attempts too the reboot occurred. lastb     : shows all the bad login attempts. lastlog   : shows the listing of all the users too when did they login. id        : impress existent too effective user too grouping IDs. whoami    : whoami - impress effective userid. uname     : impress organisation information.   -a      : impress all the data (Kernel name, nodename, kernel-release, kernel-version, machine, processor, hardware-platform) pstree    : display a tree of processes. hostname  : prints out the hostname of the machine which is stored inwards /etc/hostname. 

Useful Utilities/ Commands

Grep - Global Regular Expression Print

Two ways to furnish input to Grep:
  • search a given file or files on a organisation (including a recursive search through sub-folders).
grep bitvijays /etc/passwd 
  • Grep also accepts inputs (usually via a pipe) from some other command or serial of commands.
cat /etc/passwd | grep bitvijays 

Syntax

grep [options] [regexp] [filename]     -i, --ignore-case     : 'it DoesNt MatTTer WhaT thE CAse Is'    -v, --invert-match    : 'everything , BUT that text'    -A <NUM>              : Print NUM lines of trailing context after matching lines.    -B <NUM>              : Print NUM lines of trailing context earlier matching lines.    -C <NUM>              : Print additional (leading too trailing) context lines earlier too after the match.    -a, --text            : Process a binary file every bit if it were text; this is equivalent to the --binary-files=text option.    -w                    : Whole-word search    -L --files-without-match : which outputs the names of files that do NOT comprise matches for your search pattern.    -l --files-with-matches  : which prints out (only) the names of files that do comprise matches for your search pattern.     -H <pattern> filename    : Print the filename for each match.        example: grep -H 'a' testfile                 testfile:carry out few cyber-crime investigations         Now, let’s run the search a flake differently:                truthful cat testfile | grep -H 'a'                (standard input):carry out few cyber-crime investigations 
Note
Regular human face should live enclosed inwards unmarried quotation marks or double quotes (allows environs variables to live used), to forbid the musical rhythm out (Bash or others) from trying to interpret too expand the human face earlier launching the grep process.

Using regular expressions

grep 'v.r' testfile give thank you lot you really much 
In the search above, . is used to correspond whatever unmarried grapheme - matches “ver” inwards “very”.
H5N1 regular human face may live followed past times i of several repetition operators:
  • The menstruation (.) matches whatever unmarried character.
  • ? way that the preceding item is optional, too if found, volition live matched at the most, once.
  • * way that the preceding item volition live matched null or to a greater extent than times.
  • + way the preceding item volition live matched i or to a greater extent than times.
  • {n} way the preceding item is matched just n times, patch {n,} way the item is matched n or to a greater extent than times. {n,m} way that the preceding item is matched at to the lowest degree n times, but non to a greater extent than than m times. {,m} way that the preceding item is matched, at the most, m times.

Search a specific string

Scan files for a text introduce inwards them Find a way to scan my entire linux organisation for all files containing a specific string of text. Just to clarify, I’m looking for text within the file, non inwards the file name.
grep -rnw 'directory' -e "pattern" --include={*.c,*.h} --exclude=*.o    -r                    : search recursively   -n                    : impress line of piece of job number   -w                    : correspond the whole word.   --include={*.c,*.h}   : Only search through the files which stimulate got .c or .h extensions.   --exclude=*.o         : Exclude searching inwards files alongside .o extensions. 
Note
–exclude or –include parameter could live used for efficient searching.

Line too give-and-take anchors

  • The ^ anchor specifies that the blueprint next it should live at the start of the line:
grep '^th' testfile this 
  • The $ anchor specifies that the blueprint earlier it should live at the terminate of the line.
grep 'i$' testfile Hi 
  • The operator < anchors the blueprint to the start of a word.
grep '\<fe' testfile behaviour out few cyber-crime investigations 
  • > anchors the blueprint to the terminate of a word.
grep 'le\>' testfile is essay file 
  • The b (word boundary) anchor tin give notice live used inwards identify of < too > to signify the starting fourth dimension or terminate of a word:
grep -e '\binve' testfile behaviour out few cyber-crime investigations 

Shell expansions - input to Grep

If nosotros don’t single-quote the blueprint passed to Grep, the musical rhythm out could perform musical rhythm out expansion on the blueprint too genuinely feed a changed blueprint to Grep.
grep "$HOME" /etc/passwd root:x:0:0:root:/root:/bin/bash 
We used double quotes to brand the Bash musical rhythm out supersede the environs variable $HOME alongside the actual value of the variable (in this case, /root). Thus, Grep searches the /etc/passwd file for the text /root, yielding the 2 lines that match.
grep `whoami` /etc/passwd root:x:0:0:root:/root:/bin/bash 
Here, back-tick expansion is done past times the shell, replacing whoami alongside the user call (root) that is returned past times the whoami command.

Copy - Copy files too directories

cp <SOURCE> <DIRECTORY>   -r        : recursive.   -a        : similar to preserve,   -p        : preserve   -v        : verbose. 

cutting - take away sections from each line of piece of job of files

cut OPTION... [FILE]...  -d        : utilisation DELIM instead of TAB for champaign delimiter.  -f        : select alone these fields. 

Pipes

>         : direct normal output. 2>        : direct error output. &>        : direct all output. 

tar - Archiving utility

tar  -c        : create archive  -t        : listing the content of the file  -x        : extract the files  -j        : bzip2 format  -z        : gzip format 

detect - Searching files

find / -name somename  -user       : File is owned past times user uname (numeric user ID allowed). -group      : File belongs to grouping gname (numeric grouping ID allowed). -size       : File uses n units of space. c/k/M/G: bytes/Kilobytes/Megabytes/Gigabytes. -name       : Base  of  file  call 

Delete empty file too directories

find -empty -type d -delete detect -empty -type f -delete 
Find each file inwards the electrical flow directory too tell it’s type too grep JPEG files.
find . -type f -exec file {} + | grep JPEG 

Other commands

nm-applet : a applet for network manager. wc        : impress newline, word, too byte counts for each file.  -c       : impress the bytes count.  -l       : impress the lines count.  -w       : impress the give-and-take count. form      : form lines of text files. diff      : compare files line of piece of job past times line. less      : impress data i per page. to a greater extent than      : prints data i per page. caput      : prints foremost 10 lines tail      : prints concluding 10 lines. whatis    : Provides a i line of piece of job description of the commands. which     : locate a command. whereis   : locate the binary, source, too manual page files for a command. locate    : detect files past times call cal       : Display calendar engagement      : Display date. Date command provides multiples options for displaying twenty-four hours too time, really helpful inwards creating backups alongside call having fourth dimension too date. tr        : Converts from smaller to uppercase. tr stands for translate.  -d       : delete characters inwards the text. tee       : saves output inwards file every bit good every bit frontward it. touching     : Create null byte files, mainly used for changing the timestamps of the file. brand      : If your computer program source file call is test.c/cpp, too so you lot tin give notice straight write brand test, this would compile the test.c/cpp program. Remember this it's a faster way. stat      : View detailed data well-nigh a file, including its name, size, concluding modified engagement too permissions. uniq      : Report or omit repeated lines.   -c      : prefix lines past times the number of occurrences. (--count) 

Special Characters

*(asterik)          : H5N1 wildcard used to stand upwards for null or to a greater extent than characters inwards a filename. For example: ls *.txt volition listing all the names ending inwards ".txt" such every bit "file1.txt" too "file23.txt". ?(question mark)    : H5N1 wildcard used to stand upwards for a unmarried grapheme inwards a filename. For instance ls pic?.jpg would correspond "pic1.jpg" too "pic2.jpg" but non "pic24.jpg" or "pic.jpg". [](square brackets) : These are used to specify a hit of values to match. For example, "[0-9]" too "[a-z]". ;(semi colon)       : Command separator that tin give notice live used to run multiple commands on a unmarried line of piece of job unconditionally. &&(double ampersand): Command separator which volition alone run the 2d command if the foremost i is successful (does non render an error.) ||(double pipe)     : Command separator which volition alone run the 2d command if the foremost command failed (had errors). Commonly used to terminate the script if an of import command fails. # (Comments)        : Lines starting fourth dimension alongside a # (with the exception of #!) are comments too volition non live executed. 

Bash

Equality Tests

test      : checks file types too compare values   -d      : cheque if the file is a directory   -e      : cheque if the file exists   -f      : cheque if the file is a regular file   -g      : cheque if the file has SGID permissions   -r      : cheque if the file is readable   -s      : cheque if the file's size is non 0   -u      : cheque if the file has SUID permissions   -w      : cheque if the file is writeable   -x      : cheque if the file is executable 
Example
if essay -f /etc/foo.txt too so 
It tin give notice also live written as
if [ -f /etc/foo.txt ]; too so  --square brackets [] shape test. -- There has to live white infinite surrounding both foursquare bracket 

List of equality tests

Checks equality betwixt numbers

x -eq y         : Check is x is equals to y x -ne y         : Check if x is non equals to y x -gt y         : Check if x is greater than y x -lt y         : Check if x is less than y 

Checks equality betwixt strings

x = y           : Check if x is the same every bit y x != y          : Check if x is non the same every bit y -n x            : Evaluates to truthful if x is non null -z x            : Evaluates to truthful if x is null. ##Check inwards the next way --> if [ -z "$VAR" ]; 

Bash Command Substitution

Command exchange allows the output of a command to supersede the command itself. Command exchange occurs when a command is enclosed every bit follows:
$(command) 
or
`command` 
Bash performs the expansion past times executing command too replacing the command exchange alongside the criterion output of the command, alongside whatever trailing newlines deleted.

Bash Case Modification

Taken from Case Modification
${PARAMETER^} ${PARAMETER^^} ${PARAMETER,} ${PARAMETER,,} ${PARAMETER } ${PARAMETER  } 
These expansion operators modify the instance of the letters inwards the expanded text.
The ^ operator modifies the foremost grapheme to uppercase, the , operator to lowercase. When using the double-form (^^ too ,,), all characters are converted.
The operators too contrary the instance of the given text (in PARAMETER). reverses the instance of foremost missive of the alphabet of words inwards the variable patch reverses instance for all.

Example: Parameter ^

VAR="hack the PLANET"  echo ${VAR^} Hack the PLANET  echo ${VAR^^} HACK THE PLANET 

Example: Parameter ,

VAR="HACK THE PLANET"  echo ${VAR,} hACK THE PLANET  echo ${VAR,,} hack the planet 

Example: Parameter

VAR="hack the PLANET"  echo ${VAR } Hack The pLANET  echo ${VAR  } HACK THE planet 

Bash Programming

Bash For Loop

for i inwards $( ls ); do     echo item: $i done 

Bash If Statement

if [ "foo" = "foo" ]; then        echo human face evaluated every bit true else        echo human face evaluated every bit false fi 

Bash loop thru array of strings

## declare an array variable declare -a arr=("element1" "element2" "element3")  ## instantly loop through the higher upwards array for i inwards "${arr[@]}"    do        echo "$i"        # or do whatever alongside private chemical constituent of the array    done 
The value of the variable whose call is inwards this variable tin give notice live constitute by
echo ${!n} 
For example:
eth0="$(ip -o -4 address | grep eth0 | awk '{print $4}')" wlan0="$(ip -o -4 address | grep wlan0 | awk '{print $4}')" ##eth0 too wlan0 contains the subnet of the eth0 too wlan0.  for interfaces inwards "eth0" "wlan0"  do    ##var would genuinely acquire the value of that variable    var="${!interfaces}"  done 
Sample Output alongside ${!interfaces}:
10.233.113.136/23 
Sample Output alongside ${interfaces}:
eth0 wlan0 

Important Definitions

Information

Confidentiality, Integrity, Availability

We desire our data to
  • be read past times alone the right people (confidentiality).
  • only live changed past times authorized people or processes (integrity)
  • be available to read too utilisation whenever nosotros desire (availability).

Non-repudiation

Non-repudiation is well-nigh ensuring that users cannot deny cognition of sending a message or performing some online activity at some afterwards dot inwards time. For example, inwards an online banking organisation the user cannot live allowed to claim that they didn’t ship a payment to a recipient after the depository fiscal establishment has transferred the funds to the recipient’s account.

Difference betwixt su too sudo

su

Change users or move out superuser. The divergence betwixt “su -” too “su” is that quondam “su -” would switch to the novel user directory. It would also alter the environs variable according to the changed user. Whereas “su” would alone alter the user but volition remain inwards the same directory.
Example: “su -“
root@Kali-Home: # su - bitvijays bitvijays@Kali-Home: $ pwd /home/bitvijays 
Example: “su”
root@Kali-Home: # su bitvijays bitvijays@Kali-Home:/root$ pwd /root 

su -c

Executing command every bit some other user
su -c "command" : Specify a command that volition live invoked past times the musical rhythm out using its -c. 
Example:
su bitvijays -c id uid=1000(bitvijays) gid=1001(bitvijays) groups=1001(bitvijays) 

sudo

Execute a command every bit some other user. The divergence betwixt su too sudo is ‘su’ forces you lot to percentage your root password to other users whereas ‘sudo’ makes it possible to execute organisation commands without root password. ‘sudo’ lets you lot utilisation your ain password to execute organisation commands i.e. delegates organisation responsibleness without root password.

Important File Formats

/etc/passwd

The /etc/passwd file is a colon-separated file that contains the next information:
  • User name
  • Encrypted password
  • User ID number (UID)
  • User’s grouping ID number (GID)
  • Full call of the user (GECOS)
  • User habitation directory
  • Login shell
root:!:0:0::/:/usr/bin/ksh daemon:!:1:1::/etc: bin:!:2:2::/bin: sys:!:3:3::/usr/sys: adm:!:4:4::/var/adm: uucp:!:5:5::/usr/lib/uucp: guest:!:100:100::/home/guest: nobody:!:4294967294:4294967294::/: lpd:!:9:4294967294::/: lp:*:11:11::/var/spool/lp:/bin/false invscout:*:200:1::/var/adm/invscout:/usr/bin/ksh nuucp:*:6:5:uucp login user:/var/spool/uucppublic:/usr/sbin/uucp/uucico paul:!:201:1::/home/paul:/usr/bin/ksh jdoe:*:202:1:John Doe:/home/jdoe:/usr/bin/ksh 

/etc/shadow

The /etc/shadow file contains password too concern human relationship expiration data for users, too looks similar this:
smithj:Ep6mckrOLChF.:10063:0:99999:7:xx: 
As alongside the passwd file, each champaign inwards the shadow file is also separated alongside “:” colon characters, too are every bit follows:
  • Username, upwards to viii characters. Case-sensitive, usually all lowercase. H5N1 direct correspond to the username inwards the /etc/passwd file.
  • Password, thirteen grapheme encrypted. H5N1 blank entry (eg. ::) indicates a password is non required to log inwards (usually a bad idea), too a * entry (eg. :*:) indicates the concern human relationship has been disabled.
  • The number of days (since Jan 1, 1970) since the password was concluding changed.
  • The number of days earlier password may live changed (0 indicates it may live changed at whatever time)
  • The number of days after which password must live changed (99999 indicates user tin give notice move out along his or her password unchanged for many, many years)
  • The number of days to warn user of an expiring password (7 for a total week)
  • The number of days after password expires that concern human relationship is disabled
  • The number of days since Jan 1, 1970 that an concern human relationship has been disabled
  • A reserved champaign for possible hereafter use

/etc/group

The /etc/group file stores grouping data or defines the user groups. There is i entry per line, too each line of piece of job has the next format (all fields are separated past times a colon (:)
cdrom:x:24:john,mike,yummy 
Where,
  • group_name: Name of group.
  • Password: Generally password is non used, thus it is empty/blank. It tin give notice shop encrypted password. This is useful to implement privileged groups.
  • Group ID (GID): Each user must live assigned a grouping ID. You tin give notice run into this number inwards your /etc/passwd file.
  • Group List: It is a listing of user names of users who are members of the group. The user names, must live separated past times commas.

Tips too tricks

Apt-get error?

We oft do mistakes patch updating using apt-get which just leaves us alongside command line of piece of job access to the organisation (GUI messed up). Possibly nosotros unintentionally removed some necessary packages.
In this case, expect for /var/log/apt/history.log, expect for the fourth dimension just about which your organisation was broken. Copy the removed packages which would live inwards the format of
libapt-inst1.5:amd64 (0.9.7.9+deb7u5, 0.9.7.9+deb7u6), apt-utils:amd64 (0.9.7.9+deb7u5, 0.9.7.9+deb7u6). 
To reinstall these packages you lot just demand the bundle call such as
libapt-inst1.5, apt-utils.  *Step1* : Use sed to search for blueprint "), " too supersede it alongside "), \n". This would split the packages past times novel line. Within vi ":%s/), /\n/g" *Step2* : Use cutting -d ":" -f 1 to take away :amd64 too anything after that. *Step3* : Now nosotros stimulate got to acquire them dorsum inwards i line of piece of job rather than multiple lines. Within vi ":%s/\n/ /g" 

Track /etc directory

Etckeeper may live a flake to a greater extent than advanced, too it is used to lay your whole /etc directory nether revision control. To install too initialize it,
apt-get install etckeeper etckeeper init cd /etc git commit -am Initial 
After that, you lot tin give notice run into pending changes inwards /etc past times cd-ing into it too running
git status or git diff 
at whatever time, too you lot tin give notice run into previous, committed changes past times running
git log or git log -p 
You tin give notice override pending changes to whatever file alongside the concluding committed version with
git checkout FILENAME 

ls showing total path

ls -R /path | awk '/:$/&&f{s=$0;f=0} /:$/&&!f{sub(/:$/,"");s=$0;f=1;next} NF&&f{ impress s"/"$0 }' 

Keyboard shortcuts

Moving

Ctrl + a : Move to the start of line. Ctrl + e : Move to the terminate of line. Alt  + b : Move to the start of the electrical flow give-and-take Alft + f : Move to the terminate of the electrical flow give-and-take 

Erasing

Ctrl + w : Cut from cursor to previous whitespace. Ctrl + u : Cut from cursor to the start of line. Ctrl + k : Cut from cursor to the terminate of line. Ctrl + y : Paste the concluding cutting text. 

Window

WinKey + H : Minimize/ Hide the Window WinKey + Up Arrow Key : Maximize the electrical flow windows WinKey + Down Arrow Key : Return to master copy 

Searching History

Search every bit you lot type. Ctrl + r too type the search term; 
Read Command Line Editing for to a greater extent than information.

Awk converting to normal output to csv

A B --> "A","B" awk '{print "\"" $1 "\",\"" $2"\""}' 

Finding most opened upwards ports inwards nmap scan

grep "^[0-9]\+" <nmap file .nmap extension> | grep "\ open\ " | form | uniq -c | form -rn | awk '{print "\""$1"\",\""$2"\",\""$3"\",\""$4"\",\""$5" "$6" "$7" "$8" "$9" "$10" "$11" "$12" "$13"\""}' > test.csv 

cat

When truthful cat sees the string - every bit a filename, it treats it every bit a synonym for stdin. To acquire just about this, nosotros demand to alter the string that truthful cat sees inwards such a way that it all the same refers to a file called -. The usual way of doing this is to prefix the filename alongside a path - ./-, or /home/Tim/-. This technique is also used to acquire just about similar issues where command line of piece of job options clash alongside filenames, so a file referred to every bit ./-e does non appear every bit the -e command line of piece of job selection to a program.

Practice

That was most in all probability a lot of information, to exercise all the it’s ever improve to do some hands on.

Programming, Debugging too Git

Task 1 : Git

Learn git, would advise to do a xv mo tutorial on try.github.com.

Task 2 : Vi/ gcc/ make

Create a pocket-sized computer program using vi alongside syntax on, compile it using gcc using make.

Task 3 : gdb

Debug it using gdb -tui selection to run into the source code, experiment alongside breakpoints, too printing values.
Tip
Track that computer program using git, upload them to a remote server, too so delineate your code, cheque if its the same.

System administration

Task 1 : Login/ Logout Messages

Change the messages earlier login, after login. Remember the escapes sequences used inwards the /etc/issue. homo agetty lists them.

Task 2 : Gather Information

Supposed you lot got access via musical rhythm out to a linux organisation too extract some data from it. Create a script.

Task 3 : Add User

  • Create a Alice, Bob, even alongside the password “password” HINT: laid password using chpasswd, expect some examples inwards google to alter from cmdline.
  • Login from eve
  • Copy too preserve all the configuration files from /etc too salvage it inwards even habitation directory inwards the folder etc-backup-YYYYMMDD, direct all errors to cp.err
  • Change the possessor of all the files inwards the folder just created to Bob too the grouping of all the files to Alice too alter the permission of all the files to 440 i.e r–r—– HINT: would stimulate got to live logined every bit root
  • Provide me all the unique shells used past times the user introduce inwards the organisation inwards CAPS. HINT: /etc/passwd file contains all the shells, 3 4 commands would live used.
  • Cover your tracks, clear out the /var/log/auth.log (Have a expect at this file too create a backup earlier clearing), construct clean your terminal history HINT: homo pages would assistance you.
  • Delete all the user Bob, Alice, eve. Make certain you lot delete their files too.
  • Turn off the ping responses for your organisation permanently too plough on the Syn-cookies protection mechanism. {Search on Google}
  • Use your previous script to create 3 users Alice, Bob, eve.
  • create a folder dept within it 2 folder hr, web.
  • create 2 grouping hr too web.
  • change grouping of spider web folder to spider web too hr to hr.
  • add Alice too Bob user to spider web group
  • add Alice to hr group.
  • check that Bob is non able to move inwards in the hr folder too Alice is able to move inwards in both hr too spider web folder
  • add user Bob to sudo grouping too cheque if it is able to run sudo ifconfig ?

Bash Scripting

Task 1 : Gather IP Addresses

Objective to acquire few IP addresses of Microsoft.com Domains.
  • Download the index.html page of microsoft.com
  • Every link inwards html is referred past times href. Filter all the href (which would comprise the link to dissimilar domains for Microsoft)
  • Sort too detect unique list. Get their ip addresses
  • HINT: Tools such every bit cut, grep, wget, sort, uniq, host too footling flake of bash scripting would live used.

Interesting Stuff

Blogger
Disqus
Pilih Sistem Komentar

No comments

Advertiser