Alaska.Labs Cheat Sheet

Filesystem

Delete all folders older 7 days

find ./SOMEFOLDER/*/* -maxdepth 0 -mtime +7 -type d -exec rm -r {} \;

Cron

Edit your crontab

crontab -e

Edit root crontab

sudo crontab -e

List cron jobs

crontab -l

Environment

Set globally

sudo nano /etc/environment

System wide proxy

Edit environment

http_proxy=http://yourproxy:8080/
https_proxy=http://yourproxy:8080/
HTTP_PROXY=http://yourproxy:8080/
HTTPS_PROXY=http://yourproxy:8080/

To load the new variables:

source /etc/environment

Apt proxy

touch /etc/apt/apt.conf.d/95proxies

Fill in

Acquire::http::proxy "http://yourproxy:8080/";
Acquire::ftp::proxy "ftp://yourproxy:8080/";
Acquire::https::proxy "http://yourproxy:8080/";

Edit profile

nano .profile
PATH=$PATH:/usr/local/go/bin
GOPATH=$HOME/go

Load profile

source .profile

Cowsay the correct way

Thanks to https://superuser.com/questions/529407/scp-giving-out-a-blank-line-and-not-transfering-files

The usage of cowsay can cause problems when trying to transfer files via scp. Line 1-4 prevent the execution of cowsay, if an non-interactive connection is established.

Edit .bashrc

case $- in
    *i*) ;;
    *) return;;
esac

fortune | cowsay

Systemd

List all Serives

sudo systemctl list-unit-files

Passwords

Hash md5

echo PASSWORD | md5sum

Network

Who is listening on which port

netstat -ntpl

Flush DNS

sudo systemd-resolve --flush-caches

Apache

Reverse proxy

Install

sudo apt-get install apache2
sudo a2enmod proxy
sudo a2enmod proxy_http

Edit /etc/apache2/sites-available/000-default.conf

<VirtualHost *:80>
ProxyPreserveHost On
ProxyRequests off
ProxyPass / http://127.0.0.1:3000/
ProxyPassReverse / http://127.0.0.1:3000/
</VirtualHost>

Restart

sudo systemctl restart apache2

.htaccess

Edit /etc/apache2/sites-available/000-default.conf

<VirtualHost *:80>
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:8000/NAME
ProxyPassReverse / http://127.0.0.1:8000/NAME
</VirtualHost>

Add .htaccess to VirtualHost

<Location /NAME>
AuthType Basic
AuthName “Wrapper auth”
AuthBasicProvider file
AuthUserFile “/PATHTOHTPASSWD/htpasswd”
Require valid-user
</Location>

Self signed certificates

Create certificate

sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/ssl/private/apache-selfsigned.key -out /etc/ssl/certs/apache-selfsigned.crt

You will be asked for some infomation. Just put in, what you want:

Country Name (2 letter code) [AU]:
State or Province Name (full name) [Some-State]:
Locality Name (eg, city) []:
Organization Name (eg, company) [Internet Widgits Pty Ltd]:
Organizational Unit Name (eg, section) []:
Common Name (e.g. server FQDN or YOUR name) []:
Email Address []:

Optional: Create strong Diffie-Hellman

sudo openssl dhparam -out /etc/ssl/certs/dhparam.pem 2048

SSL Params

SSLCipherSuite EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
SSLProtocol All -SSLv2 -SSLv3
SSLHonorCipherOrder On
# Disable preloading HSTS for now. You can use the commented out header line that includes
# the “preload” directive if you understand the implications.
#Header always set Strict-Transport-Security “max-age=63072000; includeSubdomains; preload”
Header always set Strict-Transport-Security “max-age=63072000; includeSubdomains”
Header always set X-Frame-Options DENY
Header always set X-Content-Type-Options nosniff
# Requires Apache >= 2.4
SSLCompression off
SSLSessionTickets Off
SSLUseStapling on
SSLStaplingCache “shmcb:logs/stapling-cache(150000)

Edit /etc/apache2/sites-available/default-ssl.conf

sudo nano /etc/apache2/sites-available/default-ssl.conf

Change to

SSLCertificateFile /etc/ssl/certs/apache-selfsigned.crt
SSLCertificateKeyFile /etc/ssl/private/apache-selfsigned.key

Eanble everything

sudo a2enmod ssl
sudo a2enmod headers
sudo a2ensite default-ssl
sudo a2enconf ssl-params

Restart Apache2

sudo systemctl restart apache2

SSH

Tunnel

ssh -fN  -L 1234:destination_server:4321 username@server
* -f: Force ssh to go to background before one command is executed, but it will display the password prompt.
* -N: Tell ssh not to execute a command (-f would require one command)
* -L: Open a tunnel from the local port 1234 to a destination server with the port 4321

SSHPass

sudo apt-get install sshpass

SSH

sshpass -p ‘strongPassword’ ssh user@192.168.2.77 command_to_run

SCP

sshpass -p ‘strongPassword’ scp *.tar.gz user@192.168.2.77:/home/user

Git

Credentials

git config user.name "someone"
git config user.email "someone@alaskalabs.de"
git config credential.helper store

Push after that:

git push <<URL>>.git

Update all remote branches

git remote update origin --prune

Display all branches

git branch -a

Ignore file changes

git update-index --assume-unchanged src/file/to/ignore 

Gitea

Update

wget -O gitea https://dl.gitea.io/gitea/1.13.6/gitea-1.13.6-linux-amd64
chmod +x gitea
cp /usr/local/bin/gitea /tmp

sudo systemctl stop gitea.service 
sleep 10

sudo cp gitea /usr/local/bin/
sudo systemctl start gitea.service 
sleep 10
sudo systemctl status gitea.service 

Compression

TAR

Compress

tar czvf FILENAME.tar.gz .FOLDER1/ .FOLDER2/

Extract

tar xzvf FILENAME.tar.gz

ZIP

Compress

zip -r -v FILENAME.zip .FOLDER/ ./FOLDER2

Compress all files in folder

for file in *.iso; do zip -v "${file%}.zip" "$file"; done

Compress every subfolder in seperate files

for i in */; do zip -r "${i%/}.zip" "$i"; done

Extract

unzip FILENAME.zip

RAR

Install

suo apt-get install unrar-free

Extract

unrar x FILENAME.rar

Extract all in one folder

for f in *.rar;do unrar e "$f";done

Database

MySQL / Mariadb

Install

sudo apt install mariadb-server mariadb-client
sudo apt install mysql-server mysql-client

Secure it

mysql_secure_installation

Login as root

mysql – u -p<PASSWORD> 

Setup database

CREATE DATABASE 'yourDB';
CREATE USER 'user1'@'%' IDENTIFIED BY 'password1';
GRANT ALL PRIVILEGES ON 'yourDB'.* TO 'user1'@'%';
FLUSH PRIVILEGES;

Migrate

The basic call to backup a MySQL looks like this

mysqldump -u root -p[root_password] [database_name] > dumpfilename.sql

Or for all databases

mysqldump -u root -pSTRONGROOTPASSWORD ––all-databases > backup.sql

(no space between -p and the password!)

Copy

scp backup.sql user@host:/home/user

Import

mysql -u root -p[root_password] [database_name] < backup.sql

Or for all daabases

mysql -u root -pSTRONGROOTPASSWORD < backup.sql

Users

Get all users
SELECT User FROM mysql.user;
Create user
CREATE USER 'myuser'@localhost IDENTIFIED BY 'mypassword';
Grant all rights
GRANT USAGE ON *.* TO 'myuser'@'%' IDENTIFIED BY 'mypassword';
Grant priviledges to specific db
GRANT ALL privileges ON `mydb`.* TO 'myuser'@localhost;
Apply changes
FLUSH PRIVILEGES;

Oracle

Query HOST_NAME

SELECT host_name FROM v$instance;

Query SERVICE_NAME

SELECT value FROM v$parameter WHERE name like ‘%service_name%’;

Postgres

Connect localhost with sudo

sudo -u postgres psql postgres

Create DB and grant rights

CREATE DATABASE new_database;
CREATE USER new_user WITH PASSWORD 'password';
GRANT ALL PRIVILEGES ON DATABASE "new_database" to new_user;

Copy Database

SELECT pg_terminate_backend (pid) FROM pg_stat_activity WHERE datname = 'sourcedb';
CREATE DATABASE targetdb WITH TEMPLATE sourcedb;

Disable pager in psql

\pset pager off

See also

Login

psql -h 127.0.0.1 -U user postgres

Delete all tables

select 'drop table if exists ' || tablename || ' cascade;'  from pg_tables where schemaname = 'public';

Execute the statements.

Backup database with inserts

DATE_WITH_TIME=$(date "+%Y%m%d-%H%M%S")
TARGET_DB=SOME_DATABASE
sudo -u postgres pg_dump --inserts $TARGET_DB | gzip > "$TARGET_DB"-$DATE_WITH_TIME.gz

( –data-only for only the data, without create statements)

Import Backup with inserts and data-only

psql -U USERNAME -d DATABASENAME -a -f FILENAME

or just

\i FILENAME

Add Citus Nodes

psql --dbname=postgres```
CREATE EXTENSION citus;
SELECT * FROM master_add_node('WORKER_IP', 5432);
SELECT * FROM master_get_active_worker_nodes();
SELECT * FROM run_command_on_workers('show ssl');

Powershell

Send mail

try {
    $smtpServer = “mailserver.yourserver”
    $smtpPort = “25”
    $smtpUser = “user”
    $smtpPwd = “password”

    $msg = New-Object System.Net.Mail.MailMessage
    $msg.From = “admin@mailserver.yourserver”
    $msg.To.Add(“user@othermailserver”)
    $msg.Subject = “A Subject”
    $msg.Body = “The Message”
    $msg.IsBodyHtml = $false

    $smtp = New-Object System.Net.Mail.SmtpClient($smtpServer, $smtpPort)
    $smtp.Credentials = New-Object System.Net.NetworkCredential($smtpUser, $smtpPwd)

    $smtp.Send($msg)
} catch {
    exit 1
}

Execute script with arguments

$arg1="Something"
$arg2=80
Powershell.exe -NoProfile -ExecutionPolicy Bypass -Command c:\temp\test.ps1 $arg1 $arg2
  • NoProfile: PowerShell does not load the user profile.
  • Bypass: Nothing is blocked and no warnings or prompts.

Check TCP Port

try{
    $tcp=new-object System.Net.Sockets.TcpClient
    $tcp.Connect("192.168.2.1",80)
    If($tcp.Connected)
    {
        Write-Host "It works"
    }
    else
    {
        Write-Host "It doesnt work"
    }
    $tcp.Close()
}
catch {
  Write-Host "Error"  
}

OPS

Restart failed program every 5 min

Create a script:

nano restart.sh

Put in the code and replace htop with your program name:

#!/bin/sh

ps cax | grep htop > /dev/null
if [ $? -eq 0 ]; then
echo “Process running.”
else
echo “Process is down.”
fi

Make the script executable:

chmod +x restart.sh

Create a cron job:

crontab -e

Create a new line (replace /home/user/):

*/5 * * * * /home/user/restart.sh

Java

Install AdoptOpenJDK

wget -qO - https://adoptopenjdk.jfrog.io/adoptopenjdk/api/gpg/key/public | sudo apt-key add -
sudo add-apt-repository --yes https://adoptopenjdk.jfrog.io/adoptopenjdk/deb/
sudo apt update
sudo apt install adoptopenjdk-8-hotspot

Kill

Stop-Process -processname *java*
Stop-Process -processname *jp2launcher*

Specific - Get PID

$javaActive = jps -v | select-string "<<executionpath>>"
Write-host $javaActive.ToString().Substring(0,$javaActive.ToString().IndexOf(" "))

Kill specific

jps -v | select-string "<<executionpath>>"
Stop-Process $javaActive.ToString().Substring(0,$javaActive.ToString().IndexOf(" "))

Monitor

Register a source in the Windows application log (run as admin):

New-EventLog -LogName Application -Source "My Application"

The checker script (example Android Studio):

$javaActive = jps -v
if($javaActive -like "*-Didea.platform.prefix=AndroidStudio*")
{
 Write-EventLog -LogName Application -Source "My Application" -EntryType Information -EventID 1  -Message "Application is running."
}
else
{
 Write-EventLog -LogName Application -Source "My Application" -EntryType Error -EventID 2  -Message "Application is not running."
 Optional: code to restart
}

Docker

Run with ports and Volumes

docker run -dit -p HOSTPORT:DOCKERPORT -p HOSTPORT:DOCKERPORT -v source=VOLUMENAME,target=/opt/..../ --name NAME IMAGETAG

Export Image

sudo docker save IMAGETAG > NAME.tar & zip -v NAME.zip NAME.tar

Import Image

docker load -i IMAGENAME.tar

Import Conta

Synology

Disable thumbnail generation

cd /var/packages/FileStation/target/sbin/
sudo chmod -x thumbd 
sudo reboot

Search @eaDir

find /volume1/ -type d -name "@eaDir"

Delete @eaDir

find /volume1/ -type d -name "@eaDir" -print0 | xargs -0 rm -rf

Backup all

sudo rsync -auv --delete --progress --exclude '@eaDir' --exclude '#recycle' --stats /volume1/video/ /volumeUSB1/usbshare1-2/video/
sudo rsync -auv --delete --progress --exclude '@eaDir' --exclude '#recycle' --stats /volume1/music/ /volumeUSB1/usbshare1-2/music/
sudo rsync -auv --delete --progress --exclude '@eaDir' --exclude '#recycle' --stats /volume1/photo/ /volumeUSB1/usbshare1-2/photo/
sudo rsync -auv --delete --progress --exclude '@eaDir' --exclude '#recycle' --stats /volume1/homes/ /volumeUSB1/usbshare1-2/homes/
sudo rsync -auv --delete --progress --exclude '@eaDir' --exclude '#recycle' --stats /volume1/books/ /volumeUSB1/usbshare1-2/books/

Multimedia

MOC

Install

sudo apt-get install mocp

Config

On Raspberry PI you will get this error:

pi@pi:~ $ mocp 
Running the server...
Trying JACK...
Trying ALSA...
Trying OSS...

FATAL_ERROR: No valid sound driver!

FATAL_ERROR: Server exited!

Create a correct config:

cp /usr/share/doc/moc/examples/config.example ~/.moc/config

Add correct ALSA config:

ALSADevice = default
ALSAMixer1 = HDMI

LastFM scrobble

wget mocp-scrobbler.py https://raw.githubusercontent.com/fluxid/mocp-scrobbler/master/mocp-scrobbler.py
mkdir ~/.mocpscrob
nano ~/.mocpscrob/config

The config:

[scrobbler]
login=YOUR_LASTFM_LOGIN
password=YOUR_PASSWORD
streams=true
hostname=post.audioscrobbler.com

Start:

#!/bin/bash
python3 mocp-scrobbler.py -d
mocp

Foliate

sudo apt-get install gjs libwebkit2gtk-4.0-dev libwebkit2gtk-4.0-37 meson gettext iso-codes gir1.2-handy-0.0 gir1.2-gspell-1 gir1.2-tracker-2.0

meson build --prefix=/usr
ninja -C build
sudo ninja -C build install

Games

Warzone

Build

sudo apt-get -y install git gcc g++ clang cmake libc-dev dpkg-dev ninja-build zip unzip pkg-config gettext asciidoctor
sudo apt-get -y install libpng-dev libsdl2-dev libopenal-dev libphysfs-dev libvorbis-dev libtheora-dev libxrandr-dev libfribidi-dev libfreetype6-dev libharfbuzz-dev libfontconfig1-dev libcurl4-gnutls-dev gnutls-dev libsodium-dev libsqlite3-dev
mkdir build && cd build
cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCMAKE_INSTALL_PREFIX:PATH=~/wz/install -GNinja ..
cmake --build . --target install
cd ~/wz/install/bin/
./warzone2100