Linux Cheat Sheet V1.0
Linux Cheat Sheet V1.0
Bl
ack
ha
tA
k
The Ultimate Linux
Administration
Cheat Sheet
by Andrei Dumitrescu
TABLE OF CONTENTS
Linux Paths
The ls Command
File Timestamps and Date
Viewing files (cat, less, more, head, tail, watch)
@
Bl
a
Working with files and directory (touch, mkdir, cp, mv, rm, shred)
ck
ha
The cp command The mv command The rm command
tA
Piping and Command Redirection
k
Finding Files (find, locate)
locate find
File Permissions
SUID (Set User ID) SGID (Set Group ID) The Sticky Bit UMASK
Changing File Ownership (root only)
Processes
Process Viewing (ps, pstree, pgrep)
Dynamic Real-Time View of Processes(top)
Killing processes (kill, pkill, killall)
Networking
Getting info about the network interfaces (ifconfig, ip, route)
Setting the network interfaces (ifconfig, ip, route)
Network static configuration using Netplan (Ubuntu)
OpenSSH
Copying files using SCP and RSYNC
SCP RSYNC
WGET
NETSTAT and SS
LSOF
nmap
Scanning hosts and networks using nmap
ck
ha
Getting System Hardware Information
tA
Working directly with device files (dd)
k
Service Management using systemd and systemctl
Bash Programming
Bash Aliases Bash Variables Special Variable and Positional Arguments
Program Flow Control (if..elif..else statements)
Test Conditions For loops While Loops Case Functions
MAN Pages
man command # => Example: man ls
SHORTCUTS:
h => getting help
q => quit
enter => show next line
space => show next screen
/string => search forward for a string
?string => search backwards for a string
n/N => next/previous appearance
a
man -k "copy files"
ck
apropos passwd
ha
tA
k
Keyboard Shortcuts
# autocompletes the command or the filename if its unique
TAB
# opening a terminal
CTRL + ALT + T
Bash History
# displaying the history
history
a ck
# printing the number of commands saved in the history file (~/.bash_history)
ha
echo $HISTFILESIZE
tA
k
# printing the number of history commands saved in the memory
echo $HISTSIZE
# running a specific command from the history (example: the 20th command)
!20
# running the last nth (example: 10th) command from the history
!-10
a
su # => enter the root password
ck
ha
tA
Linux Paths
k
Paths:
- absolute
- relative
# installing tree
sudo apt install tree
The ls Command
ls [OPTIONS] [FILES]
# ~ => user's home directory
# . => current directory
# .. => parent directory
ck
ls -l ~
ha
tA
# -a => listing all files and directories including hidden ones
k
ls -la ~
# -d => displaying information about the directory, not about its contents
ls -ld /etc
# Note: ls does not display the size of a directory and all its contents. Use du instead
du -sh ~
# displaying atime
ls -lu
# displaying mtime
ls -l
ls -lt
# displaying ctime
@
Bl
ls -lc
a ck
# displaying all timestamps
ha
stat file.txt
tA
k
# displaying the full timestamp
ls -l --full-time /etc/
# creating an empty file if it does not exist, update the timestamps if the file exists
touch file.txt
ack
# displaying the output sorted by modification time, newest files first
ha
ls -lt
tA
k
# displaying and sorting by atime
ls -ltu
# concatenating 2 files
cat filename1 filename2 > filename3
less shortcuts:
h => getting help
q => quit
enter => show next line
space => show next screen
/string => search forward for a string
?string => search backwards for a string
n/N => next/previous appearance
a
tail -n +5 filename
ck
ha
# showing the last 10 lines of the file in real-time
tA
tail -f filename
k
# showing the first 10 lines of a file
head filename
Working with files and directory (touch, mkdir, cp, mv, rm,
shred)
# creating a new file or updating the timestamps if the file already exists
touch filename
The cp command
# copying file1 to file2 in the current directory
cp file1 file2
a
cp -v file1 file2
ck
ha
# recursively copying dir1 to dir2 in the current directory
tA
cp -r dir1 dir2/
k
# copy more source files and directories to a destination directory
cp -r file1 file2 dir1 dir2 destination_directory/
The mv command
# renaming file1 to file2
mv file1 file2
# moving only if the source file is newer than the destination file or when the destination file is
missing
mv -u file1 dir1/
The rm command
# removing a file
rm file1
# removing a directory
rm -r dir1/
@
Bl
# removing a directory without prompting
a
rm -rf dir1/
ck
ha
# removing a file and a directory prompting the user for confirmation
tA
rm -ri fil1 dir1/
k
# secure removal of a file (verbose with 100 rounds of overwriting)
shred -vu -n 100 file1
Piping Examples:
Command Redirection
# output redirection
ps aux > running_processes.txt
who -H > loggedin_users.txt
# appending to a file
id >> loggedin_users.txt
a
ck
ha
# installing plocate
tA
sudo apt install plocate
k
# updating the locate db
sudo updatedb
# displaying statistics
locate -S
find
Example: find ~ -type f -size +1M # => finding all files in ~ bigger than 1 MB
Options:
-type f, d, l, s, p
-name filename
-iname filename # => case-insensitive
-size n, +n, -n
-perm permissions
-links n, +n, -n
-atime n, -mtime n, ctime n
@
Bl
-user owner
a
-group group_owner
ck
ha
tA
Searching for text patterns (grep)
k
grep [OPTIONS] pattern file
Options:
-n # => print line number
-i # => case insensitive
-v # inverse the match
-w # search for whole words
-a # search in binary files
-R # search in directory recursively
-c # display only the number of matches
-C n # display a context (n lines before and after the match)
VIM
a
q! => quit the file without saving
ck
wq! => save/write and quit
ha
e! => undo to the last saved version of the file
tA
set no => set line numbers
k
set nonu => unset line numbers
syntax on|off
%s/search_string/replace_string/g
Account Management
Important files:
/etc/passwd # => users and info: username:x:uid:gid:comment:home_directory:login_shell
/etc/shadow # => users' passwords
/etc/group # => groups
@
Bl
# creating a user account
a
useradd [OPTIONS] username
ck
ha
Options:
tA
-m => create home directory
k
-d directory => specify another home directory
-c "comment"
-s shell
-G => specify the secondary groups (must exist)
-g => specify the primary group (must exist)
Exemple:
useradd -m -d /home/john -c "C++ Developer" -s /bin/bash -G sudo,adm,mail john
Example:
usermod -aG developers,managers john # => adding the user to two secondary groups
# creating a group
groupadd group_name
# deleting a group
groupdel group_name
Monitoring Users
who -H # => displays logged in users
id # => displays the current user and its groups
whoami # => displays EUID
@
Bl
a
# listing who’s logged in and what’s their current process.
ck
w
ha
uptime
tA
k
# printing information about the logins and logouts of the users
last
last -u username
File Permissions
Legend:
u = user
g = group
o = others/world
a = all
r = read
w = write
x = execute
- = no access
stat /etc/shadow
File: /etc/shadow
Size: 1721 Blocks: 8 IO Block: 4096 regular file
Device: 805h/2053d Inode: 524451 Links: 1
Access: (0640/-rw-r-----) Uid: ( 0/ root) Gid: ( 42/ shadow)
Access: 2020-08-24 11:31:49.506277118 +0300
Modify: 2020-08-22 14:43:36.326651384 +0300
Change: 2020-08-22 14:43:36.342652202 +0300
Birth: -
ck
ha
PERMISSIONS EXAMPLE
tA
u g o
k
rwx rwx rwx chmod 777 filename
rwx rwx r-x chmod 775 filename
rwx r-x r-x chmod 755 filename
rwx r-x --- chmod 750 filename
rw- rw- r-- chmod 664 filename
rw- r-- r-- chmod 644 filename
rw- r-- --- chmod 640 filename
stat /usr/bin/umount
File: /usr/bin/umount
Size: 39144 Blocks: 80 IO Block: 4096 regular file
Device: 805h/2053d Inode: 918756 Links: 1
Access: (4755/-rwsr-xr-x) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2020-08-22 14:35:46.763999798 +0300
Modify: 2020-04-02 18:29:40.000000000 +0300
Change: 2020-06-30 18:27:32.851134521 +0300
Birth: -
# setting SUID
chmod u+s executable_file
chmod 4XXX executable_file # => Example: chmod 4755 script.sh
ck
File: projects/
ha
Size: 4096 Blocks: 8 IO Block: 4096 directory
tA
Device: 805h/2053d Inode: 266193 Links: 2
k
Access: (2750/drwxr-s---) Uid: ( 1001/ student) Gid: ( 1002/ student)
Access: 2020-08-25 11:02:15.013355559 +0300
Modify: 2020-08-25 11:02:15.013355559 +0300
Change: 2020-08-25 11:02:19.157290764 +0300
Birth: -
# setting SGID
chmod 2750 projects/
chmod g+s projects/
stat /tmp/
File: /tmp/
Size: 4096 Blocks: 8 IO Block: 4096 directory
Device: 805h/2053d Inode: 786434 Links: 20
Access: (1777/drwxrwxrwt) Uid: ( 0/ root) Gid: ( 0/ root)
Access: 2020-08-22 14:46:03.259455125 +0300
Modify: 2020-08-25 10:49:53.756211470 +0300
Change: 2020-08-25 10:49:53.756211470 +0300
Birth: -
UMASK
# displaying the UMASK
umask
@
Bl
# setting a new umask value
a
umask new_value # => Example: umask 0022
ck
ha
tA
Changing File Ownership (root only)
k
# changing the owner
chown new_owner file/directory # => Example: sudo chown john a.txt
Processes
ck
ps -f -u username
ha
tA
# checking if a process called sshd is running
k
pgrep -l sshd # matches against the process name
pgrep -f sshd # matches against the full command line
ps -ef | grep sshd
ack
# listing all signals
ha
kill -l
tA
k
# sending a signal (default SIGTERM - 15) to a process by pid
kill pid # => Example: kill 12547
Networking
@
Bl
Getting info about the network interfaces (ifconfig, ip, route)
ack
ha
# displaying information about enabled interfaces
tA
ifconfig
k
# displaying information about all interfaces (enabled and disabled)
ifconfig -a
ip address show
# activating an interface
ifconfig enp0s3 up
ip link set enp0s3 up
ck
ifconfig enp0s3 192.168.0.222/24 up
ha
ip address del 192.168.0.111/24 dev enp0s3
tA
ip address add 192.168.0.112/24 dev enp0s3
k
# setting a secondary ip address on sub-interface
ifconfig enp0s3:1 10.0.0.1/24
network:
version: 2
renderer: networkd
ethernets:
enp0s3:
dhcp4: false
addresses:
@
Bl
- 192.168.0.20/24
a
gateway4: "192.168.0.1"
ck
nameservers:
ha
addresses:
tA
- "8.8.8.8"
k
- "8.8.4.4"
OpenSSH
# CentOS
sudo dnf install openssh-server openssh-clients
a
sudo systemctl enable sshd # => CentOS
ck
ha
sudo systemctl is-enabled ssh # => Ubuntu
tA
sudo systemctl is-enabled sshd # => CentOS
k
# 3. Securing the SSHd daemon
# change the configuration file (/etc/ssh/sshd_config) and then restart the server
man sshd_config
g) Other configurations:
ClientAliveInterval 300
ClientAliveCountMax 0
MaxAuthTries 2
MaxStartUps 3
LoginGraceTime 20
SCP
# copying a local file to a remote destination
scp a.txt john@80.0.0.1:~
scp -P 2288 a.txt john@80.0.0.1:~ # using a custom port
a
ck
ha
RSYNC
tA
# synchronizing a directory
k
sudo rsync -av /etc/ ~/etc-backup/
# mirroring (deleting from destination the files that were deleting from source)
sudo rsync -av --delete /etc/ ~/etc-backup/
# excluding files
rsync -av --exclude-from='~/exclude.txt' source_directory/ destination_directory/
# exclude.txt contents:
*.avi
music/
abc.mkv
WGET
# installing wget
apt install wget # => Ubuntu
dnf install wget # => CentOS
ck
wget -i urls.txt # urls.txt contains urls
ha
tA
# starting the download in the background
k
wget -b -P kali/ https://cdimage.kali.org/kali-2020.2/kali-linux-2020.2-installer-amd64.iso
tail -f wget-log # => checking its status
NETSTAT and SS
LSOF
nmap
a
## Scanning Networks is your own responsibility ##
ck
ha
You can use scanme.nmap.org for safe scanning purposes.
tA
k
# Syn Scan - Half Open Scanning (root only)
nmap -sS 192.168.0.1
# Connect Scan
nmap -sT 192.168.0.1
# Scan Version
nmap -p 22,80 -sV 192.168.0.1
# Excluding an IP
nmap -sS 192.168.0.0/24 --exclude 192.168.0.10
# OS Detection
nmap -O 192.168.0.1
# reading the targets from a file (ip/name/network separated by a new line or a whitespace)
nmap -p 80 -iL hosts.txt
tA
k
DPKG
# getting info about a deb file
dpkg --info google-chrome-stable_current_amd64.deb
# removing a package
sudo dpkg -r google-chrome-stable
# purging a package
sudo dpkg -P google-chrome-stable
APT
# updating the package index (doesn't install/uninstall/update any package)
sudo apt update
a
ck
# upgrading all applications
ha
sudo apt full-upgrade
tA
sudo apt full-upgrade -y # => assume yes to any prompt (useful in scripts)
k
# removing a package
sudo apt remove apache2
# removing the saved deb files from the cache directory (var/cache/apt/archives)
sudo apt clean
ck
# run every minute
ha
* * * * * /path_to_task_to_run.sh
tA
k
# run every hour at minute 15
15 * * * * /path_to_task_to_run.sh
tA
k
# displaying full hardware information
lshw
lshw -short # => short format
lshw -json # => json format
lshw -html # => html format
# installing inxi
apt install inxi
inxi -Fx
# getting info about pci buses and about the devices connected to them
lspci
lspci | grep -i wireless
lspci | grep -i vga
# installing hdparm
@
Bl
apt install hdparm
a
hdparm -i /dev/sda
ck
hdparm -I /dev/sda
ha
tA
# benchmarking disk read performance
k
hdparm -tT --direct /dev/sda
ck
sudo systemctl status nginx.service
ha
tA
# stopping a service
k
sudo systemctl stop nginx
# starting a service
sudo systemctl start nginx
# restarting a service
sudo systemctl restart nginx
# unmasking a service
sudo systemctl unmask nginx
Bash Programming
Bash Aliases
# listing all Aliases
alias
# creating an alias: alias_name="command"
alias copy="cp -i"
@
Bl
a
To make the aliases you define persistent, add them to ~/.bashrc
ck
ha
# removing an alias: unalias alias_name
tA
unalias copy
k
Useful Aliases
alias c="clear"
alias cl="clear;ls;pwd"
alias root="sudo su"
alias ports="netstat -tupan"
alias ssh config="sudo vim /etc/ssh/sshd_config"
alias my_server="ssh -p 3245-l user100 80.0.0.1"
alias update=”sudo apt update && sudo apt dist-upgrade -y && sudo apt clean”
alias lt="ls -hSF --size -1"
alias ping='ping -c 5'
# interactive File Manipulation
alias cp="cp -i"
alias mv="mv -i"
alias rm="rm -i"
Important alias
# This may look a bit confusing, but essentially, it makes all of the other aliases you define
function correctly when used with sudo.
alias sudo='sudo ' # use single quotes, not double quotes.
Bash Variables
# defining a variable: variable_name=value
# variable names should start with a letter or underscore and can contain letters, digits and
underscore
os="Kali Linux"
version=10
ck
env
ha
printenv
tA
k
# searching for an environment variable
printenv PATH
env | grep -i path
# creating new environment variables for the user: in ~/.bashrc add export MYVAR=”value”
export IP="80.0.0.1"
# displaying a message
read -p "Enter the IP address: " ip
ping -c 1 $ip
#!/bin/bash
echo "\$0 is $0"
echo "\$1 is $1"
echo "\$2 is $2"
@
Bl
echo "\$3 is $3"
a
echo "\$* is $*"
ck
echo "\$# is $#"
ha
tA
# Move to the script's directory and run it as: ./script_name.sh Ubuntu CentOS "Kali Linux"
k
"Windows 10"
i=1
if [[ $i -lt 10 ]]
then
echo "i is less than 10."
fi
#################
i=100
if [[ $i -lt 10 ]]
then
echo "i is less than 10."
else
echo "i is greater than or equal to 10."
fi
################
i=10
if [[ $i -lt 10 ]]
then
echo "i is less than 10."
elif [[ $i -eq 10 ]]
then
echo "i is 10"
else
echo "i is greater than or equal to 10."
fi
@
Bl
TEST CONDITIONS
ack
ha
man test
tA
k
# For numbers (integers) ###
# -eq equal to
# -ne not equal to
# -lt less than
# -le less than or equal to
# -gt greater than
# -ge greater than or equal to
# For files:
# -s file exists and is not empty
# -f file exists and is not a directory
# -d directory exists
# -x file is executable by the user
# -w file is writable by the user
# -r file is readable by the user
# For Strings
# = the equality operator for strings if using single square brackets [ ]
# == the equality operator for strings if using double square brackets [[ ]]
# != the inequality operator for strings
# -n $str str is nonzero length
# -z $str str is zero length
For loops
#!/bin/bash
# iterating over a list of strings
for os in Ubuntu CentOs Slackware "Kali Linux"
do
echo "os is $os"
done
a
for x in {10..100..5}
ck
do
ha
echo $x
tA
done
k
# iterating over a list of files
for item in ./* # files in the current dir
do
if [[ -f $item ]]
then
echo "Displaying the contents of $item"
sleep 1
cat $item
echo "#######################"
fi
done
# C/Java style
for ((i = 0 ; i <= 50 ; i++))
do
echo "i = $i"
done
While Loops
#!/bin/bash
i=0
while [[ $i -lt 10 ]]
do
echo "i: $i"
((i++)) # same as: let i=i+1
done
Case
#!/bin/bash
echo -n "Enter your favorite pet:"
read PET
@
Bl
a
case "$PET" in
ck
dog)
ha
echo "Your favorite pet is the dog."
tA
;;
k
cat | Cat)
echo "You like cats."
;;
fish | "African Turtle")
echo "Fishes or turtles are great!"
;;
*)
echo "Your favorite pet is unknown!"
esac
Functions
#!/bin/bash
#!/bin/bash
create_files () {
echo "Creating $1"
touch $1
chmod 400 $1
ack
# calling the function with 2 args
ha
create_files aa.txt bb.txt
tA
k
# function that returns a value (output of a command)
function lines_in_file() {
grep -c "$1" "$2"
}