System#
Linux#
Files and directories#
Find large files#
Display files older than 60 days#
Delete files older than 60 days#
Find and exec a command#
--relative flag creates subdirectories in the target directory
Follow symlinks with find command#
Sort by size#
Get absolute path of a file#
Sync directories#
Redirect stderr and stdout#
# stdout
command 1> /dev/null
# stderr
command 2> /dev/null
# stderr to stdout to a file
command > /dev/null 2>&1
# stderr to stdout to a file
command &> /dev/null
Copy directory content including hidden files#
Copy Reference file#
With options: -p(preserve permissions), -r(recursive)
rsync multiple source directories#
- Remote sync
- Local sync
Get some informations about a program#
Print shared object dependencies#
Display permissions and user/group with tree#
Prevent file/dir modification and deletion#
- View file extended attributes
- Set the immuable flag
Search and replace a string in multiple files#
- Search
- Replace
- Backup files before replacing
Rename multiple files#
Archiving and compressing#
- Extract Tar file
Memory, CPU and process management#
Sort processes by memory usage#
Sort processes by cpu usage#
Sort processes by start time#
- Reverse the order
With start time#
ps using grep and displaying headers#
ps -eo user,pid,ppid,lstart,%mem,%cpu,cmd --sort=start_time | { head -1; grep '\.py[[:blank:]]'; } | grep -v grep
List file descriptors#
List processes based on name/pattern#
Kill processes based on name/pattern#
Show CPU details#
top then, press 1 to display usage per CPU.
Display a tree of processes#
Keep processes running after exiting the shell#
- Redirect to a file and to standard error and output
- Different files for standard output and error
Clear cache/buffer#
or
Clear swap#
Disks#
Input/Output(I/O) performance
LVM#
- Display file system types
Example
- Extend a filesystem(with
-r|--resizefs)
Example
- Increase size of an XFS filesystem
Example
DNS queries#
for record_type in A AAAA CNAME MX NS TXT; do
dig +noall +answer +multiline <fqdn> "${record_type}"
done
Managing Users#
- Add user
- Change password
- Change UID and GID
- Change user primary group
SSH#
Generate SSH key pair#
Start ssh-agent in the background#
Add the SSH key to the ssh-agent#
Disable Strict Host Key Checking#
Useful params#
Execute multi-line SSH command#
Get SSH version#
Permissions#
chmod 700 ~/.ssh
chmod 644 ~/.ssh/authorized_keys
chmod 644 ~/.ssh/known_hosts
chmod 644 ~/.ssh/config
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub
User config file#
Host *
LogLevel error
Host <name1>
HostName <ip or fqdn>
User <username>
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
Host <name2>
HostName <ip or fqdn>
User <username>
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa
ProxyCommand ssh -W %h:%p <name1>
Regenerate SSH host keys#
On RHEL, if missing, ssh_host keys are generated during the boot
ssh-keygen -f /etc/ssh/ssh_host_rsa_key -N '' -q -t rsa
ssh-keygen -f /etc/ssh/ssh_host_ecdsa_key -N '' -q -t ecdsa
ssh-keygen -f /etc/ssh/ssh_host_ed25519_key -N '' -q -t ed25519
Logs#
SSHFS#
Install(client side)#
Mount a remote FS#
Example
Automatically mount the remote FS#
SSL#
Check a certificate#
- Check a certificate encoded in PKCS7
Extract the private key from the PFX file#
Extract the certificate from the PFX file#
Extract the decrypted private key#
Extract the CA chain from the PFX file#
View a CSR file#
Get a website certificate#
echo | openssl s_client -showcerts -servername <example.com> -connect <example.com>:443 2>/dev/null | openssl x509 -inform pem -noout -text
Git#
Setup git configuration#
Display config#
Work with Git#
Stage all changes#
Commit staged changes#
- Edit previous commit message
Revert to a previous commit#
Discard local changes#
Diff between commits#
Diff between last commit and the working tree#
Show informations recorded in the reflogs#
~/.gitconfig#
[credential]
helper = store --file /path/to/.gitcred
[user]
name = <name>
email = <email>
# GPG config
signingkey = <signingkey>
[http]
[http "https://gitlab.example.com"]
proxy = http://<ip or fqdn>:<port>
[core]
# vscode as a default editor
editor = code --wait
[commit]
# GPG config
gpgsign = true
[alias]
graph = log --oneline --graph --decorate
llog = log --graph --name-status --pretty=format:\"%C(red)%h %C(reset)(%cd) %C(green)%an %Creset%s %C(yellow)%d%Creset\" --date=relative
acp = "!f() { git add -A && git commit -m \"$@\" && git push; }; f"
Multiple configs
[includeIf "gitdir:~/personal/"]
path = ~/.gitconfig-personal
[includeIf "gitdir:~/work/"]
path = ~/.gitconfig-work
Vim#
Find and replace#
# Syntax
:[range]s/{pattern}/{string}/<flags>
# Replace in all lines
:%s/hello/hi/g
# Confirm before replacing
:%s/hello/hi/gc
# Case-insensitive search
:%s/hello/hi/gi
# Replace between lines 1 to 5
:1,5s/hello/hi/g
Comment#
Uncomment#
Set number#
Unset number#
Undo and redo#
Undo = Press u
Redo = Press CTRL+R
List the available undo options#
Delete blank lines#
Show EOL characters#
systemd#
List all running systemd services
List all enabled systemd services
List all services with activating status
List all failed systemd services
List all active sockets
Debug services with non-zero exit code
while IFS= read -r svc_name; do
echo "---"
svc_name=$(echo "${svc_name}" | awk '{print $1}')
systemctl status "${svc_name}"
done < <(systemctl list-units --type=service --state=activating --quiet)
Show the most recent system errors
Monitor logs in real-time
Monitor logs in real-time for a specific service
Show log entries since a specific date and time.
Display the paths and directories used by the systemd system
Show the current locale and keyboard settings
Grub#
Modify /etc/default/grub
Update grub.cfg file
Cron#
# * * * * * <command to execute>
# | | | | |
# | | | | day of the week (0–6) (Sunday to Saturday;
# | | | month (1–12) 7 is also Sunday on some systems)
# | | day of the month (1–31)
# | hour (0–23)
# minute (0–59)
VirtualBox#
Error: Please disable the KVM kernel extension, recompile your kernel and reboot (VERR_SVM_IN_USE).
Fix for VirtualBox 7.1.4 and Kernel 6.12
Update /etc/default/grub file: Add kvm.enable_virt_at_load=0 parameter to GRUB_CMDLINE_LINUX_DEFAULT
Networking#
NetworkManager#
Check if NetworkManager is running
List all connection profiles
Check device status
Get details about connection
Configure network
nmcli con mod <con_name> ipv4.addresses <ip_addr/mask> ipv4.method manual ipv4.gateway <gw> ipv4.dns "<dns1> <dns2>" ipv4.dns-search <domain>
Restart NetworkManager
Network configuration with network scripts(doc)#
Example
Routing and host information for all network interface: /etc/sysconfig/network
Network connections and statistics#
Monitoring all listening TCP connections
Monitoring all listening UDP connections
Monitoring all listening port(tcp/udp) and established connections
Display CLOSE-WAIT socket connections#
Kill CLOSE-WAIT socket connections#
Test TCP connections#
Test UDP connections#
Debug#
tcpdump (with root)#
Checksum: md5sum or sha256sum#
Hardware#
Trace system calls and signals#
Basic usage
Attach to an running process
Auditd#
Failed login attempts#
Failed system call#
AUID system call#
List of login events#
$HOME#
~/.bashrc#
shopt -s histappend
PROMPT_COMMAND="history -a;$PROMPT_COMMAND"
HISTCONTROL=ignoreboth
HISTFILESIZE=50000
HISTSIZE=${HISTFILESIZE}
HISTTIMEFORMAT="$(date +"%Y-%m-%dT%H:%M:%S%z") "
if [ -f ~/.bash_aliases ]; then
. ~/.bash_aliases
fi
# Setup the ssh-agent
if [ ! -S ~/.ssh/ssh_auth_sock ]; then
eval `ssh-agent`
ln -sf "$SSH_AUTH_SOCK" ~/.ssh/ssh_auth_sock
fi
export SSH_AUTH_SOCK=~/.ssh/ssh_auth_sock
ssh-add -l > /dev/null || ssh-add
GPG_TTY=$(tty)
export GPG_TTY
export DATE_ISO8601=$(date +"%Y-%m-%dT%H-%M-%S%z")
[ -f ~/.fzf.bash ] && source ~/.fzf.bash
source <(kubectl completion bash)
# Custom Prompt
# Display exit code if not equal 0
__sh_exitcode() { ret=$?; if [[ $ret != 0 ]]; then echo "$ret "; fi }
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
PS1='\[\033[1;31m\]$(__sh_exitcode)\[\033[1;32m\](label) \[\033[1;37m\]\u\[\033[0;39m\]@\[\033[1;37m\]\h\[\033[0;39m\]:\[\033[1;34m\]\w\[\033[0;39m\]\$\[\033[0;39m\] '
else
PS1='$(__sh_exitcode)\u@\h:\w\$ '
fi
~/.inputrc#
set show-all-if-ambiguous off
set colored-completion-prefix on
set colored-stats on
"\e[A": history-search-backward
"\e[B": history-search-forward
"\e[C": forward-char
"\e[D": backward-char
# pgup
"\e[6~": menu-complete-backward
# pgdn
"\e[5~": menu-complete
~/.tmux.conf#
#unbind C-b
#set -g prefix C-a
#bind -n C-a send-prefix
unbind C-c
bind -n C-k killp
bind -n C-Left split-window -h
bind -n C-Right split-window -h
bind -n C-Down split-window -v
bind -n C-Up split-window -v
bind -n M-Left select-pane -L
bind -n M-Right select-pane -R
bind -n M-Up select-pane -U
bind -n M-Down select-pane -D
bind -n C-x setw synchronize-panes
set -g visual-activity off
set -g visual-bell off
set -g visual-silence off
set -g monitor-activity off
set -g bell-action none
set -g mouse on
bind z source-file ~/.tmux.conf
~/.bash_aliases#
# https://opensource.com/article/19/7/bash-aliases
# Sort by modification time
alias ll="ls -lthrA --color=auto"
# Sort by file size
alias lt="ls --human-readable --size -1 -S --classify"
# View only mounted drives
alias mnt="mount | awk -F' ' '{ printf \"%s\t%s\n\",\$1,\$3; }' | column -t | egrep ^/dev/ | sort"
# Count files
alias count="find . -type f | wc -l"
# Add a copy progress bar
alias cpv="rsync -ah --info=progress2"
# Find a command in your grep history
# Example: gh <search_something>
alias gh="history | grep"
# Get all paths of json doc
alias jpaths="jq -r '[paths | join(".")]'"
Date and time#
Show current time settings#
Set timezone#
RabbitMQ#
- Check RabbitMQ cluster status
- List queues
- List consumers
Tools#
- Extract full paths of json keys
- Example
- Base64 Encoding/Decoding
Encoding
Decoding
- Convert Yaml file to Json file
- Diff between two directories
- Remove comments and blank lines
- Check if a TCP port is open or closed
- Repeating a character N times
With new line
- Decoding JSON Web Token(JWT)
Shell scripting#
- Read a file line by line
- List all executables
- Use tabs as delimiter
- Run local script on remote machine
- Interactive SSH terminal in script
RedHat-based Linux#
Admin#
List installed packages#
List all available versions of a package#
Update a package#
Download RPM package file#
- Resolve and download needed dependencies
Downgrade a package#
versionlock: Protect packages from being updated#
Finds the packages providing the given file#
Exclude package from getting updated#
Example
Clean all cached files(packages included)#
or
then
Remove old kernels#
Disable/Enable Repo#
Show all repos
Disable a repo
Show disabled repos
Enable a repo
Show enabled repos
or
View transaction history#
Security and bugfixes updates#
Check security and/or bugfixes updates#
Display information about update advisories#
Install security and/or bugfixes updates#
Display information about CVE#
Display information about RHSA ID#
Install specific update#
Example
Windows#
Powershell#
- Test a connection
- Network stats
- Get the basic network adapter properties
- Get routing table
- Find large files
Get-ChildItem c:\ -r -Force -ErrorAction SilentlyContinue |sort -descending -property length | select -first 10 FullName, Length
Get-ChildItem c:\ -r -Force -ErrorAction SilentlyContinue |sort -descending -property length | select -first 10 name, DirectoryName, @{Name="GB";Expression={[Math]::round($_.length / 1GB, 2)}}
Admin#
- Local administrator account.
Shortcuts#
ctrl + alt + F2 |
x11: Get a virtual terminal |
ctrl + alt + F9 |
x11: Back to X |