Redirection
- STDIN
<or0< - STDOUT
>or1>.>>or1>>to append. -
STDERR
2>.2>>to append. -
Redirect STDERR to SDTOUT
2>&1 -
Redirect STDERR and STDOUT to different files
-
/dev/null
Find your way
whichshows the full path of (shell) commands.typebash builtin. Alternative ofwhich.realpathprint the resolved path of a file.pwdprint name of current/working directory.apropossearch the manual page names and descriptions. Equivalent toman -k.manan interface to the system reference manuals.aliasbash builtin.ll="ls -lAh".historybash builtin. Manipulate the history list.envrun a program in a modified environment and show the current environment variables.setread and write variables.-
unsetdelete variables. -
lslist directory contents. cdchange working directory.mvmove (rename) files.cplnmkdirrmdirrm-
find -
catconcatenate files and print on the standard output. headoutput the first part of files.filedetermine file type.tailoutput the last part of files.morefile perusal filter for crt viewing (pager).lessopposite of more (pager).dutouchcutsortwc-
grep -
df mountlsblkfindmntfdiskgdiskblkidpartedpartprobemkfstune2fse2labelxfs_adminmkswapswaponandswapofffindfsfsckshowmount-
smbclient -
wshow who is logged on and what they are doing. whoshow who is logged on.lastandlastbshow a listing of last logged in users.surun a command with substitute user and group ID.sudo&sudoeditexecute a command as another userwhoamiwhoshow who is logged ongetentget entries from administrative database.usersprint the user names of users currently logged in to the current hostidpasswdchagechange user password expiry informationvipw&vigredit the password or group fileuseraddcreate a new user or update default new user informationusermodmodify a user accountuserdeldelete a user account and related filesuserdbctlinspect users, groups and group memberships (good visibility)groupaddcreate a new groupgroupdeldelete a groupgroupmemsadminister members of a user's primary groupgroupmodmodify a group definition on the system-
groupsdisplay current group names -
chown chmodchgrpnewgrpgetfaclsetfaclumaskchattr- change file attributes on a Linux file system-
lsattr -
ip ssnetstatpingifconfignmcli&nmtuitools for controlling NetworkManager-
hostnamectl -
reboot haltpoweroff-
uptime -
lscpu lspci-
lsusb -
uptime -
free -
timedatectl datehwclock-
tzselect -
compgenbash builtin. Display possible completions depending on the options.compgen -clist binaries.compgen -alist aliases.compgen -blist builtins.compgen -klist keywords.compgen -A functionlist functions.compgen -A function -abcklist all the above.
ls -AH ${PATH//:/ }list all files in$PATHdirectories. Orfind ${PATH//:/ } -maxdepth 1 -executable. OrIFS=: ; ls -AH $PATHwhence -pm '*'zsh builtin.print -rC1 -- $commands
Process management
- shell job commands started from the command line. interactive processes
- daemon processes in the background that provide services.
- kernel thread part of the kernel.
- When a process is started from a shell, it becomes the child of that shell. When the shell stops all children are terminated.
- PID Process ID. The name is represented between brakets
[]. -
Priority is between
0priority (-20niceness) (maximum priority),20(0niceness) (default) and39(19niceness) (minimum). using-20priority may have bad consequences. -
&append to a command to run in the background. jobsshow running jobs and ID.fgbring last job to foreground.bgrun last job in the background.Ctrl+zstop currently running job.Ctrl+dsends EOF to the current job indicating it should stop waiting for input.Ctrl+ccancel current interactive job.killkillallpkillnohupdisownpssnapshot of the current processes.ps -ef --forestorps auxpgrepnice&renicetoptrap
Example to use jobs:
Process signals
Some process signals; man 7 signal for more information:
- SIGTERM (15) ask a process to stop
- SIGKILL (9) force stop a process
- SIGHUP (1) hung up a process. Some processes reload their configuration this way.
- SIGUSR1 (10) custom user signal. Some processes reserve this signal for custom actions.
Process states
- Running
R- Active and using CPU or in the queue. - Sleeping
S- Waiting for an event to complete. - Uninterruptible sleep
D- Sleep state that can not be stopped. - Stopped
T- Process stopped. - Zombie
Z- Process stopped but could not be removed from memory by it's parent.
More info
- kill may be a shell builtin in some cases. You may have it installed at /usr/bin/kill.
Files
/etc/profile,~/.profileand~/.bash_profileprocessed upon login./etc/bashrcand~/.bashrcprocessed when subshells start./etc/motdis displayed after login./etc/issueis displayed before login./etc/passwduser information. Fields:- Username
- Password (empty as
/etc/shadowis used) - UID
- GID
- Comment
- Home directory
- Shell
/etc/shadowhashed user passwords. Fields:- Login name
- Encrypted password
- Days since epoch from last password change
- Days before password may be changed
- Days after which password must be changed
- Days before password is to expire that user is warned
- Days after password expires that account is disabled'
- Days since epoch that account is disabled
- Reserved field for future use
/etc/groupgroups. Fields:- Group name
- Group password
- GID
- Members (user1,user2,user3)
/etc/gshadowgroup passwords/etc/skelskeleton directory for new users/etc/default
File system tree.
/root./bootfiles needed to boot the kernel./devdevice files. Used to access physical devices. Created by the kernel./etcconfiguration files./homeuser(s) files./mediaand/mntused to mount devices./optoptional packages installed./procinformation about processes. Created by the kernel./rootuser root home./runinformation about user and processes from last boot. Created by the kernel./srvto serve files. Used by NFS, FTP and HTTP./sysfiles to interface with hardware devices. Created by the kernel./tmptemporal files. Deleted at boot./usruser usable programs and data. User System Resources.-
/varfiles that variate in size. Logs, mail and spools. -
/usr/share/docdocumentation for larger software. -
/proc/sysrq-triggertriger magic-sysrq commands. -
/boot,/home,/usrand/varcan be in separate file systems.
File system
An inode stores the data block where the file contents are stored; the creation, access and modification time; permissions and owners.
A hard link must be in the same file system; you can not create a hard link of a directory and when the last hard link to an inode is removed, the data is also removed.
A symbolic link (soft link or symlink (symbolic links)) link to a file name and no the inode. When the original file is removed the symlink becomes invalid.
symlinks of directories are files. If you remove link/ instead of link you risk deleting all the contents of the linked directory.
Permissions
- SUID -
u+s- only on files - user executes file with permissions of file owner. - SGID -
g+s- on files executes file with permissions of owner group; on directories files created in directory get the same group owner. - Sticky bit -
+t- only folders - prevents users from deleting files from other users.
ACLs
Default ACL: permissions for all new items.
Mask
mask of 022 gives 644 for files and 755 for folders. Defaults to 666 for files and 777 for folders.
| value | files | directories |
|---|---|---|
0 |
6 RW |
7 Everything |
1 |
6 RW |
6 RW |
2 |
4 RO |
5 RX |
3 |
4 RO |
4 RO |
4 |
2 W |
3 WX |
5 |
2 W |
2 W |
6 |
0 - |
1 X |
7 |
0 - |
0 - |
Extended attributes
Awhen a file is accessed, its atime record is not modified.athe file can only be opened in append mode for writing.cautomatically compressed on the disk by the kernel.isets the immutable bit (cannot be modified).swhen a file is deleted, its blocks are zeroed and written back to the disk.uwhen a file is deleted, its contents are saved.
Interfaces
- console as in the old CRTs connected to the mainframe or your computer. Hardware devices that allows basic IO.
- terminal or TTY is a device that does more than basic IO (read and write data). Now we use Pseudo Terminals like a terminal emulator; xterm for example.
- shell or prompt is a program that processes commands. bash for example.
- TTY means TeleTYpewriter
chvtchange foreground virtual terminal
Tasks
Cron
crondis the service. There are multiple packages that providecrond.crontabis used to show (-l) and edit (-e) the crontab for the current user or another user (-u username)./var/spool/cronthe location of all user crontabs. Always edit withcrontab./etc/crontabsystem-wide crontab./etc/cron.hourlydirectory that contains executable files (not crontab files), like shell scripts, that get executed every hour. Also exist versions that rundaily,weeklyandmonthly. They do not run at a fixed time.- For
/etc/crontabyou have to specify the user name. /etc/cron.dlocation of custom crontab files. Drop your here instead of editing/etc/crontab./etc/cron.allowfile that contains user names (one by line). Only listed users can usecron./etc/cron.denyfile that contains user names (one by line). All users of the system can usecronexcept those listed in the file.- If neither
cron.allownorcron.denyexist only root can usecron.
Example of /etc/crontab
# 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
* */4 10-20 1,2,3,4 sat,sun user-name command to be executed
*every single one*/nonce everynbeingna numbern-mfromntombeingnandmnumbersn,m,j,k,latn,m,j,kandl
anacron
If the computer is off when a cron task should have been execute it does not get executed. With anacron it makes sure all tasks are executed when the computer turns on again.
The main and only file is /etc/anacrontab.
man 8 anacrontab and man 5 anacrontab
Example /etc/anacrontab. Pretty self explanatory.
#period in days delay in minutes job-identifier command
1 5 cron.daily nice run-parts /etc/cron.daily
7 25 cron.weekly nice run-parts /etc/cron.weekly
@monthly 45 cron.monthly nice run-parts /etc/cron.monthly
at
atdis the daemon that runs the jobs.atis the command line utility to schedule a job.atrmis the cli tool used to remove a job.atqquery currently queued jobs. Same asat -l.batchexecutes commands when system load levels permit; when the load average drops below 0.8, or the value specified in the invocation ofatd.
man 1 batch, man 1 at and man 8 atd
Some examples
at now +5 minutes -f /path/to/script
echo "curl http://127.0.0.1/api/test" | at 14:22
echo "reboot" | at teatime
echo "logger hello world" | batch
atq
atrm 2
Logging
Location of logs
/var/log/messagescommon log file./var/log/dmesgkernel log messages./var/log/secureauthentication-related messages./var/log/boot.logrelated to system startup./var/log/audit/audit.logaudit messages like SELinux./var/log/maillogmail-related messages./var/log/journal/$(cat /etc/machine-id)journaldmessages (not stored in plain text) when local storage (Storage=autofor example) is enabled forjournald. More info inman 5 journald.conf
Software
journalctlQuery the systemd journal.journalctl -fto follow.loggerenter messages into the system logdmesgprint or control the kernel ring buffer.dmesg -wto follow.logrotaterotates, compresses, and mails system logs
Explaining a log line
There are two RFCs for logging that container in-depth information on formatting: RFC5424 "The Syslog Protocol" and RFC3164 "The BSD syslog Protocol"
Jul 31 20:55:44date and timecomputerhostnamesudo[]process name46711process idpam_unix(sudo:session): session closed for user rootmessage content
journalctl commands
journalctl -xe
journalctl -f
journalctl --no-pager
journalctl _UID=1000
journalctl -n 20
journalctl -p err.
journalctl --since yesterday
journalctl -o verbose
journalctl --dmesg
journalctl _SYSTEMD_UNIT=sshd.service
journalctl -p 3 -xb
Partitioning schemes
Device types
/dev/hdaIDE./dev/sdaSCSI and SATA. Also used for virtio (qemu/kvm) devices./dev/nvmeXnYNVMe whereXis the device andYis the partition.Yis normally1./dev/xvdaXen virtual disk.
Partition types
82Linux Swap83Linux8eLinux LVM
File systems
XFSext4ext3ext2BtrFSNTFSVFAT
How to know the file system used in a partition?
df -T(only for mounted file systems)sudo file -sL /dev/sda1(too much information)sudo lsblk -fsudo blkidsudo parted /dev/sdap
mount
mount /dev/sda /mnt
mount -t vfat /dev/sda /mnt -o uid=1000,gid=1000
mount UUID="..." /mnt -o ro,nosuid
mount LABEL="My Drive" /mnt/drive
fstab
- Dump: set to
1to enable the user of thedumputility. Used for some backup tools. - Check:
0to disable (do not enable for network file systems);1to enable check on boot for the root file system and2to enable it for other file systems.
Some examples:
Device Mount point FS type Mount options Dump Check
------------------------------------------------------------------------------
/dev/mapper/root / ext4 rw,noatime 0 1
UUID=... / ext4 defaults 0 2
tmpfs /tmp tmpfs size=2G 0 0
/path/to/swap swap swap defaults 0 0
192.168.0.1:/nfs /mnt nfs noauto,user 0 0
LVM
- LVM means Logical Volume Manager
- Dynamic partitions:
- Snapshots:
- physical extent size:
- building blocks:
- device mapper:
Consists on:
- Physical volumes (
PV): a disk like/dev/sda. Mark the disk to be used in LVM - Volume group (
VG): abstraction of all available storage. A bunch of disks grouped together. - Logical volume (
LV):
Use LVM:
- Create a partition.
- Set the partition type to
8e00. [is this redundant?] pvcreateto makes a disk usable in LVM. [is this redundant?]pvsorpvdisplayto display current physical volumes.vgcreate vgname /dev/sda1to add a physical volume (/dev/sda1) to a volume group (vgname).vgsorvgdisplayto display current volume groups.lvcreate -n lvname -L 5G vgnameto create a logical volume (lvcreate) namedlvnameinside the volume groupvgnamewith a size of5G.lvsorlvdisplayto display current logical volumes.- Create a filesystem in the drive
mkfs.ext4 /dev/mapper/lvname -
Mount and use it.
-
You can add all partitions in a disk to a volume group with
vgcreate vgname /dev/sda. - You can remove any of them with
pvremove,vgremoveandlvremove. - The actual logical volumes devices are
/dev/dm-X. Other representations are just symlinks. - You can find logical volumes in
/dev/mapper/named likevgname-lvname. - You can also find logival volumes in
/dev/vgname/lvname.
root@host:~# ls -l /dev/dm-0
brw-rw---- 1 root disk 253, 0 Aug 8 20:35 /dev/dm-0
root@host:~# ls -lA /dev/mapper/
lrwxrwxrwx 1 root root 7 Aug 8 20:35 vgname-lvname -> ../dm-0
root@host:~# ls -l /dev/vgname/lvname
lrwxrwxrwx 1 root root 7 Aug 8 20:35 /dev/vgname/lvname -> ../dm-0
- You can extend a volume group with
vgextendand reduce it withvgreduce. - For logical volumes you have
lvresize,lvextendandlvreduce. You also have to resize the filesystem.
Kernel management
- tainted kernel: kernel that contains closed source drivers.
-
modules are drivers. modules can be loaded and removed while running.
-
uname procinfomodprobejournalctl -kandjournalctl --dmesgshows clock time.systemd-udevloads the appropriate drivers and udev rules at boot.udevadm
Kernel modules
/etc/modules-load.dand/usr/lib/modules-load.dlsmodmodinfomodprobeinsmodandrmmodthey do not load dependencies.lspci -kshow drivers loaded for each device./etc/modprobe.d
Boot
Secuence:
- POST
- UEFI/BIOS selects the bootable device
- Bootloader
- Kernel
- Init -> initrd.target
- Root File System
- Default target
GRUB2
vmlinuz:initramfs: contains drivers needed to boot.- dracut: creates a
initramfsimage. - entry:
- kernel boot parameters:
man 7 bootparam
Files and folders:
/etc/default/grubGRUB configuration file/etc/grub.d/scripts to configure entries./usr/lib/dracut/dracut.conf.dsystem default configuration./etc/dracut.conf.dcustom configuration files./etc/dracut.confmain dracut configuration file.
Commands:
- Reconfigure GRUB:
grub-mkconfig -o /boot/grub/grub.cfg - Install GRUB:
grub-install /dev/sda
GRUB prompt
- Enter pressing
ein the boot menu. rd.breakstops the boot procedure.init=/bin/shchanges init for a shell.systemd.unit=emergency.targetchanges the target to load.
Recover root password
- Pres
eon GRUB - Ennter
rd.breakand pressCtrl + xto boot mount -o remount,rw /sysrootchroot /sysrootpasswd- If you have SELinux run
chcon -t shadow_t /etc/shadow - Reboot
Time and date
- Hardware clock refferes to the same as Real-time clock.
- Usually the time in the HW clock is in UTC.
- Epoch time is the number of seconds since January 1, 1970 in UTC.
- Hardware clock is the hardware clock that resides on the main board of a computer
- System time time maintained by the OS. Read from HW on boot.
- Software clock is similar to system time
- UTC is Coordinated Universal Time
- DST is Daylight saving time
- Local time time of current time zone
- Stratum is the reliability of an NTP time source, the lower the better. 1 or 2 is common.
Commands
- Enable NTP:
timedatectl set-ntp 1 -
Seconds from Epoch to human readable date:
date --date '@1420987251' -
Manage local time:
date - Current system time:
date - Current system day of month, month, and year:
date +%d/%m/%y -
Set the current time:
date -s 12:45 -
Manage hardware time:
hwclock - Synchronize current system time to the hardware clock:
hwclock --systohc -
Synchronize current hardware time to the system clock:
hwclock --hctosys -
Manage time:
timedatectl - Shows current time settings:
timedatectl status - Sets current time:
timedatectl set-time TIME - Sets current time zone:
timedatectl set-timezone ZONE - Shows a list of all time zones:
timedatectl list-timezone - Change the RTC from/to local time from/to UTC:
timedatectl set-local-rtc [0|1] - Disable or enable NTP:
timedatectl set-ntp [0|1] -
Set the local time:
ln -sf /usr/share/zoneinfo/America/Los_Angeles /etc/localtime -
Change the time zone:
tzselect
Locales
Files are parsed one after another in the order of "C" locale.
Locales also specify the order or files.
firewalld
firewalldservice that can configure firewall rules by using different interfaces.- Uses
nftablesoriptables - Applications can request ports to be opened using DBus A zone is a collection of rules that are applied to incoming packets matching a specific source address or network interface. Firewalld applies to incoming packets only by default, and no filtering happens on outgoing packets Firewalld service specifies what exactly should be accepted as incoming and outgoing traffic in the firewall. It typically includes ports to be opened, as well as supporting kernel modules that should be loaded. Behind each service is a configuration file that explains which UDP or TCP ports are involved and, if so required, which kernel modules must be loaded. To get a list of all services available on your computer, you can use the command firewall-cmd --get-services Default (RPM installed) XML files are stored in /usr/lib/firewalld/services. Custom XML files can be added to the /etc/firewalld/services directory
Tools
- CLI:
firewall-cmd - GUI:
firewall-config
Show commands
- Show available zones:
firewall-cmd --get-zones - Show current default zone:
firewall-cmd --get-default-zone - Set default zone:
firewall-cmd --set-default-zone=<zone> - show available services (all services):
firewall-cmd --get-services - Show services available in the current zone (in use):
firewall-cmd --list-services - Show a lot more information:
firewall-cmd --list-all - Show a lot more information about a specific zone:
firewall-cmd --list-all --zone=public
Add commands
- Temporally add the service "vnc-server" to the default zone:
firewall-cmd --add-service=vnc-server - Temporally add the service "vnc-server" to the specified zone:
firewall-cmd --add-service=vnc-server --zone=<zone> - Permanently add a service to the default zone:
firewall-cmd --add-service vnc-server --permanent - Permanently add a service to the specified zone:
firewall-cmd --add-service vnc-server --zone=<zone> --permanent
Remove commands
- Remove the service from the default zone:
firewall-cmd --remove-service vnc-server - Remove the service from the default zone:
firewall-cmd --remove-service vnc-server [--zone=<zone>] [--permanent] - This does not apply it to the currently running firewall; you have to reload the configuration:
firewall-cmd --add-port=2022/tcp --permanent - This does not apply it to the currently running firewall; you have to reload the configuration:
firewall-cmd --remove-port=2022/tcp --permanent - Add an interface to the defatul zone:
firewall-cmd --add-interface=<inferface> - Remove an interface from the defatul zone:
firewall-cmd --remove-interface=<inferface> - Add a specific IP adress:
firewall-cmd --add-source=<ipaddress/netmask> - Removes a specific IP adress:
firewall-cmd --remove-source=<ipaddress/netmask>
Reload commands
- Write current configuration to disk:
firewall-cmd --permanent - Reload the configuration:
firewall-cmd --reload - Reload the configuration:
systemctl restart firewalld