Stephen J Marks
"Do One Thing Well" - Doug Mcllroy
Hello! I’m a Computer Science and Math major with a deep passion for Linux, holding expertise as a Linux specialist. My enthusiasm extends beyond just using the system—I am a committed open source enthusiast, actively contributing to and learning from the community. I am currently seeking a position that allows me to leverage my skills in Linux, particularly in roles related to system administration and DevOps. My professional journey includes significant experience in IT at Managed Service Providers, where I’ve honed my technical and problem-solving skills. I’m also proud to hold certifications from CompTIA and RedHat, which underscore my commitment and expertise in the field. I am excited about the opportunities to bring my technical acumen and passion for Linux to a dynamic team, where I can contribute to meaningful projects and continue to grow in my career.
I want this site to not only be a place where I advertise myself, but can also be myself. So here anything relating to my interests will be found. When I’m not immersed in the digital world, I love stepping into nature. Camping and hiking are my go-to activities for recharging and reconnecting with the outdoors. I also love watching and analyzing films, or consuming material on math, science, or cooking.
Passions 🔥
- Linux & Open Source 🐧
- Films 🎥
- Camping & Hiking 🌲
- Mathematics 🧮
- Cooking & Baking 🍳
- Socializing 🗣️
Links
- My Github: steveonlinux
- This site's repo
Resume 📄
Profile 🖋️
Dynamic system administrator and proficient coder, leveraging a broad knowledge base in technology with sharp programming skills. A dedicated, adaptable enthusiast passionate about advancing the field through open-source contributions.
Degrees and Certifications 🎓
Bachelor's of Computer Science
- Institution: Cal State Bakersfield (In Progress)
Associate of Computer Science & Math
- Institution: Bakersfield College
- Year: 2023
Red Hat Linux Certified Administrator
- Certifying Body: Red Hat
- Year: 2023
CompTIA+ Certifications Itemized
- Certifying Body: CompTIA+
- Years: 2020 - 2022
- Details:
- Linux+
- Network+
- Security+
Employment 🛠️
Library STEM Programming Consultant
- Employer: County of Kern
- Years: 2023 - Current
- Role: Spearheaded and executed educational programs, successfully engaging local youth in computer science, elevating their proficiency in STEM subjects.
IT Support Engineer & Administrator Level 2
- Employer: LanPro Systems
- Years: 2020 - 2022
- Role: Administered Linux VoIP servers, resolved complex tickets, managed AD users, performed system backups, provisioned servers & workstations, and implemented scripts & automated tasks.
Peer Tutor
- Institution: Bakersfield College
- Years: 2019 - 2020
- Role: Led peer instruction in key computer science areas; significantly improving classmates' understanding and performance in programming, logic, and binary arithmetic.
Tutor
- Institutions: Bakersfield College; Tutoring Club; Freelance
- Years: 2019 - Current
- Role: Effectively tutored in computer science, math, and physics; elevating student achievements in college and K-12.
Contact 📞
- Email: stephenmarks5309@gmail.com
- Phone: 661-473-3280
- Website: stevemarks.xyz
Strengths 💪
- Linux
- Programming/Scripting
- System/Server Administration
- Automation (Ansible / K8s / etc)
- Virtualization (KVM / VMware)
- Orchestration (Docker / K8s)
- Provisioning (Ansible / Terraform)
- Integration (Jenkins / Git)
- Text Editing (VIM / VS)
Languages 🌐
- Shell: Fluent
- C: Fluent
- Python: Fluent
- Rust: Basic
- Powershell: Intermediate
- SQL: Basic
- Assembly (x86 / ARM / MIPS): Competent
- AWK: Basic
- HTML + Markdown / CSS: Fluent
- Latex: Intermediate
Works
These are links to my "books" or other writings. My goal is to solidify my own knowledge base while sharing whatever I know with others. I'm majorly self taught and promote self-teaching. Everything here is perpetually in progress.
Steve's Blog
This will be a blog where I will dump anything I want. It will probably be mostly tech related. Specifically Linux and open source stuff. Thoughts, critiques, criticisms, guides, advice, projects, anything. However, there will probably be some life stuff here too. This will be fun. There will be typos.
Enjoy
On Installing Gentoo For Some Reason (2024-08-21)
I decided to install Gentoo on a whim. I've done it a couple of times in the past, even on Raspberry Pis. But that was before the recent change implementing mass binary alternatives to the compilation Gentoo is known for. Binaries have been available for a while already, but I'm interested to check out this change. Gentoo's biggest con for me is the time it takes to install packages if you don't have a Threadipper. Here I will just be going over my thoughts and experiences. This isn't an actual guide, for that use their handbook for the appropriate architecture.
Where
I decided to install Gentoo in a vm. I went with virtualbox over kvm/qemu because a bridged network will already be setup for ssh and it will be easier to get a shared clipboard going.
Installation of Minimal Linux Distros
Minimal distros like Gentoo and Arch have the essential parts of every distribution, just less obfuscated. Their installation generally has the following cadence:
- Partition drives and create filesystems
- mount root partition
- chroot into root partition
- setup up install in chroot environment
- network, packages, fstab, bootloader, users, etc.
- post install Chroot is a command that essentially changes the root to a new location. So that everything within the chroot is happening relative to that new root. That is why we chroot into the mounted root partition during installs because at that point we are configuring the actual system to be installed. Take not of this command as it will ultimately help troubleshoot installs from a live cd. Often other paths have to be mounted from the host system to the chroot so that it can be a functioning live environment essentially.
Tips for Installing Gentoo
- Remember to utilize chroot. You don't have to complete the install all at once. Per the handbook, past that point you can always mount your root partition into an environment and with the correct mounts and get back into the system. For there you can continue the installation or fix an issue.
- If you are not installing Gentoo in a GUI already, and you have access to another machine on the network, I recommend remoting into the machine Gentoo is being installed on via SSH. This can be done after being chrooted. Copy and pasting from a web browser makes things so convenient. This will require network bridging
- Get network up:
net-setup [interface]
- Change root's password via
passwd
- Start the ssh daemon with:
/etc/init.d/sshd start
- Get network up:
- Take advantage of the newly available binaries for better install times
- Use ccache. At the very least. ccache is a program that caches compiled source so it doesn't have to be recompiled later. Makes later compilations quicker, which is needed on Gentoo.
- Use distcc is you have other computers on the network with good CPUs. distcc distributes compilation workloads across multiple computers. Can make your install a breeze.
My Troubles
- Forgot boot flag on
/boot
which I caught before it mattered - fstab typo which caused first boot to be to
emergency.target
I fixed both by chrooting back into root and fixing the issue.
Gentoo is fun
I like Gentoo for messing around. It seems like a good educational tool the way LFS can be. Also seems great for development environments. Would never use it on an actual install for a server or desktop though...again. In those instances there is way too much upkeep for what is gained.
Major Packaging Systems Disambiguation 📦 (2024-08-21)
Package Formats
Package formats are the way that software data is organized for distribution prior to installation. Every major
Linux branch will have a package format it utilizes. The two most major types are .deb
and .rpm
. They are found on
Debian based distros and Red Hat based distros respectively. Package installers and managers exist for every format and there are
typically several for each type that "wrap" or encapsulate another, and sometimes its even in a nested sense. They
can be described as having levels such as: "low", "medium", and "high".
.deb
A .deb
package is the package used for Debian based distributions. The most major ones being Debian itself and Ubuntu. Deb packages consist three ordered files. Two are tar archives that support compression. One for the metadata known as control information and another for the installable data. The third is a file containing the format version number.
- The structure of a .deb package
dpkg
Dpkg is a low level packaging tool. It isn't a package manager because it doesn't actually manage the packages and dependencies. The dpkg
command can be used to install and remove .deb
files directly.
dpkg -i filename.deb
installs a packagedpkg -l
lists files that match a patterndpkg -S
searches for a filename from installed packagesdpkg -r packagename
removes an installed packages The packagesdpkg
anddpkg-dev
contain the suit of utilities and development tools respectively.
apt-get and apt
Apt-get is a medium level package manager that utilizes dpkg. It can be thought of as a front-end for dpkg. Apt is a wrapper for apt-get that supports greater functionality such as: better dependency resolution, native search capabilities, and autoremoval of orphaned packages during upgrades. Apt is an amalgamation of the functionalities of separate utilities like apt-get
and apt-cache
. It is recommended that apt-get be reserved for automation. But for the most part apt and apt-get have the same sub-commands and functionality. Apt and Apt-get share the following:
apt update
syncs the package indexes and sourcesapt upgrade
installs the current versions of packagesapt install
installs individual or listed packagesapt clean
clears cache of package filesapt autoclean
only clears package files that can no longer be downloaded.
apt exclusive
apt search
, apt show
, apt policy
, apt purge
apt
also has a set of sub-commands not found in apt-get
such as:
apt search
searches the list of packages for a regex term.apt show
outputs information on a given package
apt Frontends
The are graphical front ends for apt as well like the following:
.rpm
The counterpart to .deb
in Red Hat based and upstream distros is the .rpm
package format. The file has the naming convention: name-version-release-arch.rpm
. This name is appended with -devel
for libraries containing two separate packets for precompiled code and the headers. The package is usually provided in binary format and contains:
- The lead, which identifies the file as an RPM file and contains some obsolete headers.
- The signature, which can be used to ensure integrity and/or authenticity.
- The header, which contains metadata including package name, version, architecture, file list, etc.
- A file archive (the payload), which usually is in cpio format, compressed with gzip. The rpm2cpio tool enables retrieval of the cpio file without needing to install the RPM package.
rpm
rpm is the low level counterpart of dpkg for .rpm
packages and its purpose and syntax is similar:
rpm -i packagename.rpm
installs a packagerpm -U packagename.rpm
upgrades a packagerpm -ivh package-file
installs a package with verbose output and a progress barrpm -q query-options package
searches for an installed package
YUM (Yellow Dog Updater, Modified)
Yellow Dog Updater or YUM
is a medium level package manager for Red Hat based distros that acts as an rpm front-end. However, it has since been deprecated.
DNF (Dandified YUM)
Dandified YUM or DNF is the high level package manager that has replaced YUM has the current and up to date rpm front-end. The syntax is similar to apt.
DNF Command Reference
DNF (Dandified YUM) is the package manager for Fedora, CentOS, and RHEL distributions. Here is a list of commonly used commands:
-
Update Package Cache:
dnf check-update
-
Upgrade All Packages:
dnf upgrade
-
Upgrade Specific Package:
dnf upgrade <package_name>
-
Install a Package:
dnf install <package_name>
-
Remove a Package:
dnf remove <package_name>
-
List Available Groups:
dnf group list
-
Install a Package Group:
dnf group install <group_name>
-
Remove a Package Group:
dnf group remove <group_name>
-
Search for a Package:
dnf search <keyword>
-
Display Information about a Package:
dnf info <package_name>
-
Clean Cache:
dnf clean all
-
Auto-remove Unneeded Packages:
dnf autoremove
-
List Enabled Repositories:
dnf repolist
-
Add a Repository:
dnf config-manager --add-repo <repository_url>
-
Enable a Repository:
dnf config-manager --set-enabled <repository_name>
-
Disable a Repository:
dnf config-manager --set-disabled <repository_name>
Advanced Tips and Tricks
Advanced Tips for apt
-
Full Upgrade vs Safe Upgrade:
apt full-upgrade
performs upgrades that may also remove installed packages if that's necessary to upgrade the system as a whole.apt upgrade
will only upgrade packages without removing any packages.
-
Holding Packages:
- To prevent a package from being automatically updated, use
sudo apt-mark hold package_name
. - To allow it again, use
sudo apt-mark unhold package_name
.
- To prevent a package from being automatically updated, use
-
Searching Package Listings:
- Use
apt-cache search keyword
to search for packages. It searches descriptions and names. apt-cache pkgnames
starts listing packages alphabetically.
- Use
-
List All Versions of a Package Available for Installation:
- Use
apt list -a package_name
to see all versions of a package available in your repositories.
- Use
-
Using Snapshots:
- If you want to return your packages to a previous state, you can use
apt
with snapshots from a backup tool like Timeshift.
- If you want to return your packages to a previous state, you can use
-
Automatic Removal of Unused Packages:
- After uninstalling an application, use
sudo apt autoremove
to remove dependencies that were installed with applications and that are no longer used by anything else on the system.
- After uninstalling an application, use
-
Find Which Package a File Belongs to:
- Use
apt-file search path/to/file
to find out which package a particular file belongs to.
- Use
Advanced Tips for dnf
-
History and Undo/Redo Operations:
dnf history
lists transaction history. You can undo or redo transactions usingdnf undo transaction_id
ordnf redo transaction_id
.
-
Repository Management:
- Enable or disable repositories on the fly with
dnf config-manager --set-enabled repo_name
ordnf config-manager --set-disabled repo_name
.
- Enable or disable repositories on the fly with
-
DNF Automatic:
- Install
dnf-automatic
for automatic daily package updates. It can be configured to only download, download and install, or even send email notifications.
- Install
-
List and Remove Orphaned Packages:
- Use
dnf list extras
to list orphaned packages (packages not available from currently configured repositories). - Remove them with
dnf remove $(dnf repoquery --extras --exclude='kernel*')
.
- Use
-
Using DNF Plugins:
- Enhance
dnf
's capabilities by installing plugins likednf-plugin-system-upgrade
for upgrading Fedora releases, ordnf-plugins-core
for additional features like managing core repositories.
- Enhance
-
Cache Management:
- Use
dnf clean dbcache
to clean the cache to reduce disk space usage.dnf makecache
to regenerate the cache improving the performance of future installations.
- Use
-
Find if a Specific Package is Available:
- Use
dnf provides '*/filename'
to find which packages provide a specific file.
- Use
On Inodes and the Inode Pointer Structure (2024-07-30)
Inodes are a fundamental part of the data structure that stores and references all data available on a storage device.
File Names Are References
The way files and directories are abstracted the end user typically thinks of files being nested. However, this isn't truly the case. Directories are simply lists of inode and file name pairs of the file names underneath, the name of the parent, and the name of itself. An inode is an entity that has a unique number and contains the file metadata, and pointers to the actual data the file "contains". That's it. Inodes do not store their "names" and all the filesystem really cares about are the inodes. File names are essentially just a human readable label mapped to an inode.
What Does An Inode Contain And Reference?
Inodes are where the file's metadata is stored. However, the data itself is not there. The data is referenced through a system of pointers also stored in the inode.
Typical Inode Pointer Structure
The typical pointer structure is implemented in ext* filesystems among others. It has the following qualities:
- *inode pointer structure:
- 12 direct pointers that directly point to blocks of the file's data
- 1 singly indirect pointer (pointing to a block of direct pointers)
- 1 doubly indirect pointer (pointing to a block of single indirect pointers)
- 1 triply indirect pointer (pointing to a block of doubly indirect pointers)
- fixed block size (increase redirection when required, data can be stored non contiguously
- inodes assigned fixed amount at filesystem instantiation, amount of indirect blocks are not fixed
- number of pointers dependent on block size and size of pointers The pointers are set up to use direct pointers and others with varying levels of indirection. This is so that the structure can support varying amounts of data while remaining static. If more space is needed, the system can simply use any unclaimed data block at some far off address through redirection.
Pointers and Metadata
Here is a diagram of the structure of inodes:
You can see the structure of the pointers that were previously discussed. However, the undiscussed metadata section is present as well. This section contains metadata such as filer permissions, ownership, edit history, etc. An exact list of metadata in an inode will be provided in the next subsection.
Viewing Contents of Inodes
The contents of inodes can be viewed using the stat
system call.
stat test.txt
File: test.txt
Size: 15 Blocks: 8 IO Block: 4096 regular file
Device: 259,2 Inode: 30158006 Links: 3
Access: (0644/-rw-r--r--) Uid: ( 1001/ steve) Gid: ( 1001/ steve)
Access: 2024-07-26 08:23:43.390310050 -0700
Modify: 2024-07-26 08:24:02.074309630 -0700
Change: 2024-07-28 13:29:14.971830641 -0700
Birth: 2024-07-26 08:23:43.390310050 -0700
This command lists the contents of the inode test.txt
is paired to. The metadata an inode contains includes:
- File Type: Indicates the type of file (e.g., regular file, directory, symbolic link).
- Permissions: Specifies read, write, and execute permissions for the owner, group, and others.
- Owner User ID (UID): The user ID of the file's owner.
- Owner Group ID (GID): The group ID of the file's owner group.
- File Size: The size of the file in bytes.
- Number of Hard Links: The count of hard links pointing to this inode.
- Timestamps:
- Access Time (atime): Last time the file was accessed.
- Modification Time (mtime): Last time the file content was modified.
- Change Time (ctime): Last time the inode metadata was changed.
- File Size in Blocks: The number of blocks allocated to the file.
- Extended Attributes: Additional metadata such as security labels or custom attributes.
- Flags: File flags indicating special characteristics or behaviors (e.g., immutable, append-only).
- Generation Number: A number that changes each time the inode is reused, used to detect stale file handles.
- File System Identifier: An identifier for the file system where the inode resides.
- The device ID of the file if it is a device file. Links are discussed in the next section.
Hard Links and Soft Links
Hard Links Are Names
File names are known as hard links. And the nature of the inode structure inherently allows files to have multiple hard links. the -i
option on various commands outputs information on a file's inodes.
30158006 .rw-r--r-- 15 steve 26 Jul 08:24 test.txt
Here ls -li
long lists with the inode number. So test.txt
is mapped to inode 30158006
. To create a hard link the command ln
is used.
ln test.txt hard_link_to_test.txt
This command creates a hard link named hard_link_to_test.txt
to test.txt
.
ls -li test.txt hard_link_to_test.txt
30158006 .rw-r--r-- 15 steve 26 Jul 08:24 hard_link_to_test.txt
30158006 .rw-r--r-- 15 steve 26 Jul 08:24 test.txt
Here we can see that these two files share the same inode number: 30158006
. This means that both file names are mapped to that inode and thus are referencing the same data.
Soft Links Are Pointers To Names
There is also the concept of a soft link
aka a symbolic link
. These links are file names that are pointers to other names. A soft link can be created with the -s
option as in ln -s
.
ln -s test.txt soft_link_to_test.txt
This command creates a soft link named soft_link_to_test.txt
to test.txt
.
ls -li test.txt hard_link_to_test.txt soft_link_to_test.txt
30158006 .rw-r--r-- 15 steve 26 Jul 08:24 hard_link_to_test.txt
30157667 lrwxrwxrwx 8 steve 28 Jul 13:37 soft_link_to_test.txt -> test.txt
30158006 .rw-r--r-- 15 steve 26 Jul 08:24 test.txt
Here we can see that the soft link does not share the inodes of the hard links but has its own. That is because it is pointing to the file name test.txt
and not mapped to that filename's inode as a hard link would be. A soft link is mapped to its own inode, and that inode contains the path of the file being pointed to.
To unlink a link the unlink
command can be used.
unlink hard_link_to_test.txt
╭─steve@kathy-office ~/test
╰─❯ unlink soft_link_to_test.txt
╭─steve@kathy-office ~/test
╰─❯ ls -li test.txt hard_link_to_test.txt soft_link_to_test.txt
"hard_link_to_test.txt": No such file or directory (os error 2)
"soft_link_to_test.txt": No such file or directory (os error 2)
30158006 .rw-r--r-- 15 steve 26 Jul 08:24 test.txt
Link Use Cases
Hard Links
I've seen hard links described as a "poor man's backup" which means that if one filename is deleted the inode isn't inaccessible. There is still some other name mapped to that inode. When a file is deleted via something like rm
, the data still exists. This will be covered in a later section. This also saves space, if what is hard linked in large, but needs to exists in multiple paths. And since inodes store metadata such as permissions and file attributes, the hard link will share them as well.
Soft Links
Soft links allow for having files accessible from multiple paths without moving or copying anything. Another use is version management. Say there is one service or script that runs and depends on something having a certain path or name. but it changes regularly. A soft link to it won't. So instead of rewriting anything, the soft link can just be redirected. Soft links also have the capability of linking to files across filesystems and devices, where hard links can't.
Restrictions
Linking has some limitations due to the inherent structure of filesystems and inodes.
Linking To Directories
Directories can not be hard linked in Linux. Historically this has been possible, but most operating systems disable this behavior now to avoid cycles. A notable counterexample is that a superuser can make hard links to directories in MacOS 10.5. Directories can be soft linked because a soft link's inode just contains the path of the file being pointed to.
Inode Exhaustion
Filesystems have a limited and fixed number of inodes for use, and all data stored needs an inode pointing to it. If one created countless small files containing nothing each would require an inode and they would eventually run out, and no more files can be created. This is known as inode exhaustion. And since the files were empty there wold still be ample free space, and everything would appear fine on the surface. The number of available inodes can be checked using df -i
.
df -i
Filesystem Inodes IUsed IFree IUse% Mounted on
udev 1.7M 535 1.7M 1% /dev
tmpfs 1.7M 936 1.7M 1% /run
/dev/nvme0n1p2 58M 606K 57M 2% /
tmpfs 1.7M 712 1.7M 1% /dev/shm
tmpfs 1.7M 6 1.7M 1% /run/lock
tmpfs 1.7M 94 1.7M 1% /tmp
/dev/nvme0n1p1 0 0 0 - /boot/efi
tmpfs 348K 106 348K 1% /run/user/1001
Based on this output we can see I have plenty of inodes free.
Setting Number of Inodes in Filesystem
Since the amount of inodes are fixed the only way to alter it is to set it at filesystem creation. Say we are creating an ext4
filesystem. The mkfs.ext4
can do this. The following is from its man page:
>-N number-of-inodes
Overrides the default calculation of the number of inodes that should be reserved for the file system (which is based on the number of blocks and the bytes-per-inode
ratio). This allows the user to specify the number of desired inodes directly.
Note that there are some exceptions. For instance Btrfs is capable of dynamically allocating inodes so the amount is not fixed.
Alternative Structures and Filesystems
Many filesystems exist that are fundamentally different that something like ext*. They do not use inodes but utilize other data structures such as B-trees. The following is a list of filesystems that do not use inodes:
- FAT (File Allocation Table): Used by MS-DOS and early versions of Windows, FAT file systems, including FAT12, FAT16, and FAT32, use a file allocation table to manage files rather than inodes.
- exFAT (Extended File Allocation Table): Designed by Microsoft to replace FAT32, exFAT is optimized for flash drives and does not use inodes.
- ReFS (Resilient File System): Developed by Microsoft, ReFS uses B-trees for metadata storage and does not use inodes.
- HFS (Hierarchical File System): Used in older Apple Macintosh systems, HFS uses a catalog file and extents overflow file for metadata instead of inodes.
- HFS+ (Hierarchical File System Plus): An updated version of HFS used in macOS before APFS, HFS+ uses B-trees for metadata storage, avoiding the inode structure.
- APFS (Apple File System): The current file system for macOS and iOS, APFS uses container and volume structures with object identifiers instead of inodes.
- NTFS (New Technology File System): Used by modern versions of Windows, NTFS uses a Master File Table (MFT) to store metadata rather than inodes.
- IBM GPFS (General Parallel File System): Now known as Spectrum Scale, GPFS uses a distributed metadata model with descriptors rather than traditional inodes.
Retrieving Unclaimed Data
Recall that when a hard link is deleted via rm
the data still exists, however once the last hard link to the inode is gone the metadata is deleted and there is no way to access the data. The data still exists but the space it occupies is now unclaimed can be reclaimed and overwritten by new data. If data needs to be recovered cease all writes immediately. Either unmount the drive or boot into a live environment. The drive can not be written to until the data is located. There are a number of programs that can inspect data fields for information indicating the types of data stored there. They may utilize a technique of data recovery known as file carving in which data is reconstituted from fragments.
In conclusion, understanding inodes is a critical part of understanding linking and the filesystems used on Linux.
Resources
On Pseudo Devices (2024-07-30)
One of the most interesting and powerful design philosophies behind Unix and its kin is the notion of everything being a file. Everything. For instance the kernel state is is abstracted as files in /proc
, and access to data in physical devices is abstracted as files in /dev
. Files is /dev
are known as special files. There is a kind of special file called pseudo devices. These kinds of files don't necessarily abstract access to physical devices, but abstract data and its manipulation as files. I find this concept incredibly fascinating and is one of the reasons I love using and learning Linux. This post will be on pseudo devices - what they are, why they exist, and how they are and can be used.
Available Pseudo devices in Linux
Pseudo devices can be found in /dev
. Here is a list of all the pseudo devices available in Linux:
- /dev/null - A special file that discards all data written to it and provides zero bytes when read.
- /dev/zero - Provides a continuous stream of null (zero value) bytes.
- /dev/random - Provides random data generated from environmental noise.
- /dev/urandom - Similar to /dev/random but uses a pseudo-random number generator to provide data.
- /dev/full - Always returns an error indicating that the device is full when writing to it.
- /dev/ptmx - Used to create a new pseudo-terminal master and slave pair.
- /dev/tty - Represents the controlling terminal for the current process.
- /dev/console - Represents the system console.
- /dev/loopX - Loopback devices that allow a file to be mounted as a filesystem.
- /dev/ppp - Represents a point-to-point protocol network device.
- /dev/ttyS* or /dev/ttyUSB* or /dev/ttyACM* - Serial devices.
- /dev/net/tun and /dev/net/tap - Network tunnel devices for tunneling IP traffic (TUN) and Ethernet frames (TAP).
- /dev/fuse - Filesystem in Userspace, allows non-privileged users to create their own filesystem without modifying kernel code.
- /dev/shm - Represents a temporary filesystem for shared memory.
- /dev/mem - Provides access to the physical memory of the system.
- /dev/kmsg - Used for logging kernel messages.
- /dev/bus/usb - Represents USB devices and buses.
- /dev/disk/by-id - Symbolic links to storage devices based on their IDs.
- /dev/disk/by-path - Symbolic links to storage devices based on their physical paths.
- /dev/input/event* and /dev/input/mice - Represents input devices like keyboards, mice, and other human interface devices.
Most of these devices serve the system, however there are pseudo devices available that can provide certain functionalities in the cli and scripts.
Data Manipulation
/dev/null/
can be used as a trash can basically. Any data you don't need can be streamed to this device as if you're chucking it into a black hole never to be see again. It's most often sued as a place to redirect either stdout
or stderr
in scripts or one-liners.
# Run the command in the background and discard its output
command > /dev/null 2>&1 &
dev/zero
...outputs a stream of zeroes. This is often used for wiping out a file or drive. Here is a line that does this by writing to a file, and once the drive is full, the file is deleted.
dd if=/dev/zero of=zeros; rm zeros
This can be part of a larger script used for backing up drives.
#Fill up the blank space on drive with zeros first (optional):
dd if=/dev/zero of=zeros; rm zeros
#Recommended: Unmount drive before backing it up.
#Creating the archive:
dd if=/dev/sda1 conv=noerror | gzip -c > sda1.img.gz
#Extracting the archive:
cat sda1.img.gz | gzip -dc | dd of=/dev/sda1 conv=noerror
#Storing disk info:
fdisk /dev/sda -l > sda1.txt
Random Data Generation
/dev/random
or dev/urandom
generates a random stream of data. This data can be dumped to overwrite drives with random data, or generate very strong passwords. Note that the c functions random()
, srandom()
, and the system call getrandom()
are also at your disposal.
#!/bin/bash
# Generate the password
PASSWORD=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c "$1")
echo "Generated password: $PASSWORD"
This small script generates a random password of a length given as a command line argument.
#!/bin/bash
# Check if the user provided a drive as an argument
if [ $# -eq 0 ]; then
echo "Usage: $0 /dev/sdX"
echo "Example: $0 /dev/sda"
exit 1
fi
# Drive to overwrite
DRIVE=$1
# Confirm with the user before proceeding
read -p "WARNING: This will irreversibly overwrite all data on $DRIVE. Are you sure? (yes/no): " CONFIRM
if [ "$CONFIRM" != "yes" ]; then
echo "Operation cancelled."
exit 1
fi
# Overwrite the drive with random data
echo "Overwriting $DRIVE with random data. This may take a while..."
dd if=/dev/urandom of=$DRIVE bs=1M status=progress
echo "Overwrite complete."
This one overwrites a drive with random data.
Always take advantage of pseudo devices, especially /dev/null
in scripts and the cli. There are other pseudo devices we use on Linux such as pseudoterminals, serial devices, and even pipes themselves are considered pseudo devices. I recommend reading up on these as well.
Links
Bootloaderless Boot With EFIstub (2024-07-25)
The most prevalent bootloader on Linux is GRUB2, but there are other offerings put there such as LIFO. But did you know that...you don't need a bootloader at all?
UEFI
UEFI, the replacement of the legacy BIOS, is actually capable of selecting and loading kernels directly, which I don't see many people doing. You don't actually need a booatloader with UEFI. The downside is that if you would like to boot other OSs, you'll have to access the UEFI every time you would like to boot something else. But if you only have a single OS installed, I don't see any downsides.
EFIstub
This can be achieved with an EFIstub. An EFIstub is essentially a kernel that is executable by EFI. This may already be built into the kernel you're using if CONFIG_EFI_STUB=y
is set. If not... well compiling the kernel will be its own post. The UEFI essentially just needs an entry for the kernel that is being booted. You could do this form withing your UEFI's shell, but I use efibootmgr
for this. It can manage UEFI boo entries from within Linux. If the UEFI is configured appropriately and its version supports it, booting the kernel shouldn't be an issue. Note that keeping the kernel that is being booted updated automatically is distro specific so refer to your distro's documentation. Arch's states:
pacman will directly update the kernel that the EFI firmware will read if you mount the ESP to /boot.
So that's what I did.
efibootmgr
Setting the UEFI boot entry is jsut a single command. I wrote a small script that can be used to automate the process. The script sets it up using the UUID of the root partition. It creates an entry and deletes the previous one if it already exists.
#!/bin/sh
# Delete the existing boot entry
efibootmgr -b 0 -B > /dev/null
printf "Deleted boot entry: 0000\n\n"
# Retrieve the UUID for the root partition
ROOT_UUID=$(sudo blkid | grep root | awk -F 'UUID="' '{split($2, a, "\""); print a[1]}')
# Reload the entry with the new UUID
printf "Reloaded entry 0000...\n"
efibootmgr --disk /dev/nvme0n1 --part 1 --create --label "Arch Linux" --loader /vmlinuz-linux --unicode "root=UUID=$ROOT_UUID rw initrd=\initramfs-linux.img rd.driver.blacklist=nouveau nvidia-drm.modeset=1" --verbose --timeout 0 | grep "Boot0000"
After this I select my kernel in the UEFI boot config and I'm good to go. If you use this script remember to use your own kernel boot parameters if you need them and to use the path to the correct disk. In my case its /dev/nvme0n1
.
You should have a fast boot and a good time.
Built-ins, Utilities, Functions, and System Calls Disambiguation (2024-07-25)
The differences between these haven't always been clear to me in the context of Linux. Many shared names also caused me some confusion. I'm assuming this is the case for others and an explanation may serve them.
Core Utilities
Core utilities or coreutils are just sets of programs commonly installed on systems by default. The most common and ubiquitous set of coreutils are are the GNU coreutils. If you're on Linux, you're probably using them. The coreutils are discrete binaries that can each be ran for basic and essential functionality required to use a system. For example, ls
and mv
are coreutils. There are alternative sets of coreutils such as uutils, which are the gnu ones rewritten in Rust. There is also Busybox which are coreutils reimplemented as a single binary. Busybox is usually found on distributions of Linux like Alpine that are extremely small intended for embedded environments. And other operating systems have their equivalents such as the BSDs. In fact there are some that I personally prefer over gnu counterparts such as doas.
Shell Built-ins
The first bit of confusion arises with the introduction of shell built-ins. A shell being an environment used to interact with the components and indirectly the kernel of the operating system; a built-in is a command that is in the shell itself. It is not its own program or binary and does not exist anywhere on the system. The which
command can tell you if a command is built-in or not. which
outputs the path of executable files, so if you run a command as an argument and a path isn't output, its built-in.
The printf
command is a case where there is likely both a binary installed and a shell built-in (at least in the case of bash). To force the use of the binary one would just run the path to it. For example:
/usr/bin/printf "Hello World!\n"
Hello World!
To force the use of the built-in the command builtin
(which funnily enough is itself built-in) can be ran with the desired built-in command as an argument. For example:
builtin printf "Hello World!\n"
Hello World!
By default the binary is used.
C Functions
You may have noticed that printf
shares the name of the c standard function c printf()
. At the end of the day almost everything in Linux is ultimately C and the printf
command is a kind of wrapper that just invokes the c function to output and format text. glibc is the gnu implementation of the c standard library which is, like the coreutils, on the vast majority of Linux distributions.
System Calls
Like commands that share the names of c functions, they can also share the names of system calls. System calls a c function that utilizes the kernel API to interface with the kernel. There exists c wrapper functions for system calls invoke the system call. Let's use the wait
command as an example going down the layers of abstraction from top to bottom.
wait Built-in
The wait
command is a built-in that detects changes in the status of a process.
$ sleep 10 &
$ jobs -l
[1] + 18057 Running sleep 10
$ wait 18057
[1] + Done sleep 10
$
wait
terminates once the job ends.
wait C Function
The wait()
function in the c standard library is what the wait
built-in is effectively wrapping.
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Child process
printf("Child process is running\n");
sleep(1); // Simulate some work with sleep
exit(EXIT_SUCCESS);
} else {
// Parent process
wait(NULL); // Wait for the child to terminate
printf("Child process has terminated\n");
}
return 0;
}
The above program contains fork()
and wait()
, two c functions that wrap system calls. This code demonstrates the use of wait()
as a c function.
wait System Call
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/syscall.h>
int main() {
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Child process
printf("Child process is running\n");
sleep(1); // Simulate some work with sleep
exit(0);
} else {
// Parent process
syscall(SYS_wait4, -1, NULL, 0, NULL); // Wait for the child to terminate
printf("Child process has terminated\n");
}
return 0;
}
The above code utilizes syscall()
which is a function that accepts system calls themselves as parameters. SYS_wait
is the actual system call. And all system calls share the same naming scheme.
System Calls All The Way Down
So every command - whether it be a binary or built-in - issued is ultimately some c code and a system call. And many share the same name! So when you're reading some documentation or a man page, understand the distinctions between them, or how there all parts of a greater whole at times abstracting one another. Then there is no need to be confused.
Some System Calls
SYS_read
: Read from a file descriptor.SYS_write
: Write to a file descriptor.SYS_open
: Open a file.SYS_close
: Close a file descriptor.SYS_stat
: Get file status.SYS_fstat
: Get file status of an open file.SYS_lstat
: Get file status of a symbolic link.SYS_poll
: Wait for some event on a file descriptor.SYS_lseek
: Reposition read/write file offset.SYS_mmap
: Map files or devices into memory.SYS_mprotect
: Set protection on a region of memory.SYS_munmap
: Unmap a region of memory.SYS_brk
: Change data segment size.SYS_rt_sigaction
: Examine and change a signal action.SYS_rt_sigprocmask
: Examine and change blocked signals.SYS_ioctl
: Control device.SYS_pread64
: Read from a file descriptor at a given offset.SYS_pwrite64
: Write to a file descriptor at a given offset.SYS_readv
: Read data into multiple buffers.SYS_writev
: Write data from multiple buffers.SYS_access
: Check user's permissions for a file.SYS_pipe
: Create a pipe.SYS_select
: Synchronously monitor multiple file descriptors.SYS_sched_yield
: Yield the processor.SYS_mremap
: Remap a virtual memory address.SYS_msync
: Synchronize a file with a memory map.SYS_mincore
: Determine whether pages are resident in memory.SYS_madvise
: Give advice about use of memory.SYS_shmget
: Get a System V shared memory segment.SYS_shmat
: Attach a System V shared memory segment.SYS_shmctl
: Control operations on a shared memory segment.SYS_dup
: Duplicate a file descriptor.SYS_dup2
: Duplicate a file descriptor to a given descriptor.SYS_pause
: Wait for a signal.SYS_nanosleep
: High-resolution sleep.SYS_getitimer
: Get the value of an interval timer.SYS_alarm
: Set an alarm clock for delivery of a signal.SYS_setitimer
: Set the value of an interval timer.SYS_getpid
: Get process ID.SYS_sendfile
: Transfer data between file descriptors.SYS_socket
: Create an endpoint for communication.SYS_connect
: Initiate a connection on a socket.SYS_accept
: Accept a connection on a socket.SYS_sendto
: Send a message on a socket.SYS_recvfrom
: Receive a message from a socket.SYS_sendmsg
: Send a message on a socket.SYS_recvmsg
: Receive a message from a socket.SYS_shutdown
: Shut down part of a full-duplex connection.SYS_bind
: Bind a name to a socket.SYS_listen
: Listen for connections on a socket.SYS_getsockname
: Get socket name.SYS_getpeername
: Get name of connected peer socket.SYS_socketpair
: Create a pair of connected sockets.SYS_setsockopt
: Set options on sockets.SYS_getsockopt
: Get options on sockets.SYS_clone
: Create a child process.SYS_fork
: Create a child process.SYS_vfork
: Create a child process and block parent.SYS_execve
: Execute program.SYS_exit
: Terminate the calling process.SYS_wait4
: Wait for process to change state.SYS_kill
: Send a signal to a process.SYS_uname
: Get system information.SYS_semget
: Get a System V semaphore set.SYS_semop
: Operate on a System V semaphore set.SYS_semctl
: Control a System V semaphore set.SYS_shmdt
: Detach a System V shared memory segment.SYS_msgget
: Get a System V message queue.SYS_msgsnd
: Send a message to a System V message queue.SYS_msgrcv
: Receive a message from a System V message queue.SYS_msgctl
: Control operations on a System V message queue.SYS_fcntl
: Manipulate file descriptor.SYS_flock
: Apply or remove an advisory lock on an open file.SYS_fsync
: Synchronize a file's in-core state with storage device.SYS_fdatasync
: Synchronize a file's in-core state with storage device.SYS_truncate
: Truncate a file to a specified length.SYS_ftruncate
: Truncate an open file to a specified length.SYS_getdents
: Get directory entries.SYS_getcwd
: Get current working directory.SYS_chdir
: Change working directory.SYS_fchdir
: Change working directory of the calling process.SYS_rename
: Change the name or location of a file.SYS_mkdir
: Create a directory.SYS_rmdir
: Remove a directory.SYS_creat
: Create a file.SYS_link
: Create a new name for a file.SYS_unlink
: Delete a name and possibly the file it refers to.SYS_symlink
: Create a symbolic link.SYS_readlink
: Read value of a symbolic link.SYS_chmod
: Change permissions of a file.SYS_fchmod
: Change permissions of an open file.SYS_chown
: Change ownership of a file.SYS_fchown
: Change ownership of an open file.SYS_lchown
: Change ownership of a file, not following symbolic links.SYS_umask
: Set file mode creation mask.SYS_gettimeofday
: Get time.SYS_getrlimit
: Get resource limits.SYS_getrusage
: Get resource usage.SYS_sysinfo
: Get system information.SYS_times
: Get process times.SYS_ptrace
: Trace a process.SYS_syslog
: Read and/or clear kernel message ring buffer; set console_loglevel.SYS_setuid
: Set user identity.SYS_setgid
: Set group identity.SYS_setpgid
: Set process group ID.SYS_getppid
: Get parent process ID.SYS_getpgrp
: Get process group ID.SYS_setsid
: Create a session and set process group ID.SYS_setreuid
: Set real and effective user IDs.SYS_setregid
: Set real and effective group IDs.SYS_getgroups
: Get list of supplementary group IDs.SYS_setgroups
: Set list of supplementary group IDs.SYS_setresuid
: Set real, effective, and saved user IDs.SYS_getresuid
: Get real, effective, and saved user IDs.SYS_setresgid
: Set real, effective, and saved group IDs.SYS_getresgid
: Get real, effective, and saved group IDs.SYS_getpgid
: Get process group ID.SYS_setfsuid
: Set user ID used for filesystem checks.SYS_setfsgid
: Set group ID used for filesystem checks.
gnu++ in Rust (2024-07-24)
I've discussed rewrites of commonly used gnu utilites in Rust. I've written a script that installs cargo and every Rust rewrite with it. The script also optionally writes alias definitions to the appropriate shell rc file. It assumes bash by default. The script source will be pasted below, and the repo is on my Github.
Source
#!/bin/bash
# Default list of crates
default_crates=(
"bat"
"choose"
"exa"
"lsd"
"git-delta"
"du-dust"
"duf"
"broot"
"fd-find"
"ripgrep"
"sd"
"bottom"
"gping"
"procs"
"zoxide"
"dns-doge"
"mcfly"
"xh"
"hyperfine"
)
# Default shell config file
shell_config=".bashrc"
# Usage function
usage() {
echo "Usage: $0 [-a] [-s SHELL_CONFIG] [-f PACKAGE_FILE] [-h]"
echo " -s: Specify shell configuration file (.bashrc or .zshrc)"
echo " -f: Specify a file with a list of packages"
echo " -h: Display this help message"
exit 1
}
flag=0
# Parse command-line options
while getopts ":as:f:h" opt; do
case $opt in
a)
flag=1
;;
s)
shell_config="$OPTARG"
;;
f)
package_file="$OPTARG"
;;
h)
usage
;;
\?)
echo "Invalid option: -$OPTARG" >&2
usage
;;
esac
done
# Read packages from file if specified
if [ -n "$package_file" ]; then
if [ -f "$package_file" ]; then
mapfile -t default_crates < "$package_file"
else
echo "Error: Package file not found: $package_file"
exit 1
fi
fi
install_rust() {
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
PATH="$HOME/.cargo/bin:$PATH"
printf "\n" >> "$HOME/$shell_config"
echo "export PATH=$PATH" >> "$HOME/$shell_config"
}
# Function to set up aliases
setup_aliases() {
{
printf "\n"
echo "#gnu++ Rust Alternative Aliases"
echo "alias cat='bat --paging=always'"
echo "alias ls='exa -la'"
echo "alias diff='git-delta'"
echo "alias du='du-dust'"
echo "alias df='duf'"
echo "alias tree='broot'"
echo "alias find='fd'"
echo "alias grep='rg'"
echo "alias find='fd'"
echo "alias cut='choose'"
echo "alias sed='sd'"
echo "alias top='btm'"
echo "alias ps='procs'"
echo "alias cd='z'"
echo 'eval "$(zoxide init bash)"'
echo "alias dig='doge'"
} >> "$HOME/$shell_config"
echo "Aliases added to $HOME/$shell_config"
}
# Install packages and set up aliases
install_rust_crates() {
for package in "${default_crates[@]}"; do
cargo install --locked "$package"
done
}
main() {
install_rust
install_rust_crates
if [ "$flag" -eq 1 ]; then
setup_aliases
fi
echo "Installation complete."
}
main
Usage
Usage: ./gnu++.bash [-a] [-s SHELL_CONFIG] [-f PACKAGE_FILE] [-h]
-s: Specify shell configuration file (.bashrc or .zshrc)
-f: Specify a file with a list of packages
-h: Display this help message
What I Use 🐧 (2024-07-23)
I realized I've yet to discuss what it is I use day to day in terms of Linux. This is a quick post dedicated to my setup.
Desktops/Laptops
On the desktop and I use Arch Linux. Arch is a rolling release distribution which means packages, including the kernel, are the latest available versions... which can lead to some issues. I've had small issues over the years using it mostly relating to dependencies breaking on updates. Usually manually holding back a package in /etc/pacman.conf
fixes these issues. Random issues like some files not being deleted properly by the package manager preventing an update also arise but usually the issue can be manually fixed by reading an error message and investigating. All that being said the nature of Arch means that package availability is incredible. Not to mention the aur or Arch User Repository which is a repo consisting of packages packaged by users and developers themselves. While these may be inherently less trustworthy than official packages, I've almost never run into a situation where what I as looking for wasn't available on Arch.
Window Manager
My previously favorite window manager was dwm. I liked dwm but the philosophy involving manually patching source is very tedious and arbitrary. It seemed like core functionality was missing by default. So I decided to switch to hyprland because I wanted to switch to Wayland as my display server...protocol. Hyprland is technically a compositor that manages windows. Wayland has been amazing for me. Beforehand I was plagued by screen tearing on Xorg. However, I had to get an AMD gpu for my desktop for Wayland compatibility, but I needed to upgrade that anyway. Hyprland is amazing too. It is fast, clean, and offers amazing functionality. Very cool animations, great defaults, and the config file is easy to read and edit.
Servers
For server I either use Debian, Rocky Linux, or PiOS if I'm running things off of a Pi.
Dotfiles
My dotfiles are available on my Github.
Raspberry Pi at Home 🥧 (2024-07-22)
Let's Take a Trip To Pie Country
What is an SBC?
A SBC or single board computer is a computer...on a single board. All the components, CPU, RAM, flash, i/o, on a single PCB or printed circuit board. They're usually really small and relatively inexpensive. They're commonly used for small hobbyist projects because they often have buses one can just shove raw wires into, they're small enough to cram into whatever you want, and have relatively low power usages. They are commonly associated with edge computing and IoT or internet of things. These are two interrelated concepts involving smart fridges and toasters. Thermostats, air quality sensors, and home security systems. Washers and dryers. Even soldering irons and your girlfriend's hair iron. Devices containing tiny computers connected to the internet, sometimes storing information and doing computations on a user's local infrastructure.
Buying Options
There are many brands to choose from:
Manufacturer | Flagship Board | Processor | Architecture | RAM Options | Storage Options | Connectivity | Price Range |
---|---|---|---|---|---|---|---|
Raspberry Pi | Raspberry Pi 5 | Broadcom BCM2712 | ARM Cortex-A76 | 4GB, 8GB | microSD, USB 3.0 | Wi-Fi 6, Bluetooth 5.0, Gigabit Ethernet | $60 - $80 |
ASUS | Tinker Board 2S | Rockchip RK3399 | ARM Cortex-A72/A53 | 2GB, 4GB | 16GB eMMC, microSD | Wi-Fi 5, Bluetooth 4.2, Gigabit Ethernet | $85 - $100 |
NVIDIA | Jetson Nano 2GB | NVIDIA Maxwell GPU | ARM Cortex-A57 | 2GB | microSD | Wi-Fi (with USB adapter), Bluetooth (with USB) | $59 |
ODROID | ODROID-N2+ | Amlogic S922X | ARM Cortex-A73/A53 | 2GB, 4GB | microSD, eMMC | Gigabit Ethernet, Wi-Fi (with adapter), Bluetooth | $79 - $90 |
Rock Pi | Rock Pi 4C+ | Rockchip RK3399 | ARM Cortex-A72/A53 | 4GB | microSD, eMMC | Wi-Fi 5, Bluetooth 5.0, Gigabit Ethernet | $69.99 |
Banana Pi | Banana Pi M5 | Amlogic S905X3 | ARM Cortex-A55 | 4GB | microSD, eMMC | Wi-Fi 5, Bluetooth 5.0, Gigabit Ethernet | $64 - $75 |
Pine64 | Pine A64+ | Allwinner A64 | ARM Cortex-A53 | 2GB, 4GB | microSD | Wi-Fi (with USB adapter), Bluetooth (with USB) | $29.99 - $39.99 |
BeagleBoard | BeagleBone AI-64 | TI AM5729 | ARM Cortex-A15 | 4GB | microSD, eMMC | Wi-Fi, Bluetooth, Gigabit Ethernet | $100 - $125 |
UDOO | UDOO Bolt V8 | AMD Ryzen V1605B | x86-64 | 8GB, 16GB | M.2 NVMe, SATA | Wi-Fi, Bluetooth, Gigabit Ethernet | $389 - $409 |
Khadas | Khadas VIM3 Pro | Amlogic A311D | ARM Cortex-A73/A53 | 4GB | eMMC, microSD | Wi-Fi 5, Bluetooth 5.0, Gigabit Ethernet | $139.99 |
Libre Computer | AML-S905X-CC (Le Potato) | Amlogic S905X | ARM Cortex-A53 | 1GB, 2GB, 4GB | microSD | Wi-Fi (with USB adapter), Bluetooth (with USB) | $35 - $55 |
FriendlyARM | NanoPi M4V2 | Rockchip RK3399 | ARM Cortex-A72/A53 | 2GB, 4GB | microSD, eMMC | Wi-Fi 5, Bluetooth 5.0, Gigabit Ethernet | $65 - $75 |
Radxa | Rock Pi 3 Model A | Rockchip RK3588 | ARM Cortex-A76/A55 | 2GB, 4GB, 8GB | eMMC, microSD | Wi-Fi 6, Bluetooth 5.0, Gigabit Ethernet | $99 - $150 |
Orange Pi | Orange Pi 5B | Rockchip RK3588S | ARM Cortex-A76/A55 | 4GB, 8GB, 16GB | eMMC, microSD | Wi-Fi 6, Bluetooth 5.0, Gigabit Ethernet | $89 - $129 |
However, the market is dominated by the Raspberry Pi. It is the de facto option and is synonymous with the term SBC. There are a number of models to choose from:
Model | Release Date | Processor | Architecture | RAM Options | Storage Options | Connectivity | Price Range |
---|---|---|---|---|---|---|---|
Raspberry Pi Model B | 2012 | Broadcom BCM2835 | ARM11 | 256MB | SD Card | 100 Mbps Ethernet, 2x USB 2.0 | $25 - $35 |
Raspberry Pi Model A | 2013 | Broadcom BCM2835 | ARM11 | 256MB, 512MB | SD Card | 1x USB 2.0 | $20 - $25 |
Raspberry Pi Model B+ | 2014 | Broadcom BCM2835 | ARM11 | 512MB | microSD | 100 Mbps Ethernet, 4x USB 2.0 | $25 - $35 |
Raspberry Pi Model A+ | 2014 | Broadcom BCM2835 | ARM11 | 256MB, 512MB | microSD | 1x USB 2.0 | $20 - $25 |
Raspberry Pi 2 Model B | 2015 | Broadcom BCM2836 | ARM Cortex-A7 | 1GB | microSD | 100 Mbps Ethernet, 4x USB 2.0 | $35 |
Raspberry Pi Zero | 2015 | Broadcom BCM2835 | ARM11 | 512MB | microSD | 1x mini HDMI, 1x micro USB | $5 |
Raspberry Pi 3 Model B | 2016 | Broadcom BCM2837 | ARM Cortex-A53 | 1GB | microSD | Wi-Fi 4, Bluetooth 4.1, 100 Mbps Ethernet, 4x USB 2.0 | $35 |
Raspberry Pi Zero W | 2017 | Broadcom BCM2835 | ARM11 | 512MB | microSD | Wi-Fi 4, Bluetooth 4.1, 1x mini HDMI, 1x micro USB | $10 |
Raspberry Pi 3 Model A+ | 2018 | Broadcom BCM2837B0 | ARM Cortex-A53 | 512MB | microSD | Wi-Fi 4, Bluetooth 4.2, 1x USB 2.0 | $25 |
Raspberry Pi 3 Model B+ | 2018 | Broadcom BCM2837B0 | ARM Cortex-A53 | 1GB | microSD | Wi-Fi 4, Bluetooth 4.2, Gigabit Ethernet (300 Mbps), 4x USB 2.0 | $35 |
Raspberry Pi 4 Model B | 2019 | Broadcom BCM2711 | ARM Cortex-A72 | 1GB, 2GB, 4GB, 8GB | microSD | Wi-Fi 5, Bluetooth 5.0, Gigabit Ethernet, 2x USB 3.0, 2x USB 2.0 | $35 - $75 |
Raspberry Pi 400 | 2020 | Broadcom BCM2711 | ARM Cortex-A72 | 4GB | microSD | Wi-Fi 5, Bluetooth 5.0, Gigabit Ethernet, 3x USB 3.0, 1x USB 2.0 | $70 |
Raspberry Pi Pico | 2021 | RP2040 | ARM Cortex-M0+ | 264KB SRAM | 2MB Flash | 26x GPIO, 2x SPI, 2x I2C, 2x UART, 3x ADC | $4 |
Raspberry Pi Pico W | 2022 | RP2040 | ARM Cortex-M0+ | 264KB SRAM | 2MB Flash | Wi-Fi 4, 26x GPIO, 2x SPI, 2x I2C, 2x UART, 3x ADC | $6 |
Raspberry Pi 4 Model A | 2022 | Broadcom BCM2711 | ARM Cortex-A72 | 2GB | microSD | Wi-Fi 5, Bluetooth 5.0, Gigabit Ethernet, 1x USB 3.0, 1x USB 2.0 | $25 |
Raspberry Pi Zero 2 W | 2021 | Broadcom BCM2710A1 | ARM Cortex-A53 | 512MB | microSD | Wi-Fi 4, Bluetooth 4.2, 1x mini HDMI, 1x micro USB | $15 |
Raspberry Pi 5 | 2023 | Broadcom BCM2712 | ARM Cortex-A76 | 4GB, 8GB | microSD, USB 3.0 | Wi-Fi 6, Bluetooth 5.0, Gigabit Ethernet, 2x USB 3.0, 2x USB 2.0 | $60 - $80 |
Why Raspberry Pi?
It being the de facto option it has the most support. The Pi project has: a Linux distribution, hardware /software support, devices such as sensors and monitors, and forums. And the massive slice of the market Pi has means third party support is substantial as well. There are countless add on boards or HATs and enclosures that can be had. No matter the fact that competing SBCs may have comparable or even surpassing performance capabilities, many will choose Raspberry Pi due the overwhelming support. The greatest con is the availability. Raspberry Pis have historically been extremely difficult to come by. Especially considering memory shortages, and global pandemic, and a chip shortage over the last few years, the 4th model was essentially impossible to get, especially at retail. There are entire databases dedicated to tracking retailer stocks. However, the release of the 5th model placated most and made obtaining at a reasonable price possible.
What I Use Them For
Again there are a plethora of way to utilize a Pi due to the sheer amount of openness and attachable boards and devices. I personally use them in my homelab. I use them to host a variety of services, usually through containerization such as Docker. My Raspberry Pi 4s and 5s serve:
- DNS through PiHole
- Dynamic DNS through ddclient and DuckDNS
- VPNs through PiVPN
- IP KVM using the PiKVM board
- File sharing through Samba
- Media through Plex
- Password management through Passbolt
- Site hosting through Apache and Nginx
A freshly arrived piKVM
That piKVM running booted off of a USB
I've used containers to run things like this as often as possible. Many utilities are available as container images on Dockerhub, however mileage may vary as ARM image are less common. I prefer containers due to the contained nature of the binaries and configurations. Everything can be contained in a single docker-compose file, which is very convenient. In the past I've even had my Pis clustered using Kubernetes, but that was more for educational purposes. I've also experimented with different Linux distributions on Pis. There is of course Pi OS, the officially supported one. However,the major distributions have ARM versions that run on Pis and there are others specifically designed for Pis:
Distribution | Description | Website |
---|---|---|
Raspberry Pi OS | Official operating system for Raspberry Pi, based on Debian. Includes a range of educational tools. | raspberrypi.org |
Ubuntu | Popular Linux distribution with an official version for Raspberry Pi. | ubuntu.com |
Manjaro ARM | Arch-based distribution optimized for ARM devices, including Raspberry Pi. | manjaro.org |
Kali Linux | Security-focused distribution with a version for Raspberry Pi. | kali.org |
RetroPie | Distribution focused on retro gaming emulation for Raspberry Pi. | retropie.org.uk |
LibreELEC | Minimalist distribution for running Kodi media center on Raspberry Pi. | libreelec.tv |
Pi-hole | Network-wide ad blocker that runs on Raspberry Pi. | pi-hole.net |
OSMC | Open Source Media Center based on Debian, designed for Raspberry Pi. | osmc.tv |
RISC OS | Lightweight operating system originally developed by Acorn Computers, available for Raspberry Pi. | riscosopen.org |
Gentoo | Highly customizable distribution with an ARM version for Raspberry Pi. | gentoo.org |
Arch Linux ARM | Lightweight and flexible distribution for ARM devices, including Raspberry Pi. | archlinuxarm.org |
DietPi | Extremely lightweight Debian-based distribution with a small footprint for Raspberry Pi. | dietpi.com |
Twister OS | Distribution that aims to provide a true desktop computing experience on Raspberry Pi. | twisteros.com |
Raspbian XP, Raspbian 95 | Custom distributions based on Raspberry Pi OS with themes mimicking Windows XP and Windows 95. | pi-apps.io |
BalenaOS | Container-based distribution optimized for IoT devices, including Raspberry Pi. | balena.io |
LineageOS | Android-based distribution available for Raspberry Pi. | konstakang.com |
Recalbox | Distribution focused on retro gaming emulation, similar to RetroPie. | recalbox.com |
Lakka | Lightweight distribution focused on retro gaming, using RetroArch emulator. | lakka.tv |
MotionEyeOS | Distribution focused on turning Raspberry Pi into a video surveillance system. | motioneyeos.org |
For instance installing and running Gentoo on one was... an experience.
All in all, Pis are a great way to learn and an even better way to run services at home at a low monetary cost and low power cost.
Over The Wire (Bandit) 🧑💻 (2024-07-17)
This is a wargame or ctf game that has the player interact with and penetrate a Linux system. The goal of each level is to retrieve a password or key located somewhere on a server. This can be used to access this next level, which is a user on the server.
SPOILER WARNING
I will provide the prompt and hints to each level and my answers. I may describe my methodology, reasoning, or solution if it is warranted. Do not read if you intend on playing yourself.
Level 0
The goal of this level is for you to log into the game using SSH. The host to which you need to connect is bandit.labs.overthewire.org, on port 2220. The username is bandit0 and the password is bandit0. Once logged in, go to the Level 1 page to find out how to beat Level 1.
Solution
ssh bandit0@bandit.labs.overthewire.org -p 2220
- Once logged in
cat readme
will output password to level 1. - Password:
ZjLjTmM6FvvyRnrb2rfNWOZOTa6ip5If
Level 1
The password for the next level is stored in a file called - located in the home directory
ssh bandit1@bandit.labs.overthewire.org -p 2220
- The name of the file containing the password needs to be referenced as a file as
-
is reserved for other uses in the shell. cat ./-
will do the trick- Password:
263JGJPfgU6LtdEvgfWU1XP5yac29mFx
Level 2
The password for the next level is stored in a file called spaces in this filename located in the home directory
ssh bandit2@bandit.labs.overthewire.org -p 2220
- This is a similar issue as whitespace has a reserved use is shells as well. The file must be referenced by encasing it with quotes,
cat "spaces in this filename"
or by escaping the spaces,cat spaces\ in\ this\ filename
. - Password:
MNk8KNH3Usiio41PRUEoDFPqfxLPlSmx
Level 3
The password for the next level is stored in a hidden file in the inhere directory.
ssh bandit3@bandit.labs.overthewire.org -p 2220
cat inhere/...Hiding-From-You
- Password:
2WmrDFRmJIq3IPxneAaMGhap0pFhF3NJ
Level 4
The password for the next level is stored in the only human-readable file in the inhere directory. Tip: if your terminal is messed up, try the “reset” command.
ssh bandit4@bandit.labs.overthewire.org -p 2220
- This is the first level that doesn't essentially have a single solution. Essentially do whatever you need to to determine which file is human readable or cat everything to a file and sift through garbage until you see the password.
- Using
file
and a wildcard:
bandit4@bandit:~$ file inhere/*
inhere/-file00: data
inhere/-file01: data
inhere/-file02: data
inhere/-file03: data
inhere/-file04: data
inhere/-file05: data
inhere/-file06: data
inhere/-file07: ASCII text
inhere/-file08: data
inhere/-file09: data
Looks to be inhere/-file07
.
bandit4@bandit:~$ cat inhere/-file07
4oQYVPkxZOOEOO5pTW81FB8j8lxXGUQw
Level 5
The password for the next level is stored in a file somewhere under the inhere directory and has all of the following properties: human-readable 1033 bytes in size not executable
- Most automated solution is probably just using
find
find . -size 1033c \! -executable
bandit5@bandit:~$ find . -size 1033c \! -executable
./inhere/maybehere07/.file2
- Can cat this in a one liner by running
find
in a subshell:
bandit5@bandit:~$ cat $(find . -size 1033c \! -executable)
HWasnPhtq9AVKe0dmk45nxy20cvUa6EG
Level 6
The password for the next level is stored somewhere on the server and has all of the following properties: owned by user bandit7 owned by group bandit6 33 bytes in size
- Same deal as last level except different switches and searching from root.
- After running I also redirected
stderr
to/dev/null
because there were too many permission denials getting in the way of reading output
bandit6@bandit:~$ find / -user bandit7 -group bandit6 -size 33c 2>/dev/null
/var/lib/dpkg/info/bandit7.password
bandit6@bandit:~$
- And we can cat it in a one liner for fun
bandit6@bandit:~$ cat $(find / -user bandit7 -group bandit6 -size 33c 2>/dev/null)
morbNTDkSW6jIlUc0ymOdMaLnOlFVAaj
bandit6@bandit:~$
Level 7
The password for the next level is stored in the file data.txt next to the word millionth
- First instinct is to
cat
then pipe intogrep
for "millionth".
cat data.txt | grep millionth
millionth dfwvzFQi4mU0wfNbFOe9RoWskMLg7eEc
bandit7@bandit:~$
- Yup
Level 8
The password for the next level is stored in the file data.txt and is the only line of text that occurs only once
- First instinct is to cat then pipe into uniq maybe.
- My first instinct,
cat data.txt | uniq -u
, contains too many entries. After researching I realize that repeated lines need to be adjacent to be detected as repeated, so let's sort then pipe intouniq
.
bandit8@bandit:~$ sort data.txt | uniq -u
4CKMh1JI91bUIZZPXDqGanal4xvAg0JM
bandit8@bandit:~$
- Got it
Level 9
The password for the next level is stored in the file data.txt in one of the few human-readable strings, preceded by several ‘=’ characters.
- We can use
strings
to convert the garbage data to text, then grep the file for some "=".
bandit9@bandit:~$ strings data.txt -d | grep ==
[========== the
T%========== passwordG
}========== ist"
========== FGUW5ilLVJrxX9kMYMmlN4MgbpfMiqey
bandit9@bandit:~$
- Password:
FGUW5ilLVJrxX9kMYMmlN4MgbpfMiqey
Level 10
The password for the next level is stored in the file data.txt, which contains base64 encoded data
From wikipedia: >In computer programming, Base64 is a group of binary-to-text encoding schemes that transforms binary data into a sequence of printable characters, limited to a set of 64 unique characters. More specifically, the source binary data is taken 6 bits at a time, then this group of 6 bits is mapped to one of 64 unique characters.
- I can use
base64
to decode the data by piping into it fromcat
.
bandit10@bandit:~$ cat data.txt | base64 -d
The password is dtR173fZKb0RRsDFSGsg2RWnpNVj3qRr
- Success!
Level 11
The password for the next level is stored in the file data.txt, where all lowercase (a-z) and uppercase (A-Z) letters have been rotated by 13 positions
tr
can be used to effectively rotate every character back.
bandit11@bandit:~$ cat data.txt | tr 'a-z' 'n-za-m' | tr 'A-Z' 'N-ZA-M'
The password is 7x16WNeHIi5YkIhWsfFIqoognUTyj9Q4
I need to learn tr syntax, I just found the implementation of Rot13 in tr
online and added rotation for capitals as well and piped the output a second time. That worked.
Level 12
The password for the next level is stored in the file data.txt, which is a hexdump of a file that has been repeatedly compressed. For this level it may be useful to create a directory under /tmp in which you can work. Use mkdir with a hard to guess directory name. Or better, use the command “mktemp -d”. Then copy the datafile using cp, and rename it using mv (read the manpages!)
mkdir /tmp/sm;cp data.txt /tmp/sm/; cd /tmp/sm
- I will probably have to convert from hex to binary or something and uncompress that multiple times
xxd -r data.txt | gzip -d > out
xxd
can convert data from hex to binary and vice-versa.bzip2 out -d -c > out2
gzip out2 -d -c > out3
tar -xvf out3
tar -xvf data5.bin
bzip2 data6.bin -d -c > out7
tar -xvf out7
gzip data8.bin -d -c > out9
bandit12@bandit:/tmp/sm$ cat out9
The password is FO5dwFsc0cbaIiH0h8J2eUks2vdTDwAn
bandit12@bandit:/tmp/sm$
- I gave up on renaming every time so the scheme is inconsistent, but I just checked the output using
file
every time to determine what decompression algorithm or archival tool to use until it was completely unwrapped as a text file. - Password:
FO5dwFsc0cbaIiH0h8J2eUks2vdTDwAn
Level 13
The password for the next level is stored in /etc/bandit_pass/bandit14 and can only be read by user bandit14. For this level, you don’t get the next password, but you get a private SSH key that can be used to log into the next level. Note: localhost is a hostname that refers to the machine you are working on
bandit13@bandit:~$ cat sshkey.private
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAxkkOE83W2cOT7IWhFc9aPaaQmQDdgzuXCv+ppZHa++buSkN+
gg0tcr7Fw8NLGa5+Uzec2rEg0WmeevB13AIoYp0MZyETq46t+jk9puNwZwIt9XgB
ZufGtZEwWbFWw/vVLNwOXBe4UWStGRWzgPpEeSv5Tb1VjLZIBdGphTIK22Amz6Zb
ThMsiMnyJafEwJ/T8PQO3myS91vUHEuoOMAzoUID4kN0MEZ3+XahyK0HJVq68KsV
ObefXG1vvA3GAJ29kxJaqvRfgYnqZryWN7w3CHjNU4c/2Jkp+n8L0SnxaNA+WYA7
jiPyTF0is8uzMlYQ4l1Lzh/8/MpvhCQF8r22dwIDAQABAoIBAQC6dWBjhyEOzjeA
J3j/RWmap9M5zfJ/wb2bfidNpwbB8rsJ4sZIDZQ7XuIh4LfygoAQSS+bBw3RXvzE
pvJt3SmU8hIDuLsCjL1VnBY5pY7Bju8g8aR/3FyjyNAqx/TLfzlLYfOu7i9Jet67
xAh0tONG/u8FB5I3LAI2Vp6OviwvdWeC4nOxCthldpuPKNLA8rmMMVRTKQ+7T2VS
nXmwYckKUcUgzoVSpiNZaS0zUDypdpy2+tRH3MQa5kqN1YKjvF8RC47woOYCktsD
o3FFpGNFec9Taa3Msy+DfQQhHKZFKIL3bJDONtmrVvtYK40/yeU4aZ/HA2DQzwhe
ol1AfiEhAoGBAOnVjosBkm7sblK+n4IEwPxs8sOmhPnTDUy5WGrpSCrXOmsVIBUf
laL3ZGLx3xCIwtCnEucB9DvN2HZkupc/h6hTKUYLqXuyLD8njTrbRhLgbC9QrKrS
M1F2fSTxVqPtZDlDMwjNR04xHA/fKh8bXXyTMqOHNJTHHNhbh3McdURjAoGBANkU
1hqfnw7+aXncJ9bjysr1ZWbqOE5Nd8AFgfwaKuGTTVX2NsUQnCMWdOp+wFak40JH
PKWkJNdBG+ex0H9JNQsTK3X5PBMAS8AfX0GrKeuwKWA6erytVTqjOfLYcdp5+z9s
8DtVCxDuVsM+i4X8UqIGOlvGbtKEVokHPFXP1q/dAoGAcHg5YX7WEehCgCYTzpO+
xysX8ScM2qS6xuZ3MqUWAxUWkh7NGZvhe0sGy9iOdANzwKw7mUUFViaCMR/t54W1
GC83sOs3D7n5Mj8x3NdO8xFit7dT9a245TvaoYQ7KgmqpSg/ScKCw4c3eiLava+J
3btnJeSIU+8ZXq9XjPRpKwUCgYA7z6LiOQKxNeXH3qHXcnHok855maUj5fJNpPbY
iDkyZ8ySF8GlcFsky8Yw6fWCqfG3zDrohJ5l9JmEsBh7SadkwsZhvecQcS9t4vby
9/8X4jS0P8ibfcKS4nBP+dT81kkkg5Z5MohXBORA7VWx+ACohcDEkprsQ+w32xeD
qT1EvQKBgQDKm8ws2ByvSUVs9GjTilCajFqLJ0eVYzRPaY6f++Gv/UVfAPV4c+S0
kAWpXbv5tbkkzbS0eaLPTKgLzavXtQoTtKwrjpolHKIHUz6Wu+n4abfAIRFubOdN
/+aLoRQ0yBDRbdXMsZN/jvY44eM+xRLdRVyMmdPtP8belRi2E2aEzA==
-----END RSA PRIVATE KEY-----
- I will copy this key to my host's
~/.ssh
directory and login by forcing the use of the key for access:ssh bandit14@bandit.labs.overthewire.org -p 2220 -i .ssh/id_bandit14
- I'm in!
Level 14
The password for the next level can be retrieved by submitting the password of the current level to port 30000 on localhost.
- I can
cat
the password referenced in the last level and pipe it intonetcat
to send it to the port.
bandit14@bandit:~$ cat /etc/bandit_pass/bandit14 | netcat localhost 30000
Correct!
8xCjnmgoKbGLhHFAZlGE5Tmu4M2tKJQo
Level 15
The password for the next level can be retrieved by submitting the password of the current level to port 30001 on localhost using SSL encryption. Helpful note: Getting “HEARTBEATING” and “Read R BLOCK”? Use -ign_eof and read the “CONNECTED COMMANDS” section in the manpage. Next to ‘R’ and ‘Q’, the ‘B’ command also works in this version of that command…
- I will need to encrypt what I send to the port beforehand. This can be acchomplished with openssl's s_client.
- From the man page: >DESCRIPTION This command implements a generic SSL/TLS client which connects to a remote host using SSL/TLS. It is a very useful diagnostic tool for SSL servers.
openssl s_client -ign_eof -connect localhost:30001
- I then manually enter the password
8xCjnmgoKbGLhHFAZlGE5Tmu4M2tKJQo
Correct!
kSkvUpMQ7lBYyCM4GBPvCvT1BfWRy0Dx
closed
bandit15@bandit:~$
- Mission accomplished!
Level 16
The credentials for the next level can be retrieved by submitting the password of the current level to a port on localhost in the range 31000 to 32000. First find out which of these ports have a server listening on them. Then find out which of those speak SSL and which don’t. There is only 1 server that will give the next credentials, the others will simply send back to you whatever you send to it.
- I will search for candidate ports
bandit16@bandit:~$ netstat -tulpn
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
netstat: no support for `AF INET (tcp)' on this system.
tcp6 0 0 :::31691 :::* LISTEN -
tcp6 0 0 :::31046 :::* LISTEN -
tcp6 0 0 :::22 :::* LISTEN -
tcp6 0 0 :::2232 :::* LISTEN -
tcp6 0 0 :::2231 :::* LISTEN -
tcp6 0 0 :::2230 :::* LISTEN -
tcp6 0 0 :::2220 :::* LISTEN -
tcp6 0 0 :::31960 :::* LISTEN -
bandit16@bandit:~$
- 31691, 31046, and 31960 are candidates
- However none are over ssl, the port may be open but not listening. I can scan with
nmap
.
nmap -p 31000-32000 localhost
Starting Nmap 7.94SVN ( https://nmap.org ) at 2024-07-16 01:36 UTC
Nmap scan report for localhost (127.0.0.1)
Host is up (0.00014s latency).
Not shown: 996 closed tcp ports (conn-refused)
PORT STATE SERVICE
31046/tcp open unknown
31518/tcp open unknown
31691/tcp open unknown
31790/tcp open unknown
31960/tcp open unknown
Nmap done: 1 IP address (1 host up) scanned in 0.11 seconds
- I will not manually check each with
s_client
.
openssl s_client -ign_eof -connect localhost:31790
kSkvUpMQ7lBYyCM4GBPvCvT1BfWRy0Dx
Correct!
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAAKCAQEAvmOkuifmMg6HL2YPIOjon6iWfbp7c3jx34YkYWqUH57SUdyJ
imZzeyGC0gtZPGujUSxiJSWI/oTqexh+cAMTSMlOJf7+BrJObArnxd9Y7YT2bRPQ
Ja6Lzb558YW3FZl87ORiO+rW4LCDCNd2lUvLE/GL2GWyuKN0K5iCd5TbtJzEkQTu
DSt2mcNn4rhAL+JFr56o4T6z8WWAW18BR6yGrMq7Q/kALHYW3OekePQAzL0VUYbW
JGTi65CxbCnzc/w4+mqQyvmzpWtMAzJTzAzQxNbkR2MBGySxDLrjg0LWN6sK7wNX
x0YVztz/zbIkPjfkU1jHS+9EbVNj+D1XFOJuaQIDAQABAoIBABagpxpM1aoLWfvD
KHcj10nqcoBc4oE11aFYQwik7xfW+24pRNuDE6SFthOar69jp5RlLwD1NhPx3iBl
J9nOM8OJ0VToum43UOS8YxF8WwhXriYGnc1sskbwpXOUDc9uX4+UESzH22P29ovd
d8WErY0gPxun8pbJLmxkAtWNhpMvfe0050vk9TL5wqbu9AlbssgTcCXkMQnPw9nC
YNN6DDP2lbcBrvgT9YCNL6C+ZKufD52yOQ9qOkwFTEQpjtF4uNtJom+asvlpmS8A
vLY9r60wYSvmZhNqBUrj7lyCtXMIu1kkd4w7F77k+DjHoAXyxcUp1DGL51sOmama
+TOWWgECgYEA8JtPxP0GRJ+IQkX262jM3dEIkza8ky5moIwUqYdsx0NxHgRRhORT
8c8hAuRBb2G82so8vUHk/fur85OEfc9TncnCY2crpoqsghifKLxrLgtT+qDpfZnx
SatLdt8GfQ85yA7hnWWJ2MxF3NaeSDm75Lsm+tBbAiyc9P2jGRNtMSkCgYEAypHd
HCctNi/FwjulhttFx/rHYKhLidZDFYeiE/v45bN4yFm8x7R/b0iE7KaszX+Exdvt
SghaTdcG0Knyw1bpJVyusavPzpaJMjdJ6tcFhVAbAjm7enCIvGCSx+X3l5SiWg0A
R57hJglezIiVjv3aGwHwvlZvtszK6zV6oXFAu0ECgYAbjo46T4hyP5tJi93V5HDi
Ttiek7xRVxUl+iU7rWkGAXFpMLFteQEsRr7PJ/lemmEY5eTDAFMLy9FL2m9oQWCg
R8VdwSk8r9FGLS+9aKcV5PI/WEKlwgXinB3OhYimtiG2Cg5JCqIZFHxD6MjEGOiu
L8ktHMPvodBwNsSBULpG0QKBgBAplTfC1HOnWiMGOU3KPwYWt0O6CdTkmJOmL8Ni
blh9elyZ9FsGxsgtRBXRsqXuz7wtsQAgLHxbdLq/ZJQ7YfzOKU4ZxEnabvXnvWkU
YOdjHdSOoKvDQNWu6ucyLRAWFuISeXw9a/9p7ftpxm0TSgyvmfLF2MIAEwyzRqaM
77pBAoGAMmjmIJdjp+Ez8duyn3ieo36yrttF5NSsJLAbxFpdlc1gvtGCWW+9Cq0b
dxviW8+TFVEBl1O4f7HVm6EpTscdDxU+bCXWkfjuRb7Dy9GOtt9JPsX8MBTakzh3
vBgsyi/sN3RqRBcGU40fOoZyfAMT8s1m/uYv52O6IgeuZ/ujbjY=
-----END RSA PRIVATE KEY-----
closed
bandit16@bandit:~$
- It was port 31790 and a key was returned, I will add it to my host's
~/.ssh
.ssh bandit17@bandit.labs.overthewire.org -p 2220 -i ~/.ssh/id_bandit17
works!
Level 17
There are 2 files in the homedirectory: passwords.old and passwords.new. The password for the next level is in passwords.new and is the only line that has been changed between passwords.old and passwords.new NOTE: if you have solved this level and see ‘Byebye!’ when trying to log into bandit18, this is related to the next level, bandit19
- We can just
diff
to find the differing line:
bandit17@bandit:~$ diff passwords.new passwords.old
42c42
< x2gLTTjFwMOhQ8oWNbMN362QKxfRqGlO
---
> FtePUTiLiwPzjIFw2T7o57oBS4zUvPpg
So the password is: x2gLTTjFwMOhQ8oWNbMN362QKxfRqGlO
Level 18
The password for the next level is stored in a file readme in the homedirectory. Unfortunately, someone has modified .bashrc to log you out when you log in with SSH.
- I know that you can pass a command to
ssh
to be ran rather than initializing a shell ssh bandit18@bandit.labs.overthewire.org -p 2220 'cat readme'
- The password was returned:
bandit18@bandit.labs.overthewire.org's password: cGWpMaKXVwDUNgPAVJbWYuGHVn9zl3j8
Level 19
To gain access to the next level, you should use the setuid binary in the homedirectory. Execute it without arguments to find out how to use it. The password for this level can be found in the usual place (/etc/bandit_pass), after you have used the setuid binary.
bandit19@bandit:~$ ./bandit20-do
Run a command as another user.
Example: ./bandit20-do id
- Evidently, we can use this binary to
cat
bandit20's password since it is the owner of the file that contains it.
bandit19@bandit:~$ ./bandit20-do cat /etc/bandit_pass/bandit20
0qXahG8ZjOVMN9Ghs7iOWsCfZyXOUbYO
Level 20
There is a setuid binary in the homedirectory that does the following: it makes a connection to localhost on the port you specify as a commandline argument. It then reads a line of text from the connection and compares it to the password in the previous level (bandit20). If the password is correct, it will transmit the password for the next level (bandit21). NOTE: Try connecting to your own network daemon to see if it works as you think
- I believe I have to connect to a port of my choosing using the
suconnect
binary and then send the password to that port while it is open. I have some options. I can either use a multiplexer or throwsuconnect
's process to the background. - I am mistaken, it it the other way around. I must send the password to the port first, then
suconnect
grabs it.
bandit20@bandit:~$ echo -n "0qXahG8ZjOVMN9Ghs7iOWsCfZyXOUbYO" | netcat -l -p 30003 &
[1] 867141
bandit20@bandit:~$ ./suconnect 30003
Read: 0qXahG8ZjOVMN9Ghs7iOWsCfZyXOUbYO
Password matches, sending next password
EeoULMCra2q0dSkYj561DX7s1CpBuOBt
[1]+ Done echo -n "0qXahG8ZjOVMN9Ghs7iOWsCfZyXOUbYO" | netcat -l -p 30003
- Password:
EeoULMCra2q0dSkYj561DX7s1CpBuOBt
Level 21
A program is running automatically at regular intervals from cron, the time-based job scheduler. Look in /etc/cron.d/ for the configuration and see what command is being executed.
bandit21@bandit:~$ cat /etc/cron.d/cronjob_bandit22
@reboot bandit22 /usr/bin/cronjob_bandit22.sh &> /dev/null
* * * * * bandit22 /usr/bin/cronjob_bandit22.sh &> /dev/null
bandit21@bandit:~$ cat /usr/bin/cronjob_bandit22.sh
#!/bin/bash
chmod 644 /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
cat /etc/bandit_pass/bandit22 > /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
bandit21@bandit:~$ cat /tmp/t7O6lds9S0RqQh9aMcz6ShpAoZKF7fgv
tRae0UfB9v0UzbCdn9cY0gQnds9GF58Q
bandit21@bandit:~$
Password: tRae0UfB9v0UzbCdn9cY0gQnds9GF58Q
Level 22
A program is running automatically at regular intervals from cron, the time-based job scheduler. Look in /etc/cron.d/ for the configuration and see what command is being executed. NOTE: Looking at shell scripts written by other people is a very useful skill. The script for this level is intentionally made easy to read. If you are having problems understanding what it does, try executing it to see the debug information it prints.
bandit22@bandit:~$ cat /etc/cron.d/cronjob_bandit23
@reboot bandit23 /usr/bin/cronjob_bandit23.sh &> /dev/null
* * * * * bandit23 /usr/bin/cronjob_bandit23.sh &> /dev/null
bandit22@bandit:~$ cat /usr/bin/cronjob_bandit23.sh
#!/bin/bash
myname=$(whoami)
mytarget=$(echo I am user $myname | md5sum | cut -d ' ' -f 1)
echo "Copying passwordfile /etc/bandit_pass/$myname to /tmp/$mytarget"
cat /etc/bandit_pass/$myname > /tmp/$mytarget
bandit22@bandit:~$
- Based on this, the password whose name was hashed by
md5sum
- I will manually run the command using "bandit23" as
myname
in a subshell and cat the appropriate file.
bandit22@bandit:~$ cat /tmp/$(echo I am user bandit23 | md5sum | cut -d ' ' -f 1)
0Zf11ioIjMVN551jX3CmStKLYqjk54Ga
Level 23
A program is running automatically at regular intervals from cron, the time-based job scheduler. Look in /etc/cron.d/ for the configuration and see what command is being executed. NOTE: This level requires you to create your own first shell-script. This is a very big step and you should be proud of yourself when you beat this level! NOTE 2: Keep in mind that your shell script is removed once executed, so you may want to keep a copy around…
bandit23@bandit:~$ cat /etc/cron.d/cronjob_bandit24
@reboot bandit24 /usr/bin/cronjob_bandit24.sh &> /dev/null
* * * * * bandit24 /usr/bin/cronjob_bandit24.sh &> /dev/null
bandit23@bandit:~$ cat /usr/bin/cronjob_bandit24.sh
#!/bin/bash
myname=$(whoami)
cd /var/spool/$myname/foo
echo "Executing and deleting all scripts in /var/spool/$myname/foo:"
for i in * .*;
do
if [ "$i" != "." -a "$i" != ".." ];
then
echo "Handling $i"
owner="$(stat --format "%U" ./$i)"
if [ "${owner}" = "bandit23" ]; then
timeout -s 9 60 ./$i
fi
rm -f ./$i
fi
done
- Based on the script that is being run by cron, we just need to write a script that gets the name of bandit24's password for us. This script executes every script in
/var/spool/bandit24/foo/
if it is owned by bandit23 then deletes it. However, the script will be ran as bandit24 since it is that user's cronjob. Therefore, I can get the contents of/etc/bandit_pass
from a script in/var/spool/bandit24/foo/
. - I am having an issue getting output from the script presumably due to permissions. I modified the target directory with
chmod 777
.
#!/bin/bash
cat /etc/bandit_pass/bandit24 >> /tmp/sm2/out.txt
This did the trick:
gb8KRRCsshuZXI0tUuR6ypOFjiZbf3G8
- Success!
Level 24
A daemon is listening on port 30002 and will give you the password for bandit25 if given the password for bandit24 and a secret numeric 4-digit pincode. There is no way to retrieve the pincode except by going through all of the 10000 combinations, called brute-forcing. You do not need to create new connections each time
- This is the script I've formulated:
#!/bin/sh
code=0
while [ $code -le 9998 ];
do
code=$((code+1))
pass="gb8KRRCsshuZXI0tUuR6ypOFjiZbf3G8 ${code}"
echo "Trying code $pass"
echo $pass | nc localhost 30002 -w 1 | tee -a out.txt
done
- But it is very slow, there must be a faster way.
- Firstly, it starts at 0 because it just increments it doesn't handle every digit independently.
#!/bin/bash
for i in {0000..9999}
do
pass="gb8KRRCsshuZXI0tUuR6ypOFjiZbf3G8 ${i}"
echo "Trying code $pass"
echo $pass | nc localhost 30002 -w 1 | tee -a out.txt
done
- This is better! Didn't know bash supported iterating over ranges this way. Now looking into improving speed. Could utilize parallelization in some way. I could:
- Throw the jobs into the background with a max number running any time
- Utilize
parallel
#!/bin/bash
export pass_prefix="gb8KRRCsshuZXI0tUuR6ypOFjiZbf3G8 "
generate_and_try() {
i=$1
pass="${pass_prefix}${i}"
echo "Trying code $pass"
echo $pass | nc localhost 30002 -w 1 | tee -a out.txt
}
export -f generate_and_try
export pass_prefix
# Generate the sequence and run in parallel
seq -w 0000 9999 | parallel -j 100 generate_and_try
parallel
handles the parallelization... luckily it is installed...- Instead of a loop this solution utilizes
seq
to generate codes - The code is passed as a cmdline arg
- I will then search the output for the string "Correct". One could also
grep -v
the string "Wrong".
Correct! The password of user bandit25 is iCi86ttT4KSNe1armKiwbQNmB3YJP3q4
- Success!
Level 25
Logging in to bandit26 from bandit25 should be fairly easy… The shell for user bandit26 is not /bin/bash, but something else. Find out what it is, how it works and how to break out of it.
- I know that default shells are in
/etc/passwd
. cat /etc/passwd | grep -i bandit26
yieldsbandit26:x:11026:11026:bandit level 26:/home/bandit26:/usr/bin/showtext
showtext
is a script:
#!/bin/sh
export TERM=linux
exec more ~/text.txt exit 0
* And there is a key in the home directory
```terminal
ls
bandit26.sshkey
bandit25@bandit:~$ cat bandit26.sshkey
-----BEGIN RSA PRIVATE KEY-----
MIIEpQIBAAKCAQEApis2AuoooEqeYWamtwX2k5z9uU1Afl2F8VyXQqbv/LTrIwdW
pTfaeRHXzr0Y0a5Oe3GB/+W2+PReif+bPZlzTY1XFwpk+DiHk1kmL0moEW8HJuT9
/5XbnpjSzn0eEAfFax2OcopjrzVqdBJQerkj0puv3UXY07AskgkyD5XepwGAlJOG
xZsMq1oZqQ0W29aBtfykuGie2bxroRjuAPrYM4o3MMmtlNE5fC4G9Ihq0eq73MDi
1ze6d2jIGce873qxn308BA2qhRPJNEbnPev5gI+5tU+UxebW8KLbk0EhoXB953Ix
3lgOIrT9Y6skRjsMSFmC6WN/O7ovu8QzGqxdywIDAQABAoIBAAaXoETtVT9GtpHW
qLaKHgYtLEO1tOFOhInWyolyZgL4inuRRva3CIvVEWK6TcnDyIlNL4MfcerehwGi
il4fQFvLR7E6UFcopvhJiSJHIcvPQ9FfNFR3dYcNOQ/IFvE73bEqMwSISPwiel6w
e1DjF3C7jHaS1s9PJfWFN982aublL/yLbJP+ou3ifdljS7QzjWZA8NRiMwmBGPIh
Yq8weR3jIVQl3ndEYxO7Cr/wXXebZwlP6CPZb67rBy0jg+366mxQbDZIwZYEaUME
zY5izFclr/kKj4s7NTRkC76Yx+rTNP5+BX+JT+rgz5aoQq8ghMw43NYwxjXym/MX
c8X8g0ECgYEA1crBUAR1gSkM+5mGjjoFLJKrFP+IhUHFh25qGI4Dcxxh1f3M53le
wF1rkp5SJnHRFm9IW3gM1JoF0PQxI5aXHRGHphwPeKnsQ/xQBRWCeYpqTme9amJV
tD3aDHkpIhYxkNxqol5gDCAt6tdFSxqPaNfdfsfaAOXiKGrQESUjIBcCgYEAxvmI
2ROJsBXaiM4Iyg9hUpjZIn8TW2UlH76pojFG6/KBd1NcnW3fu0ZUU790wAu7QbbU
i7pieeqCqSYcZsmkhnOvbdx54A6NNCR2btc+si6pDOe1jdsGdXISDRHFb9QxjZCj
6xzWMNvb5n1yUb9w9nfN1PZzATfUsOV+Fy8CbG0CgYEAifkTLwfhqZyLk2huTSWm
pzB0ltWfDpj22MNqVzR3h3d+sHLeJVjPzIe9396rF8KGdNsWsGlWpnJMZKDjgZsz
JQBmMc6UMYRARVP1dIKANN4eY0FSHfEebHcqXLho0mXOUTXe37DWfZza5V9Oify3
JquBd8uUptW1Ue41H4t/ErsCgYEArc5FYtF1QXIlfcDz3oUGz16itUZpgzlb71nd
1cbTm8EupCwWR5I1j+IEQU+JTUQyI1nwWcnKwZI+5kBbKNJUu/mLsRyY/UXYxEZh
ibrNklm94373kV1US/0DlZUDcQba7jz9Yp/C3dT/RlwoIw5mP3UxQCizFspNKOSe
euPeaxUCgYEAntklXwBbokgdDup/u/3ms5Lb/bm22zDOCg2HrlWQCqKEkWkAO6R5
/Wwyqhp/wTl8VXjxWo+W+DmewGdPHGQQ5fFdqgpuQpGUq24YZS8m66v5ANBwd76t
IZdtF5HXs2S5CADTwniUS5mX1HO9l5gUkk+h0cH5JnPtsMCnAUM+BRY=
-----END RSA PRIVATE KEY-----
bandit25@bandit:~$
- The solution for this was ultimately simple yet very elusive. So the text contained in
~text.txt
was too short to do anything with and would immeditaly exit. I explored for any possible ssh switch or techqiue I could employ. I checked every permission. But the simpliest solution was just... to make the window smaller... That forcesmore
to enter an interactive mode since all the text can't be displayed. From there you cna evert Vi and do whatever you need to. - I first redefined the shell:
:set shell=/bin/bash
- And enter a shell from Vi using
:shell
- Now I am in and technically in:
Level 26
Good job getting a shell! Now hurry and grab the password for bandit27!
- Then catted the password
bandit26@bandit:~$ cat /etc/bandit_pass/bandit26 s0773xxkk0MXfdqOfPRVr9L3jJBUOgCZ
bandit26@bandit:~$ ```
- Password:
s0773xxkk0MXfdqOfPRVr9L3jJBUOgCZ
- Remember this is just bandit 26's password.
bandit26@bandit:~$ ls -l
total 20
-rwsr-x--- 1 bandit27 bandit26 14880 Jul 17 15:57 bandit27-do
-rw-r----- 1 bandit26 bandit26 258 Jul 17 15:57 text.txt
bandit26@bandit:~$ ./bandit27-do cat /etc/bandit_pass/bandit27
upsNCc7vzaRDx6oZC6GiR6ERwe1MowGB
bandit26@bandit:~$
- Looks like there is a binary with the
suid
bit set allowing me to run it as bandit27 since they are the owner and bandit26's group has execute permissions on. The binary evidently takes a command as an argument to be ran. I used this to get the password for bandit27. - Password:
upsNCc7vzaRDx6oZC6GiR6ERwe1MowGB
Level 27
There is a git repository at ssh://bandit27-git@localhost/home/bandit27-git/repo via the port 2220. The password for the user bandit27-git is the same as for the user bandit27.
Clone the repository and find the password for the next level.
- I make a directory in
tmp
and clone the repo
bandit27@bandit:/tmp/gh$ git clone ssh://bandit27-git@localhost:2220/home/bandit27-git/repo
bandit27@bandit:/tmp/gh/repo$ cat README
The password to the next level is: Yz9IpL0sBcCeuG7m9uQFt8ZNpS4HZRcN
- There was simply a
README
containing the password
Level 28
There is a git repository at ssh://bandit28-git@localhost/home/bandit28-git/repo via the port 2220. The password for the user bandit28-git is the same as for the user bandit28. Clone the repository and find the password for the next level.
- It is the same process as before, but the contents are little different.
bandit28@bandit:/tmp/gh28/repo$ ls
README.md
bandit28@bandit:/tmp/gh28/repo$ cat README.md
# Bandit Notes
Some notes for level29 of bandit.
## credentials
- username: bandit29
- password: xxxxxxxxxx
bandit28@bandit:/tmp/gh28/repo$
- Looks like we will have to brute for a password a 10 character password, which would take way too long. As in like millions of years... using a supercomputer... so this can't be the solution.
bandit28@bandit:/tmp/gh28/repo$ git log
WARNING: terminal is not fully functional
Press RETURN to continue
commit 8cbd1e08d1879415541ba19ddee3579e80e3f61a (HEAD -> mast
er, origin/master, origin/HEAD)
Author: Morla Porla <morla@overthewire.org>
Date: Wed Jul 17 15:57:30 2024 +0000
fix info leak
commit 73f5d0435070c8922da12177dc93f40b2285e22a
Author: Morla Porla <morla@overthewire.org>
Date: Wed Jul 17 15:57:30 2024 +0000
add missing data
commit 5f7265568c7b503b276ec20f677b68c92b43b712
Author: Ben Dover <noone@overthewire.org>
Date: Wed Jul 17 15:57:30 2024 +0000
initial commit of README.md
bandit28@bandit:/tmp/gh28/repo$
- The solution looks it is going to be looking at each commit to see when a password added. This can be a accomplished with
checkout
. There seems to be three commits and the password was ultimately in the middle one.
bandit28@bandit:/tmp/gh28/repo$ git checkout 73f5d0435070c8922da12177dc93f40b2285e22a
Previous HEAD position was 5f72655 initial commit of README.md
HEAD is now at 73f5d04 add missing data
bandit28@bandit:/tmp/gh28/repo$ ls
README.md
bandit28@bandit:/tmp/gh28/repo$ cat README.md
# Bandit Notes
Some notes for level29 of bandit.
## credentials
- username: bandit29
- password: 4pT1t5DENaYuqnqvadYs1oE4QLCdjmJ7
bandit28@bandit:/tmp/gh28/repo$
- Password:
4pT1t5DENaYuqnqvadYs1oE4QLCdjmJ7
Level 29
There is a git repository at ssh://bandit29-git@localhost/home/bandit29-git/repo via the port 2220. The password for the user bandit29-git is the same as for the user bandit29. Clone the repository and find the password for the next level.
bandit29@bandit:/tmp/b29/repo$ cat README.md
# Bandit Notes
Some notes for bandit30 of bandit.
## credentials
- username: bandit30
- password: <no passwords in production!>
bandit29@bandit:/tmp/b29/repo$
- Probably going to have to go to a different branch based on this.
bandit29@bandit:/tmp/b29/repo$ git branch -r
WARNING: terminal is not fully functional
Press RETURN to continue
origin/HEAD -> origin/master
origin/dev
origin/master
origin/sploits-dev
bandit29@bandit:/tmp/b29/repo$
- I'll checkout dev
bandit29@bandit:/tmp/b29/repo$ git checkout dev
Previous HEAD position was 5a53eb8 initial commit of README.md
branch 'dev' set up to track 'origin/dev'.
Switched to a new branch 'dev'
bandit29@bandit:/tmp/b29/repo$ ls
code README.md
bandit29@bandit:/tmp/b29/repo$ ls code/
gif2ascii.py
bandit29@bandit:/tmp/b29/repo$ cat README.md
# Bandit Notes
Some notes for bandit30 of bandit.
## credentials
- username: bandit30
- password: qp30ex3VLz5MDG1n91YowTv4Q8l7CDZL
bandit29@bandit:/tmp/b29/repo$
- There it is! Password:
qp30ex3VLz5MDG1n91YowTv4Q8l7CDZL
Level 30
There is a git repository at
ssh://bandit30-git@localhost/home/bandit30-git/repo
via the port2220
. The password for the userbandit30-git
is the same as for the userbandit30
. Clone the repository and find the password for the next level.
bandit30@bandit:/tmp/b30/repo$ cat README.md
just an epmty file... muahaha
bandit30@bandit:/tmp/b30/repo$ git tag
WARNING: terminal is not fully functional
Press RETURN to continue
secret
bandit30@bandit:/tmp/b30/repo$ git show secret
WARNING: terminal is not fully functional
Press RETURN to continue
fb5S2xb7bRyFmAvQYQGEqsbhVyJqhnDy
bandit30@bandit:/tmp/b30/repo$
- The
README
had nothing, but there was a tag namedsecret
that contained the password. - Password:
fb5S2xb7bRyFmAvQYQGEqsbhVyJqhnDy
Level 31
There is a git repository at ssh://bandit31-git@localhost/home/bandit31-git/repo via the port 2220. The password for the user bandit31-git is the same as for the user bandit31. Clone the repository and find the password for the next level.
bandit31@bandit:/tmp/b31/repo$ cat README.md
This time your task is to push a file to the remote repository.
Details:
File name: key.txt
Content: 'May I come in?'
Branch: master
bandit31@bandit:/tmp/b31/repo$
- Here it seems we must write a file
key.txt
that contains the required string. - We can
touch key.txt; echo "May I come in? > key.txt"
- Then
add key.txt
,commit
, thenpush
. - The
.gitignore
needed to be edited. because every text file was being ignored via:*.txt
- Once pushed we succeeded!
bandit31-git@localhost's password:
Enumerating objects: 4, done.
Counting objects: 100% (4/4), done.
Delta compression using up to 2 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 321 bytes | 321.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
remote: ### Attempting to validate files... ####
remote:
remote: .oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.
remote:
remote: Well done! Here is the password for the next level:
remote: 3O9RfhqyAlVBEZpVb6LYStshZoqoSx5K
remote:
remote: .oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.oOo.
remote:
To ssh://localhost:2220/home/bandit31-git/repo
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'ssh://localhost:2220/home/bandit31-git/repo'
bandit31@bandit:/tmp/b31/repo$
- Password:
3O9RfhqyAlVBEZpVb6LYStshZoqoSx5K
Level 32
After all this git stuff, it’s time for another escape. Good luck!
WELCOME TO THE UPPERCASE SHELL
>> ls
sh: 1: LS: Permission denied
Where am I?
- We can't use commands because they are all made uppercase. In this peculiar situation we'd have access to environment variables and command line arguments however. Considering that the first arg,
$0
, is the shell itself, i can call a new shell with it?
>> $0
$
- YES!
- I switched to a bash shell and got the next password
bandit33@bandit:~$ cat /etc/bandit_pass/bandit33
tQdtbs5D5i2vJwkO8mEyYEyTL8izoeJ0
bandit33@bandit:~$
Level 33
At this moment, level 34 does not exist yet.
bandit33@bandit:~$ cat README.txt
Congratulations on solving the last level of this game!
At this moment, there are no more levels to play in this game. However, we are constantly working
on new levels and will most likely expand this game with more levels soon.
Keep an eye out for an announcement on our usual communication channels!
In the meantime, you could play some of our other wargames.
us
If you have an idea for an awesome new level, please let us know!
bandit33@bandit:~$
I WON! 🥳
What I Learned
This game was very fun and forces us to really think about how certain aspects of a Linux system works and how they interact with one another. The topics that are generally touched on are:
- Basic command line utilities
ls
,cd
,mkdir
, etc.
- Text manipulation
cat
,grep
,uniq
,sort
,seq
,strings
,tr
- Redirection
- Redirection Operators, Pipes,
tee
- Redirection Operators, Pipes,
- Permissions
- Remote Access and Remote Command Execution
ssh
- System File Locations and Root Directories
etc/passwd
,/tmp
, `/bin
- Processes
&
,bg
,fg
,tmux
,screen
,ps
- Scheduling
cron
- Shells
bash
,sh
- Environment Variables and Arguments,
$0
,TERM
- Base Conversions, Encoding, and Hashing
base64
,md5sum
- Compression and Archiving
tar
,gzip
,bzip2
- Basic networking Concepts and Utilities
nc
,netstat
- Scripting
- Conditionals, Comparisons, Loops
- Optionally parallelization through
parallel
- Git Concepts and Subcommands
checkout
,branch
,tag
,add
,commit
,push
Basic Calculus in C (2024-07-10)
Numerical Methods of Differentiation
I just wrote this up because I was curious about how to code calculus stuff which I had never done before. This lead me to falling down a rabbit hole on numerical methods.
Anyone who has taken Calculus in school is familiar with some numerical methods of differentiation or integration. The basis of the definition of a derivative is itself an approximation:
\[ f'(x) = \lim_{{h \to 0}} \frac{f(x+h) - f(x)}{h} \]
A secant line where the distance between the two intersections is an infinitesimal.
I've recently learned that this is a class of method known as the Finite Difference Method where a derivative is calculated using the same difference quotient with a finite distance that is sufficiently small:
\[f'(x) \approx \frac{f(x+h) - f(x)}{h}\]
New to me is the Symmetric Difference Quotient which also approximates the slope, but by using two secant lines equidistant from x
.
\[f'(x) \approx \frac{f(x+h) - f(x-h)}{2h}\]
The accuracy will be off by a proportion of h
using the former method and by h^2
using the latter one.
The accuracy will also be affected by the choice of forward, back, or central difference, round-off error, or truncation error, which funnily enough is often notated using big-O.
Numerical Methods of Integration
Riemann Sums is the other numerical method that is often learned to introduce the concept of an integral. And has been in use since antiquity - like when Archimedes approximated the area of the circle through methods of exhaustion.
Riemann sums partition the area under a curve either from the left, right, or midpoint and if those partitions or slices are sufficiently small, you get a good approximation. This method utilizes rectangles:
\[\int_{a}^{b} f(x) , dx \approx \sum_{i=0}^{n-1} f\left( \frac{x_i + x_{i+1}}{2} \right) \Delta x\]
But can utilize other polygons such a trapezoids:
\[\int_{a}^{b} f(x) , dx \approx \frac{\Delta x}{2} \left[ f(x_0) + 2 \sum_{i=1}^{n-1} f(x_i) + f(x_n) \right]\]
There are a plethora numerical methods for both differentiation and integration that have been developed over the centuries that have their applications in engineering, manufacturing, physics, and computer science.
Numerical Differentiation Methods | Numerical Integration Methods |
---|---|
Finite Difference Methods | Basic Methods |
- Forward Difference | - Rectangle Rule (Midpoint Rule) |
- Backward Difference | - Trapezoidal Rule |
- Central Difference | - Simpson's Rule |
Higher-Order Finite Difference Methods | Extended Newton-Cotes Formulas |
- Second-Order Forward Difference | - Simpson's 3/8 Rule |
- Second-Order Backward Difference | - Boole's Rule |
- Second-Order Central Difference | - Newton-Cotes Formulas |
- Higher-Order Central Differences | Gaussian Quadrature |
Richardson Extrapolation | - Gauss-Legendre Quadrature |
Spectral Methods | - Gauss-Chebyshev Quadrature |
- Fourier Spectral Methods | - Gauss-Hermite Quadrature |
- Chebyshev Spectral Methods | - Gauss-Laguerre Quadrature |
Spline Methods | Romberg Integration |
- Linear Spline Differentiation | Adaptive Quadrature Methods |
- Quadratic Spline Differentiation | - Adaptive Simpson's Method |
- Cubic Spline Differentiation | - Adaptive Trapezoidal Method |
Polynomial Interpolation Methods | Multi-dimensional Methods |
- Lagrange Interpolation Differentiation | - Monte Carlo Integration |
- Newton's Divided Difference Differentiation | - Quasi-Monte Carlo Methods |
- Hermite Interpolation Differentiation | - Sparse Grid Methods |
Least Squares Methods | - Cubature Rules |
- Least Squares Polynomial Differentiation | Specialized Methods |
Numerical Methods for Specific Problems | - Clenshaw-Curtis Quadrature |
- Finite Volume Methods | - Lobatto Quadrature |
- Finite Element Methods | - Filon's Method (for oscillatory integrals) |
- Boundary Element Methods | - Double Exponential Integration |
Miscellaneous Methods | Numerical Differentiation Based Methods |
- Savitzky-Golay Filter | - Richardson Extrapolation |
- Automatic Differentiation | - Extrapolated Romberg Integration |
- Complex Step Differentiation | Modern Methods |
- Spectral Methods | |
- Spline-based Methods | |
- Quadrature by Expansion | |
- Finite Element Method |
Numerical Methods in C
Since these methods discretize functions they are how one could create algorithms to perform differentiation or integration. For example:
// Forward difference method
double forward_difference(double x, double h) {
return (f(x + h) - f(x)) / h;
}
// Backward difference method
double backward_difference(double x, double h) {
return (f(x) - f(x - h)) / h;
}
// Central difference method
double central_difference(double x, double h) {
return (f(x + h) - f(x - h)) / (2 * h);
}
These c function will approximate a derivative given some function.
How about integration:
// Trapezoidal rule function
double trapezoidal(double a, double b, int n) {
double h = (b - a) / n;
double sum = 0.5 * (f(a) + f(b));
for (int i = 1; i < n; i++) {
sum += f(a + i * h);
}
return sum * h;
}
This will calculate an integral given a number of sub-intervals.
Or this:
// Simpson's rule function
double simpsons(double a, double b, int n) {
double h = (b - a) / n;
double sum = f(a) + f(b);
for (int i = 1; i < n; i++) {
double x = a + i * h;
if (i % 2 == 0) {
sum += 2 * f(x);
} else {
sum += 4 * f(x);
}
}
return sum * h / 3;
}
Which does the same according to Simpson's Rule.
In Conclusion
Numerical methods seem essential to most calculus applications in the real world, however it isn't emphasized at all in the university calculus series. I'm glad I read up on it. I may update this with more advanced methods translated to c.
Rewrites of GNU Utilities (2024-06-27)
There seems to be a modern trend of rewriting common GNU utilities, especially in Rust. The GNU utils have been rewritten before, most notably as BusyBox, the GNU core utils as a single binary meant to be used in extremely small embedded Linux environments. However, Rust seems to be a popular language used to write these newer ones, evidently because Rust is a new darling language. However it seems to have a newfound relevance as rust code was recently added to the Linux kernel.
These rewrites often offer improved functionality over their much older counterparts, have more human readable options, syntax, and outputs, and some even boast greater efficiency and speed. Now, if true, these improvements are likely never human detectable. No person will likely ever feel a difference in speed at a cli, but it is fun to note. Despite these improvements these rewrites will likely never gain widespread use these the originals are already installed and countless scripts and other tools already depend on their existence. But a poweruser who wants to have fun and utilize newer, more powerful and intuitive tools, should have at it. I'd actually recommend many of them, they're amazing. I'd just caution these users to not come too accustomed to using them as if they ever want to become a professional, they'll immediately encounter a situation where only GNU utils are at their disposal. I definitely have to keep this in mind when either using a rewrite or my own aliases.
In this post, I'm going list the ones I personally use and others I've never tried but am interested in.
bat
A cat
clone with syntax highlighting and Git integration.
exa
A modern replacement for ls
.
lsd
The next gen file listing command. Backwards compatible with ls
.
delta
A viewer for git
and diff
output
dust
A more intuitive version of du
written in rust.
duf
A better df
alternative
broot
A new way to see and navigate directory tree
s
fd
A simple, fast and user-friendly alternative to find
.
ripgrep
An extremely fast alternative to grep
that respects your gitignore
ag
A code searching tool similar to ack
, but faster.
fzf
A general purpose command-line fuzzy finder.
mcfly
Fly through your shell history
. Great Scott!
choose
A human-friendly and fast alternative to cut
and (sometimes) awk
jq
sed
for JSON data.
sd
An intuitive find & replace CLI (sed
alternative).
cheat
Create and view interactive cheatsheets on the command-line.
tldr
A community effort to simplify man
pages with practical examples.
bottom
Yet another cross-platform graphical process/system monitor.
glances
Glances an Eye on your system. A top
/htop
alternative for GNU/Linux, BSD, Mac OS and Windows operating systems.
gtop
System monitoring dashboard for terminal.
hyperfine
A command-line benchmarking tool.
gping
ping
, but with a graph.
procs
A modern replacement for ps
written in Rust.
httpie
A modern, user-friendly command-line HTTP client for the API era.
curlie
The power of curl
, the ease of use of httpie
.
xh
A friendly and fast tool for sending HTTP requests. It reimplements as much as possible of HTTPie's excellent design, with a focus on improved performance.
zoxide
A smarter cd
command inspired by z
.
dog
A user-friendly command-line DNS client. dig
on steroids
Linux Learning Resources (2024-06-26)
I am currently a RHCSA who will eventually be an RHCE. This requires me to keep my skills fresh. The learning seemingly never stops; there is always something else to know. Whether it be a new tool that is really cool, or a facet of something's design that is intriguing or indicates how it can be manipulated.
All this constant learning and re-learning requires resources. I've read an untold number of documentation/wiki articles, and have watched countless Youtube videos on topics relating to Linux. Here, I want to document the resources that have served me best and that have provided the most digestible knowledge. Maybe it will help others. It will be categorized along the lines of format. Also, each resource will be rated from 1-5 penguins 🐧. The more penguins the better.
Books
I find books the worst method of learning Linux. It isn't conducive to hands on learning. However, portions of these books so relay and explain underlying concepts pretty well. Most books take the form of that of a manual that is good for referencing but not learning. And even then, something printed on paper easily becomes outdated. Books that are meant for preparing for a specific exam are better as they often include lab material.
-
Linux Bible by Christopher Negus, published on August 5, 2020. 🐧🐧🐧
-
Unix and Linux System Administration Handbook by Evi Nemeth, Garth Snyder, Trent R. Hein, Ben Whaley, and Dan Mackin, published on July 14, 2017.🐧🐧🐧
-
Red Hat RHCSA 9 Cert Guide: Red Hat Enterprise Linux 9 (EX200) by Sander van Vugt, published on January 7, 2023. 🐧🐧🐧🐧
-
Linux From Scratch by Gerard Beekmans, published on August 1, 2021. 🐧🐧
-
ProLUG Big Book of Labs 🐧🐧🐧🐧🐧
-
Linux Kernel in a Nutshell by Greg Kroah-Hartman, published on December 22, 2006. 🐧🐧
-
Linux Kernel Development by Robert Love, published on October 12, 2010. 🐧🐧
Wikis
In my opinion, wikis are the best written resource. They often succinctly describe the nature of something and provide the most pertinent tools and their use cases. They are also written and maintained by the experts themselves. Examples are often provided as snippets that can be copied and pasted directly into a terminal.
-
ArchWiki 🐧🐧🐧🐧
-
Gentoo Wiki 🐧🐧🐧
-
Red Hat Customer Portal 🐧🐧🐧🐧🐧
Websites
There are websites out their specifically dedicated to learning Linux. Some are small readings that include a quizzes for example. Others are hands on labs similar to something like HackTheBox. Some are just there to help guide continuing education.
- OverTheWire(Bandit) 🐧🐧🐧🐧🐧
- Linux Journey 🐧🐧🐧🐧🐧
- DevOps Learning Roadmaps 🐧🐧🐧🐧🐧
- Kubernetes Learning Roadmaps 🐧🐧🐧🐧🐧
Youtube Channels
The issue with Youtube channels relating to Linux is that they are often not related to administration at all. They are mostly from the perspective of a desktop user, albeit a poweruser. Some may lean towards admin more than others, and some may focus entirely on scripting. But most focus on the industry and landscape in general. Regardless, these are the channels I've watched and enjoyed over the years, and have learned from greatly.
- Chris Titus Tech 🐧🐧🐧🐧🐧
- Brodie Robertson🐧🐧🐧
- DistoTube🐧🐧🐧🐧
- Linux Cast🐧🐧
Why mdbook? (2024-06-24)
There are a plethora of static site generation tools out there. One could essentially use any language or framework they desire. My requirements were a tool that is visually and functionally simple. I am not a front end developer, and I have no desire to be one. My first attempt was using a Jekyll template. While Jekyll and it's templates seem decent, they didn't offer the amount of editing capabilities I was looking for. Rather than being locked into a directory structure or toolbar formatting. I've also considered tools like Docusaurus because every website I've seen in it looks nice, but it seems I'd be directly editing source more than I'd like to. Eventually, since I have experience with writing in Markdown, especially with Gitbook and mdbook, I decided to use what I am most familiar with.
Why Markdown is Amazing
Markdown is probably the best text formatting "language" other than Latex. It is simple and portable. It's parsed and ultimately converted into HTML so it can exist essentially anywhere. And tools like Pandoc allow one to convert into into any document format one needs like pdf or even the dreaded troff for man pages. Aside form conversions numerous platforms support markdown natively like Github and the zettelkasten-astic note taking program Obsidian. One could write Markdown in one, and take it essentially anywhere. Notes, webpages, and documentation oh my. And if you need functionality the specific parser you're using doesn't support, many support overriding the defaults because, everything will ultimately be HTML and CSS. You could resort to editing anything you needed to by hand anyway.
mdbook As A Personal Site
The rust🦀 project, mdbook is definitely intended to be used for books, not personal sites. However the chapter bar is functionally a navbar,each, I can still link to other pages from within a page if I have to, and it naturally lends itself to a blog. Now the cons are that mdbook lacks a tagging system. Or any system for automatically maintaining blog posts. However, like I said, I'm not locked into any structure. I can invent any scheme my heart desires through the use of shell scripts and Github actions. I can design a system that assigns names according to a convention, fills in content for posts according to a template, orders the posts by date written, implement some kind os psuedo tagging system, etc. All that being said, I was always looking for something quick and dirt, where I can just market myself and flex my interests. This will do.
Links
- The Markdown Guide
- The Markdown Guide Book They Deserve The Money
- This site's repo
Notes
This chapter is where I will dump my notes. Anything is fair game. I use Obsidian to take notes, which uses Markdown, so I can simply copy/paste whatever I write to here.
Cheatsheet DUMP
Bash Cheatsheet
Command | Description |
---|---|
ls | List directory contents |
cd | Change directory |
pwd | Print working directory |
cp source destination | Copy files or directories |
mv source destination | Move/rename files or directories |
rm file | Remove files |
mkdir directory | Create a new directory |
rmdir directory | Remove an empty directory |
echo "text" | Print text to the terminal |
cat file | Concatenate and display file content |
less file | View file content one screen at a time |
grep "pattern" file | Search for a pattern in a file |
find path -name "pattern" | Find files and directories |
ps aux | Display currently running processes |
kill PID | Kill a process by PID |
top | Display and update sorted process list |
chmod permissions file | Change file permissions |
chown user:group file | Change file owner and group |
df -h | Display disk usage in human-readable format |
du -sh directory | Display directory size in human-readable format |
ln -s target link_name | Create a symbolic link |
alias name='command' | Create an alias for a command |
export VARIABLE=value | Set an environment variable |
history | Show command history |
tar -czf archive.tar.gz file | Create a compressed archive using gzip |
tar -xzf archive.tar.gz | Extract a compressed archive using gzip |
uptime | Show how long the system has been running |
whoami | Display the current username |
sudo command | Execute a command as the superuser |
ssh user@host | Connect to a remote host via SSH |
scp source user@host:destination | Copy files over SSH |
crontab -e | Edit cron jobs |
jobs | List background jobs |
bg job_id | Resume a background job |
fg job_id | Bring a background job to the foreground |
nohup command & | Run a command immune to hangups |
diff file1 file2 | Compare the contents of two files |
source file | Read and execute commands from a file in the current shell |
Redirection Cheatsheet
Command | Description |
---|---|
command > file | Redirect standard output (stdout) to a file (overwrite) |
command >> file | Redirect standard output (stdout) to a file (append) |
command 2> file | Redirect standard error (stderr) to a file (overwrite) |
command 2>> file | Redirect standard error (stderr) to a file (append) |
command &> file | Redirect both standard output (stdout) and standard error (stderr) to a file (overwrite) |
command &>> file | Redirect both standard output (stdout) and standard error (stderr) to a file (append) |
command < file | Redirect input from a file |
command <<< "string" | Redirect a string as input |
command1 \| command2 | Use the output of command1 as input for command2 (pipe) |
command1 \|& command2 | Pipe both stdout and stderr of command1 to command2 (bash 4.0+) |
command > /dev/null | Discard standard output (stdout) |
command 2> /dev/null | Discard standard error (stderr) |
command &> /dev/null | Discard both standard output (stdout) and standard error (stderr) |
command > file 2>&1 | Redirect stdout to a file and stderr to the same file |
command 2>&1 > file | Redirect stderr to the current stdout, then redirect stdout to a file |
command1 2>&1 \| command2 | Redirect both stdout and stderr of command1 to command2 |
command > file1 2> file2 | Redirect stdout to file1 and stderr to file2 |
command < file1 > file2 | Redirect input from file1 and output to file2 |
exec > file | Redirect all subsequent stdout in the script to a file |
exec 2> file | Redirect all subsequent stderr in the script to a file |
exec > /dev/tty | Restore stdout to the terminal |
exec 2> /dev/tty | Restore stderr to the terminal |
command1 \| tee file | Pipe output of command1 to file and also display it on the terminal |
command1 \| tee -a file | Pipe output of command1 to file (append) and also display it on the terminal |
command << EOF | Here document: redirect multiple lines of input to a command until EOF |
command <<- EOF | Here document with leading tab strip: redirect input until EOF |
command <&- | Close standard input (stdin) |
command >&- | Close standard output (stdout) |
command 2>&- | Close standard error (stderr) |
Important System Directories and Files
/etc
Directory/File | Description |
---|---|
/etc/passwd | User account information |
/etc/shadow | Secure user account information (passwords) |
/etc/group | Group account information |
/etc/gshadow | Secure group account information |
/etc/fstab | Filesystem mount table |
/etc/hosts | Static table lookup for hostnames |
/etc/resolv.conf | DNS server information |
/etc/hostname | System's hostname |
/etc/sysconfig/network | Basic network configuration |
/etc/sysconfig/network-scripts/ | Network scripts and configuration files |
/etc/crontab | Cron job schedule |
/etc/cron.d/ | Additional cron job schedules |
/etc/ssh/sshd_config | SSH server configuration |
/etc/sudoers | sudo configuration file |
/etc/systemd/system/ | Systemd unit files for services and targets |
/etc/selinux/config | SELinux configuration file |
/etc/yum.conf | YUM package manager configuration |
/etc/yum.repos.d/ | Repository configuration files for YUM |
/var
Directory/File | Description |
---|---|
/var/log/ | Directory containing log files |
/var/log/messages | General system log file |
/var/log/secure | Security and authentication log |
/var/log/audit/ | Audit log files |
/var/log/dmesg | Kernel ring buffer log |
/var/log/httpd/ | Apache HTTP server logs |
/var/spool/cron/ | User crontab files |
/var/spool/mail/ | User mail files |
/var/lib/ | Variable state information |
/var/lib/mysql/ | MySQL database files |
/var/lib/pgsql/ | PostgreSQL database files |
/var/www/html/ | Default directory for web server content |
/usr
Directory/File | Description |
---|---|
/usr/bin/ | User binaries |
/usr/sbin/ | System binaries |
/usr/local/ | Local software and custom scripts |
/usr/share/ | Shared data and resources for applications |
/usr/lib/ | Libraries for binaries in /usr/bin and /usr/sbin |
/usr/lib64/ | 64-bit libraries |
/usr/include/ | Header files for C programming |
/usr/src/ | Source code files |
/usr/share/doc/ | Documentation files for installed packages |
/usr/share/man/ | Manual pages |
/boot
Directory/File | Description |
---|---|
/boot/vmlinuz- | Linux kernel image |
/boot/initramfs- | Initial RAM filesystem |
/boot/grub2/ | GRUB 2 bootloader configuration and files |
/boot/efi/ | EFI boot files |
/proc
Directory/File | Description |
---|---|
/proc/cpuinfo | CPU information |
/proc/meminfo | Memory information |
/proc/version | Kernel version |
/proc/cmdline | Kernel command line |
/proc/devices | Device information |
/proc/diskstats | Disk statistics |
/proc/uptime | System uptime |
/proc/loadavg | System load average |
/proc/mounts | Mounted filesystems |
/proc/partitions | Partition information |
/proc/swaps | Swap space utilization |
/proc/sys/ | Kernel tunable parameters |
/proc/net/ | Network status information |
/sys
Directory/File | Description |
---|---|
/sys/class/ | Information about device classes |
/sys/block/ | Information about block devices |
/sys/fs/ | Filesystem information |
/sys/kernel/ | Kernel information and tunable parameters |
/sys/module/ | Information about loaded kernel modules |
/sys/devices/ | Information about devices |
/dev
Directory/File | Description |
---|---|
/dev/sda | First SCSI disk drive |
/dev/sdb | Second SCSI disk drive |
/dev/tty | Terminal devices |
/dev/null | Null device (discard output) |
/dev/random | Random number generator |
/dev/urandom | Non-blocking random number generator |
Vim Cheatsheet
Command | Description |
---|---|
i | Enter insert mode |
Esc | Exit insert mode |
:w | Save the file |
:q | Quit Vim |
:wq | Save and quit Vim |
:q! | Quit without saving |
:e filename | Open a file |
:n | Open the next file |
:p | Open the previous file |
/pattern | Search for a pattern |
n | Repeat the last search |
N | Repeat the last search in the opposite direction |
:s/old/new/g | Replace all occurrences of old with new in the current line |
:%s/old/new/g | Replace all occurrences of old with new in the file |
yy | Yank (copy) the current line |
p | Paste the yanked text |
dd | Delete the current line |
u | Undo the last action |
Ctrl-r | Redo the last undone action |
gg | Go to the first line of the file |
G | Go to the last line of the file |
0 | Go to the beginning of the line |
$ | Go to the end of the line |
dG | Delete from the current line to the end of the file |
v | Enter visual mode |
V | Enter visual line mode |
Ctrl-v | Enter visual block mode |
:help | Open Vim help |
:!command | Execute an external command |
:r !command | Read the output of a command into the current file |
:set number | Show line numbers |
:set nonumber | Hide line numbers |
:syntax on | Enable syntax highlighting |
:syntax off | Disable syntax highlighting |
tmux Cheatsheet
Command | Description |
---|---|
tmux new -s session_name | Create a new session named session_name |
tmux attach -t session_name | Attach to an existing session named session_name |
tmux list-sessions | List all sessions |
tmux kill-session -t session_name | Kill the session named session_name |
tmux new-window -n window_name | Create a new window named window_name |
tmux split-window -h | Split the current window horizontally |
tmux split-window -v | Split the current window vertically |
tmux select-pane -t :0 | Select pane 0 |
tmux resize-pane -L | Resize the current pane to the left |
tmux resize-pane -R | Resize the current pane to the right |
tmux resize-pane -U | Resize the current pane upwards |
tmux resize-pane -D | Resize the current pane downwards |
tmux kill-pane -t pane_number | Kill the pane with the specified pane_number |
tmux list-windows | List all windows in the current session |
tmux kill-window -t window_number | Kill the window with the specified window_number |
tmux rename-window new_name | Rename the current window to new_name |
tmux list-panes | List all panes in the current window |
tmux swap-pane -s pane1 -t pane2 | Swap the position of pane1 and pane2 |
tmux move-pane -t target_pane | Move the current pane to target_pane |
tmux set-option -g prefix C-a | Change the prefix key to Ctrl-a |
tmux bind-key [key] [command] | Bind a key to a tmux command |
tmux unbind-key [key] | Unbind a key from a tmux command |
tmux source-file ~/.tmux.conf | Reload the tmux configuration file |
tmux save-buffer ~/buffer.txt | Save the tmux paste buffer to a file |
tmux show-options -g | Show all global options |
tmux display-message "message" | Display a message in the status line |
tmux clock-mode | Enter clock mode in the current pane |
tmux list-keys | List all key bindings |
tmux capture-pane -S -100 | Capture the last 100 lines of the current pane |
tmux show-environment | Show the tmux environment variables |
tmux detach-client -t session_name | Detach the client from session_name |
tmux rename-session new_session_name | Rename the current session to new_session_name |
tmux rotate-window -U | Rotate the current window upwards |
tmux rotate-window -D | Rotate the current window downwards |
tmux list-clients | List all clients |
tmux select-layout even-horizontal | Arrange panes in an even horizontal layout |
tmux select-layout even-vertical | Arrange panes in an even vertical layout |
tmux select-layout tiled | Arrange panes in a tiled layout |
tmux Hotkeys Cheatsheet
Hotkey | Description |
---|---|
Ctrl-b | Default prefix key (can be changed) |
Ctrl-b ? | List all key bindings |
Ctrl-b d | Detach from the current session |
Ctrl-b c | Create a new window |
Ctrl-b , | Rename the current window |
Ctrl-b w | List all windows |
Ctrl-b n | Move to the next window |
Ctrl-b p | Move to the previous window |
Ctrl-b l | Move to the last (previously active) window |
Ctrl-b & | Kill the current window |
Ctrl-b % | Split the current pane vertically |
Ctrl-b " | Split the current pane horizontally |
Ctrl-b x | Kill the current pane |
Ctrl-b o | Switch to the next pane |
Ctrl-b ; | Switch to the last active pane |
Ctrl-b q | Display pane numbers |
Ctrl-b z | Toggle pane zoom |
Ctrl-b { | Swap pane with the previous pane |
Ctrl-b } | Swap pane with the next pane |
Ctrl-b Space | Toggle through layouts |
Ctrl-b Ctrl-o | Rotate panes |
Ctrl-b t | Show a clock |
Ctrl-b m | Mark the current pane |
Ctrl-b ' | Prompt for an index to switch to |
Ctrl-b ! | Break the current pane into a new window |
Ctrl-b s | List all sessions |
Ctrl-b : | Enter the tmux command prompt |
Ctrl-b [ | Enter copy mode (scrollback buffer) |
Ctrl-b ] | Paste the buffer |
Ctrl-b - | Split the window vertically |
Ctrl-b = | Split the window horizontally |
Ctrl-b f | Find window by text |
Ctrl-b r | Reload tmux configuration |
SSH Cheatsheet
Command | Description |
---|---|
ssh user@host | Connect to a remote host |
ssh -p port user@host | Connect to a remote host on a specific port |
ssh -i keyfile user@host | Connect using a specific private key file |
ssh-copy-id user@host | Copy your public key to a remote host |
ssh-keygen -t rsa -b 4096 | Generate a new RSA key pair |
ssh-add keyfile | Add a private key to the SSH agent |
ssh-agent bash | Start the SSH agent |
scp source user@host:destination | Copy files to a remote host |
scp user@host:source destination | Copy files from a remote host |
rsync -avz source user@host:destination | Sync files to a remote host |
rsync -avz user@host:source destination | Sync files from a remote host |
ssh user@host command | Execute a command on a remote host |
ssh -L local_port:remote_host:remote_port user@host | Create an SSH tunnel (local forwarding) |
ssh -R remote_port:local_host:local_port user@host | Create an SSH tunnel (remote forwarding) |
ssh -D local_port user@host | Create a dynamic SOCKS proxy |
~. | Terminate the SSH session |
~C | Open command line interface during an SSH session |
~& | Background the SSH session |
ssh -X user@host | Enable X11 forwarding |
ssh -v user@host | Verbose mode (debugging) |
ssh -vv user@host | More verbose mode |
ssh -q user@host | Quiet mode (suppress warnings) |
ssh -f user@host command | Run SSH in the background |
ssh -N user@host | Do not execute a remote command |
ssh -o option=value user@host | Set an option for the SSH connection |
ssh -c cipher user@host | Specify the cipher to use |
ssh-keyscan host | Retrieve SSH public keys from a host |
sshfs user@host:remote_dir local_dir | Mount a remote directory over SSH |
Git Cheatsheet
Command | Description |
---|---|
git init | Initialize a new Git repository |
git clone repository_url | Clone an existing repository |
git status | Show the status of the working directory |
git add file | Stage changes for commit |
git commit -m "message" | Commit staged changes with a message |
git push origin branch | Push commits to the remote repository |
git pull origin branch | Pull updates from the remote repository |
git fetch | Fetch changes from the remote repository |
git merge branch | Merge a branch into the current branch |
git branch | List all branches |
git branch branch_name | Create a new branch |
git checkout branch_name | Switch to a different branch |
git checkout -b branch_name | Create and switch to a new branch |
git log | Show commit history |
git log --oneline | Show commit history in a condensed form |
git diff | Show changes between commits, commit and working tree, etc |
git reset --hard commit | Reset the working directory and index to a specific commit |
git revert commit | Revert a specific commit |
git stash | Stash changes in a dirty working directory |
git stash pop | Apply stashed changes |
git remote -v | Show remote repositories |
git remote add name url | Add a remote repository |
git tag | List tags |
git tag tag_name | Create a new tag |
git rm file | Remove a file from the working directory and index |
git mv old_name new_name | Rename or move a file |
git blame file | Show what revision and author last modified each line |
git show commit | Show various types of objects |
git config --global user.name "name" | Set the global username |
git config --global user.email "email" | Set the global email |
git rebase branch | Reapply commits on top of another base tip |
git cherry-pick commit | Apply changes from a specific commit |
git bisect start | Start binary search to find the commit that introduced a bug |
git archive --format zip --output file.zip HEAD | Create a zip archive of the current branch |
git gc | Cleanup unnecessary files and optimize the local repository |
Systemd Cheatsheet
Command | Description |
---|---|
systemctl start service | Start a service |
systemctl stop service | Stop a service |
systemctl restart service | Restart a service |
systemctl reload service | Reload a service's configuration |
systemctl enable service | Enable a service to start on boot |
systemctl disable service | Disable a service from starting on boot |
systemctl status service | Show the status of a service |
systemctl is-active service | Check if a service is active |
systemctl is-enabled service | Check if a service is enabled |
systemctl list-units | List all loaded units |
systemctl list-unit-files | List installed unit files |
systemctl daemon-reload | Reload systemd manager configuration |
journalctl -u service | View logs for a specific service |
journalctl -f | Follow the system journal |
systemctl mask service | Mask a service to prevent it from being started |
systemctl unmask service | Unmask a service |
systemctl set-default target | Set the default target (e.g., multi-user, graphical) |
systemctl get-default | Get the current default target |
systemctl isolate target | Change to a different target |
systemctl show service | Show properties of a unit |
systemctl cat service | Show the unit file of a service |
systemctl edit service | Edit a unit file (creates an override file) |
systemctl reset-failed service | Reset the failed state of a unit |
systemctl poweroff | Power off the system |
systemctl reboot | Reboot the system |
systemctl suspend | Suspend the system |
systemctl hibernate | Hibernate the system |
systemctl hybrid-sleep | Hibernate and suspend the system |
systemd-analyze blame | Show the time taken to initialize each service |
systemd-analyze critical-chain | Show the critical chain of units |
systemd-analyze plot > plot.svg | Generate a graphical representation of the boot process |
timedatectl | Control the system time and date |
hostnamectl | Control the system hostname |
localectl | Control the system locale |
loginctl | Control the system logind |
Docker Cheatsheet
Command | Description |
---|---|
docker ps | List running containers |
docker ps -a | List all containers |
docker images | List all images |
docker pull image | Pull an image from a registry |
docker run image | Run a container from an image |
docker run -d image | Run a container in detached mode |
docker run -it image | Run a container in interactive mode |
docker stop container | Stop a running container |
docker start container | Start a stopped container |
docker restart container | Restart a container |
docker rm container | Remove a container |
docker rmi image | Remove an image |
docker exec -it container bash | Execute a command in a running container |
docker logs container | View logs of a container |
docker build -t image . | Build an image from a Dockerfile |
docker-compose up | Start containers defined in docker-compose.yml |
docker-compose down | Stop and remove containers defined in docker-compose.yml |
docker network ls | List all networks |
docker network create network | Create a new network |
docker volume ls | List all volumes |
docker volume create volume | Create a new volume |
docker inspect container | Display detailed information on a container |
docker tag source_image target_image | Tag an image |
docker push image | Push an image to a registry |
docker pull image | Pull an image from a registry |
docker save -o image.tar image | Save an image to a tar file |
docker load -i image.tar | Load an image from a tar file |
docker stats container | Display resource usage statistics of a container |
docker top container | Display the running processes of a container |
docker cp source_path container:dest_path | Copy files/folders between a container and the local filesystem |
docker update --cpus=2 container | Update resource limits of a container |
docker history image | Show the history of an image |
docker diff container | Inspect changes to files or directories on a container’s filesystem |
docker export container -o container.tar | Export a container’s filesystem to a tar archive |
docker import file.tar | Import a tarball to create a filesystem image |
Kubernetes Cheatsheet
Command | Description |
---|---|
kubectl get nodes | List all nodes |
kubectl get pods | List all pods in the default namespace |
kubectl get pods -n namespace | List all pods in a specific namespace |
kubectl get services | List all services in the default namespace |
kubectl describe pod pod_name | Show detailed information about a specific pod |
kubectl logs pod_name | Print the logs of a specific pod |
kubectl exec -it pod_name -- bash | Execute a command in a running pod |
kubectl apply -f file.yaml | Apply a configuration file |
kubectl create -f file.yaml | Create resources from a configuration file |
kubectl delete -f file.yaml | Delete resources defined in a configuration file |
kubectl scale --replicas=3 deployment/app | Scale a deployment to 3 replicas |
kubectl rollout status deployment/app | Check the rollout status of a deployment |
kubectl rollout undo deployment/app | Roll back a deployment |
kubectl expose deployment app --type=LoadBalancer --port=80 | Expose a deployment as a service |
kubectl port-forward pod_name 8080:80 | Forward a local port to a port on a pod |
kubectl get namespaces | List all namespaces |
kubectl create namespace namespace | Create a new namespace |
kubectl config set-context --current --namespace=namespace | Set the current namespace |
kubectl get events | List all events |
kubectl get secrets | List all secrets in the default namespace |
kubectl get configmaps | List all configmaps in the default namespace |
kubectl describe node node_name | Show detailed information about a specific node |
kubectl get deployment | List all deployments in the default namespace |
kubectl describe service service_name | Show detailed information about a specific service |
kubectl set image deployment/app app=nginx:1.16 | Update the image of a deployment |
kubectl edit deployment app | Edit a resource on the server |
kubectl delete pod pod_name | Delete a specific pod |
kubectl delete service service_name | Delete a specific service |
kubectl apply -f https://k8s.io/examples/application/deployment.yaml | Apply a deployment from a URL |
kubectl get pvc | List all persistent volume claims |
kubectl get pv | List all persistent volumes |
kubectl cordon node_name | Mark a node as unschedulable |
kubectl drain node_name | Drain a node by evicting all pods |
kubectl taint nodes node_name key=value:NoSchedule | Taint a node to prevent scheduling |
Ansible Cheatsheet
Command | Description |
---|---|
ansible all -m ping | Ping all hosts |
ansible-playbook playbook.yaml | Run a playbook |
ansible all -a "command" | Run a command on all hosts |
ansible all -m setup | Gather facts from all hosts |
ansible all -m yum -a "name=package state=present" | Install a package using yum |
ansible all -m copy -a "src=/local/path dest=/remote/path" | Copy files to remote hosts |
ansible-vault create secret.yaml | Create an encrypted file |
ansible-vault edit secret.yaml | Edit an encrypted file |
ansible-vault decrypt secret.yaml | Decrypt an encrypted file |
ansible-playbook --ask-vault-password playbook.yaml | Run a playbook with vault password |
ansible-galaxy install role_name | Install a role from Ansible Galaxy |
ansible-galaxy list | List installed roles |
ansible-doc -l | List all modules |
ansible-doc module_name | Show documentation for a specific module |
ansible-playbook -i inventory playbook.yaml | Run a playbook with a specific inventory |
ansible all -m service -a "name=service state=started" | Manage services on remote hosts |
ansible all -m file -a "path=/remote/path state=directory" | Ensure a directory exists on remote hosts |
ansible all -m user -a "name=username state=present" | Ensure a user exists on remote hosts |
ansible-playbook --check playbook.yaml | Run a playbook in check mode |
ansible-playbook --diff playbook.yaml | Show changes made by the playbook |
ansible-playbook -e "variable=value" playbook.yaml | Pass extra variables to the playbook |
ansible-playbook --tags "tag_name" playbook.yaml | Run playbook tasks with specific tags |
ansible-inventory --list -i inventory | List inventory hosts |
ansible-inventory --graph -i inventory | Show inventory graph |
ansible-config dump | Dump the Ansible configuration |
ansible-config list | List all Ansible configuration options |
ansible-pull -U repo_url | Pull and run a playbook from a remote Git repository |
ansible-playbook --limit "host_pattern" playbook.yaml | Limit playbook run to specific hosts |
ansible-playbook --start-at-task "task_name" playbook.yaml | Start playbook run at a specific task |
ansible-galaxy init role_name | Initialize a new role |
iptables Cheatsheet
Command | Description |
---|---|
iptables -L | List all rules |
iptables -A chain -j target | Append a rule to a chain |
iptables -I chain rule_num -j target | Insert a rule at a specific position in a chain |
iptables -D chain rule_num | Delete a rule from a chain by number |
iptables -F | Flush all rules |
iptables -X | Delete all user-defined chains |
iptables -P chain target | Set the default policy for a chain |
iptables -N chain | Create a new user-defined chain |
iptables -A INPUT -p tcp --dport port -j ACCEPT | Allow incoming TCP traffic on a specific port |
iptables -A OUTPUT -p tcp --sport port -j ACCEPT | Allow outgoing TCP traffic on a specific port |
iptables -A FORWARD -i interface -j ACCEPT | Allow forwarding from a specific interface |
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT | Allow established and related connections |
iptables -A INPUT -s ip_address -j DROP | Block traffic from a specific IP address |
iptables -A INPUT -p icmp -j ACCEPT | Allow ICMP (ping) traffic |
iptables -A INPUT -p udp --dport port -j ACCEPT | Allow incoming UDP traffic on a specific port |
iptables -A INPUT -p tcp --dport 22 -j ACCEPT | Allow SSH traffic |
iptables -A INPUT -j REJECT | Reject all other incoming traffic |
iptables-save > /etc/iptables/rules.v4 | Save the current rules to a file |
iptables-restore < /etc/iptables/rules.v4 | Restore rules from a file |
nftables Cheatsheet
Command | Description |
---|---|
nft list ruleset | List all rulesets |
nft add table inet filter | Create a new table |
nft add chain inet filter input { type filter hook input priority 0; } | Create a new chain |
nft add rule inet filter input ip saddr ip_address drop | Drop traffic from a specific IP address |
nft add rule inet filter input tcp dport port accept | Allow incoming TCP traffic on a specific port |
nft add rule inet filter input udp dport port accept | Allow incoming UDP traffic on a specific port |
nft add rule inet filter input icmp type echo-request accept | Allow ICMP (ping) traffic |
nft add rule inet filter input ct state established,related accept | Allow established and related connections |
nft add rule inet filter input iifname interface accept | Allow traffic from a specific interface |
nft add rule inet filter output tcp sport port accept | Allow outgoing TCP traffic on a specific port |
nft add rule inet filter forward iifname interface oifname interface accept | Allow forwarding between interfaces |
nft delete rule inet filter input handle handle_number | Delete a specific rule by handle number |
nft delete chain inet filter input | Delete a chain |
nft delete table inet filter | Delete a table |
nft -f /etc/nftables.conf | Load rules from a configuration file |
nft save > /etc/nftables.conf | Save the current ruleset to a file |
nft -i /etc/nftables.conf | Load rules from a file interactively |
nft monitor | Monitor changes to the ruleset |
nft add set inet filter blacklist { type ipv4_addr; } | Create an IP set |
nft add element inet filter blacklist { ip_address } | Add an IP address to the set |
nft delete element inet filter blacklist { ip_address } | Remove an IP address from the set |
nft add rule inet filter input ip saddr @blacklist drop | Drop traffic from IP addresses in the set |
Cron Cheatsheet
Command | Description |
---|---|
crontab -e | Edit the current user's crontab |
crontab -l | List the current user's crontab |
crontab -r | Remove the current user's crontab |
crontab -u user -e | Edit another user's crontab |
crontab -u user -l | List another user's crontab |
crontab -u user -r | Remove another user's crontab |
@reboot command | Run once at startup |
@yearly command | Run once a year (0 0 1 1 *) |
@annually command | Run once a year (0 0 1 1 *) |
@monthly command | Run once a month (0 0 1 * *) |
@weekly command | Run once a week (0 0 * * 0) |
@daily command | Run once a day (0 0 * * *) |
@midnight command | Run once a day (0 0 * * *) |
@hourly command | Run once an hour (0 * * * *) |
* * * * * command | Run every minute |
*/5 * * * * command | Run every 5 minutes |
0 * * * * command | Run at the beginning of every hour |
0 0 * * * command | Run at midnight every day |
0 0 1 * * command | Run at midnight on the first of every month |
0 0 1 1 * command | Run at midnight on January 1st |
0 9 * * 1-5 command | Run at 9 AM on weekdays |
0 22 * * 1-5 command | Run at 10 PM on weekdays |
MAILTO="email@example.com" | Send cron job output to the specified email address |
0 0 * * * /path/to/script.sh | Run a script daily at midnight |
0 5 * * * /path/to/backup.sh | Run a backup script daily at 5 AM |
*/10 * * * * /path/to/check.sh | Run a script every 10 minutes |
0 0 * * 0 /path/to/weekly.sh | Run a script weekly on Sundays at midnight |
0 0 1 * * /path/to/monthly.sh | Run a script monthly on the first day at midnight |
0 0 1 1 * /path/to/yearly.sh | Run a script yearly on January 1st at midnight |
awk Cheatsheet
Command | Description |
---|---|
awk '{print}' file | Print all lines in a file |
awk '{print $1}' file | Print the first field of each line |
awk '{print $1, $2}' file | Print the first and second fields of each line |
awk '/pattern/ {print}' file | Print lines matching a pattern |
awk 'NR==line_number' file | Print a specific line number |
awk 'NR==start, NR==end' file | Print a range of lines |
awk '{sum += $1} END {print sum}' file | Sum the first field of all lines |
awk 'BEGIN {print "Header"} {print} END {print "Footer"}' file | Add a header and footer to the output |
awk -F, '{print $1}' file | Specify a field separator (comma in this case) |
awk '{if ($1 > 10) print}' file | Print lines where the first field is greater than 10 |
awk '{gsub(/old/, "new"); print}' file | Replace all occurrences of "old" with "new" |
awk '{print NR, $0}' file | Print line numbers with output |
awk '{print length($0)}' file | Print the length of each line |
awk '{print $NF}' file | Print the last field of each line |
awk '{print $(NF-1)}' file | Print the second to last field of each line |
awk '{count[$1]++} END {for (word in count) print word, count[word]}' file | Count occurrences of each word in the first field |
awk 'NR % 2 == 0 {print}' file | Print every second line |
awk '{print toupper($0)}' file | Convert text to uppercase |
awk '{print tolower($0)}' file | Convert text to lowercase |
awk 'BEGIN {FS=":"; OFS="-"} {print $1, $2}' file | Change input and output field separators |
sed Cheatsheet
Command | Description |
---|---|
sed 's/old/new/' file | Replace the first occurrence of "old" with "new" |
sed 's/old/new/g' file | Replace all occurrences of "old" with "new" |
sed -i 's/old/new/g' file | Replace all occurrences in the file (in-place) |
sed 's/old/new/2' file | Replace the second occurrence of "old" with "new" |
sed 's/old/new/gi' file | Replace all occurrences, case insensitive |
sed '1,3s/old/new/' file | Replace occurrences between lines 1 and 3 |
sed '3s/old/new/' file | Replace occurrences on the third line |
sed '/pattern/s/old/new/' file | Replace occurrences on lines matching a pattern |
sed 's/^/prefix/' file | Add a prefix to each line |
sed 's/$/suffix/' file | Add a suffix to each line |
sed '/pattern/d' file | Delete lines matching a pattern |
sed '3d' file | Delete the third line |
sed '1,3d' file | Delete lines 1 through 3 |
sed '$d' file | Delete the last line |
sed -n '2,4p' file | Print lines 2 through 4 |
sed -n '/pattern/p' file | Print lines matching a pattern |
sed -e 'command1' -e 'command2' file | Apply multiple commands |
sed 's/.*\(pattern\).*/\1/' file | Extract and print a pattern |
sed 'y/abc/ABC/' file | Translate characters |
sed -i.bak 's/old/new/g' file | Replace all occurrences and create a backup file |
sed '10q' file | Quit after 10 lines |
sed 's/\([0-9]\{3\}\)-\([0-9]\{2\}\)-\([0-9]\{4\}\)/\1\2\3/' file | Remove dashes from SSN format |
sed 's/ *$//' file | Remove trailing whitespace |
sed 's/[^[:alnum:]]//g' file | Remove all non-alphanumeric characters |
grep Cheatsheet
Command | Description |
---|---|
grep "pattern" file | Search for a pattern in a file |
grep -i "pattern" file | Case-insensitive search |
grep -v "pattern" file | Invert match, show lines that do not match |
grep -r "pattern" directory | Recursively search in a directory |
grep -l "pattern" file | Show file names containing the pattern |
grep -c "pattern" file | Count occurrences of the pattern |
grep -n "pattern" file | Show line numbers of matches |
grep -w "pattern" file | Match whole words only |
grep -A num "pattern" file | Show num lines after match |
grep -B num "pattern" file | Show num lines before match |
grep -C num "pattern" file | Show num lines around match |
grep -e "pattern1" -e "pattern2" file | Search for multiple patterns |
grep --exclude=*.txt "pattern" * | Exclude files matching a pattern |
grep --include=*.txt "pattern" * | Include only files matching a pattern |
grep -f patternfile file | Use patterns from a file |
grep -q "pattern" file | Quiet mode, return 0 if pattern is found |
grep --color=auto "pattern" file | Highlight matches in color |
grep -o "pattern" file | Print only matching parts of a line |
grep --line-buffered "pattern" file | Use line buffering (useful for streaming) |
find Cheatsheet
Command | Description |
---|---|
find . -name "filename" | Find files by name |
find . -iname "filename" | Find files by name (case-insensitive) |
find . -type d -name "dirname" | Find directories by name |
find . -type f -name "filename" | Find regular files by name |
find . -size +1M | Find files larger than 1MB |
find . -size -1M | Find files smaller than 1MB |
find . -mtime -1 | Find files modified in the last day |
find . -atime -1 | Find files accessed in the last day |
find . -user username | Find files owned by a specific user |
find . -group groupname | Find files owned by a specific group |
find . -perm 644 | Find files with specific permissions |
find . -exec command {} \; | Execute a command on each file found |
find . -exec rm {} \; | Delete all files found |
find . -print | Print the full file names |
find . -maxdepth 1 -name "filename" | Find files in the current directory only |
find . -mindepth 2 -name "filename" | Find files not in the top-level directory |
find . -type l | Find symbolic links |
find . -type l -xtype f | Find broken symbolic links |
find . -empty | Find empty files and directories |
find . -newer file | Find files newer than a specific file |
find . -name "*.txt" -or -name "*.md" | Find files matching multiple patterns |
find . -path "./dir/*" -prune -o -name "*.txt" -print | Exclude a directory and find files |
find . -ctime +10 | Find files changed more than 10 days ago |
find . -cmin -60 | Find files changed in the last 60 minutes |
find / -type f 2>/dev/null | Find all files on the system, ignoring permission errors |
Screen Cheatsheet
Command | Description |
---|---|
screen | Start a new screen session |
screen -S session_name | Start a new session named session_name |
screen -ls | List all screen sessions |
screen -r session_name | Resume a detached session named session_name |
screen -d -r session_name | Detach and reattach to session_name |
screen -X -S session_name quit | Kill a session named session_name |
Ctrl-a d | Detach from the current session |
Ctrl-a c | Create a new window |
Ctrl-a " | List all windows |
Ctrl-a 0 | Switch to window 0 |
Ctrl-a A | Rename the current window |
Ctrl-a n | Switch to the next window |
Ctrl-a p | Switch to the previous window |
Ctrl-a k | Kill the current window |
Ctrl-a Ctrl-a | Switch between the current and previous window |
Ctrl-a S | Split the screen horizontally |
Ctrl-a \| | Split the screen vertically |
Ctrl-a tab | Switch to the next region |
Ctrl-a X | Close the current region |
Ctrl-a Q | Close all regions except the current one |
Ctrl-a space | Toggle between layouts |
Ctrl-a :resize | Resize the current region |
Ctrl-a :fit | Fit the current region to the screen |
Ctrl-a [ | Enter copy mode |
Ctrl-a ] | Paste copied text |
Ctrl-a ? | Show key bindings help |
Ctrl-a H | Begin/end logging of the session |
Ctrl-a _ | Lock the terminal |
Ctrl-a m | Monitor the current window for activity |
Ctrl-a M | Monitor the current window for silence |
Ctrl-a D D | Detach and logout from the session |
rsync Cheatsheet
Command | Description |
---|---|
rsync -av source destination | Archive mode, verbose |
rsync -avz source destination | Archive mode, compress during transfer |
rsync -av --progress source destination | Show progress during transfer |
rsync -av --delete source destination | Delete extraneous files from destination |
rsync -av --exclude='pattern' source destination | Exclude files matching a pattern |
rsync -av --include='pattern' source destination | Include only files matching a pattern |
rsync -av -e ssh source user@host:destination | Use SSH as the transport |
rsync -av --dry-run source destination | Perform a trial run with no changes made |
rsync -av --partial source destination | Keep partially transferred files |
rsync -av --bwlimit=KBps source destination | Limit bandwidth during transfer |
rsync -av --size-only source destination | Skip files that match in size |
rsync -av --checksum source destination | Skip files that match in checksum |
rsync -av --times source destination | Preserve modification times |
rsync -av --perms source destination | Preserve permissions |
rsync -av --owner source destination | Preserve owner |
rsync -av --group source destination | Preserve group |
rsync -av --links source destination | Copy symlinks as symlinks |
rsync -av --hard-links source destination | Preserve hard links |
rsync -av --copy-links source destination | Copy symlinks as files |
rsync -av --copy-dirlinks source destination | Transform symlinks to directories into real dirs |
rsync -av --no-links source destination | Skip copying symlinks |
rsync -av --safe-links source destination | Ignore symlinks that point outside source tree |
rsync -av --delete-excluded source destination | Delete excluded files from destination |
rsync -av --max-size=SIZE source destination | Limit maximum size of files to transfer |
rsync -av --min-size=SIZE source destination | Limit minimum size of files to transfer |
rsync -av --backup source destination | Backup files that are replaced |
rsync -av --backup-dir=DIR source destination | Backup files into a specific directory |
rsync -av --suffix=SUFFIX source destination | Define suffix for backup files |
rsync -av --inplace source destination | Update destination files in place |
rsync -av --append source destination | Append data onto shorter files |
rsync -av --append-verify source destination | Append and verify full file content |
rsync -av --ignore-existing source destination | Skip updating files that already exist |
rsync -av --remove-source-files source destination | Remove source files after transfer |
tar Cheatsheet
Command | Description |
---|---|
tar -cvf archive.tar file_or_directory | Create a tar archive |
tar -xvf archive.tar | Extract a tar archive |
tar -tvf archive.tar | List contents of a tar archive |
tar -cvzf archive.tar.gz file_or_directory | Create a gzip-compressed tar archive |
tar -xvzf archive.tar.gz | Extract a gzip-compressed tar archive |
tar -cvjf archive.tar.bz2 file_or_directory | Create a bzip2-compressed tar archive |
tar -xvjf archive.tar.bz2 | Extract a bzip2-compressed tar archive |
tar -cvJf archive.tar.xz file_or_directory | Create a xz-compressed tar archive |
tar -xvJf archive.tar.xz | Extract a xz-compressed tar archive |
tar -cvf - file_or_directory \| ssh user@host "tar -xvf - -C /destination" | Copy files over SSH |
tar -rf archive.tar file | Append files to an existing tar archive |
tar -uf archive.tar file | Update files in an existing tar archive |
tar -cvf archive.tar --exclude="*.txt" file_or_directory | Create tar archive excluding certain files |
tar -cvf archive.tar --exclude-vcs file_or_directory | Create tar archive excluding version control files |
tar --delete -f archive.tar file | Delete files from a tar archive |
tar -cvf archive.tar -T filelist.txt | Create tar archive from a list of files |
tar -xvf archive.tar -C /destination | Extract tar archive to a specific directory |
tar --strip-components=number -xvf archive.tar | Extract tar archive, removing a number of leading components |
tar --transform='s/old/new/' -cvf archive.tar file_or_directory | Create tar archive with transformed file names |
tar -xzvf archive.tar.gz --wildcards '*.txt' | Extract specific files from a compressed tar archive |
gzip Cheatsheet
Command | Description |
---|---|
gzip file | Compress a file |
gzip -d file.gz | Decompress a file |
gzip -k file | Compress a file, keeping the original |
gzip -r directory | Recursively compress files in a directory |
gzip -l file.gz | List compressed file details |
gzip -t file.gz | Test compressed file integrity |
gzip -v file | Compress a file with verbose output |
gzip -1 file | Compress a file with fastest speed |
gzip -9 file | Compress a file with best compression |
zcat file.gz | View contents of a compressed file |
zgrep "pattern" file.gz | Search for a pattern in a compressed file |
zless file.gz | View a compressed file with less |
zcmp file1.gz file2.gz | Compare compressed files |
zdiff file1.gz file2.gz | Show differences between compressed files |
bzip2 Cheatsheet
Command | Description |
---|---|
bzip2 file | Compress a file |
bzip2 -d file.bz2 | Decompress a file |
bzip2 -k file | Compress a file, keeping the original |
bzip2 -z file | Compress a file |
bzip2 -t file.bz2 | Test compressed file integrity |
bzip2 -c file > file.bz2 | Compress a file to standard output |
bzip2 -f file | Force compression or decompression |
bzip2 -v file | Compress a file with verbose output |
bzip2 -1 file | Compress a file with fastest speed |
bzip2 -9 file | Compress a file with best compression |
bzcat file.bz2 | View contents of a compressed file |
bzgrep "pattern" file.bz2 | Search for a pattern in a compressed file |
bzless file.bz2 | View a compressed file with less |
bzcmp file1.bz2 file2.bz2 | Compare compressed files |
bzdiff file1.bz2 file2.bz2 | Show differences between compressed files |
curl Cheatsheet
Command | Description |
---|---|
curl url | Fetch the content of a URL |
curl -o file url | Save the content to a file |
curl -O url | Save the content to a file with the same name |
curl -L url | Follow redirects |
curl -I url | Fetch headers only |
curl -d "data" url | Send data with a POST request |
curl -X POST url | Send a POST request |
curl -X PUT url | Send a PUT request |
curl -X DELETE url | Send a DELETE request |
curl -H "Header: value" url | Send a custom header |
curl -u user:password url | Send basic authentication |
curl -F "name=value" url | Send a multipart form data |
curl -k url | Allow insecure SSL connections |
curl --cert certfile url | Send a client certificate |
curl -b "name=value" url | Send cookies |
curl -c cookiefile url | Save cookies to a file |
curl --limit-rate 100k url | Limit the transfer rate |
curl --compressed url | Request a compressed response |
curl --retry num url | Retry a request on failure |
curl --silent url | Silent mode (suppress output) |
curl --progress-bar url | Display a progress bar |
curl --http2 url | Use HTTP/2 protocol |
curl --interface interface url | Use a specific network interface |
curl --ipv4 url | Use IPv4 only |
curl --ipv6 url | Use IPv6 only |
curl --location-trusted url | Follow redirects and send authentication to other hosts |
curl --data-urlencode "name=value" url | URL encode data |
curl --max-time seconds url | Set a maximum time for the request |
curl --connect-timeout seconds url | Set a maximum time for the connection |
curl --proxy proxy_url url | Use a proxy server |
wget Cheatsheet
Command | Description |
---|---|
wget url | Download a file |
wget -O file url | Save the download with a specific name |
wget -P /path url | Save the download to a specific directory |
wget -c url | Continue a partially downloaded file |
wget -b url | Download in the background |
wget -i file | Download URLs listed in a file |
wget -r url | Download recursively |
wget -l depth url | Set the download depth |
wget -k url | Convert links to be suitable for local viewing |
wget -m url | Mirror a website |
wget -p url | Download all necessary files to display a webpage |
wget --limit-rate=100k url | Limit the download speed |
wget --user=user --password=password url | Download with basic authentication |
wget --header="Header: value" url | Send a custom header |
wget --no-check-certificate url | Ignore SSL certificate errors |
wget --quiet url | Quiet mode (no output) |
wget --show-progress url | Show a progress bar |
wget --spider url | Check if a URL exists |
wget --no-clobber url | Do not overwrite existing files |
wget --timestamping url | Download only if the remote file is newer than the local file |
wget --directory-prefix=prefix url | Save files to a specific directory |
wget --tries=num url | Set the number of retries |
wget --wait=seconds url | Wait between downloads |
wget --random-wait url | Wait a random amount of time between downloads |
wget --delete-after url | Delete files after downloading |
wget --mirror url | Mirror a website |
wget --recursive url | Download files recursively |
wget --level=depth url | Set the recursion depth |
wget --user-agent="User-Agent" url | Set the user agent |
MySQL/MariaDB Cheatsheet
Command | Description |
---|---|
mysql -u user -p | Connect to the MySQL server |
CREATE DATABASE dbname; | Create a new database |
DROP DATABASE dbname; | Delete a database |
USE dbname; | Select a database |
SHOW DATABASES; | List all databases |
SHOW TABLES; | List all tables in the selected database |
DESCRIBE tablename; | Show table structure |
CREATE TABLE tablename (columns); | Create a new table |
DROP TABLE tablename; | Delete a table |
INSERT INTO tablename (columns) VALUES (values); | Insert data into a table |
SELECT * FROM tablename; | Retrieve all data from a table |
UPDATE tablename SET column=value WHERE condition; | Update data in a table |
DELETE FROM tablename WHERE condition; | Delete data from a table |
GRANT ALL PRIVILEGES ON dbname.* TO 'user'@'host' IDENTIFIED BY 'password'; | Grant privileges to a user |
FLUSH PRIVILEGES; | Reload privileges |
SHOW GRANTS FOR 'user'@'host'; | Show granted privileges |
REVOKE ALL PRIVILEGES ON dbname.* FROM 'user'@'host'; | Revoke privileges from a user |
CREATE USER 'user'@'host' IDENTIFIED BY 'password'; | Create a new user |
DROP USER 'user'@'host'; | Delete a user |
SHOW PROCESSLIST; | Show running processes |
EXIT; | Exit the MySQL shell |
mysqldump -u user -p dbname > backup.sql | Backup a database |
mysql -u user -p dbname < backup.sql | Restore a database |
SHOW STATUS; | Show server status |
SHOW VARIABLES; | Show server variables |
SHOW INDEX FROM tablename; | Show indexes in a table |
SHOW CREATE TABLE tablename; | Show the CREATE TABLE statement for a table |
ALTER TABLE tablename ADD columnname datatype; | Add a column to a table |
ALTER TABLE tablename DROP columnname; | Drop a column from a table |
ALTER TABLE tablename MODIFY columnname datatype; | Modify a column in a table |
ALTER TABLE tablename RENAME TO newtablename; | Rename a table |
CREATE INDEX indexname ON tablename (columns); | Create an index on a table |
DROP INDEX indexname ON tablename; | Drop an index from a table |
SET GLOBAL max_connections = value; | Set a global variable |
SHOW ENGINE INNODB STATUS; | Show InnoDB status |
PostgreSQL Cheatsheet
Command | Description |
---|---|
psql -U user -d dbname | Connect to the PostgreSQL server |
CREATE DATABASE dbname; | Create a new database |
DROP DATABASE dbname; | Delete a database |
\c dbname | Connect to a database |
\l | List all databases |
\dt | List all tables in the connected database |
\d tablename | Show table structure |
CREATE TABLE tablename (columns); | Create a new table |
DROP TABLE tablename; | Delete a table |
INSERT INTO tablename (columns) VALUES (values); | Insert data into a table |
SELECT * FROM tablename; | Retrieve all data from a table |
UPDATE tablename SET column=value WHERE condition; | Update data in a table |
DELETE FROM tablename WHERE condition; | Delete data from a table |
GRANT ALL PRIVILEGES ON DATABASE dbname TO user; | Grant privileges to a user |
REVOKE ALL PRIVILEGES ON DATABASE dbname FROM user; | Revoke privileges from a user |
CREATE USER username WITH PASSWORD 'password'; | Create a new user |
DROP USER username; | Delete a user |
\q | Exit the PostgreSQL shell |
pg_dump -U user -d dbname -f backup.sql | Backup a database |
psql -U user -d dbname -f backup.sql | Restore a database |
\conninfo | Show connection information |
\du | List all roles |
\di | List all indexes |
\df | List all functions |
\dn | List all schemas |
\dp | List table, view, and sequence access privileges |
ALTER TABLE tablename ADD columnname datatype; | Add a column to a table |
ALTER TABLE tablename DROP columnname; | Drop a column from a table |
ALTER TABLE tablename ALTER COLUMN columnname TYPE datatype; | Modify a column in a table |
ALTER TABLE tablename RENAME TO newtablename; | Rename a table |
CREATE INDEX indexname ON tablename (columns); | Create an index on a table |
DROP INDEX indexname; | Drop an index |
VACUUM | Clean up and optimize the database |
VACUUM FULL | Clean up and optimize the database (full) |
ANALYZE | Collect statistics about the database |
EXPLAIN SELECT * FROM tablename; | Show the execution plan for a query |
SET search_path TO schema; | Set the search path to a specific schema |
Nginx Cheatsheet
Command | Description |
---|---|
sudo systemctl start nginx | Start Nginx |
sudo systemctl stop nginx | Stop Nginx |
sudo systemctl restart nginx | Restart Nginx |
sudo systemctl reload nginx | Reload Nginx configuration |
sudo systemctl enable nginx | Enable Nginx to start on boot |
sudo systemctl disable nginx | Disable Nginx from starting on boot |
nginx -t | Test Nginx configuration |
nginx -s reload | Reload Nginx configuration |
nginx -s reopen | Reopen log files |
nginx -s stop | Stop Nginx |
nginx -s quit | Gracefully stop Nginx |
/etc/nginx/nginx.conf | Main Nginx configuration file |
/etc/nginx/sites-available/ | Directory for available site configurations |
/etc/nginx/sites-enabled/ | Directory for enabled site configurations |
sudo ln -s /etc/nginx/sites-available/site /etc/nginx/sites-enabled/ | Enable a site configuration |
sudo unlink /etc/nginx/sites-enabled/site | Disable a site configuration |
server { ... } | Define a virtual server block |
location / { ... } | Define a location block |
listen 80; | Listen on port 80 |
listen 443 ssl; | Listen on port 443 with SSL |
server_name domain.com; | Define the server name |
root /var/www/html; | Define the document root |
index index.html; | Define the default index file |
error_page 404 /404.html; | Define a custom error page |
access_log /var/log/nginx/access.log; | Define the access log file |
error_log /var/log/nginx/error.log; | Define the error log file |
proxy_pass http://backend; | Proxy requests to a backend server |
rewrite ^/old/(.*)$ /new/$1 permanent; | Rewrite URL |
location ~ \.php$ { ... } | Define a location block for PHP files |
include /etc/nginx/conf.d/*.conf; | Include additional configuration files |
ssl_certificate /etc/nginx/ssl/nginx.crt; | Define the SSL certificate |
ssl_certificate_key /etc/nginx/ssl/nginx.key; | Define the SSL certificate key |
ssl_protocols TLSv1.2 TLSv1.3; | Define the supported SSL protocols |
ssl_ciphers HIGH:!aNULL:!MD5; | Define the supported SSL ciphers |
Apache Cheatsheet
Command | Description |
---|---|
sudo systemctl start apache2 | Start Apache |
sudo systemctl stop apache2 | Stop Apache |
sudo systemctl restart apache2 | Restart Apache |
sudo systemctl reload apache2 | Reload Apache configuration |
sudo systemctl enable apache2 | Enable Apache to start on boot |
sudo systemctl disable apache2 | Disable Apache from starting on boot |
apachectl configtest | Test Apache configuration |
apachectl graceful | Gracefully restart Apache |
/etc/apache2/apache2.conf | Main Apache configuration file |
/etc/apache2/sites-available/ | Directory for available site configurations |
/etc/apache2/sites-enabled/ | Directory for enabled site configurations |
sudo a2ensite site | Enable a site configuration |
sudo a2dissite site | Disable a site configuration |
sudo a2enmod module | Enable a module |
sudo a2dismod module | Disable a module |
sudo a2enconf config | Enable a configuration |
sudo a2disconf config | Disable a configuration |
<VirtualHost *:80> ... </VirtualHost> | Define a virtual host for HTTP |
<VirtualHost *:443> ... </VirtualHost> | Define a virtual host for HTTPS |
ServerName domain.com | Define the server name |
DocumentRoot /var/www/html | Define the document root |
DirectoryIndex index.html | Define the default index file |
ErrorLog /var/log/apache2/error.log | Define the error log file |
CustomLog /var/log/apache2/access.log combined | Define the access log file |
SSLEngine on | Enable SSL |
SSLCertificateFile /etc/apache2/ssl/apache.crt | Define the SSL certificate |
SSLCertificateKeyFile /etc/apache2/ssl/apache.key | Define the SSL certificate key |
SSLProtocol all -SSLv2 -SSLv3 | Define the supported SSL protocols |
SSLCipherSuite HIGH:!aNULL:!MD5 | Define the supported SSL ciphers |
ProxyPass /app http://backend/app | Proxy requests to a backend server |
ProxyPassReverse /app http://backend/app | Adjust the URL in the Location header |
RewriteEngine on | Enable URL rewriting |
RewriteRule ^/old/(.*)$ /new/$1 [R=301,L] | Rewrite URL |
<Directory /var/www/html> ... </Directory> | Define directory-specific settings |
Options Indexes FollowSymLinks | Set directory options |
AllowOverride All | Allow .htaccess to override settings |
Require all granted | Allow access to a directory |
Redirect permanent /old /new | Redirect a URL |
Firewalld Cheatsheet
Command | Description |
---|---|
firewall-cmd --state | Check the state of firewalld |
firewall-cmd --reload | Reload firewalld configuration |
firewall-cmd --get-active-zones | List all active zones |
firewall-cmd --get-default-zone | Get the default zone |
firewall-cmd --zone=zone --list-all | List all settings in a zone |
firewall-cmd --zone=zone --add-source=source | Add a source to a zone |
firewall-cmd --zone=zone --add-port=port/protocol | Add a port to a zone |
firewall-cmd --zone=zone --remove-port=port/protocol | Remove a port from a zone |
firewall-cmd --zone=zone --add-service=service | Add a service to a zone |
firewall-cmd --zone=zone --remove-service=service | Remove a service from a zone |
firewall-cmd --permanent | Apply changes permanently |
firewall-cmd --runtime-to-permanent | Save runtime changes to permanent configuration |
firewall-cmd --add-masquerade | Enable masquerading (NAT) |
firewall-cmd --remove-masquerade | Disable masquerading (NAT) |
firewall-cmd --zone=zone --add-rich-rule='rule' | Add a rich rule to a zone |
firewall-cmd --zone=zone --remove-rich-rule='rule' | Remove a rich rule from a zone |
UFW Cheatsheet
Command | Description |
---|---|
sudo ufw enable | Enable UFW |
sudo ufw disable | Disable UFW |
sudo ufw status | Show the current status of UFW and list rules |
sudo ufw status verbose | Show the current status of UFW with detailed information |
sudo ufw allow port | Allow incoming traffic on a specific port |
sudo ufw allow from IP | Allow incoming traffic from a specific IP address |
sudo ufw allow from IP to any port port | Allow incoming traffic from a specific IP to a specific port |
sudo ufw allow proto tcp from IP to any port port | Allow incoming TCP traffic from a specific IP to a specific port |
sudo ufw deny port | Deny incoming traffic on a specific port |
sudo ufw deny from IP | Deny incoming traffic from a specific IP address |
sudo ufw deny from IP to any port port | Deny incoming traffic from a specific IP to a specific port |
sudo ufw delete allow port | Delete an allow rule for a specific port |
sudo ufw delete deny port | Delete a deny rule for a specific port |
sudo ufw default allow outgoing | Set the default policy to allow outgoing traffic |
sudo ufw default deny outgoing | Set the default policy to deny outgoing traffic |
sudo ufw default allow incoming | Set the default policy to allow incoming traffic |
sudo ufw default deny incoming | Set the default policy to deny incoming traffic |
sudo ufw reset | Reset UFW rules to the default state |
sudo ufw show raw | Show the raw iptables rules generated by UFW |
sudo ufw logging on | Enable logging for UFW |
sudo ufw logging off | Disable logging for UFW |
sudo ufw logging low | Set logging level to low |
sudo ufw logging medium | Set logging level to medium |
sudo ufw logging high | Set logging level to high |
sudo ufw app list | List all available application profiles |
sudo ufw app info Application | Show information about a specific application profile |
sudo ufw allow Application | Allow an application by profile |
sudo ufw deny Application | Deny an application by profile |
sudo ufw reload | Reload UFW to apply changes |
sudo ufw route allow proto tcp from any to any port port | Allow routing for a specific port over TCP |
sudo ufw route deny proto udp from any to any port port | Deny routing for a specific port over UDP |
SELinux Cheatsheet
Command | Description |
---|---|
sestatus | Check the status of SELinux |
getenforce | Get the current mode of SELinux |
setenforce 0 | Set SELinux to permissive mode |
setenforce 1 | Set SELinux to enforcing mode |
semanage boolean -l | List all SELinux booleans |
semanage boolean -m --on boolean_name | Enable an SELinux boolean |
semanage boolean -m --off boolean_name | Disable an SELinux boolean |
semanage fcontext -l | List all file context mappings |
semanage fcontext -a -t type '/path(/.*)?' | Add a file context mapping |
restorecon -Rv /path | Apply file context to files |
chcon -t type /path | Change the file context |
ls -Z | List files with SELinux context |
ps -Z | List processes with SELinux context |
grep AVC /var/log/audit/audit.log | Search for SELinux denials in the audit log |
ausearch -m avc -ts recent | Search for recent SELinux denials |
audit2allow -w -a | Display audit log entries that require policy changes |
audit2allow -a -M mymodule | Generate a policy module to allow denials |
semodule -i mymodule.pp | Install a policy module |
semanage port -l | List all SELinux port mappings |
semanage port -a -t type -p tcp port | Add a port mapping |
semanage port -d -p tcp port | Delete a port mapping |
semanage permissive -a type | Set a domain to permissive mode |
semanage permissive -d type | Remove a domain from permissive mode |
seinfo | Display SELinux policy information |
semodule -l | List all installed policy modules |
semodule -r module_name | Remove an installed policy module |
sealert -a /var/log/audit/audit.log | Analyze audit log for SELinux denials |
AppArmor Cheatsheet
Command | Description |
---|---|
aa-status | Check the status of AppArmor |
aa-enforce /etc/apparmor.d/profile | Set a profile to enforce mode |
aa-complain /etc/apparmor.d/profile | Set a profile to complain mode |
aa-logprof | Update profiles based on log events |
aa-genprof /path/to/executable | Generate a new profile for an executable |
aa-disable /etc/apparmor.d/profile | Disable a profile |
aa-parse -r /etc/apparmor.d/profile | Reload a profile |
apparmor_parser -r /etc/apparmor.d/profile | Reload a profile |
apparmor_parser -R /etc/apparmor.d/profile | Remove a profile from the kernel |
aa-unconfined | List unconfined processes |
aa-notify | Display AppArmor notifications |
aa-exec -p profile -- command | Execute a command under a specific profile |
aa-audit /etc/apparmor.d/profile | Set a profile to audit mode |
cat /var/log/syslog \| grep apparmor | Search for AppArmor messages in the syslog |
grep "audit" /var/log/kern.log | Search for AppArmor audit messages in the kernel log |
ls -lZ /path | List files with AppArmor context |
aa-cleanprof | Remove unnecessary rules from a profile |
aa-enforce /etc/apparmor.d/* | Set all profiles to enforce mode |
aa-complain /etc/apparmor.d/* | Set all profiles to complain mode |
journalctl -xe \| grep apparmor | Search for AppArmor events in the journal log |
sudo apparmor_parser -r /etc/apparmor.d/usr.bin.program | Reload a specific AppArmor profile |
sudo aa-genprof /path/to/program | Generate a new profile for a program |
sudo aa-logprof /var/log/syslog | Update profiles based on log events |
sudo aa-enforce /etc/apparmor.d/usr.bin.program | Enforce a specific AppArmor profile |
sudo aa-complain /etc/apparmor.d/usr.bin.program | Set a specific AppArmor profile to complain mode |
LDAP Cheatsheet
Command | Description |
---|---|
ldapsearch -x -b "base_dn" "(filter)" | Search for entries in the LDAP directory |
ldapadd -x -D "bind_dn" -W -f file.ldif | Add entries to the LDAP directory |
ldapdelete -x -D "bind_dn" -W "dn" | Delete entries from the LDAP directory |
ldapmodify -x -D "bind_dn" -W -f file.ldif | Modify entries in the LDAP directory |
ldapcompare -x -D "bind_dn" -W "dn" attribute:value | Compare attribute values |
ldapwhoami -x -D "bind_dn" -W | Show the distinguished name of the authenticated user |
ldapmodrdn -x -D "bind_dn" -W "dn" "new_rdn" | Modify the RDN of an entry |
slapcat -v -l backup.ldif | Export the LDAP directory to an LDIF file |
slapadd -v -l backup.ldif | Import an LDIF file into the LDAP directory |
slapindex | Rebuild the LDAP directory indexes |
slapd -d 1 | Start the LDAP server in debug mode |
ldapsearch -LLL -x -b "base_dn" "(filter)" attribute | Search and display specific attributes |
ldapsearch -H ldap://ldap.example.com -x -b "base_dn" "(filter)" | Search using a specific LDAP URI |
ldapsearch -ZZ -x -b "base_dn" "(filter)" | Search with StartTLS |
ldapadd -ZZ -x -D "bind_dn" -W -f file.ldif | Add entries with StartTLS |
ldapmodify -ZZ -x -D "bind_dn" -W -f file.ldif | Modify entries with StartTLS |
ldapdelete -ZZ -x -D "bind_dn" -W "dn" | Delete entries with StartTLS |
ldapwhoami -ZZ -x -D "bind_dn" -W | Show the distinguished name with StartTLS |
ldapcompare -ZZ -x -D "bind_dn" -W "dn" attribute:value | Compare attribute values with StartTLS |
ldapmodrdn -ZZ -x -D "bind_dn" -W "dn" "new_rdn" | Modify the RDN with StartTLS |
ldapsearch -Y EXTERNAL -H ldapi:/// -b "cn=config" | Search the configuration directory |
ldapadd -Y EXTERNAL -H ldapi:/// -f config.ldif | Add configuration entries |
ldapmodify -Y EXTERNAL -H ldapi:/// -f config.ldif | Modify configuration entries |
ldapdelete -Y EXTERNAL -H ldapi:/// "dn" | Delete configuration entries |
LVM Cheatsheet
Command | Description |
---|---|
pvcreate /dev/sdX | Create a physical volume |
pvdisplay | Display information about physical volumes |
pvscan | Scan all disks for physical volumes |
vgcreate vgname /dev/sdX | Create a volume group |
vgdisplay | Display information about volume groups |
vgscan | Scan all disks for volume groups |
vgextend vgname /dev/sdX | Add a physical volume to a volume group |
vgreduce vgname /dev/sdX | Remove a physical volume from a volume group |
lvcreate -L size -n lvname vgname | Create a logical volume |
lvcreate -l 100%FREE -n lvname vgname | Create a logical volume using all free space |
lvdisplay | Display information about logical volumes |
lvextend -L+size /dev/vgname/lvname | Extend a logical volume by size |
lvextend -l +100%FREE /dev/vgname/lvname | Extend a logical volume using all free space |
lvreduce -L-size /dev/vgname/lvname | Reduce the size of a logical volume |
lvremove /dev/vgname/lvname | Remove a logical volume |
lvresize -L size /dev/vgname/lvname | Resize a logical volume |
lvrename /dev/vgname/oldname newname | Rename a logical volume |
vgremove vgname | Remove a volume group |
pvremove /dev/sdX | Remove a physical volume |
vgchange -a y vgname | Activate a volume group |
vgchange -a n vgname | Deactivate a volume group |
vgmerge vgname1 vgname2 | Merge two volume groups |
vgsplit vgname new_vgname /dev/sdX | Split a volume group into two |
pvmove /dev/sdX | Move physical extents from one physical volume to another |
vgcfgbackup | Backup volume group metadata |
vgcfgrestore vgname | Restore volume group metadata |
lvconvert --type raid1 --mirrors 1 /dev/vgname/lvname | Convert a logical volume to RAID1 |
lvchange -a y /dev/vgname/lvname | Activate a logical volume |
lvchange -a n /dev/vgname/lvname | Deactivate a logical volume |
lvscan | Scan for all logical volumes |
vgextend vgname /dev/sdX | Add a physical volume to a volume group |
ZFS Cheatsheet
Command | Description |
---|---|
zpool create pool /dev/sdX | Create a new storage pool |
zpool destroy pool | Destroy a storage pool |
zpool status | Show the status of all pools |
zpool list | List all pools |
zpool add pool /dev/sdX | Add a device to a pool |
zpool remove pool /dev/sdX | Remove a device from a pool |
zpool replace pool /dev/sdX /dev/sdY | Replace a device in a pool |
zpool scrub pool | Scrub the data in a pool |
zpool export pool | Export a pool |
zpool import pool | Import a pool |
zfs create pool/dataset | Create a new dataset |
zfs destroy pool/dataset | Destroy a dataset |
zfs list | List all datasets |
zfs mount pool/dataset | Mount a dataset |
zfs unmount pool/dataset | Unmount a dataset |
zfs snapshot pool/dataset@snapshot | Create a snapshot of a dataset |
zfs rollback pool/dataset@snapshot | Roll back to a snapshot |
zfs send pool/dataset@snapshot | Send a snapshot |
zfs receive pool/dataset | Receive a snapshot |
zfs get property pool/dataset | Get a property value |
zfs set property=value pool/dataset | Set a property value |
zfs rename pool/dataset new_name | Rename a dataset |
zfs clone pool/dataset@snapshot new_dataset | Clone a snapshot |
zfs promote pool/dataset | Promote a clone to a full dataset |
zfs diff pool/dataset@snapshot1 pool/dataset@snapshot2 | Show differences between snapshots |
zfs upgrade -a | Upgrade all ZFS filesystems |
zpool upgrade -a | Upgrade all ZFS pools |
zpool history pool | Show command history for a pool |
zpool iostat pool | Show I/O statistics for a pool |
zpool clear pool | Clear errors in a pool |
zpool trim pool | Trim free space in a pool |
zfs hold tag pool/dataset@snapshot | Hold a snapshot |
zfs release tag pool/dataset@snapshot | Release a held snapshot |
zfs inherit property pool/dataset | Inherit a property from the parent |
Btrfs Cheatsheet
Command | Description |
---|---|
mkfs.btrfs /dev/sdX | Create a Btrfs filesystem |
btrfs filesystem show | Show Btrfs filesystems |
btrfs filesystem df /mountpoint | Show disk usage of a Btrfs filesystem |
btrfs filesystem balance /mountpoint | Balance a Btrfs filesystem |
btrfs filesystem resize size /mountpoint | Resize a Btrfs filesystem |
btrfs device add /dev/sdX /mountpoint | Add a device to a Btrfs filesystem |
btrfs device delete /dev/sdX /mountpoint | Remove a device from a Btrfs filesystem |
btrfs scrub start /mountpoint | Scrub a Btrfs filesystem |
btrfs scrub status /mountpoint | Show scrub status |
btrfs balance start /mountpoint | Start a balance operation |
btrfs balance status /mountpoint | Show balance status |
btrfs subvolume create /mountpoint/subvolume | Create a subvolume |
btrfs subvolume delete /mountpoint/subvolume | Delete a subvolume |
btrfs subvolume list /mountpoint | List all subvolumes |
btrfs subvolume snapshot /mountpoint/subvolume /mountpoint/snapshot | Create a snapshot |
btrfs send /mountpoint/subvolume | btrfs receive /mountpoint/snapshot` |
btrfs subvolume set-default subvolid /mountpoint | Set the default subvolume |
btrfs property set /mountpoint/subvolume ro true | Set a subvolume to read-only |
btrfs property list /mountpoint/subvolume | List properties of a subvolume |
btrfs quota enable /mountpoint | Enable quotas on a Btrfs filesystem |
btrfs qgroup show /mountpoint | Show quota groups |
btrfs qgroup limit size /mountpoint | Set a quota limit |
btrfs rescue zero-log /dev/sdX | Repair a corrupted log |
btrfs rescue chunk-recover /dev/sdX | Recover corrupted chunks |
btrfs check /dev/sdX | Check a Btrfs filesystem |
btrfs device scan | Scan for Btrfs devices |
btrfs device stats /mountpoint | Show device statistics |
btrfs filesystem defragment /mountpoint | Defragment a Btrfs filesystem |
btrfs quota rescan -w /mountpoint | Rescan quotas |
btrfs filesystem sync /mountpoint | Sync a Btrfs filesystem |
btrfs replace start /dev/sdX /dev/sdY /mountpoint | Replace a device in a Btrfs filesystem |
btrfs replace status /mountpoint | Show replace status |
Network Troubleshooting Cheatsheet
Command | Description |
---|---|
ping host | Check connectivity to a host |
ping -c count host | Send a specific number of ping requests |
ping -i interval host | Set the interval between ping requests |
ping -t ttl host | Set the time-to-live for ping packets |
traceroute host | Trace the route to a host |
traceroute -m max_ttl host | Set the maximum TTL |
traceroute -p port host | Set the destination port |
traceroute -I host | Use ICMP echo instead of UDP |
traceroute -T host | Use TCP SYN instead of UDP |
mtr host | Network diagnostic tool combining ping and traceroute |
mtr -r host | Run MTR in report mode |
mtr -c count host | Set the number of pings in MTR |
netstat -tuln | List all listening ports and services |
netstat -i | Show network interfaces |
netstat -rn | Show the routing table |
netstat -s | Display network statistics |
netstat -plnt | Show listening TCP ports |
ss -tuln | List all listening ports and services (ss command) |
ss -i | Show network interfaces (ss command) |
ss -rn | Show the routing table (ss command) |
ss -s | Display network statistics (ss command) |
ss -plnt | Show listening TCP ports (ss command) |
ip addr show | Display all IP addresses |
ip link show | Show network interfaces |
ip route show | Display the routing table |
ip link set dev iface up | Bring an interface up |
ip link set dev iface down | Bring an interface down |
ifconfig | Display network interfaces |
ifconfig iface up | Bring an interface up |
ifconfig iface down | Bring an interface down |
ifconfig iface inet addr | Assign an IP address to an interface |
ifconfig iface hw ether MAC | Assign a MAC address to an interface |
ethtool iface | Display Ethernet device settings |
ethtool -s iface speed 1000 duplex full autoneg on | Set Ethernet device speed and duplex |
tcpdump -i iface | Capture packets on an interface |
tcpdump -n host host | Capture packets to/from a specific host |
tcpdump -nn port port | Capture packets on a specific port |
tcpdump -w file.pcap | Write packets to a file |
tcpdump -r file.pcap | Read packets from a file |
dig domain | DNS lookup for a domain |
dig +short domain | Short DNS lookup for a domain |
dig -x ip | Reverse DNS lookup |
nslookup domain | DNS lookup for a domain (nslookup) |
nslookup | Enter interactive mode (nslookup) |
nslookup domain server | DNS lookup using a specific DNS server |
System Diagnostics and Logging Cheatsheet
dmesg
Command | Description |
---|---|
dmesg | Display all messages from the kernel ring buffer |
`dmesg | less` |
`dmesg | grep pattern` |
dmesg -c | Clear the ring buffer after printing |
dmesg -T | Display human-readable timestamps for each message |
dmesg -H | Enable colorized and human-readable output |
dmesg -l level | Filter messages by log level (e.g., emerg , alert , crit , err , warn , notice , info , debug ) |
dmesg -n level | Set the log level of messages to print |
dmesg -f facility | Filter messages by facility (e.g., kern , user , mail , daemon , auth , syslog , lpr , news , uucp , cron , authpriv , ftp , local0 -local7 ) |
dmesg -r | Raw output, no human-readable timestamps |
dmesg --clear | Clear the kernel ring buffer |
dmesg --level level | Set the log level for printing messages |
dmesg --facility facility | Set the facility for printing messages |
dmesg -w | Keep waiting for new messages and print them as they come |
dmesg --follow | Alias for -w , keep waiting for new messages |
journalctl
Command | Description |
---|---|
journalctl | View the systemd journal |
journalctl -b | Show messages from the current boot |
journalctl -k | Show only kernel messages |
journalctl -u service | Show messages for a specific service |
journalctl -f | Follow new messages as they appear (similar to tail -f ) |
journalctl -r | Show messages in reverse chronological order |
journalctl --since "time" | Show messages since a specific time |
journalctl --until "time" | Show messages until a specific time |
journalctl -p level | Show messages of a specific priority level (e.g., emerg , alert , crit , err , warn , notice , info , debug ) |
journalctl -xe | Show the last few log entries with details about system errors |
journalctl --disk-usage | Show the disk space used by the journal |
journalctl --vacuum-time=time | Remove journal files older than the specified time |
journalctl --vacuum-size=size | Remove old journal files until the total size is below the specified size |
journalctl -o json-pretty | Output logs in pretty JSON format |
rsyslog
(or syslog
in general)
Command/Configuration | Description |
---|---|
/etc/rsyslog.conf | Main configuration file for rsyslog |
/etc/rsyslog.d/ | Directory for additional configuration files |
sudo systemctl restart rsyslog | Restart the rsyslog service |
logger "message" | Add a message to the system log |
/var/log/messages | General system log |
/var/log/secure | Authentication and security related messages |
/var/log/maillog | Mail server logs |
/var/log/cron | Cron job logs |
/var/log/boot.log | System boot log |
/var/log/dmesg | Kernel ring buffer log |
top
/ htop
Command | Description |
---|---|
top | Display real-time system information including tasks and load |
htop | Interactive process viewer (requires installation) |
top -u username | Show only processes for a specific user |
top -p PID | Show only the specified PID(s) |
htop -u username | Show only processes for a specific user (in htop) |
free
Command | Description |
---|---|
free | Display memory usage |
free -h | Display memory usage in human-readable format |
free -m | Display memory usage in megabytes |
free -g | Display memory usage in gigabytes |
vmstat
Command | Description |
---|---|
vmstat | Display virtual memory statistics |
vmstat 1 | Display virtual memory statistics every second |
vmstat -s | Display memory statistics |
vmstat -d | Display disk statistics |
vmstat -t | Display timestamps with the output |
iostat
Command | Description |
---|---|
iostat | Display CPU and I/O statistics |
iostat -x | Display extended statistics |
iostat -d | Display device utilization statistics |
iostat -c | Display only CPU statistics |
iostat -p ALL | Display statistics for all devices and partitions |
mpstat
Command | Description |
---|---|
mpstat | Display CPU usage |
mpstat -P ALL | Display CPU usage for all processors |
mpstat 1 5 | Display CPU usage every second for 5 times |
sar
Command | Description |
---|---|
sar | Collect and report system activity |
sar -u 1 3 | Report CPU utilization every second for 3 times |
sar -r | Report memory utilization |
sar -n DEV | Report network statistics |
sar -b | Report I/O and transfer rate statistics |
netstat
/ ss
Command | Description |
---|---|
netstat -tuln | List all listening ports |
netstat -i | Display network interfaces |
netstat -rn | Display routing table |
netstat -s | Display network statistics |
ss -tuln | List all listening ports (ss command) |
ss -i | Display network interfaces (ss command) |
ss -rn | Display routing table (ss command) |
ss -s | Display network statistics (ss command) |
iftop
(requires installation)
Command | Description |
---|---|
iftop | Display real-time network bandwidth usage |
iftop -i interface | Display network bandwidth usage for a specific interface |
iftop -P | Show ports |
iftop -n | Show numerical addresses rather than resolving hosts |
tcpdump
Command | Description |
---|---|
tcpdump -i interface | Capture packets on a specific interface |
tcpdump -n host host | Capture packets to/from a specific host |
tcpdump -nn port port | Capture packets on a specific port |
tcpdump -w file.pcap | Write captured packets to a file |
tcpdump -r file.pcap | Read packets from a file |
Important /proc
Subdirectories and Files
Directory/File | Description |
---|---|
/proc/cpuinfo | Detailed information about the CPU, such as model, cores, and speed |
/proc/meminfo | Detailed information about memory usage |
/proc/version | Kernel version and build information |
/proc/cmdline | Kernel command line used to boot the system |
/proc/devices | Lists all character and block devices currently configured |
/proc/diskstats | Disk I/O statistics |
/proc/uptime | System uptime information |
/proc/loadavg | Load average of the system |
/proc/mounts | Mounted filesystems |
/proc/partitions | Information about disk partitions |
/proc/swaps | Swap space utilization |
/proc/sys | Kernel tunable parameters (sysctl) |
/proc/sys/kernel | Kernel-related parameters |
/proc/sys/net | Network-related parameters |
/proc/net | Network status information |
/proc/interrupts | Number of interrupts per CPU per I/O device |
/proc/iomem | Memory map for the system |
/proc/ioports | I/O port usage |
/proc/modules | Loaded kernel modules |
/proc/kallsyms | Kernel symbol table |
/proc/kcore | Pseudo-file representing the physical memory of the system |
/proc/slabinfo | Kernel slab allocator information |
/proc/self | Process-specific information for the current process |
/proc/self/cmdline | Command line of the current process |
/proc/self/environ | Environment variables of the current process |
/proc/self/exe | Symlink to the executable of the current process |
/proc/self/status | Current process status information |
/proc/self/limits | Resource limits of the current process |
/proc/self/mounts | Mounts of the current process |
/proc/self/cgroup | Cgroup membership of the current process |
/proc/self/fd | File descriptors opened by the current process |
/proc/self/fdinfo | Detailed information about file descriptors |
/proc/self/maps | Memory maps of the current process |
/proc/self/smaps | Extended memory maps of the current process |
/proc/self/mem | Memory of the current process |
/proc/self/task | Tasks (threads) of the current process |
/proc/[pid]/ | Information specific to process with PID |
/proc/[pid]/cmdline | Command line of the process with PID |
/proc/[pid]/environ | Environment variables of the process with PID |
/proc/[pid]/exe | Symlink to the executable of the process with PID |
/proc/[pid]/status | Status information of the process with PID |
/proc/[pid]/limits | Resource limits of the process with PID |
/proc/[pid]/mounts | Mounts of the process with PID |
/proc/[pid]/cgroup | Cgroup membership of the process with PID |
/proc/[pid]/fd | File descriptors opened by the process with PID |
/proc/[pid]/fdinfo | Detailed information about file descriptors of the process with PID |
/proc/[pid]/maps | Memory maps of the process with PID |
/proc/[pid]/smaps | Extended memory maps of the process with PID |
/proc/[pid]/mem | Memory of the process with PID |
/proc/[pid]/task | Tasks (threads) of the process with PID |
MPV Hotkeys Cheatsheet
Hotkey | Description |
---|---|
Space | Toggle play/pause |
f | Toggle fullscreen |
m | Mute/unmute audio |
9 / ( | Decrease volume |
0 / ) | Increase volume |
[ | Decrease playback speed |
] | Increase playback speed |
{ | Halve playback speed |
} | Double playback speed |
backspace | Reset playback speed to normal |
Left Arrow | Seek backward 5 seconds |
Right Arrow | Seek forward 5 seconds |
Up Arrow | Seek forward 60 seconds |
Down Arrow | Seek backward 60 seconds |
Shift+Left Arrow | Seek backward 1 second |
Shift+Right Arrow | Seek forward 1 second |
Ctrl+Left Arrow | Seek backward 10 minutes |
Ctrl+Right Arrow | Seek forward 10 minutes |
. | Move forward one frame (pause required) |
, | Move backward one frame (pause required) |
o | Show file info |
I | Show codec info |
q | Quit |
Q | Force quit (without saving the resume position) |
s | Take a screenshot |
S | Take a screenshot without subtitles |
Ctrl+s | Take a screenshot and include the OSD |
T | Toggle displaying time |
Ctrl+o | Cycle through OSD (On-Screen Display) levels |
v | Toggle subtitles |
j | Cycle through subtitles |
J | Cycle through secondary subtitles |
# | Toggle subtitle visibility |
z | Adjust subtitle delay backward |
x | Adjust subtitle delay forward |
r | Rotate video |
p | Toggle between current and previous subtitle track |
l | Adjust audio delay backward |
k | Adjust audio delay forward |
Ctrl++ | Increase subtitle font size |
Ctrl+- | Decrease subtitle font size |
Alt++ | Increase subtitle border size |
Alt+- | Decrease subtitle border size |
Ctrl+r | Toggle random playback |
Ctrl+shift+r | Toggle looping playback |
Ctrl+p | Toggle playlist navigation display |
Ctrl+u | Reload playlist |
Ctrl+Enter | Toggle between fullscreen and windowed mode |
Esc | Exit fullscreen or close OSD menu |
h | Seek to the previous chapter |
l | Seek to the next chapter |
y | Adjust subtitle delay back by 0.1 seconds |
Y | Adjust subtitle delay forward by 0.1 seconds |
t | Toggle stay-on-top mode |
Ctrl+f | Toggle autofit |
Ctrl+c | Copy current file path to clipboard |
Ctrl+v | Paste URL/file path from clipboard and open |
Linux Journey
For this I will only be taking note of material I would like to reaffirm or commit to memory. Therefore these notes are not exhaustive or that verbose since much of the material on this site I already know Link
Grasshopper
Text Fu
Data Streams (STDIO)
- Standard In (stdin)
- Numerically represented as
0
- Numerically represented as
- Standard Out (stdout)
- Numerically represented as
1
- Numerically represented as
- Standard Error (stderr)
- Numerically represented as
2
- Numerically represented as
User Management
/etc/passwd
- Contains username, default shell, home directory, UID and GID
/etc/shadow
- Contains encrypted password, change history, constraints
/etc/group
- Contains groups and users
Permissions
- File type followed by three field of three bits define permissions
- d | rwx | rwx | rwx
- So it is octal, decimal representation is 0-7 or null
umask
masks off to define default set of permissions on new files- The set user id or SUID bit enables executing a file as the owner of the file.
x
is replaced withs
. It is numerically represented as 4 prepended. - The set group id or GUID bit is a synonymous concept, numerically represented as 2 prepended S represents a SUID or GUID bit that it set, while the executable bit itself is not
- The sticky bit allows only the owner or root to edit a file. Numerically represented as 1 prepended. Represented as
t
appended. T represents a sticky bit where the executable bit itself is not set
Process Permissions:
- Process UIDs
- effective user id: permission of running user
- real user id: user that launched process
- saved user id: essentially a cached id that allows for switching between root uid is 0
When running the passwd command, your effective UID is your user ID, let's say its 500 for now. Oh but wait, remember the passwd command has the SUID permission enabled. So when you run it, your effective UID is now 0 (0 is the UID of root). Now this program can access files as root. Let's say you get a little taste of power and you want to modify Sally's password, Sally has a UID of 600. Well you'll be out of luck, fortunately the process also has your real UID in this case 500. It knows that your UID is 500 and therefore you can't modify the password of UID of 600. (This of course is always bypassed if you are a superuser on a machine and can control and change everything). Since you ran passwd, it will start the process off using your real UID, and it will save the UID of the owner of the file (effective UID), so you can switch between the two. No need to modify all files with root access if it's not required. Most of the time the real UID and the effective UID are the same, but in such cases as the passwd command they will change.
Processes
- Controlling terminal: the terminal a process is bound to
- Processes are instances of a program
ps aux
When a new process is created, an existing process basically clones itself using something called the fork system call (system calls will be discussed very far into the future). The fork system call creates a mostly identical child process, this child process takes on a new process ID (PID) and the original process becomes its parent process and has something called a parent process ID PPID. Afterwards, the child process can either continue to use the same program its parent was using before or more often use the execve system call to launch up a new program. This system call destroys the memory management that the kernel put into place for that process and sets up new ones for the new program.
- Orphans: Processes that have no parent and are adopted and queued for killing by init
- Zombies: Children that die before
wait()
is called. They will be reaped if parent callswait()
or is adopted then killed by init
Signals
- Software interrupts that can for killing, suspending, or communicating
- Processes have signal masks
Common signals Each signal is defined by integers with symbolic names that are in the form of SIGxxx. Some of the most common signals are: SIGHUP or HUP or 1: Hangup SIGINT or INT or 2: Interrupt SIGKILL or KILL or 9: Kill SIGSEGV or SEGV or 11: Segmentation fault SIGTERM or TERM or 15: Software termination SIGSTOP or STOP: Stop Numbers can vary with signals so they are usually referred by their names.
kill
sends terminate sig by default or signal of choosing through option-sig_num
Niceness
- Process CPU priority
- Number -20 through 19
- Higher == Lower Priority
- Lower == Higher Priority
/proc
/proc
contains info on pids abstracted as files in/proc/"pid_num"
Job Control
&
runs job in background of controlling terminaljobs
outputs background jobsCTRL-Z
sends current jobs to backgroundfg
moves background jobs to foregroundkill
can kill background jobs as well
Packaging
tar xvf
is good for archiving- This site discusses gunzip for compressing.
- tar supports compressing with it:
tar czvf
, and uncompressing:tar xzfv
Journeyman
Devices
/dev
is where device files reside including pseudo devices
Remember in the ls command you can see the type of file with the first bit on each line. Device files are denoted as the following: c - character b - block p - pipe s - socket
- Character: sends data one char at a time
- Block: large fized sized blocks (storage)
- Pipe: pipes data form one process to another
- Socket: Similar to pipe but with multiple processes simultaneously
Naming
- SCSI protocol: prefixed sd the a-z
zero
null
andrandom
- PATA for older hardware prefixed with hd
sysfs
/sys
contains information on devices
udev
The udev system dynamically creates and removes device files for us depending on whether or not they are connected.
- udevd is the associated daemon
- rules located in
/etc/udev/rules.d
Listing and dd
lsusb
,lspci
, andlsscsi
- dd for writing data THE DISK DESTROYER
The Filesystem
The majority of this section is already learned
Inodes
- Index table of references to file metadata and the data blocks themselves
- Created at filesystem creation
- Can be exhausted
In a typical filesystem (not all work the same), each inode contains 15 pointers, the first 12 pointers point directly to the data blocks. The 13th pointer, points to a block containing pointers to more blocks, the 14th pointer points to another nested block of pointers, and the 15th pointer points yet again to another block of pointers!
Boot The System
initrd - Specifies the location of initial RAM disk (we'll talk more about this in the next lesson). BOOT_IMAGE - This is where the kernel image is located root - The location of the root filesystem, the kernel searches inside this location to find init. It is often represented by it's UUID or the device name such as /dev/sda1. ro - This parameter is pretty standard, it mounts the fileystem as read-only mode. quiet - This is added so that you don't see display messages that are going on in the background during boot. splash - This lets the splash screen be shown.
Kernel
- initrd and initramfs are temp file systems that exists to load necessary drivers for hardware communication during boot
Kernel
- Hardware --> Kernel --> Userspace
- x86 privledge levels or protection rings: 3-->0
System Calls
- C code that provide user space processes means of communicating kernel
- Uses API
- Programs contain syscall wrappers for traps
- trap gets caught and references syscall table
strace
outputs syscalls of process
Kernel Location
You will see multiple files for different kernel versions: vmlinuz - this is the actual linux kernel initrd - as we've discussed before, the initrd is used as a temporary file system, used before loading the kernel System.map - symbolic lookup table config - kernel configuration settings, if you are compiling your own kernel, you can set which modules can be loadess
Kernel Modules
lsmod
,modprobe
, and/etc/modprobe.d/
Drivers can be a kind of kernel module if not built in
Init
SysV
0: Shutdown 1: Single User Mode 2: Multiuser mode without networking 3: Multiuser mode with networking 4: Unused 5: Multiuser mode with networking and GUI 6: Reboot
SystemD
- Target and dependency based >First, systemd loads its configuration files, usually located in /etc/systemd/system or /usr/lib/systemd/system Then it determines its boot goal, which is usually default.target Systemd figures out the dependencies of the boot target and activates them
poweroff.target - shutdown system rescue.target - single user mode multi-user.target - multiuser with networking graphical.target - multiuser with networking and GUI reboot.target - restart
- Units are files that contain config directives
The most common units are: Service units - these are the services we've been starting and stopping, these unit files end in .service Mount units - These mount filesystems, these unit files end in .mount Target units - These group together other units, the files end in .target
- Further Reading: Red Hat Wiki
Process Utilization
top
lsof
fuser
- view threads with:
ps m
uptime
,iostat
,/proc/cpuinfo
,vmstat
,sar
- Cron jobs:
crontab -e
Logging
- syslog is a service that sends info the the logger
- daemon is syslogd or rsyslogd
- logs are generally in
/var
- `/var/log/syslog
- `var/log/kern.log
- `/var/log/auth.log
- logrotate to rotate logs,
/etc/logrotate.d
I want to pivot off of this reading by taking notes from the Red Hat Wiki specifically on SystemD. All in all this website is a great resource and I highly recommend it for anyone getting into Linux.
Math
Notes from math classes I've taken transcribed to Mathjax for mdbook.
Single Variable Calculus
Limits and Continuity
Definition of a Limit: \[ \lim_{x \to c} f(x) = L \]
One-Sided Limits: \[ \lim_{x \to c^+} f(x) = L \] \[ \lim_{x \to c^-} f(x) = L \]
Limit Laws: \[ \lim_{x \to c} [f(x) + g(x)] = \lim_{x \to c} f(x) + \lim_{x \to c} g(x) \] \[ \lim_{x \to c} [f(x) - g(x)] = \lim_{x \to c} f(x) - \lim_{x \to c} g(x) \] \[ \lim_{x \to c} [f(x) \cdot g(x)] = \lim_{x \to c} f(x) \cdot \lim_{x \to c} g(x) \] \[ \lim_{x \to c} \left[ \frac{f(x)}{g(x)} \right] = \frac{\lim_{x \to c} f(x)}{\lim_{x \to c} g(x)} \]
Continuity: A function ( f(x) ) is continuous at ( x = c ) if:
- ( f(c) ) is defined.
- ( \lim_{x \to c} f(x) ) exists.
- ( \lim_{x \to c} f(x) = f(c) ).
Derivatives
Definition of the Derivative: \[ f'(x) = \lim_{h \to 0} \frac{f(x+h) - f(x)}{h} \]
Power Rule: \[ \frac{d}{dx} [x^n] = nx^{n-1} \]
Product Rule: \[ \frac{d}{dx} [uv] = u'v + uv' \]
Quotient Rule: \[ \frac{d}{dx} \left[ \frac{u}{v} \right] = \frac{u'v - uv'}{v^2} \]
Chain Rule: \[ \frac{d}{dx} f(g(x)) = f'(g(x)) g'(x) \]
Higher-Order Derivatives: \[ f''(x) = \frac{d^2 f}{dx^2} \]
Applications of Derivatives
Critical Points: Points where ( f'(x) = 0 ) or ( f'(x) ) does not exist.
Increasing/Decreasing Test:
- If ( f'(x) > 0 ) on an interval, ( f(x) ) is increasing on that interval.
- If ( f'(x) < 0 ) on an interval, ( f(x) ) is decreasing on that interval.
First Derivative Test:
- If ( f' ) changes from positive to negative at ( c ), ( f(c) ) is a local maximum.
- If ( f' ) changes from negative to positive at ( c ), ( f(c) ) is a local minimum.
Concavity and Inflection Points:
- ( f''(x) > 0 ) on an interval, ( f ) is concave up on that interval.
- ( f''(x) < 0 ) on an interval, ( f ) is concave down on that interval.
- Inflection points occur where ( f''(x) = 0 ) and changes sign.
Second Derivative Test:
- If ( f''(c) > 0 ), ( f(c) ) is a local minimum.
- If ( f''(c) < 0 ), ( f(c) ) is a local maximum.
Optimization: Use derivatives to find the maximum and minimum values of a function in a given interval.
Related Rates: Use derivatives to relate the rates of change of two or more related variables.
Integrals
Indefinite Integral (Antiderivative): \[ \int f(x) , dx = F(x) + C \] where ( F'(x) = f(x) ) and ( C ) is the constant of integration.
Basic Integration Rules: \[ \int x^n , dx = \frac{x^{n+1}}{n+1} + C ] \[ \int e^x , dx = e^x + C \] \[ \int \sin x , dx = -\cos x + C \] \[ \int \cos x , dx = \sin x + C \]
Definite Integral: \[ \int_a^b f(x) , dx \] represents the area under the curve ( f(x) ) from ( x = a ) to ( x = b ).
Fundamental Theorem of Calculus:
- \[ F(x) = \int_a^x f(t) , dt \implies F'(x) = f(x) \]
- \[ \int_a^b f(x) , dx = F(b) - F(a) \] where ( F ) is an antiderivative of ( f ).
Integration by Substitution: \[ \int f(g(x))g'(x) , dx = \int f(u) , du \] where ( u = g(x) ).
Integration by Parts: \[ \int u , dv = uv - \int v , du \]
Applications of Integrals
Area Between Curves: \[ \int_a^b [f(x) - g(x)] , dx \] where ( f(x) ) is the upper function and ( g(x) ) is the lower function.
Volume of Solids of Revolution (Disk Method): \[ V = \pi \int_a^b [f(x)]^2 , dx \]
Volume of Solids of Revolution (Washer Method): \[ V = \pi \int_a^b \left[ [R(x)]^2 - [r(x)]^2 \right] , dx \]
Arc Length: \[ L = \int_a^b \sqrt{1 + [f'(x)]^2} , dx \]
Surface Area: \[ SA = 2\pi \int_a^b f(x) \sqrt{1 + [f'(x)]^2} , dx \]
Calculus 2 Formulas
Techniques of Integration
Integration by Partial Fractions: For a rational function ( \frac{P(x)}{Q(x)} ), decompose into partial fractions before integrating.
Trigonometric Integrals: \[ \int \sin^m x \cos^n x , dx \] Use reduction formulas or trigonometric identities.
Trigonometric Substitution: Use substitutions like ( x = a \sin \theta ), ( x = a \tan \theta ), or ( x = a \sec \theta ) to simplify integrals.
Improper Integrals: \[ \int_a^\infty f(x) , dx = \lim_{b \to \infty} \int_a^b f(x) , dx \] \[ \int_{-\infty}^\infty f(x) , dx = \lim_{a \to -\infty} \lim_{b \to \infty} \int_a^b f(x) , dx \]
Series
Sequences: A sequence is an ordered list of numbers defined by a formula ( a_n ).
Series: A series is the sum of the terms of a sequence. \[ \sum_{n=1}^\infty a_n \]
Geometric Series: \[ \sum_{n=0}^\infty ar^n = \frac{a}{1-r} \quad \text{for} \quad |r| < 1 \]
Convergence Tests:
- Integral Test: \[ \sum_{n=1}^\infty a_n \quad \text{and} \quad \int_1^\infty f(x) , dx \quad \text{either both converge or both diverge} \]
- Comparison Test: If ( 0 \le a_n \le b_n ) and ( \sum b_n ) converges, then ( \sum a_n ) converges.
- Ratio Test:
\[ \lim_{n \to \infty} \left| \frac{a_{n+1}}{a_n} \right| = L ]
- If ( L < 1 ), the series converges.
- If ( L > 1 ), the series diverges.
- If ( L = 1 ), the test is inconclusive.
- Root Test:
\[ \lim_{n \to \infty} \sqrt[n]{|a_n|} = L ]
- If ( L < 1 ), the series converges.
- If ( L > 1 ), the series diverges.
- If ( L = 1 ), the test is inconclusive.
Power Series: \[ \sum_{n=0}^\infty c_n (x - a)^n \] with radius of convergence ( R ).
Taylor Series: \[ f(x) = \sum_{n=0}^\infty \frac{f^n(a)}{n!} (x - a)^n \]
Maclaurin Series: \[ f(x) = \sum_{n=0}^\infty \frac{f^n(0)}{n!} x^n \]
Parametric Equations and Polar Coordinates
Parametric Equations:
- A curve is defined by ( x = f(t) ) and ( y = g(t) ).
Slope of a Parametric Curve: \[ \frac{dy}{dx} = \frac{\frac{dy}{dt}}{\frac{dx}{dt}} \]
Arc Length of a Parametric Curve: \[ L = \int_a^b \sqrt{\left( \frac{dx}{dt} \right)^2 + \left( \frac{dy}{dt} \right)^2} , dt \]
Polar Coordinates:
- Points are defined by ( (r, \theta) ).
Converting Polar to Cartesian: \[ x = r \cos \theta \] \[ y = r \sin \theta \]
Converting Cartesian to Polar: \[ r = \sqrt{x^2 + y^2} \] \[ \theta = \tan^{-1} \left( \frac{y}{x} \right) \]
Area in Polar Coordinates: \[ A = \frac{1}{2} \int_{\alpha}^{\beta} r^2 , d\theta \]
Arc Length in Polar Coordinates: \[ L = \int_{\alpha}^{\beta} \sqrt{\left( \frac{dr}{d\theta} \right)^2 + r^2} , d\theta \]
Differential Equations
Separable Differential Equations: \[ \frac{dy}{dx} = g(x)h(y) \] Separate and integrate: \[ \int \frac{1}{h(y)} , dy = \int g(x) , dx \]
Linear First-Order Differential Equations: \[ \frac{dy}{dx} + P(x)y = Q(x) \] Solve using the integrating factor: \[ \mu(x) = e^{\int P(x) , dx} \]
General Solution: \[ y(x) = \frac{1}{\mu(x)} \left( \int \mu(x) Q(x) , dx + C \right) \]
Applications of Differential Equations
Exponential Growth and Decay: \[ \frac{dy}{dt} = ky \] Solution: \[ y(t) = y_0 e^{kt} \]
Newton's Law of Cooling: \[ \frac{dT}{dt} = k(T - T_{\text{env}}) \] Solution: \[ T(t) = T_{\text{env}} + (T_0 - T_{\text{env}}) e^{kt} \]
Logistic Growth: \[ \frac{dP}{dt} = rP \left( 1 - \frac{P}{K} \right) \] Solution: \[ P(t) = \frac{KP_0 e^{rt}}{K + P_0 (e^{rt} - 1)} \]
Calculus 3 Formulas
Vectors
Dot Product: \[ \mathbf{a} \cdot \mathbf{b} = a_1 b_1 + a_2 b_2 + a_3 b_3 \] \[ \mathbf{a} \cdot \mathbf{b} = |\mathbf{a}| |\mathbf{b}| \cos \theta \]
Projection of (\mathbf{a}) onto (\mathbf{b}): \[ \text{proj}_{\mathbf{b}} \mathbf{a} = \frac{\mathbf{a} \cdot \mathbf{b}}{\mathbf{b} \cdot \mathbf{b}} \mathbf{b} \]
Cross Product: \[ \mathbf{a} \times \mathbf{b} = \begin{vmatrix} \mathbf{i} & \mathbf{j} & \mathbf{k} \\ a_1 & a_2 & a_3 \\ b_1 & b_2 & b_3 \ \end{vmatrix} \] \[ |\mathbf{a} \times \mathbf{b}| = |\mathbf{a}| |\mathbf{b}| \sin \theta \]
Area of Parallelogram (in vectors): \[ \text{Area} = |\mathbf{a} \times \mathbf{b}| \]
Volume of Parallelepiped: \[ \text{Volume} = |\mathbf{a} \cdot (\mathbf{b} \times \mathbf{c})| \]
Equation of a Line: \[ \mathbf{r} = \mathbf{r_0} + t \mathbf{v} \]
Parametric Equation of a Line: \[ \begin{cases} x = x_0 + t a \\ y = y_0 + t b \\ z = z_0 + t c \ \end{cases} \]
Symmetric Equation of a Line: \[ \frac{x - x_0}{a} = \frac{y - y_0}{b} = \frac{z - z_0}{c} \]
Equation of a Plane (standard form): \[ ax + by + cz = d \]
Equation of a Plane (general form): \[ ax + by + cz + d = 0 \]
Distance from Point to Line: \[ D = \frac{|\mathbf{PQ} \times \mathbf{v}|}{|\mathbf{v}|} \]
Distance from Point to Plane: \[ D = \frac{|ax_1 + by_1 + cz_1 + d|}{\sqrt{a^2 + b^2 + c^2}} \]
Distance Between Parallel Planes: \[ D = \frac{|d_1 - d_2|}{\sqrt{a^2 + b^2 + c^2}} \]
Position Vector for a Projectile: \[ \mathbf{r}(t) = \left( v_{0x} t \right) \mathbf{i} + \left( v_{0y} t - \frac{1}{2} g t^2 \right) \mathbf{j} \]
Unit Tangent Vector: \[ \mathbf{T}(t) = \frac{\mathbf{r}'(t)}{|\mathbf{r}'(t)|} \]
Principal Unit Normal Vector: \[ \mathbf{N}(t) = \frac{\mathbf{T}'(t)}{|\mathbf{T}'(t)|} \]
Tangential and Normal Components of Acceleration: \[ a_T = \mathbf{a} \cdot \mathbf{T} \] \[ a_N = \sqrt{|\mathbf{a}|^2 - a_T^2} \]
Arc Length of a Space Curve: \[ s = \int_a^b |\mathbf{r}'(t)| , dt \]
Curvature: \[ \kappa = \frac{|\mathbf{T}'(t)|}{|\mathbf{r}'(t)|} = \frac{|\mathbf{r}'(t) \times \mathbf{r}''(t)|}{|\mathbf{r}'(t)|^3} \]
Angle of Inclination: \[ \theta = \arccos\left(\frac{a}{\sqrt{a^2 + b^2 + c^2}}\right) \]
Tangent Plane to Level Surface: \[ z - z_0 = f_x(x_0, y_0)(x - x_0) + f_y(x_0, y_0)(y - y_0) \]
Normal Line: \[ \frac{x - x_0}{f_x(x_0, y_0)} = \frac{y - y_0}{f_y(x_0, y_0)} = \frac{z - z_0}{-1} \]
Vector Fields: \[ \mathbf{F}(x, y, z) = P(x, y, z) \mathbf{i} + Q(x, y, z) \mathbf{j} + R(x, y, z) \mathbf{k} \]
Inverse Square Fields: \[ \mathbf{F}(\mathbf{r}) = \frac{k \mathbf{r}}{|\mathbf{r}|^3} \]
Conservative Vector Field Tests: \[ \nabla \times \mathbf{F} = \mathbf{0} \]
Curl of a Vector Field: \[ \nabla \times \mathbf{F} = \left( \frac{\partial R}{\partial y} - \frac{\partial Q}{\partial z} \right) \mathbf{i} + \left( \frac{\partial P}{\partial z} - \frac{\partial R}{\partial x} \right) \mathbf{j} + \left( \frac{\partial Q}{\partial x} - \frac{\partial P}{\partial y} \right) \]
Divergence of a Vector Field: \[ \nabla \cdot \mathbf{F} = \frac{\partial P}{\partial x} + \frac{\partial Q}{\partial y} + \frac{\partial R}{\partial z} \]
Line Integrals: \[ \int_C f(x, y, z) , ds \]
Line Integrals of a Vector Field: \[ \int_C \mathbf{F} \cdot d\mathbf{r} \]
Differential Form of Line Integral: \[ \int_C P , dx + Q , dy + R , dz \]
Fundamental Theorem of Line Integrals: \[ \int_C \nabla f \cdot d\mathbf{r} = f(\mathbf{r}(b)) - f(\mathbf{r}(a)) \]
Independence of Path: \[ \int_C \mathbf{F} \cdot d\mathbf{r} = 0 \ \text{if} \ \mathbf{F} \ \text{is conservative} \]
Partial Derivatives
Total Differential: \[ dz = f_x , dx + f_y , dy \]
Chain Rule for Functions of One Independent Variable: \[ \frac{dz}{dt} = \frac{\partial z}{\partial x} \frac{dx}{dt} + \frac{\partial z}{\partial y} \frac{dy}{dt} \]
Chain Rule for Functions of Two Independent Variables: \[ \frac{\partial z}{\partial t} = \frac{\partial z}{\partial x} \frac{\partial x}{\partial t} + \frac{\partial z}{\partial y} \frac{\partial y}{\partial t} \]
Implicit Partial Differentiation: \[ \frac{\partial z}{\partial x} = -\frac{F_x}{F_z} \] \[ \frac{\partial z}{\partial y} = -\frac{F_y}{F_z} \]
Directional Derivative: \[ D_{\mathbf{u}} f = \nabla f \cdot \mathbf{u} \]
The Gradient of a Function: \[ \nabla f = \left( \frac{\partial f}{\partial x}, \frac{\partial f}{\partial y}, \frac{\partial f}{\partial z} \right) \]
Second Partials Test: \[ D = f_{xx} f_{yy} - (f_{xy})^2 \]
Extreme Value Theorem: \[ f \ \text{has a local maximum/minimum at} \ (a, b) \ \text{if} \ D > 0 \ \text{and} \ f_{xx} > 0 \ (\text{minimum}) \ \text{or} \ f_{xx} < 0 \ (\text{maximum}) \]
Lagrange Multipliers: \[ \nabla f = \lambda \nabla g \]
Iterated, Double, and Repeated Integrals
Rectangular Regions: \[ \int_a^b \int_c^d f(x, y) , dy , dx \]
Fubini's Theorem: \[ \int_a^b \int_c^d f(x, y) , dy , dx = \int_c^d \int_a^b f(x, y) , dx , dy \]
General Regions: \[ \int_{\text{Region}} f(x, y) , dA \]
Average Value of a Function Over a Region: \[ \frac{1}{\text{Area}} \int_{\text{Region}} f(x, y) , dA \]
Double Integrals in Polar Coordinates: \[ \int_a^b \int_{r_1(\theta)}^{r_2(\theta)} f(r, \theta) , r , dr , d\theta \]
Triple Integrals in Cylindrical Coordinates: \[ \int_a^b \int_{r_1(\theta)}^{r_2(\theta)} \int_{z_1(r, \theta)}^{z_2(r, \theta)} f(r, \theta, z) , r , dz , dr , d\theta \]
Triple Integrals in Spherical Coordinates: \[ \int_a^b \int_{0}^{\pi} \int_{0}^{2\pi} f(\rho, \phi, \theta) , \rho^2 \sin(\phi) , d\theta , d\phi , d\rho \]
Surface Area: \[ \iint_S |\mathbf{r}_u \times \mathbf{r}_v| , dA \]
Change of Variables for Double Integrals: \[ \iint_R f(x, y) , dx , dy = \iint_{R'} f(g(u, v), h(u, v)) \left| \frac{\partial(x, y)}{\partial(u, v)} \right| , du , dv \]
Triple Integrals: \[ \iiint_V f(x, y, z) , dV \]
Green's Theorem: \[ \oint_C (P , dx + Q , dy) = \iint_R \left( \frac{\partial Q}{\partial x} - \frac{\partial P}{\partial y} \right) dA \]
Alternate Forms of Green's Theorem: \[ \oint_C (L , dx + M , dy + N , dz) = \iint_R (\nabla \times \mathbf{F}) \cdot \mathbf{n} , dA \]
Parametric Surfaces: \[ \mathbf{r}(u, v) = \langle x(u, v), y(u, v), z(u, v) \rangle \]
Area of Parametric Surface: \[ \iint_D |\mathbf{r}_u \times \mathbf{r}_v| , du , dv \]
Surface Integrals: \[ \iint_S f(x, y, z) , dS \]
Flux Integrals: \[ \iint_S \mathbf{F} \cdot \mathbf{n} , dS \]
Divergence Theorem: \[ \iiint_V (\nabla \cdot \mathbf{F}) , dV = \iint_S \mathbf{F} \cdot \mathbf{n} , dS \]
Stokes' Theorem: \[ \iint_S (\nabla \times \mathbf{F}) \cdot \mathbf{n} , dS = \oint_C \mathbf{F} \cdot d\mathbf{r} \]
Surfaces
Ellipsoid: \[ \frac{x^2}{a^2} + \frac{y^2}{b^2} + \frac{z^2}{c^2} = 1 \]
Hyperboloid of One Sheet: \[ \frac{x^2}{a^2} + \frac{y^2}{b^2} - \frac{z^2}{c^2} = 1 \]
Hyperboloid of Two Sheets: \[ \frac{x^2}{a^2} - \frac{y^2}{b^2} - \frac{z^2}{c^2} = 1 \]
Elliptic Cone: \[ \frac{x^2}{a^2} + \frac{y^2}{b^2} - \frac{z^2}{c^2} = 0 \]
Elliptic Paraboloid: \[ \frac{x^2}{a^2} + \frac{y^2}{b^2} = z \]
Hyperbolic Paraboloid (saddle): \[ \frac{x^2}{a^2} - \frac{y^2}{b^2} = z \]
Coordinate System Conversions
Cylindrical to Rectangular: \[ x = r \cos \theta \] \[ y = r \sin \theta \] \[ z = z \]
Spherical to Rectangular: \[ x = \rho \sin \phi \cos \theta \] \[ y = \rho \sin \phi \sin \theta \] \[ z = \rho \cos \phi \]
Spherical to Cylindrical: \[ r = \rho \sin \phi \] \[ \theta = \theta \] \[ z = \rho \cos \phi \]
Cylindrical to Spherical: \[ \rho = \sqrt{r^2 + z^2} \] \[ \phi = \arctan \left( \frac{r}{z} \right) \] \[ \theta = \theta \]
Discrete Structures
Logic
Propositional Logic
Propositional logic deals with statements that are either true or false.
- Negation: If ( P ) is a proposition, then the negation of ( P ) is written as ( \neg P ).
- Conjunction: If ( P ) and ( Q ) are propositions, then the conjunction of ( P ) and ( Q ) is written as ( P \land Q ).
- Disjunction: If ( P ) and ( Q ) are propositions, then the disjunction of ( P ) and ( Q ) is written as ( P \lor Q ).
Examples: \[ \neg P \]
\[ P \land Q \]
\[ P \lor Q \]
Truth Tables
Truth tables are used to determine the truth value of logical expressions.
Example for ( P \land Q ):
( P ) | ( Q ) | ( P \land Q ) |
---|---|---|
T | T | T |
T | F | F |
F | T | F |
F | F | F |
Logical Laws
Category | Law Name | Logical Expression |
---|---|---|
Identity Laws | Identity for (\land) | \[ P \land \text{true} \equiv P \] |
Identity for (\lor) | \[ P \lor \text{false} \equiv P \] | |
Domination Laws | Domination for (\lor) | \[ P \lor \text{true} \equiv \text{true} \] |
Domination for (\land) | \[ P \land \text{false} \equiv \text{false} \] | |
Idempotent Laws | Idempotent for (\lor) | \[ P \lor P \equiv P \] |
Idempotent for (\land) | \[ P \land P \equiv P \] | |
Double Negation | \[ \neg (\neg P) \equiv P \] | |
Commutative Laws | Commutative for (\lor) | \[ P \lor Q \equiv Q \lor P \] |
Commutative for (\land) | \[ P \land Q \equiv Q \land P \] | |
Associative Laws | Associative for (\lor) | \[ (P \lor Q) \lor R \equiv P \lor (Q \lor R) \] |
Associative for (\land) | \[ (P \land Q) \land R \equiv P \land (Q \land R) \] | |
Distributive Laws | Distributive of (\land) over (\lor) | \[ P \land (Q \lor R) \equiv (P \land Q) \lor (P \land R) \] |
Distributive of (\lor) over (\land) | \[ P \lor (Q \land R) \equiv (P \lor Q) \land (P \lor R) \] | |
De Morgan's Laws | De Morgan for (\land) | \[ \neg (P \land Q) \equiv \neg P \lor \neg Q \] |
De Morgan for (\lor) | \[ \neg (P \lor Q) \equiv \neg P \land \neg Q \] | |
Absorption Laws | Absorption for (\lor) | \[ P \lor (P \land Q) \equiv P \] |
Absorption for (\land) | \[ P \land (P \lor Q) \equiv P \] | |
Negation Laws | Negation of (\lor) | \[ P \lor \neg P \equiv \text{true} \] |
Negation of (\land) | \[ P \land \neg P \equiv \text{false} \] | |
Propositional Laws | Contradiction Law | \[ \neg \text{true} \equiv \text{false} \] |
Tautology Law | \[ \neg \text{false} \equiv \text{true} \] | |
Implication Laws | Implication Definition | \[ P \to Q \equiv \neg P \lor Q \] |
Contrapositive | \[ P \to Q \equiv \neg Q \to \neg P \] | |
Implication Identity | \[ P \to P \equiv \text{true} \] | |
Exportation | \[ (P \to (Q \to R)) \equiv ((P \land Q) \to R) \] | |
Hypothetical Syllogism | \[ (P \to Q) \land (Q \to R) \to (P \to R) \] | |
Biconditional Laws | Biconditional Definition | \[ P \leftrightarrow Q \equiv (P \to Q) \land (Q \to P) \] |
Biconditional Commutative | \[ P \leftrightarrow Q \equiv Q \leftrightarrow P \] | |
Biconditional Associative | \[ (P \leftrightarrow Q) \leftrightarrow R \equiv P \leftrightarrow (Q \leftrightarrow R) \] | |
Biconditional Identity | \[ P \leftrightarrow P \equiv \text{true} \] | |
Quantifier Laws | Universal Instantiation | \[ (\forall x , P(x)) \to P(c) \] |
Existential Instantiation | \[ (\exists x , P(x)) \to P(c) \] | |
Universal Generalization | \[ P(c) \to (\forall x , P(x)) \] | |
Existential Generalization | \[ P(c) \to (\exists x , P(x)) \] | |
Negation of Universal Quantifier | \[ \neg (\forall x , P(x)) \equiv \exists x , \neg P(x) \] | |
Negation of Existential Quantifier | \[ \neg (\exists x , P(x)) \equiv \forall x , \neg P(x) \] | |
Set Laws | Union with Universal Set | \[ A \cup U = U \] |
Intersection with Universal Set | \[ A \cap U = A \] | |
Union with Empty Set | \[ A \cup \emptyset = A \] | |
Intersection with Empty Set | \[ A \cap \emptyset = \emptyset \] | |
Complement Laws | \[ A \cup A' = U \] | |
\[ A \cap A' = \emptyset \] | ||
Additional Laws | Distributive for Quantifiers | \[ \forall x (P(x) \land Q(x)) \equiv (\forall x , P(x)) \land (\forall x , Q(x)) \] |
\[ \exists x (P(x) \lor Q(x)) \equiv (\exists x , P(x)) \lor (\exists x , Q(x)) \] |
Sets
A set is a collection of distinct objects.
Set Operations
- Union: The union of sets ( A ) and ( B ) is written as ( A \cup B ).
- Intersection: The intersection of sets ( A ) and ( B ) is written as ( A \cap B ).
- Difference: The difference of sets ( A ) and ( B ) is written as ( A - B ).
Examples: \[ A \cup B \]
\[ A \cap B \]
\[ A - B \]
Cartesian Product
The Cartesian product of sets ( A ) and ( B ) is written as ( A \times B ).
Example: \[ A \times B = { (a, b) \mid a \in A, b \in B } \]
Functions
A function ( f ) from a set ( A ) to a set ( B ) is a rule that assigns to each element of ( A ) exactly one element of ( B ).
Function Notation
If ( f ) is a function from ( A ) to ( B ), we write ( f: A \to B ).
Example: \[ f(x) = x^2 \]
Types of Functions
- Injective (One-to-One): A function ( f ) is injective if ( f(a) = f(b) ) implies ( a = b ).
- Surjective (Onto): A function ( f ) is surjective if for every ( b \in B ), there exists ( a \in A ) such that ( f(a) = b ).
- Bijective: A function ( f ) is bijective if it is both injective and surjective.
Relations
A relation ( R ) from a set ( A ) to a set ( B ) is a subset of ( A \times B ).
Properties of Relations
- Reflexive: A relation ( R ) on a set ( A ) is reflexive if ( (a, a) \in R ) for all ( a \in A ).
- Symmetric: A relation ( R ) on a set ( A ) is symmetric if ( (a, b) \in R ) implies ( (b, a) \in R ).
- Transitive: A relation ( R ) on a set ( A ) is transitive if ( (a, b) \in R ) and ( (b, c) \in R ) imply ( (a, c) \in R ).
Combinatorics
Basic Principles
- Addition Principle: If there are ( n ) ways to do something and ( m ) ways to do another thing, and these two things cannot be done at the same time, then there are ( n + m ) ways to choose one of the actions.
- Multiplication Principle: If there are ( n ) ways to do something and ( m ) ways to do another thing after that, then there are ( n \times m ) ways to do both actions.
Permutations
A permutation of a set is an arrangement of its elements in a specific order.
Example for permutations of a set with ( n ) elements: \[ P(n) = n! \]
Combinations
A combination is a selection of items from a larger pool where the order does not matter.
Example for combinations of ( n ) elements taken ( r ) at a time: \[ C(n, r) = \frac{n!}{r!(n-r)!} \]
Graph Theory
Basic Definitions
- Graph: A graph ( G ) consists of a set of vertices ( V ) and a set of edges ( E ).
- Directed Graph (Digraph): A graph where edges have a direction.
Types of Graphs
- Complete Graph: A graph in which there is a unique edge between every pair of vertices.
- Bipartite Graph: A graph whose vertices can be divided into two disjoint sets such that every edge connects a vertex in one set to a vertex in the other set.
Graph Representation
- Adjacency Matrix: A square matrix used to represent a finite graph.
- Adjacency List: A collection of lists or sets used to represent a graph.
Example Graph Theory Problems
Eulerian Path
An Eulerian path in a graph is a path that visits every edge exactly once.
Hamiltonian Path
A Hamiltonian path in a graph is a path that visits every vertex exactly once.
[ \text{Example Graph Theory Equations:} ]
Euler's formula for planar graphs: \[ V - E + F = 2 \]
This content covers the basics of discrete structures in computer science. Each topic includes definitions, examples, and relevant equations formatted using MathJax for mdBook.
Probability Theory
Basic Concepts
Sample Space ((S)): The set of all possible outcomes of a random experiment. \[ S = {s_1, s_2, \ldots, s_n} \]
Event ((E)): A subset of the sample space (S). \[ E \subseteq S \]
Probability of an Event ((P(E))): \[ P(E) = \frac{|E|}{|S|} ] where (|E|) is the number of outcomes in (E) and (|S|) is the number of outcomes in (S).
Axioms of Probability
- Non-negativity: \[ P(E) \ge 0 \]
- Normalization: \[ P(S) = 1 \]
- Additivity: For any two mutually exclusive events (A) and (B), \[ P(A \cup B) = P(A) + P(B) \]
Conditional Probability
Conditional Probability ((P(A|B))): The probability of event (A) given that event (B) has occurred. \[ P(A|B) = \frac{P(A \cap B)}{P(B)} ] provided (P(B) > 0).
Bayes' Theorem
Bayes' Theorem: \[ P(A|B) = \frac{P(B|A) P(A)}{P(B)} \]
Independent Events
Independence: Two events (A) and (B) are independent if \[ P(A \cap B) = P(A) P(B) \]
Random Variables
Random Variable ((X)): A function that assigns a numerical value to each outcome in the sample space. \[ X: S \to \mathbb{R} \]
Discrete Random Variable: A random variable that can take on a countable number of values.
Continuous Random Variable: A random variable that can take on an uncountable number of values.
Probability Distributions
Probability Mass Function (PMF) for Discrete Random Variables: \[ p_X(x) = P(X = x) \]
Probability Density Function (PDF) for Continuous Random Variables: \[ f_X(x) ] such that \[ P(a \le X \le b) = \int_a^b f_X(x) , dx \]
Cumulative Distribution Function (CDF): \[ F_X(x) = P(X \le x) \]
Expectation and Variance
Expectation (Mean) of a Discrete Random Variable: \[ \mathbb{E}[X] = \sum_x x p_X(x) \]
Expectation (Mean) of a Continuous Random Variable: \[ \mathbb{E}[X] = \int_{-\infty}^{\infty} x f_X(x) , dx \]
Variance: \[ \text{Var}(X) = \mathbb{E}[(X - \mathbb{E}[X])^2] \] \[ \text{Var}(X) = \mathbb{E}[X^2] - (\mathbb{E}[X])^2 \]
Standard Deviation: \[ \sigma_X = \sqrt{\text{Var}(X)} \]
Common Discrete Distributions
Bernoulli Distribution: \[ P(X = 1) = p, \quad P(X = 0) = 1 - p \] \[ \mathbb{E}[X] = p \] \[ \text{Var}(X) = p(1 - p) \]
Binomial Distribution: \[ P(X = k) = \binom{n}{k} p^k (1 - p)^{n - k} \] \[ \mathbb{E}[X] = np \] \[ \text{Var}(X) = np(1 - p) \]
Geometric Distribution: \[ P(X = k) = (1 - p)^{k - 1} p \] \[ \mathbb{E}[X] = \frac{1}{p} \] \[ \text{Var}(X) = \frac{1 - p}{p^2} \]
Poisson Distribution: \[ P(X = k) = \frac{\lambda^k e^{-\lambda}}{k!} \] \[ \mathbb{E}[X] = \lambda \] \[ \text{Var}(X) = \lambda \]
Common Continuous Distributions
Uniform Distribution: \[ f_X(x) = \begin{cases} \frac{1}{b - a}, & a \le x \le b \ 0, & \text{otherwise} \end{cases} \] \[ \mathbb{E}[X] = \frac{a + b}{2} \] \[ \text{Var}(X) = \frac{(b - a)^2}{12} \]
Exponential Distribution: \[ f_X(x) = \begin{cases} \lambda e^{-\lambda x}, & x \ge 0 \ 0, & \text{otherwise} \end{cases} \] \[ \mathbb{E}[X] = \frac{1}{\lambda} \] \[ \text{Var}(X) = \frac{1}{\lambda^2} \]
Normal (Gaussian) Distribution: \[ f_X(x) = \frac{1}{\sqrt{2\pi\sigma^2}} e^{-\frac{(x - \mu)^2}{2\sigma^2}} \] \[ \mathbb{E}[X] = \mu \] \[ \text{Var}(X) = \sigma^2 \]
Joint Distributions
Joint Probability Mass Function (Discrete): \[ p_{X,Y}(x, y) = P(X = x, Y = y) \]
Joint Probability Density Function (Continuous): \[ f_{X,Y}(x, y) \]
Marginal Distribution: \[ p_X(x) = \sum_y p_{X,Y}(x, y) \] \[ f_X(x) = \int_{-\infty}^{\infty} f_{X,Y}(x, y) , dy \]
Conditional Distributions
Conditional PMF: \[ p_{X|Y}(x|y) = \frac{p_{X,Y}(x, y)}{p_Y(y)} \]
Conditional PDF: \[ f_{X|Y}(x|y) = \frac{f_{X,Y}(x, y)}{f_Y(y)} \]
Covariance and Correlation
Covariance: \[ \text{Cov}(X, Y) = \mathbb{E}[(X - \mathbb{E}[X])(Y - \mathbb{E}[Y])] \] \[ \text{Cov}(X, Y) = \mathbb{E}[XY] - \mathbb{E}[X]\mathbb{E}[Y] \]
Correlation Coefficient: \[ \rho_{X,Y} = \frac{\text{Cov}(X, Y)}{\sigma_X \sigma_Y} \]
Properties:
- ( \text{Cov}(X, Y) = 0 ) implies ( X ) and ( Y ) are uncorrelated.
- ( \rho_{X,Y} ) ranges from (-1) to (1).
Moment Generating Functions
Moment Generating Function (MGF): \[ M_X(t) = \mathbb{E}[e^{tX}] \]
Properties:
- The ( n )-th moment of ( X ) is ( M_X^{(n)}(0) ).
- If ( M_X(t) = M_Y(t) ), then ( X ) and ( Y ) have the same distribution.
Law of Large Numbers
Weak Law of Large Numbers: \[ \overline{X}n = \frac{1}{n} \sum{i=1}^n X_i \to \mathbb{E}[X] \quad \text{in probability as} \quad n \to \infty \]
Strong Law of Large Numbers: \[ \overline{X}n = \frac{1}{n} \sum{i=1}^n X_i \to \mathbb{E}[X] \quad \text{almost surely as} \quad n \to \infty \]
Central Limit Theorem
Central Limit Theorem: If ( X_1, X_2, \ldots, X_n ) are i.i.d. random variables with mean ( \mu ) and variance ( \sigma^2 ), then \[ \frac{\overline{X}_n - \mu}{\sigma / \sqrt{n}} \to N(0, 1) \quad \text{as} \quad n \to \infty \]
Markov and Chebyshev Inequalities
Markov's Inequality: For a non-negative random variable ( X ) and ( a > 0 ), \[ P(X \ge a) \le \frac{\mathbb{E}[X]}{a} \]
Chebyshev's Inequality: For any random variable ( X ) with mean ( \mu ) and variance ( \sigma^2 ), \[ P(|X - \mu| \ge k\sigma) \le \frac{1}{k^2} \]
Information Theory
Entropy (Discrete): \[ H(X) = -\sum_{x} p(x) \log p(x) \]
Joint Entropy: \[ H(X, Y) = -\sum_{x,y} p(x, y) \log p(x, y) \]
Conditional Entropy: \[ H(X|Y) = -\sum_{x,y} p(x, y) \log p(x|y) \]
Mutual Information: \[ I(X;Y) = H(X) + H(Y) - H(X, Y) \] \[ I(X;Y) = \sum_{x,y} p(x, y) \log \left( \frac{p(x, y)}{p(x) p(y)} \right) \]
Kullback-Leibler Divergence: \[ D_{KL}(P || Q) = \sum_{x} p(x) \log \left( \frac{p(x)}{q(x)} \right) \]
Common Transformations
Linear Transformation: If ( Y = aX + b ), then \[ \mathbb{E}[Y] = a\mathbb{E}[X] + b \] \[ \text{Var}(Y) = a^2 \text{Var}(X) \]
Sum of Independent Random Variables: If ( X ) and ( Y ) are independent, then \[ \mathbb{E}[X + Y] = \mathbb{E}[X] + \mathbb{E}[Y] \] \[ \text{Var}(X + Y) = \text{Var}(X) + \text{Var}(Y) \]
Convolution of Two Independent Random Variables: The PDF of the sum ( Z = X + Y ) is given by \[ f_Z(z) = \int_{-\infty}^{\infty} f_X(x) f_Y(z - x) , dx \]
Important Results
Law of Total Probability: \[ P(A) = \sum_{i} P(A|B_i) P(B_i) \] where ( {B_i} ) is a partition of the sample space.
Bayes' Theorem (General Form): \[ P(B_i|A) = \frac{P(A|B_i) P(B_i)}{\sum_{j} P(A|B_j) P(B_j)} \]
Poisson Process: A counting process with rate ( \lambda ) has:
- Interarrival times ( T_i ) that are i.i.d. exponential with parameter ( \lambda ).
- Number of events in time ( t ) is Poisson distributed with parameter ( \lambda t ).
Moment Generating Function (MGF): If ( X ) has an MGF ( M_X(t) ), then the ( n )-th moment is \[ \mathbb{E}[X^n] = M_X^{(n)}(0) \]
Characteristic Function: The characteristic function of ( X ) is \[ \phi_X(t) = \mathbb{E}[e^{itX}] \] and it uniquely determines the distribution of ( X ).
Stochastic Processes
Definition: A stochastic process is a collection of random variables ( {X(t) : t \in T} ) indexed by ( T ).
Markov Process: A stochastic process where the future is independent of the past given the present.
Martingale: A stochastic process ( {X_t} ) is a martingale if \[ \mathbb{E}[X_{t+1} | \mathcal{F}_t] = X_t \]
Brownian Motion: A continuous-time stochastic process ( {B(t) : t \ge 0} ) with:
- ( B(0) = 0 ).
- Independent increments.
- ( B(t) - B(s) \sim N(0, t-s) ) for ( 0 \le s < t ).
- Continuous paths.
Central Limit Theorem (CLT) for IID Random Variables
CLT Statement: If ( X_1, X_2, \ldots, X_n ) are i.i.d. random variables with mean ( \mu ) and variance ( \sigma^2 ), then \[ \frac{\overline{X}_n - \mu}{\sigma / \sqrt{n}} \to N(0, 1) \quad \text{as} \quad n \to \infty \]
Multivariate Central Limit Theorem: If ( \mathbf{X}_1, \mathbf{X}_2, \ldots, \mathbf{X}_n ) are i.i.d. random vectors with mean vector ( \mathbf{\mu} ) and covariance matrix ( \Sigma ), then \[ \sqrt{n}(\overline{\mathbf{X}}_n - \mathbf{\mu}) \to N(\mathbf{0}, \Sigma) \quad \text{as} \quad n \to \infty \]
Law of Large Numbers (LLN)
Weak Law of Large Numbers (WLLN): For i.i.d. random variables ( X_1, X_2, \ldots, X_n ) with mean ( \mu ), \[ \overline{X}n = \frac{1}{n} \sum{i=1}^n X_i \to \mu \quad \text{in probability as} \quad n \to \infty \]
Strong Law of Large Numbers (SLLN): For i.i.d. random variables ( X_1, X_2, \ldots, X_n ) with mean ( \mu ), \[ \overline{X}n = \frac{1}{n} \sum{i=1}^n X_i \to \mu \quad \text{almost surely as} \quad n \to \infty \]
Convergence in Probability and Distribution
Convergence in Probability: A sequence of random variables ( X_n ) converges in probability to ( X ) if for all ( \epsilon > 0 ), \[ \lim_{n \to \infty} P(|X_n - X| \ge \epsilon) = 0 \]
Convergence in Distribution: A sequence of random variables ( X_n ) converges in distribution to ( X ) if for all continuity points ( x ) of ( F_X(x) ), \[ \lim_{n \to \infty} F_{X_n}(x) = F_X(x) \]
Moment Generating Functions (MGF) and Characteristic Functions
MGF of Sum of Independent Random Variables: If ( X ) and ( Y ) are independent, \[ M_{X+Y}(t) = M_X(t) M_Y(t) \]
Characteristic Function of Sum of Independent Random Variables: If ( X ) and ( Y ) are independent, \[ \phi_{X+Y}(t) = \phi_X(t) \phi_Y(t) \]
Inequalities and Bounds
Jensen's Inequality: For a convex function ( \phi ) and random variable ( X ), \[ \phi(\mathbb{E}[X]) \le \mathbb{E}[\phi(X)] \]
Cauchy-Schwarz Inequality: For any random variables ( X ) and ( Y ), \[ (\mathbb{E}[XY])^2 \le \mathbb{E}[X^2] \mathbb{E}[Y^2] \]
Markov's Inequality: For a non-negative random variable ( X ) and ( a > 0 ), \[ P(X \ge a) \le \frac{\mathbb{E}[X]}{a} \]
Chebyshev's Inequality: For any random variable ( X ) with mean ( \mu ) and variance ( \sigma^2 ), \[ P(|X - \mu| \ge k\sigma) \le \frac{1}{k^2} \]
Bayesian Inference
Posterior Distribution: \[ P(\theta|X) = \frac{P(X|\theta) P(\theta)}{P(X)} \]
Maximum A Posteriori (MAP) Estimate: \[ \hat{\theta}{MAP} = \arg\max\theta P(\theta|X) \]
Bayesian Updating: Given a prior ( P(\theta) ) and likelihood ( P(X|\theta) ), the posterior is updated as \[ P(\theta|X) \propto P(X|\theta) P(\theta) \]
Hypothesis Testing
Null Hypothesis ((H_0)): The hypothesis that there is no effect or no difference.
Alternative Hypothesis ((H_1)): The hypothesis that there is an effect or a difference.
Test Statistic: A function of the sample data used to decide whether to reject (H_0).
p-Value: The probability of obtaining a test statistic at least as extreme as the one observed, assuming (H_0) is true.
Type I Error: Rejecting (H_0) when it is true (false positive).
Type II Error: Failing to reject (H_0) when it is false (false negative).
Significance Level ((\alpha)): The probability of making a Type I error.
Power: The probability of correctly rejecting (H_0) (1 - probability of Type II error).
Confidence Intervals
Confidence Interval for Mean ((\mu)): For a normal distribution with known variance ( \sigma^2 ), \[ \left( \overline{X} - z_{\alpha/2} \frac{\sigma}{\sqrt{n}}, \overline{X} + z_{\alpha/2} \frac{\sigma}{\sqrt{n}} \right) \] where ( z_{\alpha/2} ) is the critical value from the standard normal distribution.
Confidence Interval for Proportion ((p)): \[ \left( \hat{p} - z_{\alpha/2} \sqrt{\frac{\hat{p}(1 - \hat{p})}{n}}, \hat{p} + z_{\alpha/2} \sqrt{\frac{\hat{p}(1 - \hat{p})}{n}} \right) \] where ( \hat{p} ) is the sample proportion.
Regression Analysis
Simple Linear Regression: \[ Y = \beta_0 + \beta_1 X + \epsilon \]
Least Squares Estimates: \[ \hat{\beta}_1 = \frac{\sum (X_i - \overline{X})(Y_i - \overline{Y})}{\sum (X_i - \overline{X})^2} \] \[ \hat{\beta}_0 = \overline{Y} - \hat{\beta}_1 \overline{X} \]
Coefficient of Determination ((R^2)): \[ R^2 = \frac{\sum (\hat{Y}_i - \overline{Y})^2}{\sum (Y_i - \overline{Y})^2} \]
Multiple Linear Regression: \[ Y = \beta_0 + \beta_1 X_1 + \beta_2 X_2 + \cdots + \beta_p X_p + \epsilon \]
Generalized Least Squares Estimates: \[ \hat{\beta} = (X^T X)^{-1} X^T Y \]
Common Probability Distributions
Bernoulli Distribution: \[ P(X = 1) = p, \quad P(X = 0) = 1 - p \] \[ \mathbb{E}[X] = p \] \[ \text{Var}(X) = p(1 - p) \]
Binomial Distribution: \[ P(X = k) = \binom{n}{k} p^k (1 - p)^{n - k} \] \[ \mathbb{E}[X] = np \] \[ \text{Var}(X) = np(1 - p) \]
Geometric Distribution: \[ P(X = k) = (1 - p)^{k - 1} p \] \[ \mathbb{E}[X] = \frac{1}{p} \] \[ \text{Var}(X) = \frac{1 - p}{p^2} \]
Poisson Distribution: \[ P(X = k) = \frac{\lambda^k e^{-\lambda}}{k!} \] \[ \mathbb{E}[X] = \lambda \] \[ \text{Var}(X) = \lambda \]
Uniform Distribution: \[ f_X(x) = \begin{cases} \frac{1}{b - a}, & a \le x \le b \ 0, & \text{otherwise} \end{cases} \] \[ \mathbb{E}[X] = \frac{a + b}{2} \] \[ \text{Var}(X) = \frac{(b - a)^2}{12} \]
Exponential Distribution: \[ f_X(x) = \begin{cases} \lambda e^{-\lambda x}, & x \ge 0 \ 0, & \text{otherwise} \end{cases} \] \[ \mathbb{E}[X] = \frac{1}{\lambda} \] \[ \text{Var}(X) = \frac{1}{\lambda^2} \]
Normal (Gaussian) Distribution: \[ f_X(x) = \frac{1}{\sqrt{2\pi\sigma^2}} e^{-\frac{(x - \mu)^2}{2\sigma^2}} \] \[ \mathbb{E}[X] = \mu \] \[ \text{Var}(X) = \sigma^2 \]
Gamma Distribution: \[ f_X(x) = \frac{\lambda^k x^{k-1} e^{-\lambda x}}{\Gamma(k)}, \quad x \ge 0 \] \[ \mathbb{E}[X] = \frac{k}{\lambda} \] \[ \text{Var}(X) = \frac{k}{\lambda^2} \]
Beta Distribution: \[ f_X(x) = \frac{x^{\alpha-1} (1 - x)^{\beta-1}}{B(\alpha, \beta)}, \quad 0 \le x \le 1 \] \[ \mathbb{E}[X] = \frac{\alpha}{\alpha + \beta} \] \[ \text{Var}(X) = \frac{\alpha\beta}{(\alpha + \beta)^2 (\alpha + \beta + 1)} \]
Chi-Square Distribution: \[ f_X(x) = \frac{1}{2^{k/2} \Gamma(k/2)} x^{k/2 - 1} e^{-x/2}, \quad x \ge 0 \] \[ \mathbb{E}[X] = k \] \[ \text{Var}(X) = 2k \]
Student's t-Distribution: \[ f_X(x) = \frac{\Gamma\left(\frac{\nu+1}{2}\right)}{\sqrt{\nu \pi} \Gamma\left(\frac{\nu}{2}\right)} \left(1 + \frac{x^2}{\nu}\right)^{-(\nu+1)/2} \] \[ \mathbb{E}[X] = 0 \quad \text{for} \quad \nu > 1 \] \[ \text{Var}(X) = \frac{\nu}{\nu-2} \quad \text{for} \quad \nu > 2 \]
Multivariate Normal Distribution: \[ f_X(\mathbf{x}) = \frac{1}{(2\pi)^{k/2} |\Sigma|^{1/2}} \exp \left( -\frac{1}{2} (\mathbf{x} - \mathbf{\mu})^T \Sigma^{-1} (\mathbf{x} - \mathbf{\mu}) \right) \] where ( \mathbf{\mu} ) is the mean vector and ( \Sigma ) is the covariance matrix.
Multinomial Distribution: \[ P(X_1 = x_1, X_2 = x_2, \ldots, X_k = x_k) = \frac{n!}{x_1! x_2! \cdots x_k!} p_1^{x_1} p_2^{x_2} \cdots p_k^{x_k} \] where ( X_i ) is the count of the (i)-th outcome in (n) trials, and ( p_i ) is the probability of the (i)-th outcome.
Negative Binomial Distribution: \[ P(X = k) = \binom{k+r-1}{r-1} p^r (1 - p)^k \] \[ \mathbb{E}[X] = \frac{r(1 - p)}{p} \] \[ \text{Var}(X) = \frac{r(1 - p)}{p^2} \]
Hypergeometric Distribution: \[ P(X = k) = \frac{\binom{K}{k} \binom{N-K}{n-k}}{\binom{N}{n}} \] where ( X ) is the number of successes in (n) draws from a population of (N) with (K) successes.
Linear Algebra Formulas
Vectors and Vector Spaces
Vector Definition: \[ \mathbf{v} = \begin{pmatrix} v_1 \ v_2 \ \vdots \ v_n \end{pmatrix} \]
Vector Addition: \[ \mathbf{u} + \mathbf{v} = \begin{pmatrix} u_1 \ u_2 \ \vdots \ u_n \end{pmatrix} + \begin{pmatrix} v_1 \ v_2 \ \vdots \ v_n \end{pmatrix} = \begin{pmatrix} u_1 + v_1 \ u_2 + v_2 \ \vdots \ u_n + v_n \end{pmatrix} \]
Scalar Multiplication: \[ c \mathbf{v} = c \begin{pmatrix} v_1 \ v_2 \ \vdots \ v_n \end{pmatrix} = \begin{pmatrix} c v_1 \ c v_2 \ \vdots \ c v_n \end{pmatrix} \]
Dot Product: \[ \mathbf{u} \cdot \mathbf{v} = u_1 v_1 + u_2 v_2 + \cdots + u_n v_n \] \[ \mathbf{u} \cdot \mathbf{v} = |\mathbf{u}| |\mathbf{v}| \cos \theta \]
Cross Product (in ( \mathbb{R}^3 )): \[ \mathbf{u} \times \mathbf{v} = \begin{vmatrix} \mathbf{i} & \mathbf{j} & \mathbf{k} \\ u_1 & u_2 & u_3 \\ v_1 & v_2 & v_3 \end{vmatrix} \] \[ |\mathbf{u} \times \mathbf{v}| = |\mathbf{u}| |\mathbf{v}| \sin \theta \]
Vector Space Axioms:
- Closure under addition
- Closure under scalar multiplication
- Associativity of addition
- Commutativity of addition
- Existence of additive identity
- Existence of additive inverse
- Distributivity of scalar multiplication over vector addition
- Distributivity of scalar multiplication over field addition
- Compatibility of scalar multiplication with field multiplication
- Existence of multiplicative identity
Subspace: A subset (W) of a vector space (V) that is itself a vector space under the same operations.
Matrices
Matrix Definition: \[ A = \begin{pmatrix} a_{11} & a_{12} & \cdots & a_{1n} \ a_{21} & a_{22} & \cdots & a_{2n} \ \vdots & \vdots & \ddots & \vdots \ a_{m1} & a_{m2} & \cdots & a_{mn} \end{pmatrix} \]
Matrix Addition: \[ A + B = \begin{pmatrix} a_{11} + b_{11} & a_{12} + b_{12} & \cdots & a_{1n} + b_{1n} \ a_{21} + b_{21} & a_{22} + b_{22} & \cdots & a_{2n} + b_{2n} \ \vdots & \vdots & \ddots & \vdots \ a_{m1} + b_{m1} & a_{m2} + b_{m2} & \cdots & a_{mn} + b_{mn} \end{pmatrix} \]
Scalar Multiplication: \[ cA = \begin{pmatrix} c a_{11} & c a_{12} & \cdots & c a_{1n} \ c a_{21} & c a_{22} & \cdots & c a_{2n} \ \vdots & \vdots & \ddots & \vdots \ c a_{m1} & c a_{m2} & \cdots & c a_{mn} \end{pmatrix} \]
Matrix Multiplication: \[ AB = \begin{pmatrix} a_{11} & a_{12} & \cdots & a_{1n} \ a_{21} & a_{22} & \cdots & a_{2n} \ \vdots & \vdots & \ddots & \vdots \ a_{m1} & a_{m2} & \cdots & a_{mn} \end{pmatrix} \begin{pmatrix} b_{11} & b_{12} & \cdots & b_{1p} \ b_{21} & b_{22} & \cdots & b_{2p} \ \vdots & \vdots & \ddots & \vdots \ b_{n1} & b_{n2} & \cdots & b_{np} \end{pmatrix} \]
Transpose: \[ A^T = \begin{pmatrix} a_{11} & a_{21} & \cdots & a_{m1} \ a_{12} & a_{22} & \cdots & a_{m2} \ \vdots & \vdots & \ddots & \vdots \ a_{1n} & a_{2n} & \cdots & a_{mn} \end{pmatrix} \]
Determinant (for a 2x2 matrix): \[ \det(A) = \begin{vmatrix} a & b \ c & d \end{vmatrix} = ad - bc \]
Inverse (for a 2x2 matrix): \[ A^{-1} = \frac{1}{\det(A)} \begin{pmatrix} d & -b \ -c & a \end{pmatrix} \]
Properties of Determinants:
- ( \det(A^T) = \det(A) )
- ( \det(AB) = \det(A) \det(B) )
- ( \det(A^{-1}) = \frac{1}{\det(A)} )
Systems of Linear Equations
General Form: \[ A \mathbf{x} = \mathbf{b} \]
Augmented Matrix: \[ \left( A | \mathbf{b} \right) \]
Gaussian Elimination:
- Form the augmented matrix.
- Use row operations to reach row-echelon form.
- Perform back-substitution to find the solution.
Row Operations:
- Swap two rows.
- Multiply a row by a non-zero scalar.
- Add or subtract a multiple of one row to/from another row.
Eigenvalues and Eigenvectors
Eigenvalue Equation: \[ A \mathbf{v} = \lambda \mathbf{v} \]
Characteristic Polynomial: \[ \det(A - \lambda I) = 0 \]
Solving for Eigenvalues: Find the roots of the characteristic polynomial.
Solving for Eigenvectors: Solve \( (A - \lambda I) \mathbf{v} = 0 \) for each eigenvalue \( \lambda \).
Diagonalization
Diagonalization of a Matrix: A matrix ( A ) is diagonalizable if there exists a matrix ( P ) such that \[ P^{-1} A P = D \] where ( D ) is a diagonal matrix.
Steps to Diagonalize a Matrix:
- Find the eigenvalues of ( A ).
- Find the eigenvectors of ( A ).
- Form the matrix ( P ) using the eigenvectors as columns.
- Form the diagonal matrix ( D ) using the eigenvalues.
Inner Product and Orthogonality
Inner Product (Dot Product): \[ \langle \mathbf{u}, \mathbf{v} \rangle = \mathbf{u} \cdot \mathbf{v} = u_1 v_1 + u_2 v_2 + \cdots + u_n v_n \]
Norm (Length) of a Vector: \[ |\mathbf{v}| = \sqrt{\langle \mathbf{v}, \mathbf{v} \rangle} \]
Orthogonality: Two vectors ( \mathbf{u} ) and ( \mathbf{v} ) are orthogonal if \[ \langle \mathbf{u}, \mathbf{v} \rangle = 0 \]
Orthogonal Projection: \[ \text{proj}_{\mathbf{u}} \mathbf{v} = \frac{\langle \mathbf{v}, \mathbf{u} \rangle}{\langle \mathbf{u}, \mathbf{u} \rangle} \mathbf{u} \]
Gram-Schmidt Process: To orthogonalize a set of vectors ( {\mathbf{v}_1, \mathbf{v}_2, \ldots, \mathbf{v}_n} ):
- Set ( \mathbf{u}_1 = \mathbf{v}_1 ).
- For ( k = 2 ) to ( n ): \[ \mathbf{u}k = \mathbf{v}k - \sum{j=1}^{k-1} \text{proj}{\mathbf{u}_j} \mathbf{v}_k \]
- Normalize ( \mathbf{u}_k ) to obtain orthonormal vectors ( \mathbf{e}_k = \frac{\mathbf{u}_k}{|\mathbf{u}_k|} ).
Linear Transformations
Definition: A linear transformation ( T ) from ( \mathbb{R}^n ) to ( \mathbb{R}^m ) is a function that satisfies:
- ( T(\mathbf{u} + \mathbf{v}) = T(\mathbf{u}) + T(\mathbf{v}) )
- ( T(c \mathbf{u}) = c T(\mathbf{u}) )
Matrix Representation: If ( T(\mathbf{x}) = A \mathbf{x} ), then ( A ) is the matrix representation of ( T ).
Kernel and Image:
- Kernel: ( \ker(T) = {\mathbf{x} \in \mathbb{R}^n : T(\mathbf{x}) = \mathbf{0}} )
- Image: ( \text{Im}(T) = {T(\mathbf{x}) : \mathbf{x} \in \mathbb{R}^n} )
Rank-Nullity Theorem: \[ \text{dim}(\ker(T)) + \text{dim}(\text{Im}(T)) = n \]
Determinants and Inverses
Determinant (for an ( n \times n ) matrix): \[ \det(A) = \sum_{j=1}^n (-1)^{i+j} a_{ij} \det(A_{ij}) \] where ( A_{ij} ) is the ((n-1) \times (n-1)) matrix obtained by deleting the (i)-th row and (j)-th column from ( A ).
Properties of Inverses:
- ( (A^{-1})^{-1} = A )
- ( (AB)^{-1} = B^{-1}A^{-1} )
- ( (A^T)^{-1} = (A^{-1})^T \]
Cramer's Rule: For a system ( A \mathbf{x} = \mathbf{b} ) with ( n ) equations and ( n ) unknowns: \[ x_i = \frac{\det(A_i)}{\det(A)} \] where ( A_i ) is the matrix obtained by replacing the (i)-th column of ( A ) with ( \mathbf{b} ).
Special Matrices
Identity Matrix: \[ I = \begin{pmatrix} 1 & 0 & \cdots & 0 \ 0 & 1 & \cdots & 0 \ \vdots & \vdots & \ddots & \vdots \ 0 & 0 & \cdots & 1 \end{pmatrix} \]
Diagonal Matrix: \[ D = \begin{pmatrix} d_1 & 0 & \cdots & 0 \ 0 & d_2 & \cdots & 0 \ \vdots & \vdots & \ddots & \vdots \ 0 & 0 & \cdots & d_n \end{pmatrix} \]
Symmetric Matrix: \[ A = A^T \]
Orthogonal Matrix: \[ A^T A = A A^T = I \]
Positive Definite Matrix: A symmetric matrix ( A ) is positive definite if ( \mathbf{x}^T A \mathbf{x} > 0 ) for all non-zero vectors ( \mathbf{x} ).
Quadratic Forms
Quadratic Form: \[ Q(\mathbf{x}) = \mathbf{x}^T A \mathbf{x} \] where ( A ) is a symmetric matrix.
Classification of Quadratic Forms:
- Positive definite: All eigenvalues of ( A ) are positive.
- Negative definite: All eigenvalues of ( A ) are negative.
- Indefinite: Eigenvalues of ( A ) are both positive and negative.
- Positive semidefinite: All eigenvalues of ( A ) are non-negative.
- Negative semidefinite: All eigenvalues of ( A ) are non-positive.
Singular Value Decomposition (SVD)
SVD Definition: For any ( m \times n ) matrix ( A ), there exist orthogonal matrices ( U ) and ( V ) such that \[ A = U \Sigma V^T \] where ( \Sigma ) is a diagonal matrix with non-negative real numbers on the diagonal (singular values).
Properties of SVD:
- ( U ) and ( V ) are orthogonal matrices.
- ( \Sigma ) contains the singular values of ( A ).
Orthogonal Projections and Least Squares
Orthogonal Projection onto a Subspace ( W ): \[ \mathbf{p} = A (A^T A)^{-1} A^T \mathbf{b} \] where ( A ) is a matrix whose columns form a basis for ( W ).
Least Squares Solution: To solve ( A \mathbf{x} \approx \mathbf{b} ): \[ \mathbf{x} = (A^T A)^{-1} A^T \mathbf{b} \]
Eigenvalues and Eigenvectors
Eigenvalue Equation: \[ A \mathbf{v} = \lambda \mathbf{v} \]
Characteristic Polynomial: \[ \det(A - \lambda I) = 0 \]
Solving for Eigenvalues: Find the roots of the characteristic polynomial.
Solving for Eigenvectors: Solve \( (A - \lambda I) \mathbf{v} = 0 \) for each eigenvalue ( \lambda ).
Jordan Canonical Form
Jordan Form: A matrix ( A ) is similar to a Jordan matrix ( J ) if there exists an invertible matrix ( P ) such that \[ A = P J P^{-1} \]
Jordan Block: \[ J_k(\lambda) = \begin{pmatrix} \lambda & 1 & 0 & \cdots & 0 \ 0 & \lambda & 1 & \cdots & 0 \ \vdots & \vdots & \vdots & \ddots & \vdots \ 0 & 0 & 0 & \cdots & \lambda \end{pmatrix} \]
Steps to Find Jordan Form:
- Find the eigenvalues of ( A ).
- Find the eigenvectors and generalized eigenvectors of ( A ).
- Form the Jordan blocks.
- Form the matrix ( P ) using the eigenvectors and generalized eigenvectors.
Complex Eigenvalues and Eigenvectors
Complex Eigenvalue Equation: \[ A \mathbf{v} = \lambda \mathbf{v} \]
Complex Characteristic Polynomial: \[ \det(A - \lambda I) = 0 \]
Solving for Complex Eigenvalues: Find the complex roots of the characteristic polynomial.
Solving for Complex Eigenvectors: Solve \( (A - \lambda I) \mathbf{v} = 0 \) for each complex eigenvalue ( \lambda ).
Forming the Complex Matrix: Combine the real and imaginary parts of the eigenvectors to form a complex matrix.
Properties of Complex Eigenvalues:
- Complex eigenvalues occur in conjugate pairs.
- The eigenvectors corresponding to complex eigenvalues are also complex.
Matrix Exponentials
Definition: The matrix exponential of ( A ) is defined as \[ e^A = \sum_{k=0}^\infty \frac{A^k}{k!} \]
Properties:
- ( e^{A+B} = e^A e^B ) if ( AB = BA ).
- ( e^{tA} ) solves the differential equation ( \mathbf{x}' = A \mathbf{x} ) with initial condition ( \mathbf{x}(0) = \mathbf{x}_0 ).
Systems of Linear Differential Equations
General Form: \[ \mathbf{x}' = A \mathbf{x} \]
Solution Using Eigenvalues and Eigenvectors:
- Find the eigenvalues and eigenvectors of ( A ).
- Form the general solution using the eigenvalues and eigenvectors.
- Solve for the constants using the initial conditions.
Solution Using Matrix Exponentials: \[ \mathbf{x}(t) = e^{At} \mathbf{x}_0 \]
Diagonalizable Case: If ( A ) is diagonalizable, then \[ e^{At} = P e^{Dt} P^{-1} \] where ( D ) is a diagonal matrix containing the eigenvalues of ( A ).
Non-Diagonalizable Case: If ( A ) is not diagonalizable, use the Jordan form to compute the matrix exponential.
Differential Equations Formulas
First-Order Differential Equations
Linear First-Order Differential Equation: \[ \frac{dy}{dx} + P(x)y = Q(x) \]
Solution of Linear First-Order Differential Equation: \[ y(x) = e^{-\int P(x) , dx} \left( \int Q(x) e^{\int P(x) , dx} , dx + C \right) \]
Separable Differential Equation: \[ \frac{dy}{dx} = g(y)h(x) \]
Solution of Separable Differential Equation: \[ \int \frac{1}{g(y)} , dy = \int h(x) , dx + C \]
Exact Differential Equation: \[ M(x, y) , dx + N(x, y) , dy = 0 \]
Condition for Exactness: \[ \frac{\partial M}{\partial y} = \frac{\partial N}{\partial x} \]
Integrating Factor (for non-exact equations): \[ \mu(x) = e^{\int P(x) , dx} \] \[ \mu(y) = e^{\int Q(y) , dy} \]
Second-Order Differential Equations
Homogeneous Linear Second-Order Differential Equation: \[ a \frac{d^2y}{dx^2} + b \frac{dy}{dx} + c y = 0 \]
Characteristic Equation: \[ ar^2 + br + c = 0 \]
Solution for Distinct Real Roots ((r_1) and (r_2)): \[ y(x) = C_1 e^{r_1 x} + C_2 e^{r_2 x} \]
Solution for Repeated Roots ((r)): \[ y(x) = (C_1 + C_2 x)e^{rx} \]
Solution for Complex Roots ((\alpha \pm \beta i)): \[ y(x) = e^{\alpha x} (C_1 \cos(\beta x) + C_2 \sin(\beta x)) \]
Non-Homogeneous Linear Second-Order Differential Equation: \[ a \frac{d^2y}{dx^2} + b \frac{dy}{dx} + c y = f(x) \]
General Solution: \[ y(x) = y_h(x) + y_p(x) \]
- (y_h(x)) is the solution to the homogeneous equation.
- (y_p(x)) is a particular solution to the non-homogeneous equation.
Method of Undetermined Coefficients: Assume a form for (y_p(x)) based on (f(x)) and solve for coefficients.
Variation of Parameters: \[ y_p(x) = y_1(x) \int \frac{y_2(x) f(x)}{W(y_1, y_2)} , dx - y_2(x) \int \frac{y_1(x) f(x)}{W(y_1, y_2)} , dx \] where (y_1(x)) and (y_2(x)) are solutions to the corresponding homogeneous equation and (W(y_1, y_2)) is the Wronskian.
Higher-Order Differential Equations
General Linear (n)th-Order Differential Equation: \[ a_n \frac{d^n y}{dx^n} + a_{n-1} \frac{d^{n-1} y}{dx^{n-1}} + \cdots + a_1 \frac{dy}{dx} + a_0 y = f(x) \]
Solution: \[ y(x) = y_h(x) + y_p(x) \]
Systems of Differential Equations
First-Order Linear System: \[ \mathbf{X}' = A \mathbf{X} + \mathbf{B} \]
Solution Using Eigenvalues and Eigenvectors:
- Find eigenvalues (\lambda) and eigenvectors (\mathbf{v}) of matrix (A).
- General solution: \[ \mathbf{X}(t) = c_1 e^{\lambda_1 t} \mathbf{v}_1 + c_2 e^{\lambda_2 t} \mathbf{v}_2 + \cdots + c_n e^{\lambda_n t} \mathbf{v}_n \]
Phase Plane Analysis:
- Classify critical points (nodes, saddles, spirals, centers) based on eigenvalues.
Laplace Transforms
Definition: \[ \mathcal{L}{f(t)} = \int_0^\infty e^{-st} f(t) , dt \]
Inverse Laplace Transform: \[ \mathcal{L}^{-1}{F(s)} = \frac{1}{2\pi i} \int_{\gamma - i\infty}^{\gamma + i\infty} e^{st} F(s) , ds \]
Properties:
- Linearity: \[ \mathcal{L}{af(t) + bg(t)} = a\mathcal{L}{f(t)} + b\mathcal{L}{g(t)} \]
- First Derivative: \[ \mathcal{L}{f'(t)} = sF(s) - f(0) \]
- Second Derivative: \[ \mathcal{L}{f''(t)} = s^2 F(s) - sf(0) - f'(0) \]
Laplace Transform of Common Functions: \[ \mathcal{L}{1} = \frac{1}{s} \] \[ \mathcal{L}{t^n} = \frac{n!}{s^{n+1}} \] \[ \mathcal{L}{e^{at}} = \frac{1}{s-a} \] \[ \mathcal{L}{\sin(at)} = \frac{a}{s^2 + a^2} \] \[ \mathcal{L}{\cos(at)} = \frac{s}{s^2 + a^2} \]
Fourier Series
Fourier Series Representation: \[ f(x) = a_0 + \sum_{n=1}^{\infty} \left( a_n \cos \frac{n\pi x}{L} + b_n \sin \frac{n\pi x}{L} \right) \]
Coefficients: \[ a_0 = \frac{1}{2L} \int_{-L}^{L} f(x) , dx \] \[ a_n = \frac{1}{L} \int_{-L}^{L} f(x) \cos \frac{n\pi x}{L} , dx \] \[ b_n = \frac{1}{L} \int_{-L}^{L} f(x) \sin \frac{n\pi x}{L} , dx \]
Partial Differential Equations
Heat Equation: \[ \frac{\partial u}{\partial t} = \alpha \frac{\partial^2 u}{\partial x^2} \]
Wave Equation: \[ \frac{\partial^2 u}{\partial t^2} = c^2 \frac{\partial^2 u}{\partial x^2} \]
Laplace's Equation: \[ \frac{\partial^2 u}{\partial x^2} + \frac{\partial^2 u}{\partial y^2} = 0 \]
Poisson's Equation: \[ \frac{\partial^2 u}{\partial x^2} + \frac{\partial^2 u}{\partial y^2} = f(x, y) \]
Boundary and Initial Conditions
Initial Conditions:
- (y(0) = y_0)
- (y'(0) = y_1)
Boundary Conditions:
- Dirichlet: (u(a, t) = 0)
- Neumann: (\frac{\partial u}{\partial x} \bigg|_{x=a} = 0)
Separation of Variables: Assume (u(x,t) = X(x)T(t)) and separate the PDE into ODEs for (X(x)) and (T(t)).
Physics 1 Formulas
Mechanics
Kinematics Equations (for constant acceleration): \[ v = v_0 + at \] \[ s = s_0 + v_0 t + \frac{1}{2} a t^2 \] \[ v^2 = v_0^2 + 2a(s - s_0) \] \[ s = s_0 + \frac{1}{2} (v + v_0)t \]
Newton's Laws of Motion:
- First Law (Law of Inertia): \[ \text{An object at rest stays at rest and an object in motion stays in motion unless acted upon by an external force.} \]
- Second Law: \[ \mathbf{F} = m \mathbf{a} \]
- Third Law: \[ \text{For every action, there is an equal and opposite reaction.} \]
Gravitational Force: \[ \mathbf{F} = G \frac{m_1 m_2}{r^2} \mathbf{\hat{r}} \]
Work and Energy: \[ W = \mathbf{F} \cdot \mathbf{d} = Fd \cos \theta \] \[ K = \frac{1}{2} mv^2 \] \[ U_g = mgh \] \[ E = K + U \]
Power: \[ P = \frac{W}{t} \] \[ P = \mathbf{F} \cdot \mathbf{v} \]
Momentum: \[ \mathbf{p} = m \mathbf{v} \] \[ \mathbf{F} = \frac{d\mathbf{p}}{dt} \]
Impulse: \[ \mathbf{J} = \Delta \mathbf{p} = \int \mathbf{F} , dt \]
Collisions:
- Elastic: Both momentum and kinetic energy are conserved.
- Inelastic: Momentum is conserved, kinetic energy is not.
Rotational Kinematics: \[ \theta = \theta_0 + \omega_0 t + \frac{1}{2} \alpha t^2 \] \[ \omega = \omega_0 + \alpha t \] \[ \omega^2 = \omega_0^2 + 2 \alpha (\theta - \theta_0) \]
Rotational Dynamics: \[ \tau = I \alpha \] \[ L = I \omega \] \[ \mathbf{\tau} = \frac{d\mathbf{L}}{dt} \]
Moment of Inertia (for a point mass): \[ I = \sum m_i r_i^2 \]
Torque: \[ \mathbf{\tau} = \mathbf{r} \times \mathbf{F} \]
Angular Momentum: \[ \mathbf{L} = \mathbf{r} \times \mathbf{p} \]
Oscillations and Waves
Simple Harmonic Motion (SHM): \[ x(t) = A \cos(\omega t + \phi) \] \[ v(t) = -A \omega \sin(\omega t + \phi) \] \[ a(t) = -A \omega^2 \cos(\omega t + \phi) \]
Angular Frequency: \[ \omega = 2\pi f = \sqrt{\frac{k}{m}} \]
Period: \[ T = \frac{1}{f} = 2\pi \sqrt{\frac{m}{k}} \]
Wave Equation: \[ v = f \lambda \]
Standing Waves:
- String fixed at both ends: \[ \lambda_n = \frac{2L}{n} \]
- Open-closed tube: \[ \lambda_n = \frac{4L}{n} \]
Doppler Effect: \[ f' = f \left( \frac{v \pm v_0}{v \mp v_s} \right) \]
Thermodynamics
First Law of Thermodynamics: \[ \Delta U = Q - W \]
Work Done by a Gas: \[ W = \int P , dV \]
Ideal Gas Law: \[ PV = nRT \]
Kinetic Theory of Gases: \[ \bar{E_k} = \frac{3}{2} k_B T \]
Heat Transfer:
- Conduction: \[ Q = \frac{kA(T_H - T_C)t}{d} \]
- Convection: \[ Q = hA(T_s - T_f) \]
- Radiation: \[ Q = \epsilon \sigma A T^4 \]
Second Law of Thermodynamics: \[ \text{Entropy of an isolated system always increases.} \] \[ \Delta S \ge 0 \]
Carnot Efficiency: \[ \eta = 1 - \frac{T_C}{T_H} \]
Physics 2 Formulas
Electrostatics
Coulomb's Law: \[ \mathbf{F} = k_e \frac{q_1 q_2}{r^2} \mathbf{\hat{r}} \]
Electric Field: \[ \mathbf{E} = \frac{\mathbf{F}}{q} = k_e \frac{q}{r^2} \mathbf{\hat{r}} \]
Electric Potential: \[ V = k_e \frac{q}{r} \]
Potential Energy: \[ U = qV = k_e \frac{q_1 q_2}{r} \]
Gauss's Law: \[ \oint_S \mathbf{E} \cdot d\mathbf{A} = \frac{Q_{\text{enc}}}{\epsilon_0} \]
Capacitance and Dielectrics
Capacitance: \[ C = \frac{Q}{V} \]
Parallel Plate Capacitor: \[ C = \epsilon_0 \frac{A}{d} \]
Energy Stored in a Capacitor: \[ U = \frac{1}{2} CV^2 \]
Capacitors in Series and Parallel:
- Series: \[ \frac{1}{C_{\text{eq}}} = \sum_{i} \frac{1}{C_i} \]
- Parallel: \[ C_{\text{eq}} = \sum_{i} C_i \]
Electric Current and Resistance
Current: \[ I = \frac{dQ}{dt} \]
Ohm's Law: \[ V = IR \]
Resistance: \[ R = \rho \frac{L}{A} \]
Power: \[ P = IV = I^2R = \frac{V^2}{R} \]
Resistors in Series and Parallel:
- Series: \[ R_{\text{eq}} = \sum_{i} R_i \]
- Parallel: \[ \frac{1}{R_{\text{eq}}} = \sum_{i} \frac{1}{R_i} \]
Magnetic Fields and Forces
Biot-Savart Law: \[ d\mathbf{B} = \frac{\mu_0}{4\pi} \frac{I d\mathbf{l} \times \mathbf{\hat{r}}}{r^2} \]
Ampere's Law: \[ \oint \mathbf{B} \cdot d\mathbf{l} = \mu_0 I_{\text{enc}} \]
Magnetic Force on a Moving Charge: \[ \mathbf{F} = q \mathbf{v} \times \mathbf{B} \]
Magnetic Force on a Current-Carrying Wire: \[ \mathbf{F} = I \mathbf{l} \times \mathbf{B} \]
Magnetic Flux: \[ \Phi_B = \int_S \mathbf{B} \cdot d\mathbf{A} \]
Faraday's Law of Induction: \[ \mathcal{E} = -\frac{d\Phi_B}{dt} \]
Lenz's Law: The induced emf always opposes the change in magnetic flux.
Electromagnetic Waves
Maxwell's Equations:
- Gauss's Law for Electricity: \[ \nabla \cdot \mathbf{E} = \frac{\rho}{\epsilon_0} \]
- Gauss's Law for Magnetism: \[ \nabla \cdot \mathbf{B} = 0 \]
- Faraday's Law of Induction: \[ \nabla \times \mathbf{E} = -\frac{\partial \mathbf{B}}{\partial t} \]
- Ampere-Maxwell Law: \[ \nabla \times \mathbf{B} = \mu_0 \mathbf{J} + \mu_0 \epsilon_0 \frac{\partial \mathbf{E}}{\partial t} \]
Speed of Light: \[ c = \frac{1}{\sqrt{\mu_0 \epsilon_0}} \]
Wave Equation: \[ \mathbf{E} = E_0 \cos(kx - \omega t) \mathbf{\hat{y}} \] \[ \mathbf{B} = B_0 \cos(kx - \omega t) \mathbf{\hat{z}} \]
Optics
Snell's Law: \[ n_1 \sin \theta_1 = n_2 \sin \theta_2 \]
Lensmaker's Equation: \[ \frac{1}{f} = (n - 1) \left( \frac{1}{R_1} - \frac{1}{R_2} \right) \]
Magnification: \[ M = \frac{h_i}{h_o} = -\frac{d_i}{d_o} \]
Mirror and Lens Equations: \[ \frac{1}{f} = \frac{1}{d_o} + \frac{1}{d_i} \]
Modern Physics
Photoelectric Effect: \[ E = hf - \phi \] where ( E ) is the energy of the emitted electron, ( h ) is Planck's constant, ( f ) is the frequency of the incident light, and ( \phi ) is the work function.
Compton Scattering: \[ \lambda' - \lambda = \frac{h}{m_e c} (1 - \cos \theta) \]
de Broglie Wavelength: \[ \lambda = \frac{h}{p} \]
Heisenberg Uncertainty Principle: \[ \Delta x \Delta p \ge \frac{\hbar}{2} \] \[ \Delta E \Delta t \ge \frac{\hbar}{2} \]