Skip to content

Instantly share code, notes, and snippets.

@Bes0n
Last active May 9, 2022 04:55
Show Gist options
  • Select an option

  • Save Bes0n/85916e73f5f3b1771ba2ffe8b791a4b9 to your computer and use it in GitHub Desktop.

Select an option

Save Bes0n/85916e73f5f3b1771ba2ffe8b791a4b9 to your computer and use it in GitHub Desktop.
Preparation for RHCSA based on RHEL 8

EX 200

Lesson 2 - Understanding and Using Essential Tools on RHEL 8

Accessing Linux Systems
  • ssh-keygen - generate ssh key
  • ssh-copy-id web_user@monolith - copy ssh key on remote host
  • ssh web_user@monolith cat /etc/redhat-release - get release info via ssh
  • scp web_user@monolith:/home/web_user/*.gz . - copy any tar files from remote machine on your working directory
  • sftp db_user@monolith - access remote host via secure FTP protocol
  • mget *.gz - grab all files via sftp with .gz extension
Using System Documentation on RHEL 8
  • man httpd or man mariadb - search for manuals
  • info httpd or info mariadb - search for documentation in info
  • ls -la /usr/share/doc | egrep -i "httpd|mariadb|mysql" - search for httpd|mariadb|mysql documentation in directory with case sensitive
  • sudo dnf -y install httpd mariadb - install httpd and mariadb packages
  • mariadb --help | more - get help about mariadb package
  • mariadb -? | more - same as --help
  • whatis httpd mariadb httpd mysql - get man page number
  • apropos httpd - get information about commands and function about the command
  • man 8 httpd.socket - get manual for httpd with page 8
  • more /usr/share/doc/httpd/LICENSE - get information about Apache License
Manipulating Text Files in Linux
  • sudo tree /var/log | more - get tree of directory by one page
  • sudo grep httpd /var/log/* > raw_logs/master.log - forward all found entries with httpd to master.log file
  • sudo grep httpd /var/log/* > raw_logs/master.log 2> /dev/null - draw away all errors
  • wc -l raw_logs/master.log - count number of lines in master.log file
  • journalctl --unit=httpd --no-pager >> raw_logs/master.log - append found entries related to httpd unit with no-pager key to master.log file
  • grep systemd raw_logs/master.log > httpd_logs/systemd.log - look for systemd entry in master.log file and move them to the new file systemd.log
  • egrep -v "dnf|secure" raw_logs/master.log > httpd_logs/no_dnf_secure.log - exclude entries with dnf|secure and forward output to the no_dnf_secure.log file
Editing Text Files Using vi/vim
  • vi commands
    • i - insert
    • u - undo
    • 3x - delete 3 chars after pointer
    • dd - completely remove line
    • p - paste
    • w hosts2 - write and save file as a hosts2 file
Working with Linux Files - Permissions / Links
  • chmod 755 script.sh - rwx for user, read and execute for group and other world
  • chmod -R 777 my_dir - full permission for directory recursively
  • chmod ugo+x script.sh - give execution permission for user, group and others
  • chmod -R go-wx my_dir - remove write and execute permissions for group and other
  • chmod u=rw, go=r file.txt - read and write permission for the user, and read-only permission for group and other
  • chown -R web_user:web_group /web/_data - change user and group ownew of the directory
  • chmod -R g+w /web_data/ - give write permission for group of directory
  • ln -s /web_data/* /var/www - create soft link in /var/www directory
  • ls -li /var/www - get inode numbers of soft links
  • echo 'umask 0027' >> ~/.bashrc - make newly created files not readable by other users.
    • umask works in opposite way - subtractive. Default permissions for file 666 and for directories 777.
    • if umask 0022 - that means newly created file will have permissions 744.
Compressing and Decompressing Files in Linux
  • tar cvf /home/archives/user1.tar user1 - create, verbose and put into file user1.tar content of user1 directory
  • star -cv file=/home/archives/user1.star user1 - same command as above, but with star command
  • tar tvf archives/user1.tar - list content of archive
  • star -tv file=archives/user1.star - get content of star archive
  • gzip archives/user1.tar or bzip2 archives/user1.star - compress archives
  • tar cvfz /home/archives/user2.tar.gz user2 - create archive, compress files with gzip of user2 directory
  • star -cv -bz /home/archives/user2.star.bz2 user2 - create archive, compress files with bzip2 of user2 directory
  • rm -rf user{1..5} - remove directory with name user1 to user5 names
  • tar cvfz archives/project_archive.tar.gz project{1..5} - create archive and compress with gzip directories with names project1 to project5
  • tar xvfj archives/user1.star.bz2 - unarchive and decompress bzip2 archive
  • bzip2 -d archives/CentOS-7.bz2 - decompress archive.
Labs
  • Add the cloud_user identity to the agent and to reload the agent:

    • eval $(ssh-agent -s)
  • Add your cloud_user identity to the agent, which can now act on your behalf:

    • ssh-add
  • Execute a backup command on a remote system:

    • ssh cloud_user@<SECOND_PUBLIC_IP_ADDRESS> tar -czvf wget-server2.tar.gz wget-1*.rpm
  • Hit the Up arrow and perform an scp:

    • scp cloud_user@<SECOND_PUBLIC_IP_ADDRESS>:~/wget-server2*.* .
  • ls -d *[0-9]* - list directories, but not their's content.

Lesson 3.1 Essential File Management Tools

  • find / -name "hosts" - find file by name
  • find /etc -type f -size +100M - find regular file with size more than 100M
  • find / -user student - find files related to the user
  • find /etc -exec grep -l student {} \; 2> dev/null - find any files in /etc that contains student word inside
  • find /etc -size +100c -exec grep -l student {} \; - search for files with size more than 100 bytes and with word student in it
  • find /etc -size +100c -exec grep -l student {} \; -exec cp {} /tmp \; 2>/dev/null - same as command above and copy content to /tmp folder

Lesson 3.5 Working with Links

ln /etc/hosts /root/hardhosts - create hard link for /etc/hosts ln -s /etc/hosts symhosts - create symbolic link

Labs

cp /etc/[a-c]* /tmp/files - copy files starting from abc to /tmp/files

Lesson 4.1 Using Common Test Tools

  • cut -f 3 -d : /etc/passwd - filter 3rd field with delimeter : in /etc/passwd
  • cut -f 1 -d : /etc/passwd | sort -n - numeric sort
  • cut -f 1 -d : /etc/passwd | sort | tr [a-z] [A-Z - sort output and translate lowercase to uppercase

Lesson 4.2 Using grep

  • ps aux | grep ssh
  • grep linda *
  • grep -i linda * - case insensitive
  • grep -A5 linda /etc/passwd - show 5 lines after
  • grep -B5 linda /etc/passwd - show 5 lines before
  • grep -R root /etc - recursive search

Lesson 4.3 Understanding Regular Expression

  • grep 'b.t' file
  • egrep 'b.?t' file
  • grep 'b.*t' file
Using AWK
  • awk -F : '/linda/ { print $4}' /etc/passwd
Using sed
  • sed -n 4p sedfile - print 4th line in the file
  • sed -i s/four/FOUR/g sedfile - replace four with FOUR in the file
  • sed -i -e '2d' sedfile - edit file and remove line 2
Labs
  • grep '\<root\>' * 2>/dev/null - look for root word
  • ps aux | awk '{ print $NF} - print the last column

Lesson 6.3 Understanding Regular Expression

  • useradd - create user
  • usermod - modify properties of user
  • userdel - delete user accounts
  • passwd - set user passwords

Lesson 6.4 Managing User Default Settings

  • useradd -D - specify default settings
  • /etc/default/useradd - default settings for useradd
  • /etc/login.defs - default settings of user
  • /etc/skel - files in this directory will be created during user creation

Lesson 6.5 Understanding etc/passwd and /etc/shadow

  • /etc/shadow - password properties stored in this file
  • tcpdump:!!:18847:::::: - exclamation mark in /etc/shadow file means that password is currently disabled
  • /etc/group - list of existing groups

Lesson 6.5 Creating and Managing Groups

  • groupadd - add groups
  • groupdel - delete groups
  • groupmod - modify groups
  • lid -g wheel - list users of wheel group

Lesson 6.6 Managing password properties

  • chage or passwd - change password settings
  • chage student - modify password's aging for user student

Lesson 7.2 Changing File Ownership

  • chown user[:group] file - set user-ownership
  • chgrop group file - set group-ownership

Lesson 7.4 Managing Basic Permissions

  • chmod 750 myfile - changing permission in absolute mode
  • chmod +x myscript - changing permission in relative mode

Lesson 7.5 Understanding umask

  • 666 - default umask for file
  • 777 - default umask for directory
  • umask 027 - set default umask to 027
  • /etc/profile - umask is coming from this file
  • /home/user/.bash_profile - if you want to setup umask for specific user

Lesson 7.7 Managing Special Permissions

  • SUID - special user ID
    • chmod 4770 myfile - set special user permission
    • chmod u+s myfile- set special user permission
  • GUID - special group ID
    • chmod 2770 mydir - set special group permission
    • chmod g+s mydir- set special group permission
  • Sticky bit
    • chmod 1770 mydir - set sticky bit permission
    • chmod +t mydir - set sticky bit permission
Manaing ACLs (Access Lists)
  • getfacl - shows current settings
  • setfacl -R -m g:somegroup:rx /data/groups - set read and execute permissions for /data/groups directory recursively
  • setfacl -m d:g:somegroup:rx /data/groups - set default permission for newly created files

Lesson 8.3 Managing Runtime Configuration with ip

  • ip addr - manage address properties
  • ip link - show link properties
  • ip route - manage route properties
  • ip -s link show - show statistics
  • ip addr show - show ip address properties
  • ip addr add dev ens33 10.0.0.10/24 - add secondary ip address
  • ip addr add dev ens33 10.0.0.10/24 - add secondary ip address in runtime configuration
  • ifconfig - is obsolete and shouldn't be used anymore. Use ip addr or ip link instead
  • ip route show - get information about network routes
  • ip route add default via 192.168.4.2 - add default route
  • ip route del default via 192.168.4.2 - delete default route
  • cat /ets/resolv.conf - dns file generated by NetworkManager

Lesson 8.5 Managing Persistent Networking with nmcli

  • systemctl status NetworkManager - check that network manager service is running
  • man nmcli-examples - get examples related to nmcli
  • sudo nmcli connection add con-name secondary-ip ifname eth0 ipv4.addresses 192.168.0.125 ipv4.gateway 192.168.0.1 ipv4.dns 8.8.8.8 type ethernet - add secondary ip address for interface eth0
  • nmtui - network manager in graphical interface

Lesson 8.7 Verifying Network Configuration Files

  • /etc/sysconfig/network-scripts - directory of network configuration files
  • nmcli connection up eth0 - to apply new network configuration

Lesson 8.8 Testing Network Connections

  • ping - test connectivity
  • ip addr show - show current configuration
  • ip route show - show current routing table
  • dig - test DNS nameserver working

Lesson 9.2

  • command & - start job in the background

  • To move a job to the background

    • First stop it using Ctrl+Z
    • Type bg to move it to the background
  • jobs - complete overview of running jobs

  • fg [n] - move the last job back to the foreground

  • Ctrl + C - to completeley cancel the job

Lesson 9.3 Getting Process Information with ps

  • ps - overview of current processes
  • ps aux - overview of all processes
  • ps -fax - show hierarchical relations between processes
  • ps -fU linda - show all processes owned by linda
  • ps -f --forest -C sshd - shows a process tree for a specific process
  • ps L - shows format specifiers
  • ps -eo pid,ppid,user,cmd - uses some of these specifiers to show a list of processes

Lesson 9.5 Understanding CPU Load

lscpu - get information about CPU

Lesson 9.6 Monitoring System Activity with top

  • top - dashboard that allow you to monitor current system activity
    • f - show and select from available display fields
    • M - filter on memory usage
    • W - save new display settings
    • 1 - show single CPU load
    • k - kill process
    • r - renice process

Lesson 9.7 Sending Signals to Processes

  • man 7 signals - manual for signals

  • kill PID - to kill process with specific PID

  • pkill and killall - similar to kill command

  • signals

    • 15/sigterm - termination of signal
    • 9/sigkill - kill signal
    • kill -s 15 13210 - terminate signal with pid 13210
    • kill -s 9 13210 - kill signal with pid 13210
    • killall dd - kill all processes with name dd

Lesson 9.8 Managing Priorities and Niceness

  • Nice values range: -20 up to 19

    • Negative nice value indicates an increased priority, a positive nice value indicates decreased priority
    • Users can set their processes to a lower priority, to increase priorities you need root access
  • Execute top and r - to renice process

    • nice -n -1 dd if=/dev/zero of=/dev/null & - start a process with nice value -1
    • renice -n 10 -p 4886 - renice value to 10 for process with PID 4886
Using Tuned Profiles
  • tuned - service that allows for performance optimization in an easy way
    • tuned-adm list - will show a list of profiles
    • tuned-adm profile <name> - will set a profile
    • tuned-adm active - will show the current profile
Setting up Repository Access
  • dd if=/dev/sr0 of=/rhel8.iso bs=1M - create an ISO image

  • mkdir /repo - create a directory /repo

  • /rhel8.iso /repo iso9660 defaults 0 0 - edit fstab and add the following line to the end

  • systemctl datemon-reload - to update fstab configuration

  • mount -a - mount iso

  • RHEL 8 needs two repositories - one is upstream and second one baseos

Create the file /etc/yum.repos.d/appstream.repo with following contents.

[appstream]
name = appstream
baseurl = file:///repo/AppStream
gpgcheck = 0

Create the file /etc/yum.repos.d/base.repo

[BaseOs]
name = BaseOs
baseurl = file:///repo/BaseOs
gpgcheck = 0
  • yum repolist - list repositories

Lesson 10.4 Managing packages with yum

  • yum search nmap - search for nmap package
  • yum install nmap-ncat - install package. Dependencies will be solved automatically
  • yum remove - remove package
  • yum update - will compare all packages' version with repository versions and update them if necessary
  • yum update nmap - update specific package
  • yum provides - similar to yum search, but search is looking for package name and description, while provides is looking for files to find name that you're looking for
  • yum search sepolicy - no packages will be found
  • yum provides */sepolicy - will find necessary packages for us
Last metadata expiration check: 2:49:02 ago on Sat 14 Aug 2021 12:50:54 PM CEST.
policycoreutils-devel-2.8-16.1.el8.i686 : SELinux policy core policy devel utilities
Repo        : rhel-8-for-x86_64-baseos-rpms
Matched from:
Filename    : /usr/bin/sepolicy
  • yum info nmap - get information about package
  • yum list all - list all packages
  • yum list installed list all installed packages

Lesson 10.5 Using yum modules

  • yum module - used to manage module properties
  • yum module list - list available list of modules
  • yum module provides httpd - search for a module that provides specific package
Updating Subscription Management repositories.
Last metadata expiration check: 3:01:17 ago on Sat 14 Aug 2021 12:50:54 PM CEST.
httpd-2.4.37-10.module+el8+2764+7127e69e.x86_64
Module   : httpd:2.4:820190206142837:9edba152:x86_64    
Profiles : common devel minimal
Repo     : rhel-8-for-x86_64-appstream-rpms
Summary  : Apache HTTP Server
  • yum module info php - get information about package
  • yum module info --profile php - shows profiles
  • yum module install php:7.1 or yum install @php:7.1 - install module php with specific version
  • yum module install php:7.1 - installs a specific profile
  • yum install httpd - will have yum automatically enable the module stream this package is in before installing this package.
  • yum module enable php:7.1 - enables the module, but doesn't install anything yet
  • yum module install php:7.1 - will install a specific PHP module stream.
  • yum module install php:7.2 - will update to the newer version and disable 7.1 stream
  • yum distro-sync - to update or downgrade packages from a previous module stream that are not listed in profiles that are installed with the module update

Lesson 10.6 Using yum Groups

  • yum groups are provided to give access to specific catergories of software
  • yum groups list - gives a list of most common yum groups
  • yum groups list hidded - show all yum groups
  • yum groups info <groupname> - shows which packages are in a group
  • yum groups install <groupname> - install group
  • yum groups install --with-optional "Directory Client" - install Directory Client group with Optional packages included

Lesson 10.7 yum update and yum history

  • yum history - gives a list of recently issued commands
  • yum history undo - allow you to undo a specific command, based on the history information
  • yum update - will update all packages on your system
  • yum update <packagename> - update specific package

Lesson 10.8 Using RPM Queries

  • rpm - queries by default are against the database of installed packages, add -p to query package files

    • rpm -qf /any/file - will give you a package name where file is coming from
    • rpm -ql mypackage - will show you a files that are in the package
    • rpm -qc mypackage - will show you configuration files of the package
    • rpm -qp --scripts mypackage-file.rpm - if there are any scripts inside of .rpm package
    • rpm -qd httpd - check which documentation is available for specific package
  • yumdownloader httpd - download, but don't install a package

  • rpm -qp --scripts httpd-2.4.37-39.module+el8.4.0+9658+b87b2deb.x86_64.rpm - check which scripts will be executed during package installation.

Lesson 11.2 Managing Systemd Services

  • systemctl list-unit-files - list current state of unit files
  • systemctl -t help - get list of different unit types
  • systemctl list-units - get status of running unit files
  • systemctl status vsftpd - get status about vsftpd service
  • systemctl start vsftpd - start service
  • systemctl enable vsftpd - enable (start on boot) service

Lesson 11.3 Modifying Systemd Service Configuration

  • /usr/lib/systemd/system - default system-provided systemd unit files
  • /etc/systemd/system/ - custom unit files located here. Custom files should be created here no in /usr/lib/systemd/system system-provided directory
  • /run/systemd - run-time automatically generated unit files
  • systemctl cat unit.service - configuration of unit.file
  • systemctl edit unit.service - to edit unitfiles
  • systemctl show - get list of available parameters
  • systemctl daemon-reload - to apply your changes if you modified unit files

Lesson 12.2 Scheduling tasks

  • crontab -e - create user-specific cron job
  • /etc/cron.d - generic time-specific Cron jobs
[root@localhost ~]# ls -l /etc/cron.*
-rw-r--r--. 1 root root  0 Jun 12  2019 /etc/cron.deny

/etc/cron.d:
total 8
-rw-r--r--. 1 root root 128 Jun 12  2019 0hourly
-rw-r--r--. 1 root root 108 Jan 11  2021 raid-check

/etc/cron.daily:
total 4
-rwxr-xr-x. 1 root root 189 Jan  4  2018 logrotate

/etc/cron.hourly:
total 4
-rwxr-xr-x. 1 root root 575 Jun 12  2019 0anacron

/etc/cron.monthly:
total 0

/etc/cron.weekly:
total 0
  • /etc/crontab - deprecated way of scheduling tasks
[root@localhost etc]# cat /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

Lesson 12.3 Understanding Anacron

  • Anacron is a service behind cron that takes care jobs are executed on a regular basis, but not at a specific time
  • It takes care of the jobs in /etc/cron.{hourly,daily,weekly,monthly}
  • /etc/anacrontab - configuration of anacron

Lesson 12.4 Scheduling with cron

  • crontab -e - as a specific user
  • /etc/cron.d - create a file in this directory
  • 20 16 * * * logger hello - write hello message in /var/log/messages at 16:20 every day of month, each month and each day of week.

Lesson 12.5 Scheduling Tasks with Systemd Timers

  • man 7 systemd-timer - more information about systemd timers
  • man 7 systemd-time - specification of the time format to be used
  • ls -l /usr/lib/systemd/system/*timer - get list of existing systemd timers

Lesson 12.6 Using at

  • atd - the service which should run to schedule a task with at
  • at <time> to schedule a job
  • atq - list of jobs currently scheduled
  • atrm - remove scheduled job

Lesson 12.7 Managing Temporary Files

  • systemd-tmpfiles or /usr/lib/tmpfiles.d - manges settings for creating, deleting and cleaning up of temporary files
  • systemd-tmpfiles-clean.timer - unit which can be configured to automatically clean up temporary files
    • It triggers the systemd.tmpfiles-clean.service
    • This service runs systemd-tmpfiles --clean
  • /usr/lib/tmpfiles.d/tmp.conf - file that contains settings for the automatic tmp file cleanup
  • Copy /usr/lib/tmpfiles.d/tmp.conf to /etc/tmpfiles.d/ - for defining custom configuration file of tmpfiles
  • systemctl daemon-reload and then systemd-tmpfiles --clean /etc/tmpfiles.d/tmp.conf to ensure that there are no errors in tmp.conf file

Lesson 13.1 Understanding Logging Options

  • systemd-journald - heart of all logging on the systemd
  • journalctl - logging can be accessed by this command
  • /var/log/journal - by default systemd-journal keeps logs in memory, to write them in a persistent way you should create this directory.

Lesson 13.2 Configuring Rsyslog Logging

  • rsyslogd - service should be started
  • /etc/rsyslog.conf - main configuration file
  • /etc/rsyslog.d - snap-in files can be placed here
  • Each logger line contains three items
    • facility: the specific facility that the log is created for
    • severity: the severity from which should be logged (ex: debug or emergency)
    • destination: the file or other destination the log should be written to
  • logger - command to write messages to rsyslog manually

Lesson 13.3 Working with systemd-journald

  • systemd-journald - log service that is a part of systemd
  • systemctl status <unit> - in integrates well with status output
  • journalctl - to read log entries in the journal
    • g or G - navigate from top to bottom
    • <= or => - arrow key to move left and right
    • journalctl UNIT=sshd - search logs for specific unit
  • mkdir /var/log/journal - to make journal persistent create this directory
  • vim /etc/systemd/journald.conf - to configure your journald use this configuration file

Lesson 13.4 Preserving the Systemd Journal

  • /run/log/journal - by default journal is written in this directory, which is automatically cleared on system reboot
  • /etc/systemd/journal.conf - edit this file to make the journal persistend across reboots
  • Set the Storage parameter in this file to the appropriate value
    • persistent - will store the journal in the /var/log/journal directory. This directory will be created if it doesn't exist
    • volatile - stores the journal only in /run/log/journal
    • auto - will store the journal in /var/log/journal if that exists, and in /run/log/journal if no /var/log/journal exists

Lesson 13.5 Configuring Logrotate

  • /etc/logrotate.conf - main configuration file
  • /etc/logrotate.d - snap-in files can be provided here

Lesson 14.1 Understanding Disk Layout

  • lsblk - list block devices
  • cat /proc/partitions - list of partitions from the kernel point of view
  • Storage options:
    • Partitions - use to allocate dedicated storage to specific types of data
    • LVM Logical Volumes - adds flexibility to storage (resize, snapshots and more)
    • Stratis - next generation Volume Managing Filesystem that uses thin provisioning by default. Implemented in user space, which makes API access possible.
    • Virtual Data Optimizer - focused on storing files in the most efficient way. Manages deduplicated and compressed storage pools.

Lesson 14.3 Understanding GPT and MBR Partitions

  • MBR - Master Boot Record
    • 4 partitions only with a max. size of 2TiB
    • To use more partitions, extended and logical partitions must be used
  • GPT - GUID Partition Table
    • 128 partitions max
    • More space to store partitions
    • Used to overcome MBR limitations

Lesson 14.4 Creating Partitions with parted

  • parted - default disk utility in RHEL 8
  • fdisk or gdisk can be used alternatively
  • parted /dev/sdb - create a partition
  • print - will show if there is a current partition table
  • mklabel msdos|gpt - create a partition type
  • mkpart part-type name fs-type start end
    • part-type - applies to MBR only and sets primary, logical, or extended partition
    • name - arbitrary name, required for GPT
    • fs-type - does NOT modify the filesystem, but sets some irrelevant file system dependent metadata
    • start end - specify start and end, counting from the beginning of the disk
  • mkpart primary 1024MiB 2048MiB
  • udevadm settle - ensure that the new partition device is created

Lesson 14.5 Creating MBR Partitions with fdisk

  • fdisk /dev/nvme0n3 - access disk with fdisk utility
    • n - new partition
    • m - for help
    • p - print the partition table
    • w - write table to disk and exit

Lesson 14.6 Understanding File System Differences

Filesystems

  • xfs
    • Fast and scalable
    • Uses Copy on Write tu guarantee data integrity
    • Size can be increased, not decreased
  • ext4
    • Backward compatible to ext2
    • Uses journal to guarantee data integrity
    • Size can be increased and decreased

Lesson 14.7 Making and Mounting File Systems

  • mkfs.xsf - creates an xfs file system
  • mkfs.ext4 - creates and Ext4 file system
  • mount - mount file system after creation
  • umount - unmount before disconnecting device
  • lsof /mnt - list of open files in /mnt directory

Lesson 14.8 Mounting Partitions through etc fstab

  • /etc/fstab - main configuration file to persistently mount partitions
  • /etc/fstab - used to generate systemd mounts by the systemd-fstab-generator utility
  • systemctl daemon-reload - to update systemd after editing /etc/fstab
  • mount -a - mount file systems that in fstab file, but which are not mounted yet

Lesson 14.9 Managing Persistent Naming Attributes

  • blkid - get UUID of the device
  • tune2fs - set label to ext4 file system
  • xfs_admin - set label to xfs file system
  • ls -l /dev/disk - possibilites for providing unique device names
drwxr-xr-x. 2 root root 480 Aug 16 14:33 by-id
drwxr-xr-x. 2 root root 120 Aug 16 14:33 by-partuuid
drwxr-xr-x. 2 root root 180 Aug 16 14:33 by-path
drwxr-xr-x. 2 root root 120 Aug 16 19:12 by-uuid

Lesson 14.10 Managing Systemd Mounts

  • systemctl cat tmp.mount - example of .mount file
  • \etc\systemd\system\tmp_ext4.mount - name of moutn should be the same as mount point
  • Mount file content:
[Unit]
Description=Tmp Ext4
Conflicts=umount.target
Before=local-fs.target umount.target
After=swap.target

[Mount]
What=LABEL=tmp_ext4
Where=/tmp_ext4
Type=ext4
Options=defaults
  • systemctl daemon-reload - update your systemd configuration
  • systemctl status tmp_ext4.mount - get status of newly created .mount

● tmp_ext4.mount - Tmp Ext4
   Loaded: loaded (/etc/systemd/system/tmp_ext4.mount; static; vendor preset: disabled)
   Active: active (mounted) since Mon 2021-08-16 20:00:02 CEST; 50s ago
    Where: /tmp_ext4
     What: /dev/sdb1
    Tasks: 0 (limit: 10841)
   Memory: 4.0K
   CGroup: /system.slice/tmp_ext4.mount

Lesson 14.11 Managing XFS File Systems

  • xfsdump - utility can be used for creating backups of XFS formatted devices
    • works only on a complete XFS device
    • can make full backups or different levels of incremental backups
    • xfsdump -l 0 -f /backupfiles/data.xfsdump /data - creates a full backup of the contents of the /data directory
  • xfsretosre - restore backup that was made with xfsdump
    • xfsrestore -f /backupfiles/data.xfsdump /data
  • xfsrepair - command can be manually started to repair broken XFS file systems

Lesson 14.12 Creating a Swap Partition

  • parted
    • mkpart primary linux-swap 1MiB 2048MiB - create swap partition
  • mkswap - create swap filesystem
  • swapon - activate swap

Lesson 15.1 Understanding LVM Stratis and VDO

  • LVM
    • Used during defualt installation of RHEL
    • Add flexibility to storage
  • Stratis
    • Next generation Volume Managing Filesystem that uses thin provisioning by default
    • Implemented in user space, which makes API access possible
  • Virtual Data Optimizer (VDO)
    • Focused on storing files in the most efficient way
    • Manages deduplicated and compressed storage pools

Lesson 15.3 Creating an LVM Logical Volume

  • Create a partition
    • from parted use set n lvm on
    • from fdisk select code 8e
  • pvcreate /dev/sdb1 - create physical volume
  • vgcreate vgdata /dev/sdb1 - create volume group
  • lvcreate -n lvdata -L 1G vgdata - create logical volume with name lvdata
  • findmnt - shows you existing mounts in perspective of linux file system

Lesson 15.5 Resizing LVM Logical Volumes

  • lvextend -r -L +1G /dev/vgdata/lvdata1 - extend logical volume by 1Gb and do resize2fs for file system
  • lvreduce -r -L 250M /dev/vgdata/lvdata1 - reduce size of logical volume to 250M and do resize2fs
  • lvresize -r -l +-20 /dev/vgdata/lvdata1 - increase or reduce size of logical volume by 20 extents and do resize2fs
  • In case you forgot -r option
    • e2resize - Resize for Ext file system
    • xfs_growfs - for XFS file system. Shrinking is not possible on XFS volumes

Lesson 15.6 Understanding Stratis Setup

  • On top of Stratis a regular file system is needed: XFS
  • It's built on top of any block device, including LVM devices
  • It offers advanced features
    • Thin provisioning
    • Snapshots
    • Cache tier
    • Programmatic API
    • Monitoring and Repair

Lesson 15.7 Creating Stratis Volumes

  • yum install -y stratis-cli stratisd
  • systemctl enable --now stratisd - enable and start stratis daemon
  • stratis pool create mypool /dev/nvme0n2 - create pool
  • stratis fs create mypool myfs1 - create filesystem on top of pool
  • stratis pool list - list existing pools
  • stratis fs list - list existing filesystems in stratis pool
  • stratis blockdev list stratispool - show info about clock devices used in pool

Lesson 15.8 Managing Stratis Storage Features

  • stratis pool add-data mypool /dev/nvme0n3 - to add another block device
  • Standard Linux toold don't give accurate sizes as Stratis volumes are thin provisioned
    • stratis blockdev - get information about all block devices used for Stratis
    • stratis pool - get information about all pools
    • stratis filesystem - monitor individual filesystems
  • stratis fs snapshot mypool myfs1 myfs1-snapshot
    • Changes to the original FS will not be reflected in the snapshot
    • Use mount /stratis/mypool/my-fs-snapshot /mnt - to mount it
  • Revert the original volume to the state in the snapshot
    • umount /myfs1
    • stratis fs destroy mypool myfs1
    • stratis fs snapshot mypool myfs1-snap myfs1
  • stratis filesystem destroy mypool mysnapshot - will delete a snapshot
  • stratis filesystem destroy mypool myfs - similar procedure is used for destroying file systems
  • stratis pool destroy mypool - when there are no more file systems in a pool you can delete a pool

Lesson 15.9 Understanding VDO

  • VDO (Virtual Data Optimizer) - used to optimize how data is stored on disk
  • It is used as a separate volume manager on top of which file systems will be created
  • Provides thin-provisioned storage
    • Use a logical size 10 times the physical size for VMs and containers
    • Use a logical size 30 times the physical size for object storage
  • Used in Cloud/Container environments

Lesson 15.10 Configuring VDO Volumes

  • Ensure that underlying block devices are > 4GiB
  • yum install vdo kmod-kvdo
  • vdo create --name=vdo1 --device=/dev/nvme0np2 --vdoLogicalSize=1T
  • mkfs.xfs -K /dev/mapper/vdo1
  • udevadm settle - will wait for the system to register the new device name
  • In /etc/fstab, include the x-systemd.requires=vdo.service mount option
  • vdostats --human-readable - monitor state

Lesson 15.12 Configuring LUKS Encrypted Volumes

  • Use parted to create a partition
  • cryptsetup luksFormat /dev/sdd1 - will format the LUKS device
  • cryptsetup luksOpen /dev/sdd1 secret - will open it and create a device mapper name
  • mkfs.xfs /dev/mapper/secret - create file system and map your device
  • To automate the cryptsetup luksOpen use /etc/crypttab
  • To automate mounting the volume use /etc/fstab

Lesson 16.1 Understanding the Linux Kernel

  • Kernel
    • initramfs
    • systemd-udevd
    • modprobe

Lesson 16.2 Working with Kernel Modules

  • modprobe <module_name - manually load kernel module
  • modprobe -r <module_name - manually unload kernel module
  • lsmod - list currently loaded kernel modules

Lesson 16.3 Using modprobe

  • modinfo - get module parameters
  • /etc/modprobe.conf or /etc/modprobe.d - to load specify kernel module parameters
  • modprobe <module_name> - to apply changes made for the module in configuration file

Lesson 16.4 Using proc to Tune Kernel Behavior

  • /proc - is a fily system that provides access to kernel information
    • PID directories
    • Status files
    • Tunables in /proc/sys
  • Use echo to write a value to any file in /proc/sys to change kernel performance parameters
  • Write the parameters to /etc/sysctl.conf to make them persistent
    • net.ipv4.ip_forward = 1 - add line in /etc/sysctl.conf. Where dots mean slashes /proc/sys/net/ipv4/ip_forward
  • Use sysctl -a to show a list of all current settings

Lesson 16.5 Updating the Kernel

yum update kernel or yum install kernel - to update the kernel

Lesson 17.1 Understanding the Boot Procedure

  • Boot Procedure
    • POST
    • BIOS\UEFI
    • GRUB
    • Kernel
    • Systemd
    • Services

Lesson 17.2 Modifying Grub2 Runtime Parameters

  • Press keys during boot:
    • e - to edit runtime boot options
    • c - for command prompt
    • esc - go back to menu

Lesson 17.3 Modifying Grub2 Persistent Parameters

  • /etc/default/grub - To make grup changes persistent edit this configuration file.
  • Once you done compile changes to grub.cfg
    • grub2-mkconfig -o /boot/grub2/grub.cfg
    • grub2-mkconfig -o /boot/efi/EFI/redhat/grub.cfg

Lesson 17.4 Managing Systemd Targets

  • A systemd target is a group of unit files
  • Some targets are isolatable, which means that the define the final state a system is starting in
    • emergency.target
    • rescue.target
    • multi-user.target
    • graphical.target

Lesson 17.5 Setting the Default Systemd Target

  • systemctl get-default - get info about default target
  • systemctl set-default multi-user.target - set multi-user target
  • systemctl set-default graphical.target - set graphical target

Lesson 17.6 Booting into a Specific Target

  • systemctl.unit=xxx.target - On the grub2 prompt use this value to boot into a specific target
  • systemctl isolate xxx.target - to change between targets on a running system

Lesson 18.2 Changing the Root Password

  • Enter Grub menu while booting
  • Find the line that loads the Linux kernel and add rd.break to the end of the line
  • mount -o remount,rw /sysroot - remount sysroot in read-write mode
  • chroot /sysroot - change root directory
  • passwd root - change root password
  • touch /.autorelabel - apply SELinux policy
  • Ctrl-D
  • Ctrl-D

Lesson 18.3 Troubleshooting Filesystem Issues

  • Problems occur when making typo's in /etc/fstab
  • To fix: if necessary, remount filesystem in read/write stat and edit /etc/fstab
  • Fragmentation can be an issue, different tools exist to fix
    • xfs_fsr - is the XFS file system reorganizer, it optimizes XFS file systems
    • e4defrag - can be used to defragment Ext4

Lesson 18.4 Troubleshooting Networking Issues

  • Common network issues

    • Wrong Subnet Mask
    • Wrong router
    • DNS not working
  • ip a d 192.168.4.235/32 dev ens33 - remove IP address with incorrect subnet mask

  • ip a a dev ens33 192.168.4.235/24 - assign proper IP address to device ens33

  • ip route add default via 192.168.1.1 dev eth0 - add default gateway to eth0 device

  • dhclient - renew your request to dhcp server

Lesson 18.5 Troubleshooting Performance Issues

  • Focus on the four key area's of performance

    • memory
    • cpu load
    • disk load
    • network
  • main tool for troubleshooting is top

Lesson 18.6 Troubleshooting Software Issues

  • ldconfig - update the library cache

Lesson 19.2 Essential Shell Script Components

  • chmod +x myscript.sh - make it executable
  • echo - prints the text
  • read DIR - waiting for user input and write it to DIR variable
  • cd $DIR - change directory to $DIR variable
  • By default scripts are being run in a subshell. If you want to run it in a current shell use following commands:
    • . myscript.sh
    • source myscript.sh

Lesson 19.3 Using Loops in Shell Scripts Part 1

  • if ... then .. fi

  • while ... do ... done

  • until ... do ... done

  • case ... in ... esac

  • for ... in ... do ... done

  • man test - to see existing test conditions

  • exit - special exit codes can be used

    • exit 0 - code run successfully
    • exit 1 - code run with errors
    • echo $? - to see exit code
#!/bin/bash

if [ -z $1 ]
then
    echo you have to provide an argument
    exit 6
else
    echo the argument is $1

Lesson 19.4 Using Loops in Shell Scripts Part 2

  • echo $(( 2 + 2)) - do some calculations
#!/bin/bash

COUNTER=$1
COUNTER=$(( COUNTER * 60))

minusone(){
        COUNTER=$((  COUNTER - 1 ))
        sleep 1
}

while [ $COUNTER -gt 0 ]
do
        echo you have $COUNTER seconds left
        minusone
done

[ $COUNTER = 0 ] && echo time is up && minusone
[ $COUNTER = "-1"] && echo you are one second late && minusone

while true
do
        echo you are now ${COUNTER#-} seconds late
        minusone
done

Lesson 20.3 Changing Common SSH Server Options

  • /etc/ssh/sshd_config - servers options are set here
  • /etc/ssh/ssh_config - client options are set here
    • Port 22
    • PermitRootLogin
    • PubkeyAuthentication
    • PasswordAuthentication
    • X11Forwarding

Lesson 20.4 Securely Copying Files

  • scp - can be used to securely copy files over the network using sshd process
    • scp file1 file2 student@remoteserver:/home/student
    • scp -r root@remoteserver:/tmp/files .
  • sftp - FTP client interface to securely transfer files using SSH
    • put /my/file - to upload a file
    • get /your/file - to download a file to the current directory
    • lpwd - print local working directory
    • pwd - print remote working directory
    • lcd - change local directory
    • cd - change remote directory
    • exit - stop an sftp session

Lesson 20.5 Securely Synchronizing Files

  • rsync - is using SSH to syncronize files
  • If source and target file already exists, rsync will only synchronize their differences
  • rsync can be used with many options
    • -r - recursively syncronize the entire directory tree
    • -l - synchronizes symbolic links
    • -p - preserver symbolic links
    • -n - will do a dry run before actually synchronizing
    • -a - uses archive mode
    • -A - uses archive mode and also synchronizes ACLs
    • -X - will synchronize SELinux context as well

Lesson 21.2 Creating a Basic Website

  • /var/www/html - directory where your webserver contents stored
  • /etc/httpd/conf/httpd.conf - configuration where DocumentRoot directory can be changed

Lesson 22.2 Managing SELinux Modes

  • Modes of SELinux
    • enabled
      • Enforcing - fully operational. Will block and log everything
      • Permissive - do logging, but don't block anything
    • disabled - to switching between enabled and disabled modes reboot is required. This mode can be set only from /etc/sysconfig/selinux
  • setenforce [ Enforcing | Permissive | 1 | 0 ] - to switch between enforcing and permissive mode. Reboot is not required
  • getenforce - get currently applied SELinux policy
  • /etc/sysconfig/selinux - manage the default state of SELinux

Lesson 22.3 Understanding SELinux Context Labels and Booleans

  • Every object is labeled with a context label
    • user: user specific context
    • role: role specific context
    • type: flags which type of operation is allowed on this object
  • Many commands support a -Z option to show current context information
  • ps auxZ | grep sshd - get information about context label for sshd service
    • system_u - user context
    • system_r - role context
    • system_t - context type
system_u:system_r:sshd_t:s0-s0:c0.c1023 root 20246 0.0  0.2 92320  7920 ?
  • ps auxZ | grep httpd - another example with httpd service
  • httpd_t - context type allows following
    • httpd_sys_script_exec_t - execute scripts in cgi-bin
    • httpd_sys_content_t - read context in /var/www/html/ directory
system_u:system_r:httpd_t:s0
  • getsebool -a - get SELinux boolean value(s)
  • getsebool -a | grep httpd
    • httpd_enable_homedirs - enable home directories for the users
  • setsebool -P httpd_enable_homedirs on - allow permanently httpd server to access users' home directories

Lesson 22.4 Using File Context Labels

  • semanage fcontext - set the file context label
    • This will write the context to the SELinux Policy
  • restorecon - enforce the policy setting on the file system
  • touch /.autorelabel - alternative way. Will relabel all files to the context that is specified in the policy
  • man semanage fcontext - get information about fcontext
Add file-context for everything under /web
# semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?"
# restorecon -R -v /web

Lesson 22.5 Analyzing SELinux Log Messages

  • Selinux uses auditd to write log messages to the audit log
  • sealert - it interprets messages from the audit log and writes meaningful messages to /var/log/messages
  • grep AVC /var/log/audit/audit.log - get SELinux related messages. AVC stands for - Access Vector Cash.
type=AVC msg=audit(1630010413.373:849): avc:  denied  { getattr } for  pid=29763 comm="httpd" path="/web/index.html" dev="sda2" ino=10618022 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:default_t:s0 tclass=file permissive=0 
  • journalctl | grep sealert - look for alerts in journalctl. To get more information we should run suggested command below
Aug 26 22:40:20 localhost.localdomain setroubleshoot[30064]: SELinux is preventing /usr/sbin/httpd from getattr access on the file /web/index.html. For complete SELinux messages run: sealert -l 51056217-76c4-4d51-ab2d-ec19143cdff1
  • sealert -l 51056217-76c4-4d51-ab2d-ec19143cdff1 - get more information about this error

Lesson 22.6 Resetting the Root Password and SELinux

  • load_policy -i - load SELinux for troubleshooting while you're in initramfs stage
  • restorecon -v /etc/shadow - relabel shadow with with necessary context type
  • touch /.autorelabel - ensure that rest of the file relabeled

Lesson 23.2 Understanding Firewalld Components

  • Firewalld - using different components to make firewalling easier
    • Service: - main component, contains one or more ports as well as optional kernel modules that should be loaded
    • Zone: a default configuration to which network cards can be assigned to apply specific settings
    • Ports: optional elements to allow access to specific ports
  • firewall-cmd --list-all - list current configuration

Lesson 23.3 Configuring a Firewall with firewall-cmd

  • firewall-cmd - command is used to write firewall configuration
    • --permanent - write rule to persistent configuration (but not to runtime)
    • Without --permanent - write rule to rutime (but not to persistent)
  • firewall-cmd --get-services - list services
  • firewall-cmd --add-service ftp - allow ftp service
  • firewall-cmd --add-service ftp --permanent - allow ftp service permanently
  • firewall-cmd --reload - reload firewalld
  • yum search firewall-config - search for graphical firewall utility. Not necessary at all.

Lesson 24.3 Using the Kickstart File for Automatic Installations

  • 2 files exists in user homer directory after installations
    • anaconda-ks.cfg
    • initial-setup-ks.cfg
  • Use ks=http://somwhere/ks.cfg - before installation client indicates where to get the Kickstart file from

Lesson 25.2 Setting Time with timedatectl

  • hwclock - set hardware clock and synchroniza with system time
  • date - set current time and display format
  • tzselect - allows to select the current time zone
  • timedatectl - new utility to manage all aspects of time
    • timedatectl list-timezones
    • timedatectl set-timezone

Lesson 26.1 Configuring a Base NFS Server

Procedure is following

  • Run the nfs-server service
  • Create a directory you want to share: /data
  • /data *(rw,no_root_squash) - edit /etc/exports to containt the following line
  • Configure firewalld to allow connection
    • firewall-cmd --add-service nfs
    • firewall-cmd --add-service mountd
    • firewall-cmd --add-service rpc-bind

Lesson 26.2 Mounting NFS Shares

  • showmount -e nfs-server - show exports
  • mount nfsserver:/share /mnt - mount shared directory
  • _netdev - use this mount option while mounting through /etc/fstab

Lesson 26.3 Configuring a Base Samba Server

  • Install the Samba server package
  • Create a directory to share
  • Create a local linux user
  • Set Linux Permissions
  • smbpasswd -a - add a Samba user account
  • /etc/samba/smb.conf - enable the share
  • systemctl start smb - start the service
  • firewall-cmd --add-service samba --permanent
  • firewall-cmd --reload

Lesson 26.4 Mounting Samba Shares

  • Install cifs-utils and samba-client RPM packages
  • yum groupinstall 'Network File System Client' - install necessary packages for connection
  • smbclient -L //sambahost - discover shares
  • mount -o username=sambauser //sambaserver/share /somewhere - mount a share
  • Make mount persistent through /etc/fstab, using the _netdev, username= password= mount options

Lesson 26.5 Understanding Automount

  • /etc/auto.master - here you define the directory that automount should manage
  • /etc/auto.data - here you define subdirectory on which to mount, and what to mount exactly
    • `files -rw nfsserver:/data/files
  • systemctl enable --now autofs - ensure the autofs service is started

Lesson 26.6 Configuring Automount

  • yum install autofs - install autofs package
  • autofs configuration files:
    • /etc/auto.master
    • /etc/auto.misc
  • /etc/auto.files - if you're planning to create automount. You should create auto* file in etc and name it the same as directory

Lesson 27.2 Running a Container

  • yum module install container-tools - install container management tools

  • podman pull - pre-pull the image from registry to the local system

  • podman run - pull the container (if necessary) and run it

    • podman run -d - run in detached mode
    • podman run -it - run in interactive tty mode
    • --rm - remove the container after using it
    • ctrl-p, ctrl-q - detach from a container tty
  • podman run -d nginx - you can immediately start running containers from the Docker Registry

  • podman login - to access Red Hat registry you should authenticate.

  • podman pull registry.access.redhat.com/ubi8/ubi:latest - to get a specific container, use a complete name reference

Lesson 27.3 Managing Images

  • /etc/containers/registries.conf - images are obtained from registries, which are specified in this configuration fie.
    • [reggistries.search] - additional registries can be added in this section
    • `[reggistries.insecure] - insecure registries without TLS encryption must be listed there
  • podman info - to see which registries are currently used
  • podman search - search all registries
  • podman search --no-trunc registry.redhat.io/rhel8 - search specific registry on the rhel8 string
  • Use filters:
    • --limit 5 - shows a maximum of 5 images per registry
    • --filter start=5 - shows images with 5 stars or more
  • skopeo - inspect images before pulling them
  • skopeo inspect docker://registry.redhat.io/ubi8/ubi
  • podman inspect registry.redhat.io/ubi8/ubi
  • podman rmi - remove images

Lesson 27.4 Managing Containers

  • podman run -d -p 8000:80 nginx - will map host port 8000 to container port 80
  • podman port -a - will show all current container port mappings
  • firewall-cmd -add-port=8000/tcp [permanent] - do not forget to open ports in the host firewall
  • podmam logs containername - get logs of container
  • -e VAR=value - while starting the container to pass variable values
    • podman run -d --name mydb -e MYSQL_ROOT_PASSWORD=password -p 3306:3306 mariadb
  • podman stop mycontainer
  • podman kill mycontainer
  • podman rm mycontainer
  • podman restart mycontainer
  • podman exec mycontainer uname -r - runs an additional process inside a running container
  • podman exec -it mycontainer /bin/bash - access an interactive shell
  • podman exec -l cat /etc/redhat-release - runs the command on the last container that was used in any command

Lesson 27.5 Attaching Storage to Containers

  • podman run -d -v /webfiles:/webfiles:Z nginx - if the container user is owner of the host directory, the :Z option can be used.
  • sudo chmod o+w /webfiles
  • sudo chown student:student /webfiles
  • sudo run -d --name mynewdb -v /dbfiles:/var/lib/mysql:Z -e MYSQL_ROOT_PASSWORD=password mariadb - create container with attached storage

Lesson 27.6 Managing Containers as Services

  • loginctl enable-linger - start user services for a specific user

    • loginctl enable-linger linda
    • loginctl show-user linda
    • loginctl disable-linger linda
  • podman generate systemd --name myweb --files - generate systemd unit for existing container

    • --files - Generate files instead of printing to stdout. The generated files are named {container,pod}-{ID,name}.service and will be placed in the current working directory.
  • podman generate systemd --name ephemeral_ellie --files --new - you can't keep persistent data in this container.

    • --new - Using this flag will yield unit files that do not expect containers and pods to exist.
  • /etc/systemd/system - to generate a service file for a root container, do it from this directory, because --files key will create unit file in the current working directory

  • Creating User Unit files

    • Create user specific unit files in ~/.config/systemd/user
    • Manage them using systemctl --user
      • systemctl --user daemon-reload
      • systemctl --user enable myapp.service (requires linger)
      • systemctl --user start myapp.service
    • systemctl --user - commands work only when logging in on console or SSH and do not work in sudo su sessions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment