Linux
Notes for Professionals
Detecting Linx cistribution
on
sens § Check tk Spo
Scanned with CamScannerContents
About
Chapter 1: Getting started with GNU/Linux ..
Section 1, Useful shortcuts
Section 12: File Management
Section 13: Hello World
Section 1.4 Basic Linux Utilities .
Section 15: Searching for files by patterns in nome/contents
Section 16 File Menipuiation o .
Section 17: File/Directory details . : 8
Chapter 2: Detecting Linux distribution name and version "
on 2% wh nt rking in
tion wh jt rtuution in
Section 23: Detect what RHEL / CentOs / Fecora distribution you are working in.
Section 2.4: Unome - Print Information about the current system .
Section 25: Detect basic information about your distro
Section 26. Using GNU coreutils
Section 27. Find your linux os (both debion & rpm) name and release number
Chapter 3: Getting information on a running Linux kernel
jon 311 Getting details of Linux kern
Chapter 4: Shell
ion 4.1 Changin i
Section 42: Basic Shell Utlities
Section 4.3. Create Your Own Command Allas
Section 44: Locate o file on your system
Chapter 5: Check Disk Space
Section 51 Investigate Directories For Disk Usage ... . . 19
Section 5.2: Checking Disk Space a
Chapter 6: Getting System Information :
Section 61: Statistics about CPU, Memory, Network and Disk (I/O operations) ..
Section 62: Using tools like Iscpu ond Ishw ..
Section 63 List HOrdWOLe nines
tion 64: Find CPU m informat
‘Section 65: Process monitoring and information gathering ..
Chapter 7: Is command
tion 7.1: Options for Is comman
on 7.2: Is command with mé
Chapter 8: File Compression with ‘tar! command
on 8: Compress a folder
‘Section 82: Extract o folder from an archive
‘Section 83:List contents of cn archive ..
‘Section 8.4: List archive content
Section 85: Compress and exclude one or multiple folder
Section 86: Strip leading components
Chapter 9: Services
Scanned with CamScannerChapter 10: Managing Services .
Section 10.1: Diagnosing ¢ problem with a service .. ceininssooeason essen “ 33
Section 1 ingon
ion 103: Getting the
Section 111 Seiting your own password
Section 112: Setting another user's password
Section 113: Adding a user .. sen
Section 114: Removing a user . “
Section 115: Removing a user and its home folder . : 35
ion 116 Ls he current users in .
‘Section 117: Listing groups a user is in
Chapter 12: LAMP Stack
Section 121 installing LAMP on Arch Linux
Section 122: installing LAMP on Ubuntu
Section 123: installing LAMP stack on Cento0S 6... ‘ '
Section 131: Write output to stdout, and elso to file
Section 13.2: Write output from the middle of a pipe chain to a file and pass it back to the pipe
on 13.3: wr le fi
on 13.4 ins rmman
Chapter 14: Secure Shell (SSH)
Section 141: Connecting to « remote server ..
tion 14.2: installin cH
‘Section 14.3 Configuring an SSH server to accept connections
‘Section 14.4: Passworcless connection (using a key pair)
Section 145: Generote public and private ket
jection 146: Disoble ssh service
Chapter 15: SCP
‘Section 151: Secure Coot
Section 15.2: Bosic Usage ..
Chapter 16: GnuPG (GPG)
Section 164: li ir public ke
Section 162: Create and use a GnuPG key quickly ..
Chapter 17: Network Configuration
Section 171; Local DNS resolution
tion 17,2: Configure DNS rs for domain name resolution
Section 173: See ond manipulate routes
tion 17.4: Configure @ hostname for
Section 175: interface details
Section 17,6: Adding | re
‘Section 18.2: Midnight Commander function keys in file editing mode 5452)
Chapter 19: Change root (chroot:
lon 191: Requirement
on 19.2: Manually changing
on 193: Reason’ hr
Chapter 20: Package Managers ...... Bie mint 56.
Scanned with CamScannerSection 201: How to update packages with the apt package manager ... . 56
Section 202: How to install c package with the pacman package manager .. 56
Section 203: How to updote packages with the pacman package manager 56
on 204: Hi m ith yur
Chapter 21: Compiling the Linux kernel
Hon 211: Compl f Linux 19 bunt
Credits
You may also like .. 61
Scanned with CamScannerAbout
Please feel free to share this PDF with anyone for free,
latest version of this book can be downloaded from:
‘Jigoalkicker.com/LinuxBook
This Linux® Notes for Professionals book is compiled from Stack Overflow
Documentation, the content is written by the beautiful people at Stack Overflow.
Text content is released under Creative Commons BY-SA, see credits at the end
of this book whom contributed to the various chapters. Images may be copyright
of their respective owners unless otherwise specified
This is an unofficial free book created for educational purposes and is not
affliated with official Linux® group(s) or company(s) nor Stack Overflow. All
trademarks and registered trademarks are the property of their respective
company owners
‘The information presented in this book is not guaranteed to be correct nor
accurate, use at your own risk
Please send feedback and corrections to
[email protected]
Goalkicker.com - Linux® Notes for Professionals
Scanned with CamScannerChapter 1: Getting started with GNU/Linux
Section 1.
Useful shortcuts
Using The Terminal
‘The examples in this document assume that you are using a POSIX-compliant (such as bash, sh, zsh, ksh)
shell
Large portions of GNU/Linux functionality are achieved using the terminal. Most distributions of Linux include
terminal emulators that allow users to interact with a shell from their desktop environment. A shell is a command-
line interpreter that executes user inputted commands. Bash (Bourne Again SHell) is a common default shell
among many Linux distributions and is the default shell for macs.
‘These shortcuts will work if you are using Bash with the emacs keybindings (set by default):
Open terminal
+ [etd + Alt + T Jor[ Super + T
Cursor movement
+ [GEFIT_+-A Jo to the beginning of the line you are currently typing on
+ [Ctrl + E |Goto the end of the line you are currently typing on.
+ [Ctrl + XX ] Move between the beginning of the line and the current position of the cursor.
+ [Alt_+ F | Move cursor forward one word on the current line.
+ [AIt_+ B | Move cursor backward one word on the current line,
+ [Ctrl + F | Move cursor forward one character on the current line.
+ [Ctrl + B | Move cursor backward one character on the current line.
‘Text manipulation
+ [CET +0 ] cut the line from the current position to the beginning of the line, adding it to the clipboard. if
you are at the end of the line, cut the entire line.
+ [tri + K ] cut the line from the current position to the end of the line, adding it to the clipboard. if you
are at the beginning of the line, cut the entire line.
+ [Ctri + W Delete the word before the cursor, adding it to the clipboard
+ [Ctrl + ¥ | Paste the last thing from the clipboard that you cut recently (undo the last delete at the
current cursor position).
+ [AIE+T J swap the last two words before the cursor.
+ [ALt_+ L | Make lowercase from cursor to end of word.
+ [AIt_+ U] Make uppercase from cursor to end of word.
+ [ALt_+ C | Capitalize to end of word starting at cursor (whole word if cursor is at the beginning of word).
+ [Alt + D | Delete to end of word starting at cursor (whole word if cursor is at the beginning of word).
+ [Alt + ]Prints the last word written in previous command.
« [Ctrl + T ]wap the last two characters before the cursor.
History access
+ [Ctrl + 8 ]Lets you search through previously used commands.
+ [Ctrl + G |Leave history searching mode without running a command
. Lets you copy current matched commans to command line without running it, allowing you to
Goalkicker.com ~ Linux® Notes for Professionals 2
Scanned with CamScannermake modifications before running the command.
«+ [ATE# RJ Revert any changes to a command you've pulled from your history, if you've edited it
. Shows last executed command, ie. walk back through the command history (Similar to up
arrow).
+ [CeFI_+ W] shows next executed command, Le. walk forward through the command history (Similar to
down arrow).
Terminal control
+ [CET +E | Clears the screen, similar to the clear command.
+ [Ctr +S |stop all output to the screen. This is useful when running commands with lots of long output.
But this doesn't stop the running command,
+ [Ctr +0] Resume output to the screen after stopping it with Ctrl+S.
+ [Ctrl + C JEnd currently running process and return the prompt.
+ [Ctrl + D ]Log out of the current shell session, similar to the exit or logout command. In some commands,
acts as End of File signal to indicate that a file end has been reached,
+ [Ctri +7 | suspends (pause) currently running foreground process, which returns shell prompt. You can
then use bg command allowing that process to run in the background. To again bring that process to
foreground, use fg command. To view all background processes, use jobs command.
+ [Tab ]Auto-complete files and directory names.
+ [Tab_ Tab ] shows all possibilities, when typed characters doesn't uniquely match to a file or directory
name.
Special characters
+ [Ctrl +H |same as Backspace.
+ [Ctrl + J |Same as Return (historically Line Feed).
+ [Ctrl + M |Same as Return (historically Carriage Return).
+ [Ctrl + I |Sameas Tab.
+ [Ctrl + 6 |Bell Character.
+ [etrl + @ |Null Character.
«+ [Ese ]Deadkey equivalent to the [AIt | modifier.
Close Terminal
+ [Gtr + Shift _+ W_]To close terminal tab.
+ [Ctrl + Shift + 0 |To close entire terminal.
Alternatively, you can switch to the vi keybindings in bash using set -o vi. Use set -o emacs to switch back to the
emacs keybindings.
Section 1.2: File Management Commands
Linux uses some conventions for present and parent directories. This can be a little confusing for beginners.
Whenever you are in a terminal in Linux, you will be in what is called the current working directory. Often your
command prompt will display either the full working directory, or just the last part of that directory. Your prompt
could look lke one of the following:
useréhost ~/sonedir §
user@host somedir $
user@host /hone/user/somedir $
which says that your current working directory is shome/user /somedir.
Goalkicker.com ~ Linux® Notes for Professionals 3
Scanned with CamScannerIn Linux... represents the parent directory and. represents the current directory.
‘Therefore, if the current directory is /home/user /somedir, then ed. /somedir will not change the working
directory.
The table below lists some of the most used file management commands
Directory navigation
Command utility
pwd Get the full path of the current working directory.
ed - Navigate to the last directory you were working in.
‘ed ~ or just ed Navigate to the current user's home directory.
ed. Go to the parent directory of current directory (mind the space between ed and . .)
Listing files inside a directory
‘Command utility
List the files and directories in the current directory in long (table) format (itis recommended to
use -I with Is for better readability).
As 1d dir-nane List information about the directory dir-nane instead of its contents.
As
As -a List all the files including the hidden ones (File names starting with a . are hidden files in Linux).
ane ‘Appends a symbol at the end of a file name to indicate its type (+ means executable, / means
Girectory, @ means symbolic link, = means socket, | means named pipe, > means door).
es List the files sorted by last modified time with most recently modified files showing at the top
(remember -| option provides the long format which has better readability).
As -Ih List the file sizes in human readable format.
As -IR Shows all subdirectories recursively.
tree Will generate a tree representation of the file system starting from the current directory.
File/directory create, copy and remove
Command utility
Will copy the file from source to destination. -p stands for preservation. It
©p -p source destination _preserves the original attributes of file while copying like file owner, timestamp,
group, permissions etc.
cp -R source dir
aooae Will copy source directory to specified destination recursively.
acetates In Linux there is no rename command as such. Hence mv moves/renames the
filet to file2,
‘Asks you before every file removal for confirmation. IF YOU ARE A NEW USER
rm -i filenane TO LINUX COMMAND LINE, YOU SHOULD ALWAYS USE rn ~i. You can specify
multiple files.
rm -R dir-none Will remove the directory dir-name recursively.
Will remove the directory dir recursively, ignoring non-existent files and will
rm -rf dir-name never prompt for anything. BE CAREFUL USING THIS COMMAND! You can
specify multiple directories.
Will remove the directory dir-name, if it's empty. This command can only remove
empty directories.
mkdir dir-nane Create a directory dir-name.
rmdir dirname
Create a directory hierarchy. Create parent directories as needed, if they don't
mkdir -p dir-name/dir-name ict You can specify multiple directories.
Create a fle Filename, if it doesn't exist, otherwise change the timestamp of the
touch filename
file to current time.
File/directory permissions and groups
‘Command Utility
Goalkicker.com - Linux® Notes for Professionals 4
Scanned with CamScannerChange the file permissions. Specifications = u user, 9 group, o other, + add
chnod
filename
permission, ~ remove, r read, w write,x execute,
chmod -R dir- Change the permissions of a directory recursively. To change permission of
name a cirectory and everything within that directory, use this command.
chmod go=+r myfile ‘Add read permission for the owner and the group.
chmod a +rwx myFile Allow all users to read, write or execute myfile,
chmod go -r myfile Remove read permission from the group and others.
chown ownert filename Change ownership of a file to user onnert
charp grp-owner filenane Change primary group ownership of file filename to group grp_owner.
Change primary group ownership of directory dir-nane to group grp_owner
charp -R grp_owner dir-nane recursively. To change group ownership of a directory and everything within
that directory, use this command,
Section 1.3: Hello World
‘Type the following code into your terminal, then press[ Enter
echo "Hello World
This will produce the following output:
Hello World
Section 1.4: Basic Linux Utilities
Linux has a command for almost any tasks and most of them are intuitive and easily interpreted.
Getting Help in Linux
command Usability
Read the manual page of .
Read the manual page of , related to the given section.
man -k Cutput all the software whose man pages contain keyword,
man -K Cutputs all man pages containing within them,
Cutput all the applications whose one line description matches the word editor.
Se ReeeOTTTS When not able to recall the name of the application, use this command,
help In Bash shell, this will display the list ofall available bash commands.
help In Bash shell, this will display the info about the bash command.
info View all the information about .
dpkg -1 Cutput a list of all installed packages on a Debian-based system
dpkg -L packageNane Will list out the files installed and path details for a given package on Debian.
‘dpkg -1 | grep -i —_Returnall .deb installed packages with irrespective of cases.
ess /var/1ib/dpkg/available Return descriptions of all available packages.
whatis vim List a one-line description of vim.
Display usage information about the . Sometimes command -h also
works, but not for all commands.
--help
User identification and who is who in Linux world,
Command Usability
hostname Display hostname of the system.
Goalkicker.com = Linux® Notes for Professionals 5
Scanned with CamScannerhostname -f Displays Fully Qualified Domain Name (FQDN) of the system.
pessnd Change password of current user.
whoasi_ —_Username of the users logged in at the terminal.
who List of all the users currently logged in as a user.
Display current system status, time, duration, ist of users currently logged in on system and other
user information.
last Who recently used the system.
ast root When was the last time root logged in as user.
Jastb Shows all bad login attempts into the system.
chmod Changing permissions - read,write execute of a file or directory.
Process related information
Command Usability
List all processes sorted by their current system resource usage. Displays a continually updated
mm display of processes (By default 3 seconds). Use q key to exit top.
ps List processes currently running on current shell session
Ps -U root List all ofthe processes and commands root is running
Ps aux List all the processes by ll users on the current system
Section 1.5: Searching for files by patterns in name/contents
Acommon and task of someone using the Linux Command Line (shell) is to search for files/directories with a
certain name or containing certain text. There are 2 commands you should familiarise yourself with in order to
accomplish this:
Find files by name
find /var/wwm -name ‘+.css
This will print out the full path/filename to all files under /var/www that end in .css. Example output:
Ivar /wen/htmil/text-cursor.css
Ivar /wenshtml/style.css
For more info:
man find
Find files containing text
‘grep font /var/ww/html/style.css
This will print all lines containing the pattern font in the specified file. Example output:
font-weight: bold;
font-family: monospace;
Another example:
grep font /var/wwa/html/
Goalkicker.com = Linux® Notes for Professionals
Scanned with CamScannerThis doesn’t work as you'd hoped. You get:
‘grep: /var/wew/html/: Ts a directory
You need to grep recursively to make it work, using the -R option:
‘grep -R font /var/wen/html/
Hey nice! Check out the output of this one:
Ivar twew/htm1/admin/index.php: echo ‘Erro!
Ivar /wen/html/admin/index.php: echo ‘Erroi
Ivarfwmshtml/style.css: font-weight: bold;
Ivar/wen/html/style.css: font-family: monospace;
no dicee/b>ebr/>
: try againe/b>
";
Notice that when grep is matching multiple files, it prefixes the matched lines with the filenames. You can use the -
h option to get rid of that, if you want.
For more info:
man grep
Section 1.6: File Manipulation
Files and directories (another name for folders) are at the heart of Linux, so being able to create, view, move, and
delete them from the command line is very important and quite powerful. These file manipulation commands allow
you to perform the same tasks that a graphical file explorer would perform.
Create an empty text file called myFil
‘touch myFile
Rename myFile to myFirstFile:
av myFile myFirstFile
View the contents of a file:
cat myFirstFile
View the content of a file with pager (one screenful at a time)
myFirstFile
View the first several lines of a file:
head myFirstFile
View the last several lines of a file:
‘tail myFirstFile
Edita file:
Goalkicker.com ~ Linux® Notes for Professionals, 7
Scanned with CamScannervi myFirstFile
See what files are in your current working directory:
1s
Create an empty directory called myFirst0irectory:
mkdir myFirstDirectory
Create multi path directory: (creates two directories, src and myFirstDirectory)
kdir -p sre/nyFirstDirectory
Move the file into the directory:
av ayFirstFile myFirstDirectorys
You can also rename the file:
user€linux-conputer:~$ av myFirstFile secondFileNane
Change the current working directory to myFirstDirectory:
ed myFirstDirectory
Delete a file:
ra myFirstFile
Move into the parent directory (which is represented as . .):
ed
Delete an empty directory:
radir nyFirstDirectory
Delete a non-empty directory (i.e. contains files and/or other directories):
ra -rf ayFirstDirectory
‘Make note that when deleting directories, that you delete . / not / that will wipe your whole filesystem.
Section 1.7: File/Directory details
The 1s command has several options that can be used together to show more information.
Details/Rights
The 1 option shows the file permissions, size, and last modified date. So if the root directory contained a dir called
test and a file someFile the command:
Goalkicker.com ~ Linux® Notes for Professionals
Scanned with CamScanneruser@linux-computer~§ 1s -1
Would output something like
r-- Luser users 70 Jul 22 13:36 soneFile. txt
druxrwxrwx 2 user users 4096 Jul 21 07:18 test
‘The permissions are in format of drwxrwxrwx. The first character represents the file type ¢ ifit’s a directory -
otherwise. The next three rwx are the permissions the user has over the file, the next three are the permissions the
group has over the file, and the last three are the permissions everyone else has over the file.
‘The © of rwx stands for if file can be read, the w represents if the file can be modified, and the x stands for if the
file can be executed. If any permission isn't granted a - will bein place of r, w, or x.
So from above user can read and modify soneFile. txt but the group has only read-only rights.
To change rights you can use the chaod ### FileName command if you have sudo rights. ris represented by a
value of 4, mis represented by 2, and x is represented by a 1. So if only you want to be able to modify the contents
tothe test directory
Owner rwx = 44241 = 7
Group r-x = 440#1 = 5
Other r-x = 4+0+1 = 5
So the whole command is
chnod 755 test
Now doing a 1s -1 would show something like
drwxr-xr-x 2 user users 4996 Jul 21 07:20 test
Readable size
Used in conjunction with the 1 option the h option shows file sizes that are human readable. Running
user@Linux-computer :~$ 1s -1h
Would output:
total 4166
stw-r--r-- user users 79 Jul 22 13:36 someFile.txt
rwxrwarwx 2 user users 4.0K Jul 21 07:18 test
Hidden
To view hidden files use the a option. For example
user@linux-computer:~$ 1s ~
Might list
Goalkicker.com = Linux® Notes for Professionals 9
Scanned with CamScanner-profile
someFile.txt
test
Total Directory Size
To view the size of the current directory use the s option (the h option can also be used to make the size more
readable)
user@linux-computer~$ 1s -s
Outputs
total 4166
someFile. txt test
Recursive View
Lets say test directory had a file anotherFile and you wanted to see it from the root folder, you could use the R
option which would list the recursive tree.
user@linux-computer :~$ 1s -R
Outputs
someFile.txt test
-Itest:
anotherFile
Goalkicker.com - Linux® Notes for Professionals
Scanned with CamScanner
70Chapter 2: Detecting Linux distribution
name and version
Section 2.1: Detect what debian-based distribution you are
working in
Just execute 1sb_release ~
On Debian:
$ Isb_release -2
No LSB modules are available.
Distributor ID: Debian
Description: Debian GNU/Linux testing (stretch)
Release: testing
Codenane stretch
(On Ubuntu:
$ Isb_release -2
No LSB modules are available.
Distributor ID: Ubuntu
Description: Ubuntu 14.04.4 LTS
Release: 14.04
Codename trusty
In case when you don't have 1sb_release installed you may want to try some guessing, for example, there is a file
Jetc/issve that often contains distribution name. For example, on ubuntu:
$ cat fetc/issue
Ubuntu 12.04.5 LTS \n \1
Don't use file /ete/debian_version because its contents do not match distribution name!
Note that this will also work on non-Debian-family distributions like Fedora, RHEL, or openSUSE — but that 1sb_release
‘may not be installed.
Section 2.2: Detect what systemd-based distribution you are
using
This method will work on modern versions of Arch, CentOS, CoreOS, Debian, Fedora, Mageia, openSUSE, Red Hat
Enterprise Linux, SUSE Linux Enterprise Server, Ubuntu, and others. This wide applicability makes it an ideal as a
first approach, with fallback to other methods if you need to also identify older systems.
Look at /ete/os-release. in specific, lok at variables NAME, VERSTON, 1D, VERSTON_TO, arid PRETTY NAME.
(On Fedora, this file might look like:
NAME=Fedora
VERSION="24 (Workstation Edition)"
I0=fedora
VERSTON_1D=24
PRETTY_NAME="Fedora 24 (Workstation Edition)”
ANST_COLOR="8;34
Goalkicker.com = Linux® Notes for Professionals 1
Scanned with CamScannerCPE_NAME= "cpe:/o:fedoraproject :fedora:24"
HOME_URL="https://fedoraproject.org/*
‘BUG_REPORT_URL="https://bugzilla.rechat.com/~
REDHAT_BUGZTLLA_PRODUCT="Fedor:
REDHAT_BUGZILLA_PRODUCT_VERSION-24
REDHAT_SUPPORT_PRODUCT= "Fedora
REDHAT_SUPPORT_PRODUCT_VERSION=24
PRIVACY POLICY_URL=https://fedoraproject .org/wiki/Legal :PrivacyPolicy
VARTANT="Workstation Edition®
VARIANT ID=workstation
On CentOS, this file might look like this:
NAME="CentOS Linux”
VERSION="7 (Core)"
ID="centos”
ID_LIKE="rhel fedora”
VERSION_ID="7
PRETTY_NAME="CentOS Linux 7 (Core)”
ANST_COLOR="@;31"
(CPE_NAME="cpe: /o:centos :centos:7
HOME_URL="https://wwn.centos.org/"
‘BUG_REPORT_URL="https://bugs.centos.org/*
CENTOS_MANTISBT_PROJECT="Cent0S-7’
‘CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCTs "centos’
REDHAT_SUPPORT_PRODUCT_VERSION="7"
This file is documented on the freedesktop web site; in principle, itis not systemd specific — but it will exist on all
systemd-based distributions.
From the bash shell, one can source the /ete/os-release file and then use the various variables directly, like this:
$ ( source /etc/os-release && echo “SPRETTY NAME" )
Fedora 24 (Workstation Edition)
Section 2.3: Detect what RHEL / CentOS / Fedora distribution
you are working in
Look at the contents of /ete/redhat-release
cat /etc/rechat-release
Here is the output from a Fedora 24 machine: Fedora release 24 (Twenty Four)
‘As mentioned in the debian-based response, you can also use the 1sb_re!
from a Fedora 24 machine:
-a command, which outputs this
LSB Version: :core-4.1~amd64:core-4.1-noarch :exx-4.1-and64:cxx-4.1-noarch :desktop-4.1-
and64:desktop-4.1-noarch :languages~4.1-and64languages-4.1-noarch:printing-4.1-amd64:printing-4.1-
noarch
Distributor 1D: Fedora
Description: Fedora release 24 (Twenty Four)
Release: 24
Codenane: TwentyFour
Goalkicker.com - Linux® Notes for Professionals 2
Scanned with CamScannerSection 2.4: Uname - Print information about the current
system
Uname is the short name for unix name. Just type uname in console to get information about your operating
system.
uname [OPTION]
If no OPTION is specified, unane assumes the -s option.
~a or --211 - Prints all information, omitting -p and + if the information is unknown.
Example:
Sun0S hope 5.7 Generic 106541-08 sun4m sparc SUNN, SPARCstation-10
All the options:
, ~-kernel-name Print the kernel name.
-n,-nodename Print the network node hostname.
~kernel-release Print the kernel release.
kernel-version Print the kernel version.
-m,~machine Print the machine hardware name.
-P. processor Print the processor type, or "unknown.
-i, -hardware-platform Print the hardware platform, or "unknown"
-0, ~operating-system Print the operating system.
~help Display a help message, and exit.
~version Display version information, and exit.
Section 2.5: Detect basic information about your distro
just execute uname -2.
On Arch:
$ uname -a
Linux nokia 4.6.4-1-ARCH #1 SMP PREEMPT Mon Jul 11 19:12:32 CEST 2016 x86_64 GNU/Linuxenter
cade here
Section 2.6: Using GNU coreutils
So the GNU coreutils should be avaialable on all linux based systems (please correct me if | am wrong here).
if you do not know what system you are using you may not be able to directly jump to one of the examples above,
hence this may be your first port of call.
$ uname -a
On my system this gives me the following.
Linux Scibearspace 3.16.0-4-and64 #1 SMP Debian 3,16.7-ckt25-2+debu3 (2016-07-02) x86_64
Goalkicker.com - Linux® Notes for Professionals Fe
Scanned with CamScannerGNU/Linux
Here you can see the following :
Scibearspace : the name of my pc
‘+ Scibearspace : the name of my pc
+ 3.16.0-4-amd64 : the kernel and architecture
‘* SMP Debian 3.16.7-CKT25-2+deb8u3 : tells me | am running debian with the 3.16 kernel
‘* Finaly the last part | am running debian 8 (update 3).
| would welcome any others to add in results for RHEL, and SuSe systems.
Section 2.7: Find your linux os (both debian & rpm) name and
release number
Most of linux distros stores its version info in the /etc/Isb-release (debian) or /etc/redhat-release (RPM based) file.
Using below generic command should get you past most of the Debian and RPM derivatives as Linux Mint and
Cent-Os,
Example on Ubuntu Machine:
cat Jetc/#release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=14.04
DISTRIB_CODENAME=t rusty
DISTRIB_DESCRIPTION="Ubuntu 14.04 LTS"
Goalkicker.com - Linux® Notes for Professionals 4
Scanned with CamScannerChapter 3: Getting information ona
running Linux kernel
Section 3.1: Getting details of Linux kernel
We can use command uname with various options to get complete details of running kernel,
Linux dfl-ws-5084 4.4.0-64-generic #85-Ubuntu SMP Mon Feb 20 11:50:36 UTC 2017 x86_64
x86_64 x86_64 GNU/Linux
‘As per man page here few more options
Usage: uname [OPTION),
Print certain system information. With no OPTION, same as -s.
except omit -p and -i if
-n,
of
-m,
“Pr
--help
--version
(useful in cases
history | grep myhardware.html
$ sudo Ishw -xml > myhardware.xml
To show PCI info
$ Aspei -tv
Goalkicker.com = Linux® Notes for Professionals 2
Scanned with CamScannerTo see USB info
$ lsusb -tv
To display BIOS information
$ dmidecode -q | less
To see specific information about disk (disk sda in example) you can use:
$ hdparm -i /dev/sda
Few additional utilties/commands will help gather some extra information:
§ smartetl -A /dev/sda | grep Power-On Hours # How long has this disk (system) been powered on in
total
$ hdparm -tT /dev/sda # Do a read speed test on disk sda
§ badblocks -s /dev/sda # Test for unreadable blocks on disk sda
Section 6.4: Find CPU model/speed information
Ubuntu:
$ cat /proc/cpuinfo
Sample Output:
processor: 0
vendor_id : GenuineIntel
cpu family 6
model 215
model name : Intel(R) Core(TM)2 Quad CPU 96600 @ 2.4GHz
stepping: 11
cpu Maz 1 1596.000
cache size 4096 KB
physical id 8
siblings
core id
cpu cores
apicid
initial apicid °
fpu yes
fpu_exception —: yes
cpuid level: 10
wp byes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cnov pat pse36 clflush dts
acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx Im constant_tsc arch_perfmon pebs bts rep_good pni
dtes64 monitor ds_cpl vmx est tm2 ssse3 cx16 xtpr pdem Lahf_Im tpr_shadow vnmi flexpriority
bogonips —: 4800.18
clflush size: 64
cache_alignnent —: 64
address sizes: 36 bits physical, 48 bits virtual
Power nmanagenent:
processor
3
vendor_id GenuineIntel
cpu family 6
Goalkicker.com ~ Linux® Notes for Professionals 2B
Scanned with CamScannermodel 115
model name Intel(R) Core(TM)2 Quad CPU 06608 @ 2.40GHz
stepping: 11
cpu Miz 1596. 008
cache size 4096 KB
Physical id
siblings
core id
cpu cores
apicid
initial apicid 3
fpu yes
fpu_exception : yes
cpuid level: 10
wp yes
flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cnov pat pse36 clflush dts
‘acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx lm constant_tsc arch_perfmon pebs bts rep good pni
dtes64 monitor ds_cpl vmx est tm2 ssse3 cxl6 xtpr pdem lahf_Im tpr_shadow vnmi flexpriority
bogomips —: 4800.30
clflush size: 64
cache alignment —: 64
address sizes: 36 bits physical, 48 bits virtual
Power managenent:
count processor (including cores):
$ grep -c processor /proc/cpuinfo
Section 6.5: Process monitoring and information gathering
Overall you have two ways to monitor processes at linux host
Static monitoring
Most widely used command is ps (ie., process status) command is used to provide information about the currently
running processes, including their process identification numbers (PIDs).
Here few useful options to gather specific information.
List processes in a hierarchy
$ ps -e -0 pid,args --forest
List processes sorted by % cpu usage
§ ps -e 0 pepu, cpu,nice, state, cputime, args --sort pepu | sed '/* 8.0 /c"
List processes sorted by mem (KB) usage.
$ ps -e -orss=,args= | sort -b -k1,1In | pr ~TWSCOLUMNS.
List all threads for a particular process ("firefox-bin" process in example )
$ ps -C firefox-bin -L -o pid, tid, pcpu, state
After finding specific process you can gather information related to it using 1sof to list paths that process id has.
open
Goalkicker.com = Linux® Notes for Professionals 26
Scanned with CamScanner$ lof -p $8
Or based on path find out list processes that have specified path open
$ Isof ~
Interactive monitoring
Most commonly known tool for dynamic monitoring is:
$ top
‘That mostly default commang that have huge amount options to filter and represent information in real time (in
comparison to ps command.
Still there are more advance options that can be considered and installed as top replacement
$ htop -¢ 5
or
$ atop
‘Which has ability to log all the activities into log file (default atop will log all the activity on every 600 seconds) To this,
list there are few specialised commands as iotop or iftop
§ sudo 1otop
Goalkicker.com = Linux® Notes for Professionals 7
Scanned with CamScannerChapter 7: ls command
Section 7.1: Options for Is command
Full list of options:
Ls -a istall files including hidden file starting with
As ~-color colored list [-always/never/auto]
1s -d list directories - with ' */"
1s -F add one char of */=>@| to enteries
Ls ~1 list file's inode index number
As -1 list with long format - show permissions
1s ~Ia list long format including hidden fles
1s ~1hlist long format with readable fie size
Ls -1s list with long format with file size
As -rlistin reverse order
As -Rlist recursively directory tree
1s -slistflle size
As -S sort by file size
As -t sort by time & date
1s -Xsort by extension name
Section 7.2: ls command with most used options
Is shows files and directories in present working directory. (if no arguments are passed.) It doesn't show hidden
files which starts with . by default.)
user@ubuntu14:/usr$ 1s
bin games include lib 1ib32 local sbin share src
To see all files (hidden files/folders also). Use 1s -a OR 1s -all
user@ubuntu14:/usr§ 1s -2
bin games include 1ib 1ib32 local sbin shere sre
To differentiate between files and folders and symbolic links and other, use 1s -F OR Is --classify
usereubuntul4:-$ Is -F
bash_profile_course chat_apps/ Desktop/ Downloads/__foxitsoftware/
Public/ test/ _bin/_ClionProjects/ Documents/ IDE/_—Music/
Pictures/ Templates/ Videos/
Goalkicker.com - Linux® Notes for Professionals, 28
Scanned with CamScannerHere, ending characters are used to distinguish files and folders.
“P suggest directory.
“suggest executables.
“@” suggest symbolic links.
To get more details about the files and directories, use 1s -1
user@ubuntu14:~/exanple$ 1s
total 6464
ower 1 dave dave 41 Dec 24 12:19 Z.txt
drwxr-xr-x 2 user group 4896 Dec 24 12:08 a_directory
-rwer 1 user group 6 Dec 24 12:61 a file
Lrwxrwxrwx 1 user group 6 Dec 24 12:04 a link -> a file
crw-r--r-- 1 user group 6 Dec 24 12:€3 a_newer file
orwer 1 user group 6586816 Dec 24 12:07 big.zip
In this example, the total size of the contents is 6460KB.
‘Then there is an entry for each file/directory in alphabetical order with upper case before lower case.
‘The first character is the type (e.g. d - directory, | - link).
The next 9 characters show the permissions for the user, group and other.
This is followed by the number of hard links, then the owner's name and group.
‘The next field is the size in bytes. This can be displayed in a human friendly form by adding the -h option e.g.
6586816 is displayed as 6.3M
There then follows a timestamp (usually the modification time).
‘The final field is the name. Note: links also show the target of the link,
Goalkicker.com ~ Linux® Notes for Professionals
Scanned with CamScanner
29Chapter 8: File Compression with ‘tar’
command
Common Options -
-c~create Create a new archive.
“x -extract Extract files from an archive.
atolist List the contents of an archive.
-f -file=ARCHIVE Use archive file or dir ARCHIVE.
~v-verbose Verbosely lst files processed.
Compression Opt
-a~auto-compress Use archive suffix to determine the compression program.
~bzip2 Filter the archive through bzip2.
~xz~lama Filter the archive through x2.
-2-g2ip Filter the archive through gzi
Section 8.1: Compress a folder
This creates a simple archive of a folder
ter -cf .Jay-archive.ter . /my-folder/
Verbose output shows which files and directories are added to the archive, use the -v option:
tar -ovf ./ny-archive.tar ./my-folder/
For archiving a folder compressed ‘gzip’, you have to use the -2 option :
tar -czf ./my-archive.tar.gz ./my-folder/
You can instead compress the archive with ‘bzip2’, by using the -j option:
tar -cif ./my-archive.ter.bz2 ./my-folder/
(Or compress with ‘x2’, by using the - option:
tar -cJf ./my-archive.tar.xz ./my-folder/
Section 8.2: Extract a folder from an archive
‘There is an example for extract a folder from an archive in the current location
ter -xf archive-nane. tar
If you want to extract a folder from an archive to a specfic destination
tar -xf archive-nane. tar -C ./directory/destination
Section 8.3: List contents of an archive
List the contents of an archive file without extracting it:
Goalkicker.com = Linux® Notes for Professionals 30
Scanned with CamScannertar -tf archive.tar.oz
Folder-In-Archive/
Folder-In-Archive/file1
Folder-In-Archive/Another-Folder/
Folder-In-Archive/Another-Folder /file2
Section 8.4: List archive content
There is an example of listing content
ter -tvf archive.tar
‘The option -t is used for the listing. For listing the content of a tar.gz archive, you have to use the -z option
anymore :
tar ~tavf archive.tar.gz
Section 8.5: Compress and exclude one or multiple folder
Ifyou want to extract a folder, but you want to exclude one or several folders during the extraction, you can use the
~-exelude option,
tar -cf archive.tar ./my-folder/ --exclude="ny-folder/sub1" --exclude="ay-folder /sub3"
With this folder tree:
my-folder/
subl/
sub2/
sub3/
The result will be :
Jarchive.tar
my-folder/
ssub2/
Section 8.6: Strip leading components
To strip any number of leading components, use the ~-strip-components option:
--str'ip-conponents=NUMBER
strip NUMBER leading components from file names on extraction
For example to strip the leading folder, use:
tar -xf --strip-components=1 archive-name.tar
Goalkicker.com - Linux® Notes for Professionals a
Scanned with CamScannerChapter 9: Services
Section 9.1: List running service on Ubuntu
To get a list of the service on your system, you may run:
service --status-all
‘The output of service --status-all lists the state of services controlled by System V.
The + indicates the service is running, - indicates a stopped service. You can see this by running service
SERVICENAME status for a + and - service
Some services are managed by Upstart. You can check the status ofall Upstart services with sudo initct! list. Any
service managed by Upstart will also show in the list provided by service ~status-all but will be marked with a 2
ref: https://askubuntu.com/questions/407075/how-to-read-service-status-all-res
Section 9.2: Systemd service management
Listing services
‘+ systemct! To list running services
‘* systemct --failed To list failed services
Managing Targets (Similar to Runlevels in SysV)
‘* systemctl get-default To find the default target for your system.
+ cystemct1 set-default To set the default target for your system,
Managing services at runtime
‘* systemctl start [service-name] To start a service
‘+ systemct1 stop [service-name] To stop a service
‘+ systenctl restart [service-name] To restart a service
‘+ systenctl reload [service-name] To request service to reload its configuration
‘+ systenctl status [service-name] To show current status of a service
Managing autostart of services
‘* systemctl is-enabled [service-name] To show whether a service is enabled on system boot
‘+ systemetl is-active [service-name] To show whether a service is currently active(running)
‘+ systemctl enable [service-name] To enable a service on system boot
* systenctl disable [service-name] To disable a service on system boot
Masking services
‘+ systenctl mask [service-name] To mask a service (Makes it hard to start a service by mistake)
+ systemct unmask [service-name] To unmask a service
Restarting systemd
systemct1 daemon-reload
Goalkicker.com - Linux® Notes for Professionals 32
Scanned with CamScannerChapter 10: Managing Services
Section 10.1: Diagnosing a problem with a service
‘On systems using systemd, such as Fedora => 15, Ubuntu (Server and Desktop) >= 15.04, and RHEL/CentOS >= 7:
systemct] status [servicename]
..where [servicename] is the service in question; for example, systemct1 status sshd.
This will show basic status information and any recent errors logged.
You can see further errors with journalcti. For example,journalct2 -xe will load the last 1000 logged into a pager
(like ess), jumping to the end. You can also use journalct2 -f, which will follow log messages as they come in.
To see logs for a particular service, use the -t flag, like this:
journaletl -f -t sshd
Other handy options include -p for priority (-p warnings to see only warnings and above}, -b for "since last boot",
and -$ for "since" — putting that together, we might do
journalctl -p err -S yesterday
to see all items logged as errors since yesterday.
If journalct! is not available, or if you are following application error logs which do not use the system journal, the
‘tail commang can be used to show the last few lines of a file. A useful flag for tail is -f (for “follow"), which causes
tall continue showing data as it gets appended to the file. To see messages from most services on the system:
tail -f /var/log/messages
Or, if the service is privileged, and may log sensitive data:
tail -f /var/log/secure
‘Some services have their own log files, a good example is auditd, the linux auditing daemon, which has its logs
stored in /var/log/audit/. If you do not see output from your service in /var/1og/messages try looking for service
specific logs in /var/log/
Section 10.2: Starting and Stopping Services
On systems that use the System-V style init scripts, such as RHEL/CentOS 6:
service start
service stop
On systems using systemd, such as Ubuntu (Server and Desktop) >= 15.04, and RHEL/CentOS >= 7:
systenctl
vice dnemasq
systemet] dnsmasq
Goalkicker.com = Linux® Notes for Professionals 3B
Scanned with CamScannerSection 10.3: Getting the status of a service
(on systems that use the System: style int scripts, such as RHEL/CentOS 6:
service status
‘On systems using systemd, such as Ubuntu (Server and Desktop) >= 15.04, and RHEL/CentOS >= 7.0:
systenct] status
Goalkicker.com ~ Linux® Notes for Professionals,
Scanned with CamScanner
34Chapter 11: Modifying Users
Parameter Details
The name of the user. Do not use capital letters, do not use dots, do not end it in dash, it must not
rn
username include colons, no special characters. Cannot start with a number.
Section 11.1: Setting your own password
passnd
Section 11.2: Setting another user's password
Run the following as root:
passnd username
Section 11.3: Adding a user
Run the following as root:
Section 11.4: Removing a user
Run the following as root:
Section 11.5: Removing a user and its home folder
Run the following as root:
Section 11.6: Listing groups the current user is in
sroups
More detailed information about user and group numerical IDs can be found with the id command.
Section 11.7: Listing groups a user is in
groups username
More detailed information about user and group numerical IDs can be found with id username,
Goalkicker.com ~ Linux® Notes for Professionals 35
Scanned with CamScannerChapter 12: LAMP Stack
LAMP (Linux Apache MySQL PHP) consists of the Linux operating system as development environment, the Apache
HTTP Server as web server, the MySQL relational database management system (RDBMS) as DB (Data Base) system,
and the PHP programming language as Server side (Back End) programming language.
LAMP is used as a Open Source stack of technologies solution to web development area. Windows version of this
stack is called WAMP (Windows Apache MySQL PHP)
Section 12.1: Installing LAMP on Arch Linux
With this line we will install all the necessary packages in one step, and the last update:
pacman ~Syu apache php php-apache mariadb
HTTP.
edit
Jetc/nttpd/conf /httpd .cont
Change ServerAdnin youexample.con as you need.
The folder of the WEB Pages by default is ServerRoot * /etc/httpd”. Directory must be set to the same folder, so
change the line
This folder must have read and execution access, so
chnod ofx sete/nttpd
Change AllowOverride from none (defeult) to ALL so htaccess will works.
Now you nees the ~/public_html folder for each user. (to get the root page of each user as
http://localhost/~yourusername/. Unremark this line:
Include conf/extra/httpd-userdir.conf
Now as root you need to create the ~/pub1ic_htal for each user and change the access to (755) of each one.
‘chnod 755 /home
chmod 755 fhome/username
chmod 755 /home/username/public_html
You can comment out this line if you want to use SSL:
LoadHodule ss1module modules/mod_ss1.so
IF you need to use virtual domains, uncomment the line:
Include conf/extra/httpd-vhosts.conf
and in /eteshttpd/conf fextra/ht tpd-vhosts..conf you must to add alll the virtual domains, (plus into fete /hosts
if you want to test those virtuals domains)
Goalkicker.com = Linux® Notes for Professionals 36
Scanned with CamScannerEdit /ete/httpd/conf /extra/httpd-deFault .conf and change ServerSignature to Off and ServerToken to Prod
for hiding critical data
PHP
Edit: seteshttpd/cont httpd.conf
Comment out: LoadNodule mpm_event_module modules /nod_npm_event.so
Uncomment: LoadModule mpm_prefork module modules /nod_mpn_prefork.so
‘As last item in the LoadModule list, add LoadModule php7_module modules/1ibphp7..so
As last item in the include list, add Include conf/extra/php7 module .conf
Edit sete/php/php-nd
Uncomment extension=mysql1 .so and extension=pdo_mysql.so
Change the timezone as you need, for example:
date. timezone = Anerica/Argentina/Bvenos_Aires, date.default_latitude = 8.0, date.default longitude
= 0.8
MysQu
Run as root:
mysq1_instell_db --usersmysql --basedir=/usr --datedir=/var/1ib/mysql
Now you have the root of the MySQL Server.
Start MySQL daemon:
systemct1 enable mysqld
systemctl start mysqld
At last, run!
sh fusr/bin/mysql_secure_installation
That all to get a web server ready to be customized as you need
Section 12.2: Installing LAMP on Ubuntu
Install apache:
sudo apt-get install apache?
Install MyScl:
sudo apt-get install mysql-server
Install PHP:
Goalkicker.com = Linux® Notes for Professionals 7
Scanned with CamScannersudo apt-get install phpS Libapeche2-nod-phpS
Restart system:
sudo systemctl restart apache2
Check PHP installation:
php
echo “\n\nYour PHP installation is working fine.\n\n\n";"
Section 12.3: Installing LAMP stack on CentoOS
Install Apache Web Server
First step is to install web server Apache.
sudo yun -y install httpd
Once it is installed, enable (to run on startup) and start Apache web server service.
sudo systenct! ensble --now httpd
Point your browser to:
http://localhost
‘You will see the default Apache web server page.
Install MariaDB Server
Second step is to install MariaDB:
sudo yun -y install nariadb-server
Then start and enable (on startup) the MariaDB server:
sudo systenctl enable --now nariadb
As needed, use mysql_secure installation to secure your database.
This script will allow you to do the following:
‘= Change the root user's password
+ Remove test databases
* Disable remote access
Install PHP
sudo yun -y install php php-comon
Then restart Apache's httpd service.
sudo systenct1 restart httpd
To test PHP, create a file called index.php in /var/www/html.
Then add the following line to the fle:
Goalkicker.com - Linux® Notes for Professionals,
Scanned with CamScanner
38Then point your browser to:
http/localhost/index.php
‘You should see information related to your server. if you do not, ensure that php is for sure installed correctly by
running the following command:
php --version
If you receive something like:
PHP 5.4.16 (cli) (built: Nov 6 2016 00:29:62) Copyright (c) 1997-2013 The PHP Group
Then PHP js installed correctly. If this is the case, please ensure that you've restarted your web server.
Goalkicker.com ~ Linux® Notes for Professionals 9
Scanned with CamScannerChapter 13: tee command
Options Description
‘a, ~append Append to the given FILEs. Do not overwrite
+ ~ignore-interrupts Ignore interrupt signals.
~help Display a help message, and exit.
~version Display version information, and exit.
tee -read from standard input and write to standard output and files.
‘The tee command is named after the T-splitter in plumbing, which splits water into two directions and is shaped like
an uppercase T.
tee copies data from standard input to each FILE, and also to standard output. In effect, tee duplicates its input,
routing it to multiple outputs at once.
Section 13.1: Write output to stdout, and also to a file
The following command displays output only on the screen (stdout).
gis
The following command writes the output only to the file and not to the screen.
$ 1s» file
The following command (with the help of tee command) writes the output both to the screen (stdout and to the
file.
$ Is | tee file
Section 13.2: Write output from the middle of a pipe chain to a
file and pass it back to the pipe
You can also use tee command to store the output of a command in a file and redirect the same output to another,
command,
The following command will write current crontab entries to a file crontab-beckup .txt and pass the crontab
entries to sed command, which will do the substituion. After the substitution, it will be added as a new cron job.
$ crontab -1 | tee crontab-backup.txt | sed ‘s/old/new/* | crontab —
Section 13.3: write the output to multiple files
You can pipe your output to multiple files (including your terminal) by using tee like this:
$ Is | tee filet file2 filed
Section 13.4: Instruct tee command to append to the file
By default t:
command overwrites the file. You can instruct tee to append to the file using the -a option as shown
Goalkicker.com - Linux® Notes for Professionals 40
Scanned with CamScannerbelow.
SIs | tee -a file
Goalkicker.com - Linux® Notes for Professionals
Scanned with CamScanner
aChapter 14: Secure Shell (SSH)
Asecure shell is used to remotely access a server from a client over an encrypted connection, OpenSSH is used as
an alternative to Telnet connections that achieve remote shell access but are unencrypted. The OpenSSH Client is
installed on most GNU/Linux distributions by default and is used to connect to a server. These examples show use
how to use the SSH suite to for accept SSH connections and connecting to another host.
Section 14.1: Connecting to a remote server
To connect to a server we must use SSH on the client as follows,
Woah op port weerQcorversaddress
‘+ port - The listening ssh port of the server (default port 22).
‘+ user - Must be an existing user on the server with SSH privileges.
‘* server address - The IP/Domain of the server.
For areal world example lets pretend that you're making a website. The company you chose to host your site tells
you that the server is located at web-servers.com on a custom port of 2020 and your account name usr1 has been
chosen to create a user on the server with SSH privileges. In this case the SSH command used would be as such
# ssh -p 2020 [email protected]
If account name on the remote system is the same as the one one the local client you may leave the user name off.
So if you are usr1 on both systems then you my simply use web-servers.com instead of usr [email protected].
‘When a server you want to connect to is not directly accessible to you, you can try using Proxylump switch to
connect to it through another server which is accessible to you and can connect to the desired server.
# ssh -J [email protected]:2028 [email protected] -p 2222
This will let you connect to the server 10.0.0.2 (running ssh on port 2222) through server at 10.0.0.1 (running ssh on
port 2020). You will need to have accounts on both servers of course. Also note that the 4 switch is introduced in
OpenSSH version 7.3,
Section 14.2: Installing OpenSSH suite
Both connecting to a remove SSH server and accepting SSH connections require installation of openssh
Debian:
# apt-get install openssh
Arch Linux
# pacman -S openssh
Yum
# yum install openssh
Goalkicker.com = Linux® Notes for Professionals 42
Scanned with CamScannerSection 14.3: Configuring an SSH server to accept connections
First we must edit the SSH daemon config file. Though under different Linux distributions this may be located in
different directories, usually itis stored under /etc/ssh/sshd_config
Use your text editor to change the values set in this file, all ines starting with # are commented out and must have
this character removed to take any effect. A list of recommendations follow as such.
Port (chose a number between 0 - 65535, normaly greater than four digits)
PasswordAuthentication yes
AllowUsers user] user? ...etc
Note that it is preferable to disable password logins all together and use SSH Keys for improved security as explained in
this document.
Section 14.4: Passwordless connection (using a key pair)
First of all you'll need to have a key pair. f you don't have one yet, take a look at the ‘Generate public and private
key topic.
‘Your key pair is composed by a private key (id_rsa) and public key (id_rsa.pub). All you need to do is to copy the
public key to the remote host and add its contents to the ~/. ssh/authorized_keys file.
Gne simple way to do thatis:
ssh Bessh-server> ‘cat >> ~/.ssh/authorizeé_keys' < id_rsa.pub
Once the public key is properly placed in your user's home directory, you just need to login using the respective
private key:
ssh -i id_rse
Section 14.5: Generate public and private key
To generate keys for SSH client:
sh-keygen [-t rsa | rsal | dsa ] [-C ] [-b bits]
For example:
sh-keygen -t rsa -b 4096 - C myenaileenail.com
Default location is ~/ ssh/id_rsa for private and~/.ssh/id_rsa. pub for public key.
For more info, please visit man.openbsd.org
Section 14.6: Disable ssh service
This will disable the SSH server side service, as if needed this will insure that clients cannot connect via ssh
Ubuntu
sudo service ssh stop
Goalkicker.com = Linux® Notes for Professionals a
Scanned with CamScannersudo systemctl disable sshd.service
Debian
sudo /ete/init.d/ssh stop
sudo systemct1 disable sshd.service
Arch Linux
sudo killall sshd
sudo systemctl disable sshd.service
Goalkicker.com ~ Linux® Notes for Professionals
Scanned with CamScanner
aaChapter 15: SCP
Section 15.1: Secure Copy
scp command is used to securely copy a file to or from a remote destination. Ifthe file is in current working directly
only filename is sufficient else full path is required which include the remote hostname e.g.
remote_user@some_server.org:/path/to/file
Copy local file in your CWD to new directory
sep localfile.txt /home/friend/share/
Copy remote file to you current working directory
sep rocky@arenaSt .net :/home/rocky/game/data.txt
Copy file from one remote location to another remote location
scp [email protected]:/beacon/light/bitmap.conf [email protected]:/beacon/night/
To copy directory and sub-directories use ‘1’ recursive option to sep
sep -F user€192.168.0.4:~/project/* . workspace!
Section 15.2: Basic Usage
# Copy renote file to local dir
sep user@renotehost .com:/renote/path/to/foobar.md /local/dest
# Copy local file to remote dir
sep foobar.md user@remotehost .com:/renote/dest
# Key files can be used (just like ssh)
scp -i my_key.pem foobar.md user@remotehost .com:/remote/dest
Goalkicker.com = Linux® Notes for Professionals, 5
Scanned with CamScannerChapter 16: GnuPG (GPG)
GnuPG is a sophisticated key management system which allows for secure signing or encrypting data. GPG is a
command-line tool used to create and manipulate GnuPG keys.
GnuPG is most widely used for having SSH (Secure Shell) connections without password or any means of interactive
authentication, which improves security level significantly.
Following sections describe ways to create, use, and maintain security of GnuPG keys.
Section 16.1: Exporting your public key
In order for your public-private keypair to be of use, you must make your public key freely available to others. Be
sure that you are working with your public key here since you should never share your private key. You can export
your public key with the following command
9p9 —armor —export EMAIL_ADDRESS > public_key.ase
where EMAIL_ADDRESS is the email address associated with the key
Alternately, you can upload your public key to a public key server such as keys.gnupg.net so that others can use it
To do so, enter the following in a terminal:
9p9 —list-keys
‘Then, search for the 8-cigit string (the primary ID) associated with the key you want to export. Then, issue the
command:
snd-keys PRIMARY_1D
a
where PRIMARY.ID isthe actual ID ofthat key.
Now, the public key has been uploaded to the key server and is publicly available.
Section 16.2: Create and use a GnuPG key quickly
Install haveged (example sudo apt-get install haveged) to speed up the random byte process. Then:
‘gpg --gen-key
‘gpg --list-keys
outputs:
pub 2848R/NNNNNNNN 2016-01-01
uid Name
sub 2048R/xxxx000x 2816-61-01
Then publish:
‘op9 --keyserver pgp.mit edu --send-keys NNNNNNNN
‘Then plan to revoke: https.//wmw.hackdiary,com/2004/01/18/revoking-a-gpg-key/
Goalkicker.com = Linux® Notes for Professionals 46
Scanned with CamScannerChapter 17: Network Configuration
This document covers TCP/IP networking, network administration and system configuration basics. Linux can
support multiple network devices. The device names are numbered and begin at zero and count upwards. For
example, a computer with two NICs will have two devices labeled ethO and eth.
Section 17.1: Local DNS resolution
File: /ete/hosts contains a list of hosts that are to be resolved locally(not by DNS)
Sample contents of the file:
127.0.0.1 your-node-name.your-domain.com localhost.Jocaldomain localhost
YOO XXX. XKK.XXX node-name
‘The file format for the hosts file is specified by RFC 952
Section 17.2: Configure DNS servers for domain name
resolution
File: /ete/resolv.conf contains a list of DNS servers for domain name resolution
Sample contents of the file:
nameserver 8.8.8.8 # IP address of the primary name server
nameserver 8.8.4.4 # IP address of the secondary nane server
In case internal DNS server you can validate if this server resolve DNS names properly using dig command:
$ dig google.com @your.dns.server.com +short
Section 17.3: See and manipulate routes
Manipulate the IP routing table using route
Display routing table
§ route # Displays list or routes and also resolves host nanes
§ route -n # Displays list of routes without resolving hast names for faster
esults
Add/Delete route
Option Description
‘add or del ‘Add or delete a route
“host x.x.x.x Add route to a single host identified by the IP address
-net x.x.x.x Add route to a network identified by the network address
OW Xx.x.x Specify the network gateway
netmask x.x.x.x Specify the network netmask
default Add a default route
Examples
Goalkicker.com = Linux® Notes for Professionals 7
Scanned with CamScanneradd route to. ahost $ route add -host x.x.x.x etht
add route to. anetwork$ route add -net 2.2.2. netmask 255.255.255.8 tha
Alternatively, you could also use cidr format to add a route to network route add -net 2.2.2.0/24 ethe
add default gateway $ route add default gw 2.2.2.1 etha
delete a route $ route del -net 2.2.2.0/24
Manipulate the IP routing table using ip
Display routing table
$ ip route show # List routing table
Add/Delete route
Option Description
‘add or del or change or apperd Change a route
or replace Changs. 4 rox
show or flush the command displays the contents of the routing tables or remove it
restore restore routing table information from stdin,
et this command gets a single route to a destination and prints its contents exactly as
s the kernel sees it
Examples:
+ Set default gateway to 1.2.3.254$ ip route add default via 1.2.3.254
‘+ Adds a default route (for all addresses) via the local gateway 192.168.1.1 that can be reached on device etho
$ ip route add default via 192.168.1.1 dev ethé
Section 17.4: Configure a hostname for some other system on
your network
‘You can configure your Linux (or macOS) system in order to tie in an identifier to some other system's.
IP address in your network. You can configure it:
‘+ Systemwide. You should modify the /etc/hosts file, You just have to add to that file a new line containing:
1, the remote system's IP address ,
2. one or more blank spaces, and
3, the identifier ,
‘+ For a single user. You should modify the ~/-hosts fle ~- you-d have to create it. It is not as simple as for
systemwide, Here you can see an explanation.
For instance, you could ad this line using the eat Unix tool. Suppose that you want to make a ping to a PC in yout
local network whose IP address is 192.168.1.44 and you want to refer to that IP address just by renote_pe. Then
you must write on your shell:
§ sudo cat 192.168.1.44 renote_pe
Then you can make that ping just by:
S ping remote_pe
Goalkicker.com = Linux® Notes for Professionals 48
Scanned with CamScannerSection 17.5: Interface details
ifconfig
List all the interfaces available on the machine
$ ifconfig -2
List the details ofa specific interface
Syntax: § ifconfig «interfaces
Example:
$ ifconfig etho
etha Link encap:Ethernet Hifaddr .0x:2% 30 3022030
inet addr:x.x.x.x Beast:x.x.x.x Mask:x.x.x.%
net6 addr: 00x: 00 XxX 00x 1200/64. Scope :Link
UP BROADCAST RUNNING MULTICAST MTU:15@@ Metric:1
RX packets :4426618 errors:@ dropped:1124 averruns:@ frame:0
TX packets:189171 errors:@ dropped:@ overruns:@ carrier :@
collisions:8 txqueuelen:1600
RX bytes :382611580 (382.6 MB) TX bytes :36923665 (36.9 MB)
Interrupt :16 Memory :fb5e82e0-fb6eeaa0
Ethtool - query the network driver and hardware settings
Syntax: $ ethtool
or alternatively, you could make a change to the /etc/network/inter faces file for the interface to be brought up
‘on boot and obtain DHCP IP
auto ethe
iface eth@ inet dhcp
Static configuration(Permanent Change) using /ete/network/interfaces file
If you want to statically configure the interface settings(permanent change], you could do so in the
Jetc/network/interfaces file.
Example:
auto eth@ # Bring up the interface on boot
iface eth@ inet static
address 10.10.70.10
netmask 255.255.0.0
gateway 18.10.1.1
dns-nameservers 18.18.1.20
dns-nameservers 18.10.1.30
These changes persist even after system reboot.
Goalkicker.com - Linux® Notes for Professionals, 50
Scanned with CamScannerStatic configuration(Temporary change) using ifconfig utility
Astatic IP address could be added to an interface using the ifconfig utility as follows
§ ifconfig / up
Example:
§ ifconfig etha 10.18.58.100/16 up
Goalkicker.com ~ Linux® Notes for Professionals
Scanned with CamScanner
3Chapter 18: Midnight Commander
Midnight Commander or mc is a console file manager. This topic includes the descripton of its functionalities and
examples and tips of how to use it to it’s full potential.
Section 18.1: Midnight Commander function keys in browsing
mode
Here is a list of actions which can be triggered in the Midnight Commander filesystem browsing mode by using
function keys on your keyboard.
Displays help
(FZ opens user menu
[FS Displays the contents of the selected file
[Ea _]opens the selected file in the internal file editor
[F5_|copies the selected fle to the directory open in the second panel
[6 ] Moves the selected file to the directory open in the second panel
[FT ]Makes a new directory in the directory open in the current panel
FB | Deletes the selected file or directory
F9 | Focuses to the main menu on the top of the screen
F109 | Exits me
Section 18.2: Midnight Commander function keys in file editing
mode
Midnight Commander has a built in editor which is started by F4 function key when over the desired file in the
browse mode. It can also be invoked in standalone mode by executing
ncedit
Here is a list of actions which can be triggered in the edit mode
Displays help
Saves current file
Marks the start of the text selection. Move cursor any direction to select. Second hit marks the end of the
selection,
F4 | Brings up the text search/replace dialog
Copies selected text to the cursor location (copy/paste)
F6 | Moves selected text to the cursor location (cut/paste)
F7 | Brings up the text search dialog
Goalkicker.com - Linux® Notes for Professionals 52
Scanned with CamScannerFB | Deletes selected text
F9 ] Focuses to the main menu on the top of the screen
F1@ | Exits the editor
Goalkicker.com - Linux® Notes for Professionals
Scanned with CamScanner
33Chapter 19: Change root (chroot)
Change root (chroot) is an operation that changes the apparent root directory for the current running process and
their children. A program that is run in such a modified environment cannot access files and commands outside
that environmental directory tree.
Section 19.1: Requirements
+ root privileges
another working Linux environment.such as Live CD boot or an existing distribution
‘+ matching environment architectures of chroot source and destination (check current environment
architecture with uname -n)
kernel modules which you may need in chroot environment must be loaded (for example, with modprobe)
Section 19.2: Manually changing root in a directory
. Ensure you met all requirements, as per Requirements
2. Mount the temporary API filesystems:
ed /ocation/of /new/root
mount -t proc proc prac/
mount --rbind /sys sys/
mount --rbind /dev dev/
mount --rbind /run run/ (optionally)
3, Ifyou need to use an internet connection in the chroot environment, copy over the DNS details:
ep /etc/resolv.conf etc/resolv.cont
4, Change root into /location/of/new/root, specifying the shell (/bin/bash in this example}
chroot /location/of/new/root /bin/bash
5. After chrooting it may be necessary to load the local bash configuration:
source /etc/profile
source ~/.bashre
6. Optionally, create a unique prompt to be able to differentiate your chroot environment:
export PS1=" (chroot) $PS1"
7. When finished with the chroot, you can exit t via
exit
8. Unmount the temporary fle systems:
edy
unount --recursive /location/of /new/root
Goalkicker.com = Linux® Notes for Professionals 54
Scanned with CamScannerSection 19.3: Reasons to use chroot
Changing root is commonly done for performing system maintenance on systems where booting and/or logging in
isno longer possible.
Common examples are:
++ reinstalling the bootloader
rebuilding the initramfs image
upgrading or downgrading packages
* resetting a forgotten password
building software in a clean root environment
Goalkicker.com = Linux® Notes for Professionals
Scanned with CamScanner
5Chapter 20: Package Managers
Section 20.1: How to update packages with the apt package
manager
‘The Advanced Package Tool, aptly named the ‘apt package manager can handle the installation and removal of
software on the Debian, Slackware, and other Linux Distributions, Below are some simple examples of use:
update
This option retrieves and scans the Packages.g7 files, so that information about new and updated packages is
available. To do so, enter the following command:
sudo apt-get update
upgrade
This option is used to install the newest versions of all packages currently installed on the system. Packages
currently installed with new versions available are retrieved and upgraded; under no circumstances are currently
installed packages removes, or packages not already installed retrieved and installed. To upgrade, enter the
following command:
sudo apt-get upgrade
dist-upgrade
In addition to performing the function of upgrade, dist-upgrade also intelligently handles changing dependencies
with new versions of packages. It will attempt to upgrade the most important packages at the expense of less
important ones if necessary. To do so, enter the following command:
sudo apt-get dist-upgrade
Section 20.2: How to install a package with the pacman
package manager
In order to search for packages in the databse, searching both in packages! names and descriptions:
pacaan -Ss string! string2
To install a single package or list of packages (including dependencies), issue the following command:
sudo pa
n -S package namet package_name2 ...
Section 20.3: How to update packages with the pacman
package manager
To update a specific program:
sudo pacnan -S
To update entire the system:
sudo pacman ~Syu
Goalkicker.com - Linux® Notes for Professionals 56
Scanned with CamScanner(Caaf gow
ADARSH CHETAN
Scanned with CamScanner