Bash one-liner collection
Greetings!

See how to configure convenient search and launch of terminal commands and SSH sessions in Tmux using the FZF plugin under the spoiler:

Here is the command list itself:

BASH
  1## =====================
  2## Process management
  3## =====================
  4# Show the top 5 processes by CPU usage
  5ps --sort=-%cpu -eo user,pid,ppid,state,comm | head -n6
  6# Show the top 5 processes by memory usage
  7ps --sort=-%mem -eo user,pid,ppid,state,comm | head -n6
  8# Print processes as a tree
  9ps -axf -eo user,pid,ppid,state,comm
 10# Find parent processes of zombies
 11ps -eo user,pid,ppid,state,comm | awk 'NR==1 || $4=="Z"'
 12# Show the parent process command by PID
 13ps -o pid,command --ppid 698
 14# Print the hierarchy of cgroups managed by systemd
 15systemd-cgls
 16# Print the process hierarchy (pstree)
 17pstree -p -t -n -C age
 18# Find unique binary files run by the user
 19for pid in $(ps -u $USER -o pid); do exe=$(readlink -f /proc/$pid/exe 2> /dev/null); if [[ -e "$exe" ]]; then echo "$pid:$exe"; fi; done | sort -u -t':' -k2,2
 20# Show the maximum memory limit for a process/service cgroup
 21pid=$(systemctl show <service-name> -p MainPID --value); cgroup_path=$(grep '^0::' /proc/$pid/cgroup | cut -d: -f3); cat /sys/fs/cgroup${cgroup_path}/memory.max
 22# Show the maximum CPU limit for a process cgroup
 23pid=<PID>; cgroup_path=$(grep '^0::' /proc/$pid/cgroup | cut -d: -f3); cat /sys/fs/cgroup${cgroup_path}/cpu.max
 24# Show resource limits for a process (ulimit)
 25cat /proc/<PID>/limits
 26# Find processes using the specified mount point/directory
 27lsof +D "/opt" 2> /dev/null | awk 'NR > 1 {print $2, $1}' | sort -u | while read pid p_name; do cmd=$(cat "/proc/$pid/cmdline" 2> /dev/null | tr '\0' ' '); echo "PID: $pid, NAME: $p_name, CMD: $cmd"; done
 28
 29## ==================
 30## System monitoring
 31## ==================
 32# Get a process snapshot (top in batch mode)
 33top -b -n 1
 34# Show current CPU usage (vmstat)
 35vmstat 1 2 | tail -1 | awk '{print 100 - $15 "%"}'
 36# Print mount points with usage >80%
 37df -h | awk '$5 ~ /^8[0-9]%/ {print $6}'
 38# Show the top 20 largest files/directories
 39du -h / 2> /dev/null | sort -rh | head -n 20
 40# Show the top 20 largest files/directories (with exact IEC sizes)
 41du -x --block-size=1 / 2>/dev/null | sort -rn | head -n 20 | numfmt --to=iec
 42# Show disk space usage by systemd journals
 43journalctl --disk-usage
 44# Print open files in the specified directory
 45lsof +D /opt
 46# Show system boot time in unixtime format
 47date -d "$(uptime -s)" +%s
 48# Print the top 10 most frequently used bash commands
 49history | awk '{print $2}' | sort | uniq -c | sort -rn | head
 50# Print the top 10 processes using swap memory
 51for file in /proc/*/status ; do awk '/VmSwap|Name/{printf $2 " " $3}END{ print ""}' $file; done | sort -k 2 -n -r | head -n 10
 52# Check the current swappiness value
 53cat /proc/sys/vm/swappiness
 54# Print OOM scores and adjustments for processes
 55printf "PID\tOOM Score\tOOM Adj\tCommand\n"; while read -r pid comm; do [ -f /proc/$pid/oom_score ] && [ $(cat /proc/$pid/oom_score) != 0 ] && printf "%d\t%d\t\t%d\t%s\n" "$pid" "$(cat /proc/$pid/oom_score)" "$(cat /proc/$pid/oom_score_adj)" "$comm"; done < <(ps -e -o pid= -o comm=) | sort -k 2nr
 56# Disk I/O monitoring (iotop)
 57iotop -o -P -d 5
 58# CPU and disk device statistics monitoring (iostat)
 59iostat -x 2
 60# Find IP addresses in a log file (grep)
 61grep -a -E '([0-9]{1,3}\.){3}[0-9]{1,3}' /var/log/nginx/access.log
 62# Show the system load average (sar)
 63sar -q 1 5
 64
 65## =================================
 66## File and directory management
 67## =================================
 68# Replace text in a file (creating a backup copy)
 69sed -i.bkp 's/old_text/new_text/g' ./file.txt
 70# Insert a new line at the beginning of a file
 71sed -i.bkp '1i test_line' ./file.txt
 72# Insert a multiline block at the beginning of a file
 73sed -i.bkp '1i test_line:\n    value1\n    value2' ./file.txt
 74# Change a substring in a line that starts with a specific pattern
 75sed '\|^test_line|s|line|word|'
 76# Find and set permissions 644 for all files
 77find /path -type f -exec chmod 644 {} \;
 78# Find and set permissions 755 for all directories
 79find /path -type d -exec chmod 755 {} \;
 80# Search for files while excluding specific paths
 81find ./ -path ./subpath -prune -o -name 'index.md' -ls
 82# Set ACL (Access Control List) permissions for a user
 83setfacl -m u:ivan:rwx /opt/mydata
 84# Resolve a chain of symbolic links to the final file
 85current="/path/to/symlinks"; while [[ -L "$current" ]]; do target=$(readlink "$current"); echo "$current -> $target"; if [[ "$target" == /* ]]; then current="$target"; else current="$(dirname "$current")/$target"; fi; done; echo "Final: $current"
 86# Find open files that were deleted (but are still in use)
 87lsof | grep '(deleted)'
 88# Truncate (clear) the contents of a deleted but open file
 89truncate -s 0 /proc/<PID>/fd/<FD>
 90
 91## ======================
 92## Archiving and compression
 93## ======================
 94# Create a file with random data
 95dd if=/dev/urandom of=./file1 bs=50K count=10
 96# Create a second file with random data
 97dd if=/dev/urandom of=./file2 bs=50K count=10
 98# Create a tar archive from files and directories
 99tar -c -f ./archive.tar ./file1 ./file2 ./dir/
100# Create a tar archive with verbose output
101tar -v -c -f ./archive.tar ./file1 ./file2 ./dir/
102# Create a tar archive while located in another directory
103tar -C /tmp/dir/ -c -f ./archive.tar ./
104# Extract the contents of a tar archive
105tar -x -f ./archive.tar
106# Extract a tar archive into the specified directory
107tar -C /tmp/dir/ -x -f ./archive.tar
108# Show the list of files in a tar archive
109tar -t -f ./archive.tar
110# Check tar archive integrity
111tar -t -f ./archive.tar &> /dev/null
112# Add a file to an existing tar archive
113tar -r -f ./archive.tar /etc/passwd
114# Delete a file from a tar archive
115tar --delete -f archive.tar etc/passwd
116# Create a compressed gzip tar archive (.tgz or .tar.gz)
117tar -c -z -f ./archive.tar.gz ./file1 ./file2
118# Create a compressed bzip2 tar archive (.tar.bz2)
119tar -c -j -f archive.tar.bz2 ./file1.txt ./file2.txt
120# Create a compressed xz tar archive (.tar.xz)
121tar -c -J -f archive.tar.xz ./file1.txt ./file2.txt
122# Create a compressed zstd tar archive (.tar.zst)
123tar -c --zstd -f archive.tar.zst ./file1.txt ./file2.txt
124# Create a zstd archive with maximum compression (through external zstd)
125tar -I "zstd -19" -cvf ./archive.tzst ./file* ./dir
126# Create an archive specifying an external compression utility
127tar -v -I "zstd -19" -c -f ./archive.tzst ./file1.txt ./dir
128# Create a tar archive and send it to stdout
129tar -c -f - ./file1 ./file2 ./dir/ > ./archive.tar
130# Create a compressed gzip tar archive and send it to stdout
131tar -c -z -f - ./file1 ./file2 ./dir/ > ./archive.tgz
132# Archive and compress data using an external utility (gzip)
133tar -c -f - ./file1 ./file2 ./dir/ | gzip -9 > ./archive.tgz
134# Archive files found by the find command
135find ./ -name 'file[1-2]' | tar -c -z -f ./archive.tgz -T -
136# Archive, compress, and send files to a remote host for extraction
137tar -c -z -f - ./dir/ | ssh ivan@test.r4ven.me "tar -C /tmp -x -z -f -"
138# Create a compressed tar archive on a remote host and download it locally
139ssh ivan@test.r4ven.me "tar -c -z -f - ./file1 ./file2" > ./archive.tgz
140# Download and extract a compressed tar archive from a remote host locally
141ssh ivan@test.r4ven.me "cat ./archive.tgz" | tar -C /tmp -x -z -f -
142# Create a compressed and encrypted GPG archive
143tar -c -z -f - ./file1 ./file2 ./dir/ | gpg --batch --symmetric --passphrase "MyPassword" > ./archive.tgz.gpg
144# Decrypt a GPG archive and extract its contents
145gpg -d ./archive.tgz.gpg | tar -x -z -f -
146# Split a compressed tar archive into smaller parts
147tar -c -z -f - ./dir/ | split -b 200K - ./archive.tgz.part-
148# Combine split archive parts and extract it
149cat ./archive.tgz.part-* | tar -x -z -f -
150# Compress a file with gzip
151gzip ./file1.txt
152# Decompress a gzip archive
153gunzip ./file1.txt.gz
154# Decompress a gzip archive (alternative)
155gzip -d ./file1.txt.gz
156# Compress a file while keeping the original
157gzip -k ./file1.txt
158# Compress a file with the maximum gzip compression level
159gzip -9 ./file1.txt
160# Compress a file with bzip2
161bzip2 ./file1.txt
162# Decompress a bzip2 archive
163bunzip2 ./file1.txt.bz2
164# Decompress a bzip2 archive (alternative)
165bzip2 -d ./file1.txt.bz2
166# Compress a file with bzip2 while keeping the original
167bzip2 -k ./file1.txt
168# Compress a file with the maximum bzip2 compression level
169bzip2 -9 ./file1.txt
170# Compress a file with xz
171xz ./file1.txt
172# Decompress an xz archive
173unxz ./file1.txt.xz
174# Decompress an xz archive (alternative)
175xz -d ./file1.txt.xz
176# Compress a file with xz while keeping the original
177xz -k ./file1.txt
178# Compress a file with the maximum xz compression level
179xz -9 ./file1.txt
180# Compress a file with zstd
181zstd ./file1.txt
182# Compress a file with zstd while keeping the original
183zstd -k ./file1.txt
184# Decompress a zstd archive
185unzstd ./file1.txt.zst
186# Decompress a zstd archive (alternative)
187zstd -d ./file1.txt.zst
188# Compress a file with the maximum zstd compression level
189zstd -19 ./file1.txt
190# Create a ZIP archive from files and directories
191zip ./archive.zip ./file1 ./dir/
192# Extract the contents of a ZIP archive
193unzip ./archive.zip
194# Show the list of files in a ZIP archive
195unzip -l ./archive.zip
196# Add a file to an existing ZIP archive
197zip ./archive.zip ./file2
198# Create a ZIP archive without compression
199zip -0 ./archive.zip ./file1.txt
200# Create a ZIP archive with maximum compression
201zip -9 ./archive.zip ./file1.txt
202# Create a 7z archive from files and directories
2037z a ./archive.7z ./file1 ./dir/
204# Extract the contents of a 7z archive
2057z x ./archive.7z
206# Show the list of files in a 7z archive
2077z l ./archive.7z
208# Add a file to an existing 7z archive
2097z a ./archive.7z ./file2
210# Create a 7z archive without compression
2117z a -mx=0 archive.7z ./file1.txt
212# Create a 7z archive with maximum compression
2137z a -mx=9 archive.7z ./file1.txt
214# Create a RAR archive from files and directories
215rar a ./archive.rar ./file1 ./dir/
216# Extract the contents of a RAR archive
217unrar x ./archive.rar
218# Show the list of files in a RAR archive
219unrar l ./archive.rar
220# Add a file to an existing RAR archive
221rar a ./archive.rar ./file2
222# Create a RAR archive without compression
223rar a -m0 ./archive.rar file1.txt
224# Create a RAR archive with maximum compression
225rar a -m5 archive.rar file1.txt
226# Create a ZIP archive for testing
227zip -9 ./archive.zip ./file* ./dir
228# Create a 7z archive for testing
2297z a -mx=9 archive.7z ./file* ./dir
230# Create a RAR archive for testing
231rar a -m5 ./archive.rar ./file* ./dir
232
233## ======================
234## Network and network utilities
235## ======================
236# Show unique listening TCP/UDP ports
237ss -tuln | awk '{print $5}' | grep -Eo ':[0-9]+' | sort -t: -k2 -n -u
238# Temporarily disable responses to ICMP echo requests (ping)
239echo 1 | sudo tee /proc/sys/net/ipv4/icmp_echo_ignore_all
240# Start tracking ICMP echo requests (iptables)
241iptables -A INPUT -p icmp --icmp-type echo-request -m recent --set --name PING_LIST
242# Limit the number of ICMP echo requests (iptables)
243iptables -A INPUT -p icmp --icmp-type echo-request -m recent --update --seconds 10 --hitcount 5 --name PING_LIST -j DROP
244# Check TCP port availability with curl
245curl -v telnet://10.11.12.13:1234
246# Quick TCP port availability check through bash
247echo > /dev/tcp/r4ven.me/443 && echo "open" || echo "unavailable"
248# Check SSL/TLS port availability with openssl
249openssl s_client -connect r4ven.me:443
250# Bring a network interface up/down
251sudo ip link set dev eth0 down; sudo ip link set dev eth0 up
252# Temporarily enable IP packet forwarding (routing)
253sysctl -w net.ipv4.ip_forward=1 net.ipv6.conf.all.forwarding=1
254# Enable IP packet forwarding permanently (through sysctl.d)
255echo -e 'net.ipv4.ip_forward = 1\nnet.ipv6.conf.all.forwarding = 1' > /etc/sysctl.d/99-forwarding.conf && sysctl -p /etc/sysctl.d/99-forwarding.conf
256# Run parallel ping for several hosts
257seq 20 | xargs -P20 -I{} sh -c 'ping -c5 nftables.r4ven.me > out_{}.log 2>&1'
258# Run a command with specific network capabilities
259sudo capsh --caps="cap_net_raw+ep" -- -c "/path/to/program"
260# Run a DNS query (dig) and show a short answer
261dig r4ven.me +short +answer +identify
262# Run a DNS query with delegation tracing
263dig r4ven.me +short +trace
264# Run a DNS query against the specified name server
265dig @8.8.8.8 r4ven.me +short +answer +identify
266# Check the status of a specific TCP port (nmap)
267nmap 10.11.12.13 -p 22
268# Check the status of a specific UDP port (nmap)
269nmap -sU 10.11.12.13 -p 53
270# Start a simple TCP server (netcat)
271PORT=12345; while true; do echo "Listen $PORT TCP port..."; nc -l -p $PORT | sed 's/.*/You say: &/'; echo -e "TCP-connection closed.\n"; done
272# Start a TCP server with a 'pong' response
273while true; do nc -l -p 12345 | tee /dev/tty | { read line; echo "pong"; } ; done
274# Start a simple UDP server (netcat)
275while true; do echo "pong" | nc -u -l -p 9999; done
276# Send a message to a TCP server (netcat)
277echo "Hello TCP" | timeout 1 nc -v test.r4ven.me 12345
278# Send a message to a UDP server (netcat)
279echo "ping" | nc -u -w1 test.r4ven.me 9999
280# Start a UDP server with a 'pong' response (socat)
281socat -v UDP-RECVFROM:9999,fork SYSTEM:"echo 'pong'"
282# Start a TCP server with a 'pong' response (socat)
283socat -v TCP-LISTEN:9999,fork SYSTEM:"echo 'pong'"
284# Send a message to a UDP server (socat)
285echo "ping" | socat - UDP:test.r4ven.me:9999
286# Send a message to a TCP server (socat)
287echo "ping" | socat - TCP:test.r4ven.me:9999
288# Create a simple auto-refreshing web page (ncat)
289ncat -lk 8080 -c 'echo -e "HTTP/1.1 200 OK\nContent-Type: text/html\n\n<html><meta http-equiv=\"refresh\" content=\"1\"><pre>$(date)\nONLINE</pre></html>"'
290
291## ========
292## Nftables
293## ========
294# Flush the entire nftables ruleset
295nft "flush ruleset"
296# Add the 'filter' table in the 'inet' family
297nft "add table inet filter"
298# Flush all rules in the 'inet filter' table
299nft "flush table inet filter"
300# Add the 'nat' table in the 'inet' family
301nft "add table inet nat"
302# Flush all rules in the 'inet nat' table
303nft "flush table inet nat"
304# Create a set for private LAN IPv4 addresses
305nft "add set inet filter lan4 { type ipv4_addr; flags interval; elements = { 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16, 169.254.0.0/16 } }"
306# Create a set for private LAN IPv6 addresses
307nft "add set inet filter lan6 { type ipv6_addr; flags interval; elements = { fd00::/8, fe80::/10 } }"
308# Create a set for trusted IPv4 addresses
309nft "add set inet filter trusted { type ipv4_addr; elements = { 123.34.56.78 } }"
310# Add the 'input' chain with the 'drop' policy
311nft "add chain inet filter input { type filter hook input priority 0; policy drop; }"
312# Add the 'forward' chain with the 'drop' policy
313nft "add chain inet filter forward { type filter hook forward priority 50; policy drop; }"
314# Add the 'output' chain with the 'accept' policy
315nft "add chain inet filter output { type filter hook output priority -200; policy accept; }"
316# Add the 'prerouting' chain for NAT
317nft "add chain inet nat prerouting { type nat hook prerouting priority dstnat; policy accept; }"
318# Add the 'postrouting' chain for NAT
319nft "add chain inet nat postrouting { type nat hook postrouting priority srcnat; policy accept; }"
320# Add the auxiliary 'input_wan' chain
321nft "add chain inet filter input_wan"
322# Add the auxiliary 'input_lan' chain
323nft "add chain inet filter input_lan"
324# Add a chain for logging dropped packets
325nft "add chain inet filter log_drop"
326# Drop packets with an invalid connection state
327nft "add rule inet filter input ct state invalid drop comment \"Drop invalid connections\""
328# Allow established and related connections
329nft "add rule inet filter input ct state { established, related } accept comment \"Allow established connections\""
330# Allow traffic through the loopback interface
331nft "add rule inet filter input iif lo accept comment \"Allow loopback\""
332# Allow incoming traffic from trusted IP addresses
333nft "add rule inet filter input ip saddr @trusted accept comment \"Allow trusted IPs\""
334# Limit the ICMP traffic rate
335nft "add rule inet filter input meta l4proto icmp icmp type { echo-request, destination-unreachable, time-exceeded } limit rate 10/second accept comment \"ICMP rate limited\""
336# Allow required IPv6 ICMP traffic
337nft "add rule inet filter input meta l4proto ipv6-icmp icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, parameter-problem, mld-listener-query, mld-listener-report, mld-listener-reduction, nd-router-solicit, nd-router-advert, nd-neighbor-solicit, nd-neighbor-advert, mld2-listener-report } accept comment \"Necessary IPv6 ICMP\""
338# Allow UDP traceroute
339nft "add rule inet filter input_wan udp dport 33434-33534 reject comment \"Allow UDP traceroute\""
340# Redirect IPv4 traffic from LAN to the 'input_lan' chain
341nft "add rule inet filter input ip saddr @lan4 jump input_lan comment \"LAN IPv4 processing\""
342# Redirect IPv6 traffic from LAN to the 'input_lan' chain
343nft "add rule inet filter input ip6 saddr @lan6 jump input_lan comment \"LAN IPv6 processing\""
344# Redirect IPv4 traffic from WAN to the 'input_wan' chain
345nft "add rule inet filter input ip saddr != @lan4 jump input_wan comment \"WAN IPv4 processing\""
346# Redirect IPv6 traffic from WAN to the 'input_wan' chain
347nft "add rule inet filter input ip6 saddr != @lan6 jump input_wan comment \"WAN IPv6 processing\""
348# Redirect the remaining incoming traffic to the 'log_drop' chain
349nft "add rule inet filter input jump log_drop comment \"Default drop\""
350# Allow all TCP/UDP traffic from LAN
351nft "add rule inet filter input_lan meta l4proto { tcp, udp } accept comment \"Allow all TCP/UDP from LAN\""
352# Allow specific TCP ports from LAN
353nft "add rule inet filter input_lan tcp dport { 80, 443 } accept comment \"Allowed TCP ports from LAN\""
354# Allow specific UDP ports from LAN
355nft "add rule inet filter input_lan udp dport { 53, 123 } accept comment \"Allowed UDP ports from LAN\""
356# Drop new connections from LAN with logging
357nft "add rule inet filter input_lan ct state new jump log_drop comment \"Drop all from LAN with log\""
358# Allow SSH from WAN
359nft "add rule inet filter input_wan tcp dport 22 accept comment \"Allow SSH from WAN\""
360# Allow specific TCP ports from WAN
361nft "add rule inet filter input_wan tcp dport { 80, 443 } accept comment \"Allowed TCP ports from WAN\""
362# Allow specific UDP ports from WAN
363nft "add rule inet filter input_wan udp dport { 53, 123 } accept comment \"Allowed UDP ports from WAN\""
364# Allow DNAT for port 443 on eth0
365nft "add rule inet filter input_wan iifname \"eth0\" tcp dport 443 accept comment \"DNAT: 443->43443\""
366# Allow traffic after DNAT on eth0
367nft "add rule inet filter input_wan iifname \"eth0\" ct status dnat tcp dport 43443 accept comment \"DNAT: 443->43443\""
368# Drop new connections from WAN with logging
369nft "add rule inet filter input_wan ct state new jump log_drop comment \"Drop all from WAN\""
370# Allow established and related connections for forwarding
371nft "add rule inet filter forward ct state established,related accept"
372# Allow incoming forwarding for K8s interfaces (cni)
373nft "add rule inet filter forward iifname \"cni*\" accept comment \"Allow K8s forward in\""
374# Allow outgoing forwarding for K8s interfaces (cni)
375nft "add rule inet filter forward oifname \"cni*\" accept comment \"Allow K8s forward out\""
376# Allow incoming forwarding for K8s interfaces (flannel)
377nft "add rule inet filter forward iifname \"flannel.*\" accept comment \"Allow K8s forward in\""
378# Allow outgoing forwarding for K8s interfaces (flannel)
379nft "add rule inet filter forward oifname \"flannel.*\" accept comment \"Allow K8s forward out\""
380# Allow incoming forwarding for K8s interfaces (Calico VXLAN)
381nft "add rule inet filter forward iifname \"vxlan.calico\" accept comment \"Allow K8s forward in\""
382# Allow outgoing forwarding for K8s interfaces (Calico VXLAN)
383nft "add rule inet filter forward oifname \"vxlan.calico\" accept comment \"Allow K8s forward out\""
384# Allow incoming forwarding for Docker bridges
385nft "add rule inet filter forward iifname \"br-*\" accept comment \"Allow Docker forward in\""
386# Allow outgoing forwarding for Docker bridges
387nft "add rule inet filter forward oifname \"br-*\" accept comment \"Allow Docker forward out\""
388# Allow incoming forwarding for KVM/libvirt bridges
389nft "add rule inet filter forward iifname \"virbr*\" accept comment \"Allow VMs forward in\""
390# Allow outgoing forwarding for KVM/libvirt bridges
391nft "add rule inet filter forward oifname \"virbr*\" accept comment \"Allow VMs forward out\""
392# Allow incoming forwarding for VPN tunnels (OpenVPN/WireGuard)
393nft "add rule inet filter forward iifname \"tun*\" accept comment \"Allow OC forward in\""
394# Allow outgoing forwarding for VPN tunnels (OpenVPN/WireGuard)
395nft "add rule inet filter forward oifname \"tun*\" accept comment \"Allow OC forward out\""
396# Allow incoming forwarding for WireGuard interfaces
397nft "add rule inet filter forward iifname \"wg*\" accept comment \"Allow WG forward in\""
398# Allow outgoing forwarding for WireGuard interfaces
399nft "add rule inet filter forward oifname \"wg*\" accept comment \"Allow WG forward out\""
400# Drop new forwarding connections with logging
401nft "add rule inet filter forward ct state new jump log_drop comment \"Drop all forward\""
402# Log dropped packets with rate limiting
403nft "add rule inet filter log_drop limit rate 5/second log prefix \"NFT-DROP: \" flags all counter comment \"Drop logging\""
404# Reject TCP connections with an RST packet
405nft "add rule inet filter input meta l4proto tcp reject with tcp reset comment \"Reject TCP\""
406# Reject UDP packets
407nft "add rule inet filter input meta l4proto udp reject comment \"Reject UDP\""
408# Reject packets from other protocols with an ICMP message
409nft "add rule inet filter input counter reject with icmpx type port-unreachable comment \"Reject other protocols\""
410# Protection against port scanning with rate limiting
411nft "add rule inet filter input pkttype host limit rate 5/second counter reject with icmpx type admin-prohibited comment \"Protection from port scanning\""
412# Finally drop all packets in the log_drop chain
413nft "add rule inet filter log_drop drop comment \"Drop all\""
414# Configure DNAT: redirect port 443 to 43443
415nft "add rule inet nat prerouting iifname \"eth0\" tcp dport 443 redirect to 43443 comment \"DNAT: 443->43443\""
416# Configure DNAT: redirect port 443 to 43443 (alternative syntax)
417nft "add rule inet nat prerouting iifname \"eth0\" tcp dport 443 dnat to :43443 comment \"DNAT: 443->43443 \""
418# Configure SNAT (masquerading) for all outgoing traffic (except loopback)
419nft "add rule inet nat postrouting oifname != lo masquerade comment \"SNAT: NAT processing for all\""
420# Configure SNAT (masquerading) for outgoing traffic through eth0
421nft "add rule inet nat postrouting oifname \"eth0\" masquerade comment \"SNAT: NAT procesing for eth0\""
422# Configure SNAT (masquerading) for outgoing traffic through VPN tunnels
423nft "add rule inet nat postrouting oifname \"tun*\" masquerade comment \"SNAT: NAT procesing for OC\""
424# Print the entire nftables ruleset
425nft list ruleset
426# Print the list of all nftables tables
427nft list tables
428# Print rules from a specific table (inet filter)
429nft list table inet filter
430# Print rules from a specific chain (inet filter input)
431nft list chain inet filter input
432# Print the entire ruleset with a 'handle' for each rule
433nft -a list ruleset
434# Flush all nftables tables and chains
435nft flush ruleset
436# Flush all rules in the 'inet filter' table
437nft flush table inet filter
438# Delete the 'inet filter' table
439nft delete table inet filter
440# Add a rule: allow SSH on the input chain
441nft add rule inet filter input tcp dport 22 accept
442# Print input chain rules with 'handle'
443nft -a list chain inet filter input
444# Delete a rule from a chain by its 'handle'
445nft delete rule inet filter input handle 15
446# Replace a rule in a chain by its 'handle'
447nft replace rule inet filter input handle 15 tcp dport 2222 accept
448# Load nftables rules from a file
449nft -f /etc/nftables.conf
450# Check the syntax of an nftables rules file
451nft -c -f /etc/nftables.conf
452# Save the current nftables ruleset to a file
453nft -s list ruleset > /etc/nftables.conf
454# Monitor nftables events in real time
455nft monitor
456# Trace packet traversal through nftables rules
457nft monitor trace
458# Load rules with netlink debug information
459nft --debug=netlink -f myrules.nft
460# Replace an existing nftables rule by its 'handle' (from the "Network" section)
461sudo nft replace rule inet filter input handle 23 'tcp dport 2222 accept comment "Allow SSH"'
462# View nftables logs in real time (from the "Network" section)
463sudo journalctl -k -f -g 'NFT-DROP'
464
465## ==============
466## Packet capture
467## ==============
468# Capture packets for a specific host and port
469tcpdump -i any -nn -q dst host 10.11.12.13 and dst port 443
470# Capture packets and save them to a pcap file
471sudo tcpdump -nn -i any host 10.11.12.13 -w ./tcpdump.pcap
472# Capture packets and output them to a text file
473sudo tcpdump -nn -i any host 10.11.12.13 >> ./tcpdump.txt
474# View the contents of a pcap file
475sudo tcpdump -qns 0 -X -r ./tcpdump.pcap | less
476
477## ========================
478## Encryption and certificates
479## ========================
480# Encrypt a tar archive with OpenSSL (AES-256-CBC)
481tar -czf - /var/log/apt | openssl enc -aes-256-cbc -pbkdf2 -e -out ./logs.tar.gz.enc
482# Decrypt a file encrypted with OpenSSL
483openssl enc -aes-256-cbc -pbkdf2 -d -in ./logs.tar.gz.enc -out ./logs.tar.gz
484# Check an SSL/TLS connection to a server
485openssl s_client -connect r4ven.me:443
486# Retrieve and display a remote SSL/TLS certificate
487openssl s_client -connect r4ven.me:443 < /dev/null 2> /dev/null | openssl x509 -text
488# Retrieve a remote SSL/TLS certificate with ServerName specified
489openssl s_client -connect r4ven.me:443 -servername r4ven.me < /dev/null 2>/dev/null | openssl x509 -text
490# View the contents of a local X.509 certificate
491openssl x509 -in ./ca-cert.crt -text -noout
492# Generate a self-signed SSL/TLS certificate
493openssl req -x509 -nodes -days 7300 -newkey rsa:4096 -keyout ./example.com.key -out ./example.crt -subj "/C=RU/ST=Moscow/L=Moscow/O=Example/OU=TEST/CN=example.com"
494# Get the MD5 hash of the certificate public key modulus
495openssl x509 -noout -modulus -in /var/lib/kubelet/pki/kubelet.crt | openssl md5
496# Get the MD5 hash of the private key modulus
497openssl rsa -noout -modulus -in /var/lib/kubelet/pki/kubelet.key | openssl md5
498# Create local trusted TLS certificates with mkcert
499mkcert -cert-file jenkins.local.pem -key-file jenkins.local-key.pem "jenkins.local" "localhost" "127.0.0.1"
500# Print the list of trusted root certificates (RHEL/CentOS)
501openssl crl2pkcs7 -nocrl -certfile /etc/pki/tls/certs/ca-bundle.crt | openssl pkcs7 -print_certs -text | grep "Subject:"
502# Print the list of trusted root certificates (Debian/Ubuntu)
503openssl crl2pkcs7 -nocrl -certfile /etc/ssl/certs/ca-certificates.crt | openssl pkcs7 -print_certs -text | grep "Subject:"
504# Add a new trusted certificate to the system (RHEL/CentOS)
505cp ./org_name.crt /etc/pki/ca-trust/source/anchors/org_name.crt | update-trust extract
506# Add a new trusted certificate to the system (Debian/Ubuntu)
507cp ./org_name.crt /usr/local/share/ca-certificates/org_name.crt | update-ca-certificates
508# Print the list of trusted organizations from the system store
509trust list | less
510# Encrypt a file with a symmetric key using GPG
511gpg --batch --passphrase-file /path/to/password_file --symmetric --cipher-algo AES256 example.txt
512
513## ==================
514## Web interaction
515## ==================
516# Download a file by URL using curl
517curl -fsSL https://raw.githubusercontent.com/r4ven-me/dots/main/.zshrc -o ~/.zshrc
518# Run an HTTP request with network interaction tracing
519curl --trace-ascii trace.txt r4ven.me
520# Show all hosts curl connected to (including redirects)
521curl -s -L -v https://example.com 2>&1 | grep 'Connected to'
522# Send a text message to Telegram through the Bot API
523curl -s -X POST -H 'Content-Type: application/json' -d '{"chat_id": "'"$TG_CHAT_ID"'", "text": "'"${item}: $message"'", "parse_mode": "Markdown"}' "https://api.telegram.org/bot${TG_BOT_TOKEN}/sendMessage"
524# Send a file to Telegram through the Bot API
525curl -s -X POST -F "chat_id=${TG_CHAT_ID}" -F "document=@${FILE_PATH}" -F "caption=${CAPTION_TEXT}" -F "parse_mode=Markdown" "https://api.telegram.org/bot${TG_BOT_TOKEN}/sendDocument"
526# Trigger a generic Jenkins webhook for a Git event
527curl -L -X POST -H "Content-Type: application/json" -d '{"ref":"refs/heads/main","repository":{"full_name":"test/repo"}}' "http://jenkins.example.com/generic-webhook-trigger/invoke?token=12345qwerty"
528
529## =====================
530## Users and groups
531## =====================
532# Add a new system group
533addgroup --system --gid 1995 zabbix
534# Add a new system user (without a password and shell)
535adduser --system --gecos 'Zabbix monitoring system' --disabled-password --uid 1997 --ingroup zabbix --shell /sbin/nologin --home /opt/zabbix/zabbix_data zabbix
536
537## =======
538## Systemd
539## =======
540# Edit a systemd unit file (creates an override)
541systemctl edit --full --force unitname.service
542# Show properties of a system slice
543systemctl show system.slice
544# Show all parameters and status of a systemd unit
545systemctl show unit_name
546# Check whether a systemd unit is active
547systemctl is-active --quiet cron
548# Restart a systemd unit with debug logging enabled
549sudo SYSTEMD_LOG_LEVEL=debug systemctl restart systemd-networkd
550# Print the hierarchy of cgroups managed by systemd (alternative)
551sudo systemd-cgls
552# Show the maximum memory limit for a systemd unit
553systemctl show unitname.service -p MemoryMax
554# Set or change the memory limit for a systemd unit
555systemctl set-property unitname.service MemoryMax=2G
556# Show cgroup resource usage in top style
557sudo systemd-cgtop -d 3
558
559## ============================
560## Performance and debugging
561## ============================
562# Monitor CPU performance in real time (perf top)
563perf top
564# Get summary performance statistics for a program
565perf stat ./your_program
566# Record profiling data for program execution
567perf record -g ./your_program
568# Record profiling data for a running process
569perf record -g -p $(pidof your_program)
570# Analyze recorded profiling data (perf report)
571perf report ./perf.data
572# Test disk write speed
573sync; dd if=/dev/zero of=tempfile bs=1M count=1024; sync
574# Test disk read speed (with cache clearing)
575sysctl -w vm.drop_caches=3 && dd if=tempfile of=/dev/null bs=1M count=1024
576# Trace system calls of the executed command
577strace -f -e execve ls -l
578# Attach to a running process and trace its system calls
579strace -p 123
580# Print environment variables of a running process
581sudo cat /proc/<pid>/environ | xargs -0 -n1
582
583## ===
584## SSH
585## ===
586# Generate an Ed25519 SSH key without asking for a passphrase
587ssh-keygen -q -N "" -t ed25519 -f ~/.ssh/id_ed25519_test
588# Change the comment of an existing SSH key
589ssh-keygen -c -f ~/.ssh/id_ed25519_test
590# Print the public part of an SSH key from a private file
591ssh-keygen -y -f ~/.ssh/id_ed25519
592# Copy a public SSH key to a remote host
593ssh-copy-id -i ~/.ssh/id_ed25519 user@host
594# Configure local SSH port forwarding
595ssh -q -f -N -L 127.0.0.1:5432:localhost:5432 ivan@test.r4ven.me
596# Configure temporary local SSH port forwarding
597ssh -q -f -L 127.0.0.1:5432:localhost:5432 ivan@test.r4ven.me sleep 60
598# Full temporary local SSH port forwarding with options
599ssh -q -f -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o ExitOnForwardFailure=yes -L 127.0.0.1:5432:localhost:5432 test.r4ven.me -p 2222 -l ivan -i ~/.ssh/id_ed25519_test sleep 60
600# Configure reverse (remote) SSH port forwarding
601ssh -q -f -N -R 127.0.0.1:4443:localhost:5001 ivan@test.r4ven.me
602# Delete a host record from the known_hosts file
603ssh-keygen -f ~/.ssh/known_hosts -R 192.168.1.31
604# Synchronize files and directories over SSH using rsync
605rsync --archive --compress --links --hard-links --xattrs --human-readable --delete -e "ssh -q -o StrictHostKeyChecking=no  -o UserKnownHostsFile=/dev/null -p 2222 -l test" "/path/to/local/source" r4ven.me:"/path/to/remote/destination/"
606
607## ===========
608## Databases
609## ===========
610# Get MongoDB replica set status
611mongo -u root -p "$(awk -F'"' '/auth/ {print $4}' "$MONGO_SHELL")" --eval "rs.status()"
612# Count primary nodes in a MongoDB replica set
613mongo --quiet -u root -p "$(awk -F'"' '/auth/ {print $4}' "$MONGO_SHELL")" --eval "rs.status().members.filter(m => m.stateStr === 'PRIMARY').length"
614# Count secondary nodes in a MongoDB replica set
615mongo --quiet -u root -p "$(awk -F'"' '/auth/ {print $4}' "$MONGO_SHELL")" --eval "rs.status().members.filter(m => m.stateStr === 'SECONDARY').length"
616# Count unhealthy nodes in a MongoDB replica set
617mongo --quiet -u root -p "$(awk -F'"' '/auth/ {print $4}' "$MONGO_SHELL")" --eval "rs.status().members.filter(m => m.health !== 1).length"
618# Check successful connection to MongoDB and replica set status
619mongo --quiet -u root -p "$(awk -F'"' '/auth/ {print $4}' "$MONGO_SHELL")" --eval "rs.status().ok"
620# Check MongoDB replication lag (more than 30 seconds)
621mongo --quiet -u root -p "$(awk -F'"' '/auth/ {print $4}' "$MONGO_SHELL")" --eval 'var s = rs.status(); var p = s.members.find(m=>m.stateStr==="PRIMARY").optimeDate; var bad = s.members.filter(m => m.stateStr==="SECONDARY" && Math.abs(p - m.optimeDate) > 30000).length; print(bad);'
622# Create a .pgpass file for automatic PostgreSQL authentication
623echo 'localhost:5432:mydb:myuser:mypassword' > ~/.pgpass && chmod 0600 ~/.pgpass
624# Enter the PostgreSQL console as the postgres user
625sudo -u postgres psql -U postgres
626# Set or change the PostgreSQL user password
627ALTER USER postgres WITH PASSWORD 'your_new_password'\;
628
629## =================================
630## Virtualization (QEMU/KVM, Proxmox)
631## =================================
632# Install the required tools for working with QCOW2 (qemu-utils, libguestfs-tools)
633
634apt install -y qemu-utils libguestfs-tools
635# Download the Debian 13 QCOW2 cloud image
636curl https://cloud.debian.org/images/cloud/trixie/latest/debian-13-generic-amd64.qcow2 -o debian-13-generic-amd64.qcow2
637# Resize a QCOW2 disk image
638qemu-img resize ./debian-13-generic-amd64.qcow2 20G
639# Configure a QCOW2 image (update, package installation, locales)
640virt-customize -a debian-13-generic-amd64.qcow2 --update --install qemu-guest-agent,locales,zsh,git,curl,neovim,bat,eza,fzf,grc --run-command "echo 'en_US.UTF-8 UTF-8' >> /etc/locale.gen" --run-command "echo 'ru_RU.UTF-8 UTF-8' >> /etc/locale.gen" --run-command "locale-gen"
641# Set permissions and owner for a file
642chmod 640 /tmp/.zshrc && chown root: /tmp/.zshrc
643# Copy a file from the host into a QCOW2 image
644virt-copy-in -a ./debian-13-generic-amd64.qcow2 /host/path /guest/path
645# Edit a file inside a QCOW2 image
646virt-edit -a ./debian-13-generic-amd64.qcow2 /guest/path
647# Mount a QCOW2 disk image
648guestmount -i -a ./debian-13-generic-amd64.qcow2 /mnt/qcow2
649# Unmount a QCOW2 disk image
650guestunmount /mnt/qcow2
651# Start an interactive guestfish shell for a QCOW2 image
652guestfish -i -a ./debian-13-generic-amd64.qcow2
653# Run a shell command inside a QCOW2 image (through guestfish)
654sh 'grep root /etc/passwd'
655# Print directory contents inside a QCOW2 image
656virt-ls -a ./debian-13-generic-amd64.qcow2 /path
657# View file contents inside a QCOW2 image
658virt-cat -a ./debian-13-generic-amd64.qcow2 /path/to/file
659# Copy a file from a QCOW2 image to the host
660virt-copy-out -a ./debian-13-generic-amd64.qcow2 /guest/path /host/path
661# Create a tar archive from directory contents inside a QCOW2 image
662virt-tar-out -a ./debian-13-generic-amd64.qcow2 /path /host/archive.tar
663# Extract a tar archive into a directory inside a QCOW2 image
664virt-tar-in -a ./debian-13-generic-amd64.qcow2 ./archive.tar /guest/path
665# Print the list of file systems inside a QCOW2 image
666virt-filesystems -a ./debian-13-generic-amd64.qcow2
667# Extract the Linux kernel from a QCOW2 image
668virt-get-kernel -a ./debian-13-generic-amd64.qcow2
669# Read system logs from a QCOW2 image
670virt-log -a ./debian-13-generic-amd64.qcow2
671# Get information about the operating system inside a QCOW2 image
672virt-inspector -a ./debian-13-generic-amd64.qcow2
673# Show disk space usage inside a QCOW2 image
674virt-df -a ./debian-13-generic-amd64.qcow2
675# Create a virtual machine image with virt-builder
676virt-builder <os-name>
677# Manage the image repository for virt-builder
678virt-builder-repository
679# Configure a QCOW2 image (package installation, adding an SSH key)
680virt-customize -a ./debian-13-generic-amd64.qcow2 --install vim --ssh-inject root:file:id_rsa.pub
681# Prepare a QCOW2 image for deployment (cleanup, zeroing)
682virt-sysprep -a ./debian-13-generic-amd64.qcow2
683# Reduce the size of a QCOW2 image by removing empty blocks
684virt-sparsify ./debian-13-generic-amd64.qcow2 <out.qcow2>
685# Resize partitions inside a QCOW2 image
686virt-resize --expand /dev/sda1 in.qcow2 out.qcow2
687# Install libguestfs-tools for managing images in Proxmox
688apt update && apt install -y libguestfs-tools
689# Download the Debian 13 QCOW2 cloud image
690curl https://cloud.debian.org/images/cloud/trixie/latest/debian-13-generic-amd64.qcow2 -o debian-13-generic-amd64.qcow2
691# Resize a QCOW2 image for use in Proxmox
692qemu-img resize ./debian-13-generic-amd64.qcow2 20G
693# Create a new virtual machine in Proxmox
694qm create 7777 --name "debian13-k8s-template" --memory 2048 --cores 2 --net0 virtio,bridge=vmbr0
695# Import a QCOW2 image as a disk for a Proxmox VM
696qm importdisk 7777 ./debian-13-generic-amd64.qcow2 storage --format qcow2
697# Attach the imported disk to the VM as a SCSI device
698qm set 7777 --scsihw virtio-scsi-single --scsi0 storage:7777/vm-7777-disk-0.qcow2
699# Set the Proxmox VM boot order
700qm set 7777 --boot order=scsi0
701# Add a virtual disk for Cloud-Init to the VM
702qm set 7777 --ide0 storage:cloudinit
703# Enable serial console for the Proxmox VM
704qm set 7777 --serial0 socket --vga serial0
705# Enable QEMU Guest Agent for the VM
706qm set 7777 --agent enabled=1
707# Convert the Proxmox VM to a template
708qm template 7777
709# Rescan the Proxmox VM configuration
710qm rescan --vmid 7777
711# Show the full Proxmox VM configuration
712qm config 7777
713# Add a new user role in Proxmox (pveum)
714pveum role add TFUser -privs "Pool.Allocate VM.Console VM.Allocate VM.Clone VM.Config.CDROM VM.Config.CPU VM.Config.Cloudinit VM.Config.Disk VM.Config.HWType VM.Config.Memory VM.Config.Network VM.Config.Options VM.Audit VM.PowerMgmt VM.GuestAgent.Audit Datastore.AllocateSpace Datastore.Allocate Datastore.Audit SDN.Use"
715# Add a new user in Proxmox (pveum)
716pveum user add tfuser@pve
717# Assign a role to a Proxmox user
718pveum aclmod / -user tfuser@pve -role TFUser
719# Create an API token for a Proxmox user
720pveum user token add tfuser@pve tf --privsep 0
721
722## =============================================
723## Infrastructure as Code (OpenTofu / Terraform)
724## =============================================
725# Initialize an OpenTofu working directory with module updates
726tofu init -upgrade
727# Check OpenTofu configuration syntax and logic
728tofu validate
729# Reconfigure the OpenTofu backend with new parameters
730tofu init -reconfigure -backend-config="path=./dev.tfstate"
731# Generate an OpenTofu execution plan
732tofu plan -var-file=./dev.tfvars
733# Create an execution plan and save it to a file
734tofu plan -var-file=./dev.tfvars -out ./dev.tfplan
735# View the saved OpenTofu plan file
736tofu show ./dev.tfplan
737# Apply changes described in the OpenTofu configuration
738tofu apply -var-file=./dev.tfvars
739# Apply changes with the specified parallelism level
740tofu apply -var-file=./dev.tfvars -parallelism=2
741# Destroy all resources managed by the OpenTofu configuration
742tofu destroy -var-file=./dev.tfvars
743# Check whether OpenTofu files match standard formatting
744tofu fmt -check
745# Automatically format OpenTofu configuration files
746tofu fmt
747# Recursively format OpenTofu configuration files
748tofu fmt -recursive
749# Enable debug logging for OpenTofu (DEBUG level)
750export TF_LOG="DEBUG"
751# Set the path for the OpenTofu log file
752export TF_LOG_PATH="tofu.log"
753# Follow OpenTofu logs in real time
754tail -f ./tofu.log
755# Disable OpenTofu debug logging
756unset TF_LOG TF_LOG_PATH
757
758## ==========================================
759## Containerization (Docker, Kubernetes, Helm)
760## ==========================================
761# Create a custom bridge-type Docker network
762docker network create --opt com.docker.network.bridge.name=br-monitoring --opt com.docker.network.enable_ipv6=false --driver bridge --subnet 172.22.22.0/24 --gateway 172.22.22.1 monitoring_network
763# Start a container and connect it to an existing network
764docker run -it --rm --network swarm_network alpine sh
765# Build a Docker image from a Dockerfile
766docker build -t r4venme/test .
767# Build a multi-architecture Docker image with Buildx
768docker buildx create --use && docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 -t r4venme/test:1.0 ./
769# Start a container with network utilities using another container's resources
770docker run --rm -it --network=container:test --pid container:test wbitt/network-multitool:alpine-extra bash
771# Analyze Docker image contents with Dive
772docker run --rm -it -v /var/run/docker.sock:/var/run/docker.sock wagoodman/dive:latest nginx:1.29
773# Get information about various Kubernetes objects in a namespace
774kubectl -n name_space get pods,svc,pvc,sts,pv -o wide
775# Show labels for all Kubernetes nodes
776kubectl get nodes --show-labels
777# Force-delete all resources in the specified namespace
778kubectl delete all --all -n name_space --force --grace-period=0
779# Check YAML manifest syntax on the client side
780kubectl apply --dry-run=client -f your-manifest.yaml
781# Check a manifest with the Kubernetes API server without applying changes
782kubectl apply --dry-run=server -f your-manifest.yaml
783# Add an external Helm chart repository
784helm repo add gitea-charts https://dl.gitea.com/charts/
785# Search charts in the added Helm repository
786helm search repo gitea-charts
787# Download and unpack a Helm chart
788helm pull gitea-charts/gitea --untar
789
790## ==========================
791## Version control (Git)
792## ==========================
793# Initialize a new Git repository and add the remote origin
794git init --initial-branch=main && git remote add origin ssh://git@github.com/r4ven-me/reponame.git
795# Initialize a Git repository with user and origin configuration
796git init --initial-branch=main && git config user.name "Ivan Cherniy" && git config user.email "kar-kar@r4ven.me" && git remote add origin ssh://git@github.com/r4ven-me/reponame.git
797# Add, commit, and push changes to the remote repository
798git add . && git commit -m 'upd' && git push
799# Show a nice graphical Git log
800git log --pretty=format:"%h %ad | %s%d [%an]" --graph --date=short
801# Create .gitkeep files in empty repository directories
802find /path/to/repo/ -type d -empty -exec touch {}/.gitkeep \;
803
804## =======================
805## Automation (Ansible)
806## =======================
807# Print the current Ansible inventory
808ansible-inventory --list
809# Gather system facts for the specified host
810ansible debian12-vpn -m setup -a 'filter=os_family,distribution_version'
811# Run an Ansible playbook with extra variables
812ansible-playbook playbook.yml -e 'user_name=root' -e 'user_home=/root'
813# Run a shell command on a remote host through Ansible
814ansible debian12-vpn -b -m shell -a 'systemctl start service_name'
815
816## ==========================
817## Miscellaneous / System utilities
818## ==========================
819# Print information about LVM logical volumes and snapshots
820lvs --options lv_name,lv_size,origin,lv_attr
821# Add a new job to the current user's crontab
822{ crontab -l; echo "0 3 * * 0 ls -l &> dirs.txt"; } | crontab -
823# Force system reboot through SysRq
824echo b > /proc/sysrq-trigger
825# Print help for Magic SysRq Key
826echo h > /proc/sysrq-trigger; grep 'sysrq: HELP' /var/log/kern.log
827# Enable (activate) a specific CPU core
828echo 1 > /sys/devices/system/cpu/cpu2/online
829# Redirect all script output to syslog and a timestamped file
830exec > >(tee >(logger -t $(basename "${BASH_SOURCE[0]}")) | while IFS= read -r line; do echo "$(date +"[%Y-%m-%d %H:%M:%S.%3N]") - $line"; done | tee -a "${BASH_SOURCE[0]%.*}.log") 2>&1
831# Generate a random alphanumeric string 8 characters long
832cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1
833# Show all 256 terminal foreground colors
834for i in {0..255}; do printf "\e[38;5;%sm%03d " "$i" "$i"; (( (i + 1) % 16 == 0 )) && printf "\e[0m\n"; done; printf "\e[0m\n"
835# Show all 256 terminal background colors
836for i in {0..255}; do printf "\e[48;5;${i}m %03d \e[0m" $i; [ $((($i+1)%8)) -eq 0 ] && echo; done
837# Print only commands from bash history (without numbers and date)
838history | cut -c 26-
839# Check Zabbix agent availability on a host
840zabbix_get -s 192.168.1.100 -p 10050 -k agent.ping
841# Download an example .zshrc configuration
842curl -fsSL https://raw.githubusercontent.com/r4ven-me/dots/main/.zshrc --output /tmp/.zshrc
Click to expand and view more

Copyright Notice

Author: Ivan Cherniy

Link: https://r4ven.me/en/automation/kollekciya-odnostrochnikov-bash/

License: CC BY-NC-SA 4.0

Blog materials may be used with attribution to the author and source, for non-commercial purposes, and under the same license.

Start searching

Enter keywords to search articles

↑↓
ESC
⌘K Shortcut