By Sheldon L | Published at 2019-11-09 | Updated at 2020-04-20 |
ring zero
(kernel space
);user space
;Linux: Fedora, Debian, CentOS, OpenSUSE
Power On
- BIOS
- MBR (First Sector of the Hard Disk)
- Boot Loader
- Kernel
- initramfs
- /sbin/init
- Shell by getty
- (X Windows System) GUI
/sbin/init
:
Traditionally, /sbin/init
is serial processes SysVinit
, did not easily take advantage of the parallel processing. Some modern methods, such as the use of containers, can require almost instantaneous startup times. Thus, systems now require methods with faster and enhanced capabilities
Upstart
Developed by Ubuntu and first included in 2006; Adopted in Fedora 9 (in 2008) and in RHEL 6 and its clones.
systemd
Adopted by Fedora first (in 2011); Adopted by RHEL 7 and SUSE; Replaced Upstart in Ubuntu 16.04; Replaced Upstart
in Ubuntu 16.04. It has been adopted by the major distributions
/sbin/init
now just points to /lib/systemd/systemd
;
# start|stop|restart|enable|disable
sudo systemctl start|stop|restart nfs.service
sudo systemctl enable|disable nfs.service
# Confirm
sudo ss -antlp | grep [service]
# List all available services
systemctl list-unit-files
lsof -i -P -n
A partition is a physically contiguous section of a disk, or what appears to be so in some advanced setups.
A filesystem is a method of storing/finding files on a hard disk (usually in a partition), is a prominent aspect of the kernel. In Linux, “Everything is a file”.
Each filesystem on a Linux system occupies a disk partition. Partitions help to organize the contents of disks according to the kind and use of the data contained. One advantage of this kind of isolation by type and variability is that when all available space on a particular partition is exhausted, the system may still operate normally. gparted
can displays the partition
with device node
and mount point
.
In Linux, Filesystems Structured like a tree. Merge all the file stores into a single hierarchy, which allows users and applications to access data by knowing its location within that hierarchy: such as /
, /home/user_name
, /home/user_name/Desktop/file.txt
tree -aCd -L 1 /
tree -aCd -L 1 /usr
tree -aCd -L 2 /home
tree -aCd -L 1 /var
ext2
, ext3
, ext4
are widely used in Linux. Formating command: ‘mkfs.ext3
’ (Make FileSystem)squashfs
btrfs
fat
, vfat
, ntfs
: DOS and WindowsNFS
, CIFS
(also termed SAMBA
): Network Filesystems, may have all its data on one machine or have it spread out on more than one network node.xfs
: SGIjfs
: IBMhfs
, hfs+
: MacOSjournaling
varieties: ext4
, xfs
, btrfs
, and jfs
. These have many state-of-the-art features and high performance, and are very hard to corrupt accidentally.mount point
. This is simply a directory (which may or may not be empty) where the filesystem is to be grafted on. Sometimes, you may need to create the directory if it does not already exist.mount | head -10 # mount: show all presently mounted filesystems
df -Th # df: disk free, T: filesystem Type
df -H
cat /proc/mounts
sudo mount /dev/sda5 /home # /dev/sda5: device node, /home: mount point
# There are other ways to specify the partition other than the device node, such as using the disk label or UUID.
sudo umount /home
# To be automatically available every time the system starts up,
# edit /etc/fstab (filesystem table)
man fstab
sudo systemctl start nfs
/etc/exports
contains the directories and permissions that a host is willing to share with other systems over NFS. A very simple entry in this file: /projects *.example.com(rw)
. This entry allows the directory /projects to be mounted using NFS with read and write (rw) permissions and shared with other hosts in the example.com domain.cat /etc/exports
exports -av # notify Linux about the directories you are allowing to be remotely mounted
sudo systemctl restart nfs
sudo systemctl enable nfs
# Note: On RHEL/CentOS 8, the service is called nfs-server, not nfs
/etc/fstab
is modified to accomplish this. An entry in the client’s /etc/fstab might look like: servername:/projects /mnt/nfs/projects nfs defaults 0 0
cat /etc/fstab
sudo mount [servername|IP]:/projects /mnt/nfs/projects
cat /etc/fstab
man fstab
/proc/
, /sys/
, /dev/
;/dev/
:
/dev/sda1
;/dev/input/mouse0
;/dev/input/event0
;/dev/snd/*
;/dev/ttyS*
;block
device: has finit size, can access at any position, e.g. disk drives and partitions;character
device: like a flow of characters, can read and write, but cannot seek to a given position and change arbitrary bytes, e.g. mouse, keyboard, serial ports;ls -l /dev/sda /dev/ttyS0
# results:
# brw-rw---- 1 root disk 8, 0 Apr 21 07:43 /dev/sda # b for block
# crw-rw---- 1 root dialout 4, 64 Apr 21 07:43 /dev/ttyS0 # c for character
# file type, rights, hard link count, user owner, group owner, file size (bytes indefault, or -h), timestamp, name
ls -l[t|S]r # sort by name/size reversly
file /dev/sda*
file /dev/snd/*
Files or directories prefix
Symbol | File Type | Description |
---|---|---|
d |
directory | A file used to store other files. |
- |
regular file | Includes readable files, images files, binary files, and compressed files. |
l |
symbolic link | Points to another file. |
s |
socket | Allows for communication between processes. |
p |
pipe | Allows for communication between processes. |
b |
block file | Used to communicate with hardware. |
c |
character file | Used to communicate with hardware. |
D |
Door |
/root/
or /home/user_name/
or /home/department_name/user_name/
- user’s personal files, application configuration files are often stored directly as ~/.dotfiles
. On multi-user systems, the /home
directory infrastructure is often mounted as a separate filesystem on its own partition, or even exported (shared) remotely on a network through NFS.
/bin/
and /sbin/
:
/bin/
- basic programs (cat
, cp
, ls
, mv
, ps
, rm
…)/sbin/
- system programs (fdisk
, mkfs
, sysctl
…)/usr/bin
and /bin
are actually just symbolically linked together, as are /usr/sbin
and /sbin
, in newest Linux distributions./proc/
- “pseudo-file”, contains virtual files that permit viewing constantly changing kernel data. It does not contain real files, but runtime system information. Some important entries in /proc are:
/proc/cpuinfo
/proc/interrupts
/proc/meminfo
/proc/mounts
/proc/partitions
/proc/version
/proc/<Process-ID-#>
/proc/sys
/sys/
- “pseudo-files”, giving information about the system and the hardware. Can be used to alter system parameters and for debugging purposes./dev/
- “pseudo-file”, contains device nodes
, used by most hardware and software devices, except for network devices. It is empty on the disk partition when it is not mounted. It contains entries which are created by the udev
system, which creates and manages device nodes
on Linux, creating them dynamically when devices are found:
/dev/sda1
(first partition on the first hard disk)/dev/lp1
(second printer)/dev/random
(a source of random numbers)./var/
- variable data handled by daemons, contains files that are expected to change in size and content as the system is running. It may be put on its own filesystem so that growth of the files can be accommodated and any exploding file sizes do not fatally affect the system.
/var/log
/var/lib
/var/spool
/var/tmp
./var/ftp
(the FTP service), /var/www
(the HTTP web service)…/etc/
- configuration files, no binary programs, some executable scripts. For system-wide
configuration files and only the superuser can modify files there. User-specific
configuration files are always found under their home directory.
/boot/
- kernel and other files required for early boot process
vmlinuz
: The compressed Linux kernel, required for booting.initramfs
: The initial RAM filesystem, required for booting, sometimes called initrd
, not initramfs.config
: The kernel configuration file, only used for debugging and bookkeeping.System.map
: Kernel symbol table, only used for debugging./boot/grub/grub.conf
or /boot/grub2/grub2.cfg
/lib/
and /lib64
- basic libraries (common code shared by applications) for the essential programs in /bin
and /sbin
. Most of these are what is known as dynamically loaded libraries (also known as shared libraries or Shared Objects (SO))
/bin
and /sbin
, the directories may point to those under /usr
/lib/modules/<kernel-version-number>
/media/*
- mount points for removable devices/run/
- volatile runtime data (not yet included in th FHS), modern Linux distributions place those historically done under the /media
under the /run
/run/media/student/myusbdrive
/mnt/
- temporary mount point, or these can be temporary partitions, or so-called loopback filesystems pretend to be partitions./opt/
- extra applications provided by third parties./srv/
- data used by servers hosted on this system/temp/
- temporary files (typically deleted on boot)/usr/
- Multi-user applications, utilities and data
/usr/include
- Header files used to compile applications/usr/share/
- Shared data used by applications, generally architecture-independent/usr/local/
- Data and programs specific to the local machine, used by the administrator for installing applications manually without overwriting files handled by dt packaging system (dpkg
). Subdirectories include bin
, sbin
, lib
, share
, include
…/usr/src
- Source code, usually for the Linux kernel/usr/lib
and /usr/lib64
- Libraries for programs in /usr/bin
and /usr/sbin
/usr/sbin
and /usr/bin
- Respectively, non-essential system binaries (such as system daemons) and the primary directory of executable commands on the systemdiff
/cmp
and patch
<diff|cmp> -<c|r|i|w|q> [filename1] [filename2]
# c: context before and after the lines differing in content
# r: recursively compare subdirectories
# i: ignore the case of letters
# w: ignore differences in spaces and tabs (white space)
# q: quiet: only report if files are different without listing the differences
diff3 [MY-FILE] [COMMON-FILE] [YOUR-FILE] # compare 3 files
# A patch file contains the deltas (changes) required to update an older version of a file to the new one.
# The patch files are actually produced by running diff with the correct options
diff -Nur [originalfile] [newfile] > [patchfile]
# To apply a patch, you can just do either of the two methods below:
patch -p1 < patchfile
patch [originalfile] [patchfile]
cd /tmp
cp /etc/group /tmp/group
dd if=/tmp/group of=/tmp/GROUP conv=ucase
# copy group to GROUP and convert to upper-cases, ucase: upper-case
diff -Nur group GROUP > group_GROUP
cat group_GROUP
patch --dry-run group group_GROUP
patch group group_GROUP
diff group GROUP
comm
# comm
comm scan_a.txt scan_b.txt # unique in a, unique in b, common in ab
comm -12 scan_a.txt scan_b.txt # only common in ab
vimdiff
# vimdiff
vimdiff scan_a.txt scan_b.txt # open vim with multiple files
file
utility, it examines the contents and certain characteristics to determine whether the files are plain text, shared libraries, executable programs, scripts, or something else.file *
rsync [sourcefile] [destinationfile]
# copy files from one machine to another
rsync -r [sourcefile] [archive-machine]:[archives/destinationfile] -dry-run
# Note that rsync can be very destructive!
# using the -dry-run option to ensure that it provides the results that you want
# A good combination of options
rsync --progress -avrxH --delete [sourcedir] [destdir]
Command | Usage |
---|---|
gzip |
The most frequently used Linux compression utility |
bzip2 |
Produces files significantly smaller than those produced by gzip |
xz |
The most space-efficient compression utility used in Linux |
zip |
Is often required to examine and decompress archives from other operating systems |
tar |
(tape archive) Is often used to group files in an archive and then compress the whole archive at once. |
gzip * # Each file is compressed and renamed with a .gz extension
gzip -r [projectX] # Compresses all files in the projectX directory recursively
gunzip foo # De-compresses foo found in the file foo.gz
gzip -d foo # Same as above
bzip2 * # Each file is compressed and renamed with a .bz2 extension
bunzip2 *.bz2
bzip2 -d *.bz2
xz * # Each file is compressed and renamed with a .gz extension
xz foo # Compresses foo into foo.xz using the default compression level (-6), and removes foo if compression succeeds
xz -dk bar.xz # Decompresses bar.xz into bar and does not remove bar.xz
xz -dcf a.txt b.txt.xz > abcd.txt # Decompresses a mix of compressed and uncompressed files to standard output
xz -d *.xz # Decompresses the files compressed using xz
zip backup * # Compresses all files in the current directory and places them in the backup.zip
zip -r backup.zip ~ # Archives your login directory (~) and all files and directories under it in backup.zip
unzip backup.zip # Extracts all files in backup.zip and places them in the current directory
tar zcvf mydir.tar.gz mydir # Create the archive and compress with gzip
tar jcvf mydir.tar.bz2 mydir # Create the archive and compress with bz2
tar Jcvf mydir.tar.xz mydir # Create the archive and compress with xz
tar xvf mydir.tar # Extract all the files in mydir.tar into the mydir directory
tar xvf mydir.tar.gz # Extract all the files in mydir.tar.gz into the mydir directory
# Note: You do not have to tell tar it is in gzip format
# You can separate out the archiving and compression stages:
tar cvf mydir.tar mydir ; gzip mydir.tar
gunzip mydir.tar.gz ; tar xvf mydir.tar
# BUT this is slower and wastes space by creating an unneeded intermediary .tar file.
# Archiving (Backing Up) Home Directory
tar zcvf /tmp/backup_home.tar.gz ~
ls -lh /tmp/backup* # h: human-readable
gzip
, bzip2
, and xz
time tar zcvf mydir.tar.gz mydir
time tar jcvf mydir.tar.bz2 mydir
time tar Jcvf mydir.tar.xz mydir
du -shc mydir mydir.tar.gz mydir.tar.bz2 mydir.tar.xz mydir.tar.xz
# gz is the fastest, xz is the most compressed
dd
: Disk-to-Disk, “Data Definition”, “Disk Destroyer”, “Delete Data”# Back Master Boot Record (MBR) (the first 512-byte sector on the disk
# that contains a table describing the partitions on that disk),
dd if=/dev/sda of=sda.mbr bs=512 count=1
# WARNING!
# DANGER!
dd if=/dev/sda of=/dev/sdb # make a copy of one disk onto another
vi
and emacs
text editors)GNOME
or KDE
)sudo
.SELinux
or AppArmor
. For example, all Red Hat-based systems including Fedora and CentOS always use SELinux
by default, and Ubuntu comes with AppArmor
up and running.On other operating systems, these tools have to be obtained and installed separately, often at a high cost, while on Linux they are all available at no cost through standard package installation systems.
convert
: A command line tool (part of the ImageMagick set of applications) that can modify image files in many ways. The options include file format conversion and numerous image modification options, such as blur, resize, despeckle, etc.Kickstart file
for Red Hat-based systems, an AutoYAST profile
for SUSE-based systems, and a Preseed file
for Debian-based systems.sudo apt install gnome-tweaks
dpkg
or rpm
) takes care of the details of unpacking individual packages, running scripts, getting the software installed correctly;apt
(on dpkg
), yum
(on rpm
), dnf
(replacement of yum
) or zypper
(on rpm
)) works with groups of packages, downloads packages from the vendor, and figures out dependencies.Process Types | Description | Examples |
---|---|---|
Interactive Processes | Started by a user | bash , firefox , top |
Batch Processes | Automatic processes scheduled from and then disconnected from the terminal, queued and work on a First-In, First-Out basis | updatedb , ldconfig |
Daemons | Server processes that run continuously, wait for a user or system request | httpd , sshd , libvirtd |
Threads | Lightweight processes, run under the umbrella of a main process, sharing memory and other resources, but are scheduled and run by the system on an individual basis, end without terminating the whole process, a process can create new threads at any time. | firefox , gnome-terminal-server |
Kernel Threads | Kernel tasks that users neither start nor terminate and have little control over. These may perform actions like moving a thread from one CPU to another, or making sure input/output operations to disk are completed. | kthreadd , migration , ksoftirqd |
A critical kernel function called the scheduler constantly shifts processes on and off the CPU.
Zombie Process: sometimes, a child process completes, but its parent process has not asked about its state. it is not really alive, but still shows up in the system’s list of processes.
Unix-like systems, kernel devides CPU (1 core, 1 thread) time into small slice and run each inturn. The PID is used to track process state, CPU usage, memory use, precisely where resources are located in memory, and other characteristics.
ID Type | Description |
---|---|
PID | Unique Process ID number |
PPID | Process (Parent) that started this process. If the parent dies, the PPID will refer to an adoptive parent; on recent kernels, this is kthreadd which has PPID=2 |
TID | Thread ID number. This is the same as the PID for single-threaded processes. For a multi-threaded process, each thread shares the same PID, but has a unique TID. |
ps aux | grep [keyword] # ps aux: displays all processes of all users
ps aux | head -10
ps axo stat,priority,pid,pcpu,comm | head -10
ps -u # display information of processes for a specified user
ps -ef # displays all the processes in the system in full detail
ps -eLf # displays one line of information for every thread
ps -fC [command_name]
pstree
kill -[signal] [pid] # force kill
kill -SIGKILL [pid]
kill -9 [pid] # same as above
term [pid] # terminate gracefully
The priority for a process can be set by specifying a nice value
, or niceness. -20 represents the highest priority and +19 represents the lowest. Only root user can renice a process to a negative value to give it higher priority.
You can also assign a so-called real-time priority
to time-sensitive tasks, a very high priority.
ps lf # show priority
# Setting the Priority when Starting Process
nice -n [nice_value_increament] /bin/[someSlowProcess]
# Changing the Priority of a Runing Process
renice [nice_value_increament] [PID]
renice +5 3077 # increase 5
sudo renice -5 3077 # decrease 5, must in sudo
genome-system-monitor # check priority in monitor
load average
is the average of the load number for a given period of time.
uninterruptible
sleepers, those which cannot be awakened easily.w
# load average (for 1 min, 5 min, 15 min), a single-CPU everage
top
# Output:
# 1st line: time the system has been up, users logged on, load average as `w`
# 2nd line: total processes, the number of running, sleeping, stopped, and zombie
# 3rd line: CPU time divided between users (us) and kernel (sy),
# and the percentage of user jobs running lower priority (ni),
# idle mode (id) should be low if the load average is high,
# the percentage of jobs waiting (wa) for I/O,
# hardware (hi) vs. software interrupts (si),
# steal time (st) is generally used with virtual machines, which has some of its idle CPU time taken for other uses
# Prameters of the table
# Process Identification Number (PID)
# Process owner (USER)
# Priority (PR) and nice values (NI)
# Virtual (VIRT), physical (RES), and shared memory (SHR)
# Status (S)
# Percentage of CPU (%CPU) and memory (%MEM) used
# Execution time (TIME+)
# Command (COMMAND).
# You can enter single-letter commands to change its behavior
# t: Display or hide summary information (rows 2 and 3)
# m: Display or hide memory information (rows 4 and 5)
# A: Sort the process list by top resource consumers
# r: Renice (change the priority of) a specific processes
# k: Kill a specific process
# f: Enter the top configuration screen
# o: Interactively select a new sort order in the process list
# 1: Show every single cpu
vmstat -a 2 1000 # all info, every 2 sec, run 1000 times
uptime
Foreground jobs run directly from the shell, and when one foreground job is running, other jobs need to wait for shell access (at least in that terminal window if using the GUI) until it is completed.
By default, all jobs are executed in the foreground. You can put a job in the background by suffixing & to the command, for example: updatedb &
.
# Ctrl + c : cancel process
# Ctrl + z : pauses the process and wait in background
jobs -l # jobs running in the background
fg %[job-number] # restores a job to the foreground
bg %[job-number] # restarted in the background
kill %[job-number]
[command] &
jobs -l
$ at now + 2 days
at> cat file1.txt
at> <EOT> # press Ctrl+D here
# CROND # driven by /etc/crontab (cron table), run every day/week/month...
crontab -e # 0 10 * * * /tmp/myjob.sh
# OR
touch mycrontab
echo `0 10 * * * /tmp/myjob.sh` > mycrontab
crontab mycrontab
crontab -l # list
crontab -r # remove
touch /tmp/myjob.sh
echo '#!/bin/bash' > /tmp/myjob.sh
echo 'echo Hello I am running $0 at $(date)' >> /tmp/myjob.sh
chmod +x /tmp/myjob.sh
sleep [number]<s|m|h|d> # suspends execution for at least the specified period of time
ln file1 file2 # Suppose that file1 already exists, a hard link, called file2, is created
ln -s file1 file3 # A soft link, file3 clearly points to file1 and has a different inode number
ls -li file? # prints out in the first column the inode number
echo 'file1 content' > file1
cat file1
cat file2
cat file3
echo 'more content written in file2' >> file2
cat file1
cat file2
cat file3
echo 'more content written in file3' >> file2
cat file1
cat file2
cat file3
rm file1
ls -li file?
cat file2
cat file3
Every program run from the command line has three data stream connected to it that serve as communication channels with the external environment. These streams are defined as:
Stream Name | Description | Value |
---|---|---|
STDIN | Data fed into the program (usrally is keyboard) | file descriptor 0 |
STDOUT | Output from the program (default to terminal) | file descriptor 1 |
STDERR | Err messages (default to terminal) | file descriptor 2 |
Piping: |
Redirecting: <
and >
## STDIN
# redirecting to new file
ls
echo "test"
echo "test" > redirection_test.txt
echo "test2" >> redirection_test.txt
echo "test3" 1>> redirection_test.txt # syntax is the same as above
ls
cat redirection_test.txt
echo "Kali Linux is an open source project" > redirection_test.txt
cat redirection_test.txt
# redirecting to an existing file
echo "that is maintained and funded by Offensive Security" >> redirection_test.tx
cat redirection_test.txt
## STDOUT
# redirecting from a file
wc -m < redirection_test.txt
# redirection_test.txt is STDIN
# output (char count) is STDOUT
## STDERROR
ls ./not_exist 2>> error.txt # 2: file descriptor
cat error.txt
ls ./not_exist > error.txt 2>&1
# A special shorthand notation can send anything written to file descriptor 2 (stderr)
# to the same place as file descriptor 1 (stdout)
cat error.txt
ls ./not_exist >& error.txt # an easier syntax for the above
cat error.txt
## Piping
cat error.txt | wc -m > count.txt
cat count.txt
CTRL-ALT-function key
for the VT. For example, press CTRL-ALT-F6
for ‘VT 6’. Actually, you only have to press the ALT-F6
key combination if you are in a VT and want to switch to another VT.telinit
command, as in:sudo systemctl stop <gdm|lightdm|kdm>
# OR
sudo telinit 3
sudo systemctl start <gdm|lightdm|kdm>
# OR
sudo telinit 5
lightdm
for gdm
.sudo
sudo
allows users to run programs using the security privileges of another user, generally root (superuser).su # enter sudo mode
# create the configuration file for 'student' under sudo mode
echo "student ALL=(ALL) ALL" > /etc/sudoers.d/student
chmod 440 /etc/sudoers.d/student
man
, apropos
, --help
, info
and Othersman [pages]
Divided into chapters numbered 1 through 9:
man ls
man passwd
man -k passwd # -k: key word, will return section of a key word
man -k `^passwd$`
man 5 passwd # 5: the section returned by above command
man -f passwd
man -a socket # all pages with the given name in all chapters
apropos passwd # equivalent to `man -k [pages]`
apropos partition
what is passwd # equivalent to `man -f [pages]`
n
: Go to the next nodep
: Go to the previous nodeu
: Move one node up in the indexinfo make
--help
is useful as a quick reference and it displays information faster than the man
or info
pages.uname --help
gnome-help
or yelp
, it can be more detailed as yelp man:cat
, then use Ctrl + l
to shift to other commands.khelpcenter
/usr/share/doc
halt
poweroff
sudo shutdown -h 10:00 "Shutting down for scheduled maintenance."
reboot
sudo shutdown -r 10:00 "Reboot for scheduled maintenance."