Mastering Linux
Mastering Linux
Introduction to Linux
Filesystem .........................................................................................… 12
Permissions ..................................................................................…… 13
Wildcard ............................................................................................... 14
Curl ........................................................................................................... 64
SSH ........................................................................................................... 73
Glimpse of Linux 🐧
What is Linux?
Linux is a free and open-source operating system based on the UNIX operating
system. The core component of Linux is the Linux kernel, which was created
by Linus Torvalds in 1991. The kernel is responsible for managing the system's
hardware and providing essential services for all other parts of the operating
system.
Security: Known for its strong security model and robust permissions
system.
Linux 1
Flexibility: Can be run on a wide range of hardware from personal
computers to mainframes and embedded systems.
History of Linux ⌛
1. Origins of UNIX and Early Influences (1960s-1980s)
UNIX:
Developed in the late 1960s and early 1970s at AT&T's Bell Labs by Ken
Thompson, Dennis Ritchie, and others.
Source code was freely shared with academic institutions, which led to
widespread adoption and variations.
Minix:
Inspired by Minix and the need for a free and open operating system
kernel for personal computers.
Initial Announcement:
Linux 2
3. Development and Growth (1990s)
Early Contributions:
Early versions of Linux were distributed under the GNU General Public
License (GPL), allowing anyone to use, modify, and distribute the
software.
Key Milestones:
Major Milestones:
Linux became the foundation for many cloud computing platforms and
services, such as AWS, Google Cloud, and Microsoft Azure.
Linux 3
Android, developed by Google and based on the Linux kernel, became
the dominant mobile operating system.
Continued Development:
Embedded Systems:
Linux 4
Continues to be a valuable tool in computer science education and
research.
Types of Linux
Linux distributions (distros) are versions of Linux that include the Linux kernel,
system software, and applications. Different distributions are tailored to various
needs, from general-purpose desktop use to specialized server environments.
1. General-Purpose Distributions
Distribution Description
Ubuntu User-friendly, popular for desktops and servers. Derived from Debian.
Sponsored by SUSE, known for its YaST configuration tool and strong
openSUSE
focus on user-friendliness and security.
2. Enterprise Distributions
Distribution Description
SUSE Linux Enterprise Enterprise-grade distribution, known for its strong support
Server (SLES) for virtualization and cloud environments.
3. Lightweight Distributions
Distribution Description
Linux 5
Extremely lightweight, designed to run on older hardware or low-
Puppy Linux
resource environments.
Tiny Core
Very small footprint, highly modular, and customizable.
Linux
4. Security-Focused Distributions
Distribution Description
Parrot Security
Similar to Kali, focused on security, privacy, and development tools.
OS
5. Server Distributions
Distribution Description
Ubuntu Server Server edition of Ubuntu, known for ease of use and deployment.
6. Specialized Distributions
Distribution Description
Linux 6
2. Basic Commands & Usage
Basic Linux commands
These are some of the most common and used Linux commands. you can refer
this as commands Cheatsheet.
Navigation
Command Description
cd Change directory
cd /path/to/directory Change to specified directory
cd . Current directory
cd .. Parent directory
cd ~ Home directory
cd - Previous directory
ls List files and directories
ls -l Long format
ls -a Including hidden files
ls -i Display inode numbers
ls -lh Human-readable file sizes (e.g., KB, MB, GB)
ls -r Reverse the order of the sort to list files in reverse
ls -R Recursively list subdirectories
ls -lS Sort files by size, largest first
ls -d */ List only directories
pwd Print working directory
File Management
Command Description
cp Copy files or directories
cp file1 file2 Copy file1 to file2
Linux 7
cp -r directory1 directory2 Copy directory1 to directory2 recursively
cp -i Protect from overwriting a file
mv Move or rename files/directories
mv file1 newfile Rename file1 to newfile
mv file1 /path/to/directory/ Move file1 to specified directory
rm Remove files or directories
rm file1 Remove file1
rm -r directory1 Remove directory1 recursively
rm -i directory1 Prompt before removing files or directories
touch Create an empty file
touch filename Create an empty file named filename
System Information
Command Description
uname Print system information
uname -a Print all system information
hostname Print or set system name
top Display system processes
htop Display system processes (interactive)
Linux 8
User Management
Command Description
whoami Print the current username
who Display information about users currently logged in
useradd Add a new user
passwd Change user password
usermod Modify user account
Package Management
Command Description
Process Management
Command Description
ps Display information about running processes
ps aux Detailed list of running processes
kill Terminate a process
kill PID Terminate the process with the specified PID
Networking
Command Description
ifconfig Display network configuration
ip Display network configuration
ping Test network connectivity
ping [Link] Test connectivity to [Link]
netstat Display network connections and routing tables
traceroute Trace the route to a network host
Linux 9
File Permissions
Command Description
chmod Change file permissions
chmod +x filename Make file executable
chown Change file owner
chown user:group filename Change owner of filename to user and group
System Logs
Command Description
dmesg Display kernel messages
journalctl Query and display messages from the journal
Keyboard shortcuts ⌨️
Shortcut Action
Ctrl + A Move to the beginning of the line.
Ctrl + E Move to the end of the line.
Ctrl + U Cut/delete the line before the cursor.
Ctrl + K Cut/delete the line after the cursor.
Ctrl + W Cut/delete the word before the cursor.
Ctrl + Y Paste the last cut text.
Ctrl + L Clear the terminal screen.
Ctrl + C Cancel the current command.
Ctrl + Z Suspend the current command.
Ctrl + R Search the command history.
!! Repeat the last command.
!n Execute the n th command in history.
Linux 10
General Shortcuts
Shortcut Description
Alt + F2 Open the run command dialog
Alt + Tab Switch between open applications
Ctrl + Alt + T Open a new terminal window
Ctrl + Alt + L Lock the screen
Alt + F4 Close the current window
Shortcut Description
Ctrl + O Write out (save) the file
Ctrl + X Exit the editor
Ctrl + K Cut the selected text
Ctrl + U Paste the cut text
Ctrl + W Search within the file
Linux 11
3. Files & Directories
Filesystem 📂
The Linux filesystem follows the Filesystem Hierarchy Standard (FHS), which
defines the directory structure and directory contents in Unix-like operating
systems. Understanding the Linux filesystem is crucial for system
administration, development, and troubleshooting.
key points
Standard Directories
Directory Description
/boot Static files of the bootloader, such as the kernel and initrd images.
Linux 12
User home directories. Each user has a subdirectory here (e.g.,
/home
/home/user).
/media Mount points for removable media like CDs, DVDs, and USB drives.
/run Runtime data for processes started since the last boot.
/srv Data for services provided by the system (e.g., web server data).
Filesystem Types
ext4: Default on most Linux distributions; journaling, fast, and reliable.
Btrfs: Modern, supports snapshots, RAID, and advanced features for data
integrity.
ZFS: Powerful, scalable, with RAID and built-in compression; often used in
enterprise setups.
FAT32: Simple, widely compatible but limited to 4GB files, commonly used
on USB drives.
exFAT: Supports larger files than FAT32, often used on external drives.
Filesystem Commands
Command Description Example
Linux 13
cd Change the current directory cd /home/user
🔐
Linux 14
Permissions 🔐
To view and modify file permissions, you can use the ls -l command to list
files and their permissions and the chmod command to change permissions.
chmod u+x [Link] : Adds execute permission for the owner of the file.
chmod go-w [Link] : Removes write permission for the group and others.
chmod a+r [Link] : Adds read permission for all users (owner, group, and
others).
4: read permission
2: write permission
1: execute permission
Wildcard
Linux 15
Example: .txt matches all files ending with ".txt".
Example: !*.log matches all files except those ending with ".log".
locate command 📌
The locate command in Linux is used to quickly find files and directories by
name. It relies on a database that is periodically updated, making it faster than
searching through the file system in real-time. Here’s a detailed overview:
Usage: Useful for locating files without having to perform a full file system
search.
Basic Syntax
Linux 16
pattern : The search term or pattern to look for in the file names.
Common Options
i : Perform a case-insensitive search.
locate -i pattern
locate -r 'pattern.*'
locate -n 5 pattern
locate -c pattern
2. Searching:
When you run locate , it searches through the database rather than the
file system, which is much faster.
Linux 17
3. Updating the Database:
sudo updatedb
find command 🔎
The find command in Linux is a powerful tool used to search for files and
directories in a directory hierarchy based on various criteria. Unlike locate ,
which searches a pre-built database, find performs real-time searches directly
on the filesystem.
Usage: Useful for locating files and directories with specific attributes or for
performing batch operations on files.
Basic Syntax
Linux 18
find /path/to/search -iname "filename"
d for directories
Example: +1M for files larger than 1 MB, 100k for files smaller than 100
KB
Linux 19
find /path/to/search -group groupname
print : Print the file names (default action if no other action is specified).
Examples
Find all .txt files in the current directory and its subdirectories:
Linux 20
find / -type d -name "backup"
Linux 21
4. Text Editors & String Manipulation
vim VS nano 📄
Vim and Nano: A Detailed Overview
When it comes to text editors in the Linux/Unix world, Vim and Nano are two of
the most commonly used. Each has its own strengths and is suited for different
types of users and use cases. Below is a detailed overview of both editors.
Vim
Overview:
Vim stands for Vi Improved and is an enhanced version of the older Vi text
editor.
Vim is known for its steep learning curve but offers efficiency and speed
once mastered.
Key Features:
Modes: Vim operates in several modes:
Linux 22
Basic Commands:
Opening a file: vim filename
Save and exit: Press Esc , then type :wq and press Enter .
Exit without saving: Press Esc , then type :q! and press Enter .
Pros:
Extremely powerful and flexible once mastered.
Extensive plugin support makes Vim suitable for a wide range of tasks,
including coding.
Cons:
Steep learning curve for beginners.
Nano
Overview:
Nano is a simple and easy-to-use text editor that is more accessible for
beginners compared to Vim.
Linux 23
It is designed to be straightforward, with a focus on simplicity and ease of
use.
Key Features:
Ease of Use: Nano is beginner-friendly, with commands listed at the bottom
of the editor.
Basic Commands:
Opening a file: nano filename
Pros:
Very user-friendly and easy to learn, even for users with no prior
experience.
Cons:
Less powerful than Vim; limited features and customization options.
Linux 24
String Manipulation
1. strings : used to extract readable text strings from binary files. When you
run strings on a file, it scans through the binary data looking for sequences
of printable characters and displays them. This is often useful for extracting
human-readable information from compiled executables or other binary
files.
strings [Link]
2. env : Environment variables in Linux are dynamic values that can affect the
behavior of processes and programs running in the operating system.
$ env
$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/bin
export PATH=$PATH:/path/to/new/directory
3. cut : It is used for cutting out sections from each line of a file or from piped
data.
Linux 25
# Extract 5th character from each line
cut -c 5 [Link]
4. head : By default the head command will show you the first 10 lines in a file.
6. paste : The paste command is similar to the cat command, it merges lines
together in a file.
EXAMPLES
# Display the first 5 lines (head) and the last 5 lines (ta
paste <(head -n 5 [Link]) <(tail -n 5 [Link])
# Display the first 3 lines (head) and the last 3 lines (ta
paste <(ls | head -n 3) <(ls | tail -n 3)
Linux 26
8. unexpand : Opposite of expand
tr -s '\t' ' ' < [Link] > [Link] #It will reove tabs
tr -s '\n' ' ' < [Link] # This change the newline into
tr -s ';' ' ' < [Link] # This will change semicolon to
sort [Link]
hello
HELLO
11. split : This will split it into different files, by default it will split them once
they reach a 1000 line limit.
Linux 27
# his splits [Link] into files each containing 100 lines
split -l 100 [Link]
12. join : The join command allows you to join multiple files together by a
common field:
1 John Doe
2 Jane Doe
3 Mary Sue
13. uniq : The uniq (unique) command is another useful tool for parsing text.
Note : uniq does not detect duplicate lines unless they are
14. wc : The wc command stands for "word count" and is used to count the
number of lines, words, and characters in a file.
wc [Link]
Linux 28
-w: Count words.
-c: Count characters.
$ nl [Link]
1. i
2. like
3. turtles
Grep
To find a certain pattern in a file or text, you can use the grep command
Linux 29
grep -rl --include="*.password" "secret" ~
1. egrep:
2. fgrep:
expressions.
This means that fgrep searches for literal occurrences of the specified
strings in the input text, without interpreting any metacharacters or
regular expressions.
It is faster than grep and egrep when searching for fixed strings, as it
does not need to parse and interpret regular expressions.
Example: Searching for lines containing the exact string "apple" in a file:
Linux 30
AWK
It is a powerful and versatile text processing tool in Linux. It is primarily used for
pattern scanning and processing. AWK is abbreviated after it's creators (Aho,
Weinberger, and Kernighan).
Note: The $0 variable points to the whole line. Also, make sure to use single
quotes('') to specify patterns, awk treats double quotes("") as a raw string. To
use double quotes make sure that you escape the ($) sign(s) with a backslash
(\) each, to make it work properly.
Examples:
1. Print Specific Columns:
This prints the first and third columns of each line in the file.
This prints all lines in the file that contain the specified pattern.
This calculates and prints the sum of the values in the first column.
This prints lines in the file that are longer than 10 characters.
Linux 31
This prints the first and third fields of the /etc/passwd file using : as the
field separator.
awk '{ if ($1 > 50) print $1, "is greater than 50"; else
print $1, "is not greater than 50" }' filename
This uses an if-else statement to check if the value in the first column is
greater than 50.
NR: (Number Record) is the variable that keeps count of the rows after
each line's execution... You can use NR command to number the lines
( awk '{print NR,$0}' [Link] ). Note that awk considers rows as records.
This prints lines in the file between the specified start and end patterns.
Linux 32
5. Command Redirection & Execution
Linux Redirectors ➡️
1. > (Output Redirection):
4. | (Pipe):
command1 | command2
Linux 33
Redirects the standard error (stderr) of a command to a file.
command 2>&1
Reads from standard input and writes to standard output and files
simultaneously.
Linux 34
command | tee [Link]
xargs
xargs is a command-line utility in Unix and Unix-like operating systems that
builds and executes command lines from standard input. It is often used to
process and execute command lines on the output of other commands, making
it very powerful for automating repetitive tasks.
Overview of xargs
xargs takes input from standard input (stdin) or a pipe and passes it as
arguments to another command. This is particularly useful for commands that
do not accept standard input directly or need arguments to be passed in a
specific way.
Basic Syntax
Linux 35
Examples
This command will delete file1 , file2 , and file3 by passing them as
arguments to rm .
This command finds all .log files in the current directory and its subdirectories
and deletes them.
This command finds all files and copies them to /backup , two files at a time ( -n
2 ).
and xargs .
This command will delete .log files, even if their names contain spaces or
special characters.
Linux 36
I, --replace=replace-str : Replace occurrences of replace-str in the initial
arguments with input.
t, --verbose : Print the command line on the standard error output before
executing it.
Advanced Usage
This command moves file1 , file2 , and file3 to the /backup directory, using {}
This command downloads files from a list of URLs using wget , running up to 4
download processes in parallel ( -P 4 ).
tar
The tar command in Unix and Unix-like operating systems (such as Linux) is
used to create, maintain, modify, and extract files from an archive file,
commonly called a tarball. The tar format is one of the most common archive
formats and is often used in conjunction with compression tools such as gzip
or bzip2 to create compressed archive files.
Basic Syntax
Linux 37
Commonly Used Options
Option Description
-c Create a new archive.
-x Extract files from an archive.
-v Verbosely list files processed (useful for seeing what's happening).
-f Specify the filename of the archive.
-z Filter the archive through gzip for compression or decompression.
-j Filter the archive through bzip2 for compression or decompression.
Examples
To create a tar archive and compress it with bzip2 , use the -j option:
Linux 38
tar -cJvf [Link] /path/to/directory
exclude option:
Linux 39
tar --exclude='/path/to/exclude' -cvf [Link] /pat
h/to/directory
Linux 40
Query and change the system hostname and
hostnamectl
related settings.
hostnamectl
status Display system hostname and related information. status
hostnamectl
set-hostname Set a new hostname. set-hostname
new-hostname
cat /etc/os-
release
ACL
Overview of ACLs
Purpose: To grant permissions to specific users or groups beyond the
standard owner/group/others model.
Linux 41
Usage: Useful for managing file and directory permissions in environments
with multiple users and complex access requirements.
1. getfacl
Purpose: Display ACLs for files and directories.
Syntax:
getfacl [file/directory]
Example:
getfacl [Link]
2. setfacl
Purpose: Modify ACLs for files and directories.
Syntax:
Options:
Examples:
Linux 42
Grants read, write, and execute permissions to username on [Link] .
Grants username read and execute permissions on all files created in mydir .
setfacl -b [Link]
3. Viewing ACLs
To view the ACLs associated with a file or directory, you can use getfacl :
getfacl [Link]
# file: [Link]
# owner: user
# group: group
user::rw-
user:username:rwx
group::r--
mask::rwx
other::r--
Linux 43
mask::rwx : Maximum effective permissions.
Examples of Use
Set ACL to allow a specific user to read and write a file:
Set default ACLs on a directory so that new files have read access for a
group:
getfacl -R /mydir
Devices
1. Block Devices:
Block devices represent hardware that reads or writes data in fixed-size
blocks, such as hard drives, SSDs, and USB drives.
Linux 44
Block devices are typically found under /dev and have names like /dev/sda ,
/dev/sdb , /dev/nvme0n1 , etc.
You can use the following command to list all block devices:
lsblk
2. Character Devices:
Character devices allow for input and output of data one character at a
time, such as keyboards, mice, and serial ports.
Character device files are also located under /dev , with names like
/dev/tty , /dev/console , etc.
number generator.
Linux 45
Commands to Manage Character Devices:
3. Network Devices:
Network devices represent interfaces for network communication, such as
Ethernet or Wi-Fi cards.
Network interfaces are not typically represented as files in /dev , but you
can see them using commands like ip or ifconfig .
4. Special Devices:
These include device files that provide direct access to certain system
functions, such as /dev/null and /dev/full .
/dev/full: Acts like a full disk; writing to it will always return a "no space
left" error.
5. Virtual Devices:
Linux 46
These are not physical devices but rather virtual interfaces created by the
operating system for specific purposes.
Examples:
6. USB Devices:
USB devices, such as external drives or peripherals, are represented under
/dev , typically as block or character devices.
lsusb
7. Sound Devices:
Represent audio hardware like sound cards.
lsblk
fdisk -l
Linux 47
lsblk
2. lspci :
lspci
3. lsusb :
lsusb
4. dmesg :
5. udevadm :
Manages device nodes created by udev , the device manager for the
Linux kernel.
Boot
The Linux boot process involves several stages, from powering on the system
to loading the operating system and providing a login prompt. Here’s a detailed
explanation of the steps involved:
Linux 48
1. BIOS/UEFI Initialization:
BIOS (Basic Input/Output System) or UEFI (Unified Extensible Firmware
Interface) is the firmware that initializes the hardware when the system is
powered on.
Once the POST is successful, it looks for a bootable device (hard drive,
USB, etc.), usually checking in the boot order configured in the BIOS/UEFI
settings.
The BIOS/UEFI hands over control to the bootloader on the bootable device.
2. Bootloader (GRUB):
The bootloader (most commonly GRUB — GNU GRand Unified Bootloader)
is responsible for loading the Linux kernel into memory.
The bootloader then loads the selected kernel into memory and passes
control to it.
3. Kernel Initialization:
Once the kernel is loaded into memory, it initializes the hardware
components like CPU, memory, and I/O devices.
The kernel also mounts the root filesystem in read-only mode, so it can
access the necessary system files.
The kernel then loads the initial initramfs or initrd (initial RAM filesystem or
disk), which contains necessary drivers and tools required to access the
root filesystem and other hardware components, especially for complex
hardware setups (e.g., RAID, LVM, etc.).
The kernel is the core of the operating system that manages hardware
resources and provides system services.
4. initramfs/initrd:
Linux 49
initramfs (initial RAM filesystem) or initrd (initial RAM disk) is a temporary
filesystem loaded into memory by the kernel.
It contains drivers and tools needed to mount the real root filesystem (e.g.,
RAID, encrypted disks, etc.).
After mounting the actual root filesystem, control is passed to the init
process.
init/systemd is the process that manages system initialization and all other
processes. It runs with a PID of 1.
Systemd configuration files are typically found in /etc/systemd/ and service files
in /etc/systemd/system/ .
Linux 50
At this stage, system services like networking, cron jobs, databases, web
servers, and other background daemons are started.
systemctl get-default
To switch targets:
8. User Space:
After login, the user is taken to their shell (in console mode) or desktop
environment (in graphical mode).
At this point, the boot process is complete, and the system is fully
operational.
2. Bootloader (GRUB): Loads the Linux kernel and passes control to it.
Linux 51
5. init/systemd: The first process ( PID 1 ) starts system services based on the
target or runlevel.
Symlink
What is a Symlink?
A symlink, short for symbolic link, is a type of file in Linux that serves as a
reference or pointer to another file or directory. It is a powerful tool for creating
shortcuts or aliases to files or directories, making it easier to access and
manage files.
Types of Symlinks
There are two types of symlinks:
Creating a Symlink
ln -s target_file symlink_name
target_file is the original file or directory that you want to link to.
For example:
Linux 52
ln -s /usr/bin/vim /bin/vi
This creates a symlink called vi in the /bin directory that points to the vim
Managing Symlinks
List Symlinks: Use the ls command with the l option to list symlinks:
ls -l
Check Symlink Target: Use the readlink command to check the target of a
symlink:
readlink symlink_name
rm symlink_name
Update Symlink: Use the ln command with the s option to update the
target of a symlink:
ln -s new_target_file symlink_name
Linux 53
7. Process, Services, & Package
Management
Service & Process Management
Types of Processes
1. Foreground Processes:
2. Background Processes:
3. Daemon Processes:
top
Display real-time system summary information and top
process list.
htop Interactive process viewer (requires installation). htop
pkill -9
pkill Send a signal to processes by name. firefox
Linux 54
killall
killall Send a signal to all processes by name. firefox
nice -n 10
nice Start a process with a specified priority. command
renice -n 10 -
renice Change the priority of an existing process. p 1234
Linux 55
kill -9 1234 # Forcefully kill the process with PID
1234
Linux 56
of controlling process
Resumes the
SIGCONT 18 Continue if stopped
stopped process
Can be defined by
SIGUSR1 10 User-defined signal 1
the user/application
Can be defined by
SIGUSR2 12 User-defined signal 2
the user/application
Terminates the
SIGALRM 14 Timer signal from alarm
process
Systemctl
Basic Concept
Systemd: Systemd is a system and service manager for Linux operating
systems. It is responsible for initializing the system (starting the user space
and managing services).
Linux 57
Unit Files: Systemd uses unit files to represent services, mount points,
devices, sockets, and other resources that systemd manages.
Service Management
Command Description Example
systemctl start systemctl start
<service> Start a service httpd
systemctl
systemctl
restart Restart a service restart httpd
<service>
systemctl
reload
Reload the configuration of a service without systemctl
restarting it reload httpd
<service>
systemctl
systemctl
status Check the status of a service status httpd
<service>
systemctl
systemctl
enable Enable a service to start at boot enable httpd
<service>
systemctl
systemctl
disable Disable a service from starting at boot disable httpd
<service>
systemctl is-
systemctl is-
active Check if a service is active active httpd
<service>
systemctl is-
systemctl is-
enabled Check if a service is enabled at boot enabled httpd
<service>
systemctl systemctl
daemon-reload Reload systemd manager configuration daemon-reload
System Management
Command Description Example
systemctl reboot Reboot the system systemctl reboot
Linux 58
systemctl hibernate Hibernate the system systemctl hibernate
systemctl isolate Change the system state to the systemctl isolate multi-
<target> specified target [Link]
Cron jobs
Cron jobs in Linux are used for automating tasks that you want to run at
specific intervals. Cron is a time-based job scheduler that enables you to run
commands or scripts automatically at a particular time or date. It is especially
useful for repetitive tasks like backups, monitoring, or updating systems.
A configuration file where you define cron jobs. Each user (including
the system itself) can have their own crontab file. You can edit this file
to schedule your jobs.
3. Cron Format:
Each line in the crontab follows this syntax:
* * * * * command-to-be-executed
| | | | |
| | | | +---- Day of the week (0-7) (Sunday to Saturday,
Sunday can be both 0 and 7)
| | | +------ Month (1-12)
| | +-------- Day of the month (1-31)
| +---------- Hour (0-23)
+------------ Minute (0-59)
Linux 59
Example:
30 2 * * 1 /home/user/[Link]
This cron job runs every Monday at 2:30 AM and executes the script [Link]
located in /home/user/ .
Symbols in Cron:
— Matches any value in that field.
Example: 1,2,3 would match the 1st, 2nd, and 3rd of the month.
crontab -l
crontab -e
This opens your crontab file in the default text editor (usually vim or nano ).
crontab -r
Linux 60
There are some predefined cron job schedules you can use instead of the
numeric format:
0 3 * * 0 /usr/bin/clean_cache.sh
*/15 * * * * /home/user/[Link]
Cron Permissions:
/etc/[Link] — Defines which users are allowed to use cron jobs.
If neither of these files exists, cron is available for all users by default.
Logs:
To check logs of cron jobs, you can view the system log file where cron
messages are stored:
Conclusion:
Linux 61
Cron jobs are essential for automating routine tasks, and mastering them can
significantly improve your productivity in managing systems. You can schedule
backups, monitor services, update systems, or perform any other repetitive
task efficiently with cron.
1. Install a Package:
To install a package using
dpkg , you can use the i option followed by the path to the package file. For
example:
2. Remove a Package:
To remove a package, you can use the
r option followed by the package name. For example:
dpkg -l
Linux 62
dpkg -I package_name
5. Reconfigure a Package:
If you need to reconfigure a package after installation, you can use the
reconfigure option followed by the package name. For example:
dpkg -L package_name
dpkg -l: This command lists all installed packages on the system along
with their details.
grep '^ii' : This command filters the output of dpkg -l to include only
lines that start with ii , which indicates installed packages. The ^ii
pattern matches lines where the second field starts with ii .
wc -l: This command counts the number of lines in the filtered output,
which corresponds to the number of installed packages.
Curl
Linux 63
curl is a command-line tool used to transfer data to or from a server using
various protocols, including HTTP, HTTPS, FTP, and many more. It is commonly
used to make web requests, download files, and interact with APIs. Below is a
detailed overview of curl , its usage, and some common examples.
Basic Usage
The basic syntax for curl is:
curl <[Link]
3. Follow Redirects
By default, curl does not follow redirects. Use the -L option to enable this:
This command will start by making a request to
[Link] . If the server responds with a redirect (e.g., 301 Moved
Permanently or 302 Found ), curl will automatically follow the redirect and make a
curl -L <[Link]
Linux 64
# By default, curl will follow up to 50 redirects. You can
change this limit with the --max-redirs option
curl -I <[Link]
7. Downloading a File
To download a file from a URL:
curl -O <[Link]
Linux 65
curl -H "Authorization: Bearer token" <[Link]
pi>
Additional Resource
This is contains useful resources to learn further and practice Hands- on Linux
commands
[Link]
o-linux-mastery-c691c09b437c
Networking
There are various networking tools which can be used to analyze the network
1. ping
2. traceroute
4. host
5. netstat and ss
Linux 66
6. lsof
7. nmap
10. tcpdump
13. arp
1. ping
W <wait>: Wait for the specified number of seconds for a response, then
stop sending packets.
2. traceroute
Linux 67
n : Display numerical addresses instead of hostnames.
traceroute -m 10 -n -w 2 [Link]
Description: Query the Domain Name System (DNS) to obtain information about
a specific domain name or IP address. nslookup is a simple command-line tool,
while dig (Domain Information Groper) is more powerful and flexible.
+trace : Perform a DNS trace, showing the sequence of DNS servers used to
resolve the query.
4. host
Description: A simple command-line tool that performs a DNS lookup and
displays the IP addresses associated with a given hostname.
Common options:
t <type> : Specify the record type to look up (e.g., A, AAAA, MX, etc.).
host -a [Link]
5. netstat and ss
Linux 68
Common options for ss:
ss -tunp
6. lsof
Description: Lists open files and the processes that opened them. This can be
useful for identifying network connections and the processes associated with
them.
Common options:
i : Display information about network files (e.g., sockets, pipes, and FIFOs).
p : Display the PID and name of the process associated with each file.
lsof -i -n -p
7. nmap
Description: A powerful network mapping and port scanning tool used to
identify hosts and services on a target network. Nmap uses raw IP packets to
determine the hosts and services available on a target network, as well as the
operating systems and types of packet filters/firewalls in use.
Common options:
F : Use the "fast" scan option, which uses a small number of packets and is
faster
nmap -F [Link]/24
Linux 69
Description: Command-line tools for making HTTP requests and transferring
files from or to a server. Both tools can be used to test web application
functionality, retrieve files, or perform simple web application attacks.
X <method> : Use the specified HTTP method (e.g., GET, POST, PUT, DELETE,
etc.).
d <data> : Send the specified data in the request body (for POST or PUT
requests).
X <method> : Use the specified HTTP method (e.g., GET, POST, PUT, DELETE,
etc.).
: Send the specified data in the request body (for POST or PUT
d <data>
requests).
Linux 70
Common options for nc:
zv : Scan for listening daemons (ports with services) on the target host.
nc -zv [Link]
10. tcpdump
Description: A powerful command-line tool for capturing and analyzing network
traffic in real-time. Tcpdump can be used to monitor network activity,
troubleshoot network issues, and analyze network protocols.
Common options:
Linux 71
m : Display traffic in megabits per second (Mbps).
iftop -i eth0 -n -m
add <destination>/<mask> via <gateway> dev <interface> : Add a new route to the
kernel routing table.
ip route show
13. arp
Description: Manipulate the ARP table, used by the Linux kernel to map IP
addresses to MAC addresses.
Common options:
ip addr show
Linux 72
Description: Display or manipulate the kernel routing table. route is an older
command, while ip route is its modern replacement.
add <destination>/<mask> via <gateway> dev <interface> : Add a new route to the
kernel routing table.
ip route show
SSH
SSH (Secure Shell)
SSH (Secure Shell) is a protocol used to securely connect to a remote machine
or server over a network. It encrypts the connection, ensuring that data is
securely transmitted between the client and the server.
ssh username@remote_host
Example
ssh user@[Link]
This command will prompt you for the password of the user on the remote
machine. Once authenticated, you'll be connected to the remote machine's
terminal.
Linux 73
If the SSH server is running on a port other than the default port 22, you can
specify the port number using the -p option:
Example:
In this example, SSH connects to the server on port 2222 instead of the default
port 22.
This generates a pair of keys (private and public). By default, they are
stored in ~/.ssh/id_rsa (private) and ~/.ssh/id_rsa.pub (public).
ssh-copy-id username@remote_host
This copies your public key to the remote server, allowing you to log in
without a password.
ssh username@remote_host
Linux 74
ssh -i ~/.ssh/id_rsa username@remote_host
Network Sharing
1. NFS (Network File System)
How it works:
NFS allows a client to access files on a remote server as if they were local. The
client sends a request to the server to mount a shared directory, and the server
responds with the file system information. The client can then access the files
in the shared directory.
Step-by-Step Process:
Server Side:
3. Set permissions:
Linux 75
sudo chmod 755 /shared/directory
4. Edit /etc/exports:
Add the following line to share the directory with the client IP address:
Replace
[Link] with the client's IP address.
/shared/directory [Link](ro,async,no_subtree_chec
k)
Client Side:
df -h
File Transfer:
Linux 76
cp /local/file /mnt/nfs/
ls /mnt/nfs/
2. Samba
How it works:
Samba provides a way to share files and printers between Linux and Windows
systems. The client sends a request to the server to access a shared resource,
and the server responds with the resource information.
Step-by-Step Process:
Server Side:
1. Install Samba:
3. Set permissions:
4. Edit /etc/samba/[Link]:
Add the following lines to share the directory:
Replace
username with the username of the user who will access the share.
[shared]
path = /shared/directory
available = yes
valid users = username
read only = no
Linux 77
browsable = yes
public = yes
writable = yes
2. Enter credentials:
Enter the username and password of the user who has access to the share.
File Transfer:
FTP allows users to transfer files between systems over a network. The client
sends a request to the server to access a file, and the server responds with the
file information.
Step-by-Step Process:
Server Side:
Linux 78
sudo mkdir /shared/directory
3. Set permissions:
4. Edit /etc/[Link]:
Add the following lines to configure the FTP server:
anonymous_enable=NO
local_enable=YES
write_enable=YES
Client Side:
ftp server_ip
4. Login:
Enter the username and password when prompted.
Linux 79
5. Navigate to the Shared Directory:
Use the
cd command to change to the shared directory:
cd /shared/directory
File Transfer:
1. Upload a File:
Use the
put command to upload a file:
put [Link]
2. Download a File:
Use the
get command to download a file:
get [Link]
3. List Files:
Use the
ls command to list files in the current directory:
ls
SSH allows secure remote access and file transfer over an encrypted
connection. SCP (Secure Copy Protocol) and SFTP (SSH File Transfer Protocol)
are commonly used for file transfers.
Step-by-Step Process:
Server Side:
Linux 80
2. Start SSH Service:
Client Side:
ssh username@server_ip
Replace username with your server username and server_ip with the server's
IP address.
2. Authenticate:
Enter the password when prompted.
File Transfer:
1. Using SCP:
Upload a File:
Download a File:
scp username@server_ip:/remote/path/[Link] /l
ocal/path
2. Using SFTP:
sftp username@server_ip
Upload a File:
Linux 81
put [Link]
Download a File:
get [Link]
List Files:
ls
5. Using rsync
How it works:
rsync is a powerful tool for syncing files and directories between systems. It
uses a delta-transfer algorithm, which means it only transfers the changes
made to files, making it efficient.
Step-by-Step Process:
2. Sync Files:
3. Verify Sync:
Use the
ls command to verify that files have been transferred successfully.
Linux 82
Conclusion
By following the above steps for each method, you can successfully transfer
and receive files over a network in a Linux environment. Each method has its
strengths, so choose the one that best fits your needs based on the
environment and requirements.
Http server
To start a simple HTTP server in Linux, you can use the python or http-server
Using Python:
1. Navigate to the directory you want to serve:
cd /path/to/directory
This command starts a basic HTTP server on port 8000 (you can specify a
different port if needed).
cd /path/to/directory
Linux 83
3. Start the HTTP server:
http-server -p 8080
Linux 84