Skip to content

Latest commit

 

History

62 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 

Repository files navigation

linux-cheat-sheet

This is a collection of useful Linux/shell-commands

Configuring terminal for root

To enable terminal-coloring for root, open /root/.bashrc and uncomment the following lines:

# You may uncomment the following lines if you want `ls' to be colorized:
 export LS_OPTIONS='--color=auto'
 eval "`dircolors`"
 alias ls='ls $LS_OPTIONS'
 alias ll='ls $LS_OPTIONS -l'
 alias l='ls $LS_OPTIONS -lA'

Securing the system

Consider using CaptainZero's fortress script here: https://github.com/captainzero93/security_harden_linux

Thanks to NetworkChuck (https://www.youtube.com/watch?v=ZhMw53Ud2tY)

Step 1: Enable automatic updates

Manual Updates:

apt update
apt dist-upgrade

Automatic Updates:

apt install unattended-upgrades
dpkg-reconfigure --priority=low unattended-upgrades

Step 2: Create a non-root user account (with sudo access)

adduser {username}
usermod -aG sudo {username}

Step 3: Passwords are for suckers!

  1. Create the Public Key Directory on your Linux Server
mkdir ~/.ssh && chmod 700 ~/.ssh
  1. Create Public/Private keys on your computer
ssh-keygen -b 4096
  1. Upload your Public key to the your Linux Server (Windows)
ssh-copy-id -i $env:USERPROFILE/.ssh/id_rsa.pub {username}@{server ip}

Step 4: Lockdown Logins

sudo nano /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no (if you want to only permit certification-login)

Step 5: Firewall it up

See open ports

sudo ss -tulpn

Install, configure and enable ufw

apt install ufw

if unable to find ufw, add repository (debian):

add-apt-repository "deb http://http.debian.net/debian/ jessie main contrib non-free"

See UFW status:

sudo ufw status

Allow port through firewall:

sudo ufw allow 22

Start firewall:

sudo ufw enable

Restart firewall:

sudo ufw reload

Installing Apache

Following https://www.tecmint.com/install-apache-with-virtual-hosts-on-debian-10/

apt install apache2 -y #install
systemctl start apache2 #start service
systemctl enable apache2 #start on boot

sudo ufw allow 80/tcp #allow through firewall

Configuring virtual hosts

Always configure virtual hosts in /etc/apache2/sites-available/

Example with domain name containing æ,ø,å and files in /var/www/alpha

<VirtualHost *:80>
	# Actual domain name is alpha.bodø.city but since it contains 
	# non-ascii characters we have to use punycode, more info:
	# http://handbok.dinstudio.no/0/37/o-a-i-domenenavn/
	# https://www.punycoder.com/
	
        ServerName alpha.xn--bod-2na.city
        ServerAlias www.alpha.xn--bod-2na.city

        ServerAdmin arvid@bodø.city
        DocumentRoot /var/www/alpha

	ErrorLog ${APACHE_LOG_DIR}/error-alpha.log
        CustomLog ${APACHE_LOG_DIR}/access-alpha.log combined
</VirtualHost>

When finished, enable site with command:

a2ensite site.name.conf

Always restart service after making changes:

systemctl reload apache2

Disable site with:

a2dissite site.name.conf

Limiting access with .htaccess files

https://www.linode.com/docs/guides/how-to-set-up-htaccess-on-apache/ https://phoenixnap.com/kb/how-to-set-up-enable-htaccess-apache By creating a file called .htaccess in a directory served by apache, you can limit access to files and folders based on a pattern i.e. disallowing .git folder:

RedirectMatch 404 /\.git

or disallowing directory listing (showing files and folders if no index-file is present):

Options -Indexes

But first you have to enable it by adding the following to your vhost conf (inside virtualhost definition):

<Directory /var/www/html-templates>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

HTTPS / Creating a SSL certificate

Install Certbot

sudo add-apt-repository ppa:certbot/certbot
apt-get install software-properties-common
apt install python-certbot-apache
certbot --apache -d templates.arvid.software

Installing PHP

Following https://computingforgeeks.com/how-to-install-latest-php-on-debian/

sudo apt -y install lsb-release apt-transport-https ca-certificates 
sudo wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg
echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" | sudo tee /etc/apt/sources.list.d/php.list
sudo apt update
sudo apt -y install php7.4
sudo apt install php libapache2-mod-php php-mysql

Installing MySQL

wget http://repo.mysql.com/mysql-apt-config_0.8.13-1_all.deb
sudo apt install ./mysql-apt-config_0.8.13-1_all.deb
#apt update
#apt upgrade should work
sudo apt-get install mysql-community-server
sudo systemctl status mysql

Creating database and user

CREATE DATABASE stock;
CREATE USER 'stock'@'localhost' IDENTIFIED BY 'StockFish123';
GRANT ALL PRIVILEGES ON stock.* TO 'stock'@'localhost';
FLUSH PRIVILEGES;

or use the built-in python-script to generate SQL code for you:

C:\Users\Arvid\Desktop\git\linux-cheat-sheet>python create_mysql_db_and_usr.py

Welcome!

This script will generate sql for creating a database, user,
and giving the user full permissions on the specified host like this example:

********************************************
CREATE DATABASE <dbname>;
CREATE USER '<usr>'@'<host>' IDENTIFIED BY '<pw>';
GRANT ALL PRIVILEGES ON <dbname>.* TO '<usr>'@'<host>';
********************************************

Enter value for host (default: localhost):
Enter value for db (default: ): phpmyadmin
Enter value for usr (default: ): phpmyadmin
Enter value for pw (default: ): Php@Myadm123!
********************************************

CREATE DATABASE phpmyadmin;
CREATE USER 'phpmyadmin'@'localhost' IDENTIFIED BY 'Php@Myadm123!';
GRANT ALL PRIVILEGES ON phpmyadmin.* TO 'phpmyadmin'@'localhost';

********************************************

Installing MariaDB

Latest tutorial: DigitalOcean Debian 11 MariaDB Installation

apt install mariadb-server
mysql_secure_installation

Answer according to the tutorial on the questions that come.

When you are finished you can simply

root@localhost:~# mariadb
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 36
Server version: 10.5.15-MariaDB-0+deb11u1 Debian 11

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

If the database I want to create is called games, a common way to go is to create a user with the same name that has full access to the database.

Remember that database users are always created by specifying the location/hostname/IP of the user (aka the application server).

However you can ignore this by specifying *

database: games username: games password:ChangeMyPassword123 hostname/IP if the application server: *

Installing PHP-mysql connector

sudo apt install php7.4-mysqli

Installing phpMyAdmin

Following #https://phoenixnap.com/kb/how-to-install-phpmyadmin-on-debian-10 #sudo apt install php php-cgi php-mysqli php-pear php-mbstring php-gettext libapache2-mod-php php-common php-phpseclib php-mysql -y #do I need all these?

https://computingforgeeks.com/install-phpmyadmin-with-apache-on-debian-10-buster/

Do we reaaally need phpmyadmin?

PGP Encryption

sudo apt install gnupg2 gpa
gpg --full-generate-key #1 enter #4096 enter #0 enter #y #<name and email> #o enter 
#enter passphrase

sudo gpa

Useful applications

Tmux (terminal multiplexer)

hamvocke.com - quick and easy guide to tmux

Nice cheat-sheet MohamedAlaa@github

Tmux allows you to split your terminal in many ways

Installation

sudo apt install tmux

Usage

Commands:
tmux creates a new tmux-session with a nice all-green status bar at the bottom
tmux new -s monitoring creates a new session called "monitoring"
exit exits a tmux-session
tmux ls lists active tmux-sessions
tmux attach -t 0 attaches to session id 0
tmux attach -t monitoring attaches to session with name "monitoring"

If tmux is running but you get the following error:

no server running on /tmp/tmux-1000/default

pkill -USR1 tmux

it works sometimes :)

Keyboard shortcuts:
ctrl + b + d disconnects from the current session
ctrl + b + % splits screen vertically
ctrl + b + " splits screen horizontally
ctrl + b then release the b-key and use arrows to resize window

Keyboard shortcut-commands:
ctrl + b + : to open the command prompt

:set-option -g mouse on
:set -g default-terminal "screen-256color"
:set-option history-file ~/.bash_history 
:resize-pane -D (Resizes the current pane down)
:resize-pane -U (Resizes the current pane upward)
:resize-pane -L (Resizes the current pane left)
:resize-pane -R (Resizes the current pane right)
:resize-pane -D 10 (Resizes the current pane down by 10 cells)
:resize-pane -U 10 (Resizes the current pane upward by 10 cells)
:resize-pane -L 10 (Resizes the current pane left by 10 cells)
:resize-pane -R 10 (Resizes the current pane right by 10 cells)

nload (network load)

Shows network in/out traffic as a nice graph

sudo apt install nload to install
nloadto start the monitoring-application

top

Shows process information similar to task manager in windows

top to start
f to open filter-settings shift + s write current settings to configuration file

Useful arguments:

Parameter Description
-i Do not show idle processes

s-tui

shows a nice graph displaying cpu-load

sudo apt install s-tui to install
s-tui to start

iotop

disk activity monitoring, similar to "top" but for disk activity instead

sudo iotop to run Useful arguments

Parameter Description
-o Only show active processes (that actually does I/O)
-P Show processes instead of threads

htop

like top but better apt install htop

Glances

The best monitoring utility Behaves smart

apt install glances

Glances picture

Tips & tricks

Searching for files - the find command

find / -name tmux.conf

Will search the entire file system for tmux.conf, but will spam out a whole bunch of "permission denied"-messages.
To avoid that use this little trick:

find / -name tmux.conf 2>&1 | grep -v "Permission denied"

To find files CONTAINING a search string use *

find / -name *history*

SSH keepalive

To prevent users disconnecing from terminal, add the following lines to your /etc/ssh/sshd_config

TCPKeepAlive yes
ClientAliveInterval 60

Monitoring failed login attempts

grep "authentication failure" /var/log/auth.log | awk '{ print $13 }' | cut -b7- | sort | uniq -c

Tools

Name Description
grep Finds information in input
awk Filters columns?
sed
wc Word count
sort
cut
uniq

awk

https://www.geeksforgeeks.org/awk-command-unixlinux-examples/

pstree

pstree -p shows a tree structure of which processes spawned from where

Resources

Cheat sheets

  1. https://cheatography.com/davechild/cheat-sheets/linux-command-line/

cs-page-1 cs-page-2

VSCode Remote SSH process memory problem

If you use VSCode with the remote SSH plugin, you will sometimes see hanging processes even after you exit. These can take up a lot of memory when they pile up. The processes are spawned because VSCode tries to do some autocorrect stuff described here

  1. Hit the extensions button in VS Code (which looks like building blocks on the left toolbar)
  2. Search for ‘@builtin TypeScript’
  3. Disable the TypeScript and Javascript Language Features extension
  4. Reload

Bluetooth on Linux (bluetoothctl)

apt install bluez

systemctl start bluetooth

All commands prepended by bluetoothctl <command> when done outside the interactive shell, otherwise you can do all the commands directly into the shell spawned by bluetothctl

Initial pairing

discoverable on

scan on

pair 78:2B:64:A2:F8:F1

trust 78:2B:64:A2:F8:F1

If names do not show, try this:

bluetoothctl devices | cut -f2 -d' ' | while read uuid; do bluetoothctl info $uuid; done|grep -e "Device\|Connected\|Name"

Every time

connect 78:2B:64:A2:F8:F1

and when done:

disconnect

Todo

power on

This video is nice:

Youtube - BugsRider Bluetoth Guide

IMG

ls

https://www.linuxcommands.site/linux-file-and-directory-commands/linux-ls-sort/

Mounting USB partition manually

Identify USB-device lspci lsusb dmesg | less

sudo pmount /dev/sda1 /media/a

partition now mounted

Setting up VPN over SSH with Python

VPN SSH Python guide

sudo apt-get install sshuttle
sudo yum install git
git clone git://github.com/apenwarr/sshuttle
sudo sshuttle -r user@remote_host 0.0.0.0/0 --dns
sudo sshuttle -r user@remote_host 172.194.0.0/16 172.195.0.0/16

Neofetch (nice looking status motd)

apt install neofetch
echo neofetch >> ~/.bash_profile # run automatically on login

Desktop stuff

Redshift (blue light filter)

apt install redshift
mkdir ~/.config/redshift
wget https://raw.githubusercontent.com/jonls/redshift/master/redshift.conf.sample
mv redshift.conf.sample ~/.config/redshift/redshift.conf

tcpdump

hackertarget.com examples

cyberciti.biz

tcpdump tutorial daniel miessler

tcpdump cheat sheet by packetlife

tcpdump cheat sheet comapitech

Pipe/redirecting output/etc | > >>

redirect the output (AKA stdout) to a file:

SomeCommand > SomeFile.txt  

Or if you want to append data:

SomeCommand >> SomeFile.txt

If you want stderr as well use this:

SomeCommand &> SomeFile.txt  

or this to append:

SomeCommand &>> SomeFile.txt  

if you want to have both stderr and output displayed on the console and in a file use this:

SomeCommand 2>&1 | tee SomeFile.txt

(If you want the output only, drop the 2 above)

PostgresQL installation on Linux (Debian 11)

First install

sudo apt-get -y install postgresql

Hostname get / set

Display hostname:

hostnamectl

Change hostname:

hostnamectl set-hostname <hostname> --static 

Update $PS1 variable in ~/.bashrc if you want full hostname displayed in prompt

Variable Value
\h hostname (short)
\H hostname (full)

Update from \h to \H:

if [ "$color_prompt" = yes ]; then
    PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\H\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
    PS1='${debian_chroot:+($debian_chroot)}\u@\H:\w\$ '
fi

More commands: https://linuxhint.com/bash-ps1-customization/

Remote desktop client for Linux

xfreerdp <ip>

Changing desktop environment ( on Debian 11/12 )

Very nice guide from https://linuxhint.com/change-debian-desktop-environment/

WSL-stuff

Command on Windows to forward port

netsh interface portproxy add v4tov4 listenport=4000 listenaddress=0.0.0.0 connectport=4000 connectaddress=192.168.101.100

Copying over a large number of files via SSH

tar czf - <filename> | ssh <hostname> "cd <target-directory> && tar zxvf -"

Cinnamon stuff

Cinnamon on Archlinux Wiki

Starting Cinnamon manually

If you prefer to start Cinnamon manually from the console, add the following line to Xinitrc:

~/.xinitrc
exec cinnamon-session

Debian-stuff (?)

Choosing which desktop-environment to install can be done during the installation or by running the following command:

tasksel

Libraries (common)

Library Description How to Use (compile/link)
glibc Core C library (syscalls, I/O, memory, sockets) Included by default, headers <stdio.h>, <stdlib.h>.
libm Math functions (sin, cos, sqrt) #include <math.h> → gcc prog.c -lm
libpthread POSIX threads #include <pthread.h> → gcc prog.c -lpthread
libdl Dynamic linking/loading of shared libs (dlopen, dlsym) #include <dlfcn.h> → gcc prog.c -ldl
librt Real-time (timers, POSIX semaphores, message queues) #include <time.h>, <mqueue.h> → gcc prog.c -lrt
libstdc++ Standard C++ library (STL, streams) Auto-linked by g++, can explicitly add -lstdc++
libgcc Low-level compiler support (exceptions, div ops) Auto-linked by GCC, no manual step
libcrypt Password hashing, crypt functions #include <crypt.h> → gcc prog.c -lcrypt
libnsl Network services (RPC, NIS, legacy) #include <rpc/rpc.h> → gcc prog.c -lnsl
libresolv DNS resolver functions (res_query, res_init) #include <resolv.h> → gcc prog.c -lresolv
libutil Misc. system utils (pty, login) #include <pty.h> → gcc prog.c -lutil
libsystemd Interfaces with systemd (logging, services) #include <systemd/sd-daemon.h> → gcc prog.c -lsystemd
libpam Authentication via PAM modules #include <security/pam_appl.h> → gcc prog.c -lpam
libX11 X11 graphics client lib #include <X11/Xlib.h> → gcc prog.c -lX11
libwayland Wayland graphics protocol client lib #include <wayland-client.h> → gcc prog.c -lwayland-client
libdrm Direct Rendering Manager (GPU) #include <xf86drm.h> → gcc prog.c -ldrm
libudev Device enumeration & monitoring #include <libudev.h> → gcc prog.c -ludev
libselinux SELinux security policies #include <selinux/selinux.h> → gcc prog.c -lselinux

About

No description, website, or topics provided.

Resources

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages