All The Snippets

Published: Wednesday, January 17, 2024
Last Modified: Friday, October 11, 2024

Here is a collection of (mostly Bash) code snippets for practically everything.

This is not a guide for anything specific.

Only run commands you understand.

Bash

# print all subdirectories with a size larger than 4 GB
du -h ./veracrypt1/ | grep '^[0-9\.]*G' | awk '$1+0 > 4 {print $2}'

# print all files in all subdirectories with a size larger than 4 GB
find . -type f -size +4G

# HTTP "hand off" using SSH
sudo ssh -L <local_port>:<remote_ip>:<remote_port> <public_ip_for_ssh_connection>
E.g.
sudo ssh -L 5000:192.168.2.1:443 71.12.23.52
Go to http://localhost:5000 and you can interact withe the site running on the remote server, 71.12.23.52.

# A yes/no prompt - e.g. yes_or_no "Delete all NGINX confs?" && find /etc/nginx/sites-enabled/ -mindepth 1 -delete
#!/bin/bash
function yes_or_no {
    while true; do
        read -p "$* [y/n]: " yn
        case $yn in
            [Yy]*) return 0  ;;  
            [Nn]*) echo "Aborted" ; return  1 ;;
        esac
    done
}

# Sleep
sleep 3s

# Pause prompt
read -p "Press [Enter] to continue" </dev/tty

# Gnome taskbar position at bottom, center
gsettings set org.gnome.shell.extensions.dash-to-dock extend-height false

# Monitor SSH connection attempts
watch "sudo cat /var/log/auth.log | grep "ssh.*password""

# Set Samba password
sudo smbpasswd -U USER

# Set Timezone
sudo dpkg-reconfigure tzdata

#Check Date
date

# Firewall
sudo ufw allow 4444/tcp
sudo ufw allow from 192.168.0.0/24 to any port 4444
sudo ufw allow from 192.168.0.0/24 to any app Samba
sudo ufw status numbered

# Password Change
sudo passwd USER

# SSH Config [No Password Auth / Alternative Port]
sudo nano /etc/ssh/sshd_config
    PermitRootLogin no
    AllowUsers USER
    Port 4444
    PasswordAuthentication no
    PermitEmptyPasswords no
    PubkeyAuthentication yes

# Permissions
cd /home
sudo chmod -R 700 USER/
sudo chown USER:www-data -R USER/

# OS package repository update
sudo apt update

# Directory Size
du -h -d 1

# File Count
du -a | cut -d/ -f2 | sort | uniq -c | sort -nr

# Rsync Backups
rsync -va --delete --exclude "venv" --exclude ".git" --exclude "__pycache__" /home/USER/Documents/ /media/documents_backup/

# Rsync Backups [Ambiguous SSH Port]
alias _bkcp='rsync -e "ssh -p 4444" -va --delete --exclude "venv" --exclude ".git" --exclude "__pycache__" USER@123.12.34.56:~/dir_1 :/etc/nginx/sites-enabled :/etc/systemd/system/service_1.service  ~/Documents/local/backup/'

# Disk Storage
df -h`

# Logs Sizes
sudo du -h --max-depth=1 /var/log/journal/ | sort -h

# Log Clearing
sudo journalctl --vacuum-size=500M

# Search ports
sudo netstat -peanut | grep 3306

# OpenSSL self-signed certs
openssl req -newkey rsa:2048 -new -nodes -x509 -days 3650 -keyout key.pem -out cert.pem

# Timezone
sudo timedatectl set-timezone

# USB Mount
sudo fdisk -l
sudo lsblk -fm
sudo mount /dev/sdX /media/usb/


# Auto External Drive Mount
sudo mkdir -p /mnt/DRIVE
sudo mount /dev/sdbX /mnt/DRIVE

sudo blkid # prints the UUID of all drives
# Add this to fstab: `UUID=1111111-1d11-111e-11ab-111111 /mnt/DRIVE auto nofail defaults 0 0`
sudo nano /etc/fstab


# Prepend File
echo "SET autocommit=0;" > tmpfile && cat ORIGINAL.txt >> tmpfile && mv tmpfile ORIGINAL.txt

# Append File
echo "COMMIT;" >> ORIGINAL.txt

# MYSQL - New Instance [Local Access]
sudo mysql
SET GLOBAL validate_password.length = 4;
SET GLOBAL validate_password.policy = 'LOW';
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'PASSWORD';
FLUSH PRIVILEGES;

# MYSQL - New Instance [Remote Access]
sudo ufw allow from 192.168.0.0/24 to any port 3306
sudo ufw status numbered

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf
# set `bind-address = 0.0.0.0`

sudo systemctl restart mysql

mysql -u root -p
CREATE USER 'USER'@'192.168.0.11' IDENTIFIED BY 'PASSWORD';
GRANT FILE, CREATE, ALTER, DROP, INSERT, UPDATE, DELETE, SELECT, REFERENCES, RELOAD on *.* TO 'USER'@'192.168.0.11' WITH GRANT OPTION;
FLUSH PRIVILEGES;

sudo systemctl restart mysql

# Import MySQL Dump
mysql -u root -p tablename < tablename.sql

# YouTube Download [Channel Playlist]
yt-dlp.exe -f best -ciw -o "/path/to/video/%(title)s-%(id)s.%(ext)s" -v --datebefore 20170101 --max-downloads 150 --playlist-reverse URL_LINK

# YouTube Download [Channel Playlist Reversal With Date Range]
"/path/to/scripts/yt-dlp.exe" -f best -iw -o "/path/to/video/%(upload_date)s___%(title)s___%(id)s.%(ext)s" --playlist-reverse --datebefore 20160601 --dateafter 20130814 URL_LINK

# YouTube Download [Single Video]
"/path/to/yt-dlp.exe" -f best -ciw -o "/path/to/video/%(title)s-%(id)s.%(ext)s" URL_LINK

# YouTube Download [Text File URLs]
"/path/to/yt-dlp.exe" -f best -cwi -o "/path/to/new/%(title)s-%(id)s.%(ext)s" -v -a "/path/to/links.txt"

# YouTube Download [Extract Audio]
"/path/to/yt-dlp.exe" URL_LINK -o "output.mp3" -x --audio-format "mp3"

**\~/.bashrc**

alias _rc='nano ~/.bashrc'
alias _src='source ~/.bashrc'

_mood() { sudo systemctl status $1; }
_nap() { sudo systemctl restart $1; }
_end() { sudo systemctl stop $1; }
_wake() { sudo systemctl start $1; }
_config() { sudo nano /etc/systemd/system/$1.service; }

_tell() { sudo journalctl -ex; }

_load() { sudo systemctl daemon-reload; }

**alias.cmd**

:: Create aliases on for Windows CMD
:: To run on cmd start ups, follow instructions from https://superuser.com/a/916478

@echo off
DOSKEY gpm=git push --set-upstream origin master
DOSKEY gpd=git push --set-upstream origin dev
DOSKEY gcd=git checkout dev
DOSKEY gcm=git checkout master
DOSKEY gs=git status
DOSKEY ga=git add .
DOSKEY gr=git remote add origin
DOSKEY ls=dir

**precommit.bat**

# precommit sequence for python projects on windows
@echo off 
:start
cls
echo Running isort...
py -m isort .
echo Running black...
py -m black . -S
echo Running pylint...
py -m pylint ./src --disable=C0116,C0114,E0401,C0413,C0103,C0115,I1101,E1101
echo Running coverage...
coverage run ".\test\test_all.py"
coverage html
coverage json --pretty-print
echo Updating README.md badges...
py ./src/utils/badges.py
set /p run_again="Would you like to rerun? (y/n) "
if "%run_again%" EQU "y" (
    goto :start
)
pause

HTML

**Gradient Gauge**

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        html {
            font-family: system-ui;
        }
        .gradient-bar {
            width: 100%;
            height: 50px;
            background: linear-gradient(to right, #ff4400 0%, #fcfc00 50%, #00b100 100%);
            position: relative;
            border-radius: 4px;
        }
        span {
            position: absolute;
            top: 50%;
            transform: translate(-50%, -50%);
            font-weight: bold;
            font-size: 16px;
            color: #0e0e0e;
            background-color: #cecece82;
            text-align: center;
            width: max-content;
            padding: 2px;
            border-radius: 4px;
        }
        .bottom {
            left: 10%;
        }
        .middle {
            left: 50%;
        }
        .top {
            left: 88%;
        }
    </style>
</head>
<body>
<div class="gradient-bar">
    <span class="bottom">0% - 25%<br>Poor</span>
    <span class="middle">40% - 60%<br>Good</span>
    <span class="top">80% - 100%<br>Excellent</span>
</div>
</body>
</html>
Comment
Optional
No comments yet...