Kumpulan Cheatsheet Linux

 
* Learning Nano

1. Find a text
Ctrl + W

2. Find and Replace
Ctrl + \

3. Find Help
Ctrl + G

4. Cut a Line and Paste
Ctrl + K and Ctrl + U

5. Copy some text and paste-
Copy beging Ctrl + ^ Copy end Ctrl + ^ For pasting Ctrol + U

* Add User 
adduser newuser
groups newuser
usermod -aG sudo newuser
visudo

* List Users
compgen -u 

* List Group Users
compgen -g

# /etc/sudoers
root    ALL=(ALL:ALL) ALL
newuser ALL=(ALL:ALL) ALL # ADD

deluser newuser
deluser --remove-home newuser

visudo

# /etc/sudoers
root    ALL=(ALL:ALL) ALL
newuser ALL=(ALL:ALL) ALL # DELETE

* Find files older than 60 days
find * -mtime +60

* Delete files in backup folder which are older than 60 days
rm -f `find /backup/ -mtime +60`

* Search for a string inside files
grep -H -r “search me” /var/www

* Find files owned by apache user
find /var/www/ -user apache

* Find directories owned by apache user
find /var/www/ -user apache -type d

* Listing files in a directory
ls -lh or
ls -lh -a

* Listing files with size Megabytes
ls -al --block-size=MB

* Copy an entire directory (files + subdirectories)
cp -R existingdir/ newdir/

* Zip up an entire directory
zip -r zipefilename foldername

* Count total number of files in a directory
ls -1 | wc -l
find . -type f | wc -l

* Midnight commander
mc /var

* Ncdu Command
ncdu /var

* Get directory size
du -hs /var/www
du /var
du -BM --max-depth=1 /var | sort -n | tail -n 5 
du -BM --max-depth=<strong>2</strong> /var | sort -n | tail -n 5
du -BM --max-depth=1 <strong>/var/log</strong> | sort -n | tail -n 5
du -x -d1 -h /var  | sort -hr

* Find directory size 
find /var -size +100M -printf '%s %p\n' | sort -n
find . -size +1G
find / -type f -size +1G 2>/dev/null

* Deleted files Still using space
lsof | grep -E '^COM|deleted'

* Get directory size by MB
du --max-depth=1 -B M |sort -rn
du -H /path --max-depth=1 -B M |sort -rn
du -h --max-depth=1 -x /home
du -sh *

* Get amount of free disk space available
df -h
df -H path
du -H path 

* Free Up Space on Ubuntu
- Clean the APT Cache (And Do It Regularly)
du -sh /var/cache/apt/archives
sudo apt-get clean
- Remove Old Kernels (If No Longer Required)
sudo apt-get autoremove --purge

* Get Linux version details
uname -a
cat /proc/version

* Cannot delete oversized directories: /bin/rm: Argument list too long If you’re trying to delete files inside a directory and the following command is not working

/bin/rm -rf *
/bin/rm: Argument list too long. Try this instead: find . -type f -delete

* Use tar Command Through Network Over SSH Session
tar zcvf - /wwwdata | ssh root@192.168.1.201 "cat > /backup/wwwdata.tar.gz"

* How to know the OS Name (Use any of the following one)
cat /proc/version
cat /etc/os-release
lsb_release -a
hostnamectl

* Find the largest files in a directory From the Terminal, if you want to quickly find out what the largest files are in a directory, try this variation of the ls command:
ls -lShr (It will show sorted list)

* If you want the largest file in a directory of a certain type, simply specify the file type with a wildcard to show all files fitting that description:
ls -lShr *.rar

* Show disk usage by current directory and all subdirectories
du | less

* Delete 10000 of files using rm command
find . -name*.mbox’ -print0 | xargs -0 rm

* Mount an ISO File Temporary
mount -t iso9660 -o loop /home/HsPS/disc/security.iso /mnt/cdrom

* Mount NTFS
yum install ntfs-3g
mkdir /mnt/win
mount -t ntfs-3g /dev/sdb1 /mnt/win

* Mount an ISO Permanently
vim /etc/fstab

* create a new line at the end and enter
/home/HsPS/disc/security.iso /mnt/cdrom ro,loop,_netdiv defaults 0 0

* IPVSADM commands
ipvsadm -L -n
ipvsadm -L -nc
ipvsadm -L -n --rate
ipvsadm -L -n --stats

* List Ethernet commands
lspci
lspci | less
lspci | grep -i eth

* Chmod to change all the directories to 755 (-rwxr-xr-x):
find /opt/lampp/htdocs -type d -exec chmod 755 {} \;

* Check OS Release Info
cat /etc/redhat-release

## Output ##
CentOS release 6.6 (Final)

* Following needs redhat-lsb package
lsb_release -a

## Output ##
LSB Version:    :core-4.0-amd64:core-4.0-ia32:core-4.0-noarch:graphics-4.0-amd64:graphics-4.0-ia32:graphics-4.0-noarch:printing-4.0-amd64:printing-4.0-ia32:printing-4.0-noarch
Distributor ID: CentOS
Description:    CentOS release 6.6 (Final)
Release:        6.6
Codename:       Final

* Check if Machine supports Virtualization
grep -E 'svm|vmx' /proc/cpuinfo

* TAR Syntax For compress
tar -cvf output.tar /dirname

* For uncompress
tar -xvf /tmp/data.ta
tar -xvzf community_images.tar.gz

* Linux Standard Base (LSB) To show the release number of installed distribution:
lsb_release -r

* To show the distributor ID:
lsb_release -i

* To show all of the above information:
lsb_release -a

* Concatenated command:
lsb_release -ircd

* To find Out the Kernel Version by using this command:
uname -mrs

Where:
Linux – Kernel name
3.2.0-24-generic – Kernel version
x86_64 – Kernel is 64-bit

* Port Scanning
nmap -sT -O localhost
cat /etc/services | grep 834
netstat -anp | grep 834
lsof -i | grep 834

* Add Default Route
route add default gw 192.168.1.254 eth0

* Excluding directory when creating a .tar.gz file
tar -pczf MyBackup.tar.gz /home/user/public_html/ --exclude "/home/user/public_html/tmp"

* Display files by date (descending)
ls -utlr

* Repeat a command every x interval of time in terminal
watch -n x <your command>

* TCPDump Capture and Save Packets in a File
tcpdump -w /tmp/0001.pcap -i eth0

## or
tcpdump -w 0001.pcap -i eth0 port 80
TCPDump Capture Packets from source IP
tcpdump -i eth0 src 192.168.0.2
TCPDump Capture Packets from destination IP
tcpdump -i eth0 dst 50.116.66.139
TCPDump Capture IP address Packets
tcpdump -n -i eth0

* TCPDump Capture Only N Number of Packets
tcpdump -c 5 -i eth0

* ARP Scan (Find Connected Systems in the network)
arp-scan -I wlan0 192.168.1.0/24

* Check Hypervisor
apt-cache search virt-what

* virt-what - detect if we are running in a virtual machine
sudo apt-get install virt-what
sudo virt-what

## or
sudo dmidecode | egrep -i 'manufacturer|product|vendor'

## or
sudo egrep -i 'virtual|vbox' /var/log/dmesg

* How to Find a Specific String or Word in Files and Directories The command below will list all files containing a line with the text “check_root”, by recursively and aggressively searching the ~/bin directory.

grep -Rw ~/bin/ -e 'check_root'

* You should use the sudo command when searching certain directories or files that require root permissions (unless you are managing your system with the root account).

sudo grep -Rw / -e 'check_root'

* To ignore case distinctions employ the -i option as shown:
grep -Riw ~/bin/ -e 'check_root'

* If you want to know the exact line where the string of text exist, include the -n option.
grep -Rinw ~/bin/ -e 'check_root'
grep -Rnw --include=\*.sh ~/bin/ -e 'check_root'

* If you want to know the exact line where the string of text exist, include the -n option.
grep -Rinw ~/bin/ -e 'check_root' -e 'netstat'

* View Bash History and delete it permanently! To view histroy just type-

history

* Dump History to a file
history > history.txt

* to delete the history /root/.bash_hitory file use the command instead!-
cat /dev/null > ~/.bash_history && history -c && exit

* Check Linux OS
uname -a
lsb_release -a
lsb_release -a
cat /etc/issue.net
cat /etc/debian_version

* What is my IP
curl -s checkip.dyndns.org | sed -e 's/.*Current IP Address: //' -e 's/<.*$//'

* Clear Cache in Linux
sync; echo 1 > /proc/sys/vm/drop_caches
sync; echo 2 > /proc/sys/vm/drop_caches
sync; echo 3 > /proc/sys/vm/drop_caches

* Copy a folder keeping owners and permissions intact
cp -rp /home/my_home /media/backup/my_home

* Change hostname in CentOS 7
hostnamectl set-hostname your-new-hostname

* reboot OS
reboot 

* Finding free IPs from the range using nmap
sudo nmap -v -sn -n 192.168.1.0/24 -oG - | awk '/Status: Down/{print $2}'

* Linux system resource command
lshw
lshw -short
lshw -html > lshw.html

* Recursively look for files with a specific extension
find $directory -type f -name "*.in"

* Monitor Copy command progress
watch -n 0.1 du -h /opt/dump.tar.gz

## or
watch -n 0.1 ls -h /opt/dump.tar.gz

* verify the speed of my NIC
sudo ethtool eth0 | grep Speed
Speed: 1000Mb/s

* Remount /etc/fstab Without Reboot in Linux
mount -a

* View file as uncommented 
grep -v "^#" your_file | grep -v "^$" | less

* Make scp copy hidden files
scp -rp src/. user@server:dest/

* speed-test
speed-test-cli 

* sync and rsync copy data
rsync 

* Login SSH With Key
ssh-keygen -t rsa -b 4096 -C "your_email@host.com"
cat ~/.ssh/id_rsa.pub > ~/.ssh/authorized_keys
cd /home/deploy
cat ~/.ssh/id_rsa > key

scp [user:host]/home/deploy/key your_path_dest/key

scp -r user@host:/home/path_src your_path_dest/

chmod 400 key
ssh -i key deploy@your_ip_public_remote

* Login menggunakan Copy Public Key ke remotehost dengan ssh-copy-id 

dengan key : 
ssh-copy-id -i ~/.ssh/id_rsa.pub root@remotehost -p 22

tanpa key: 
ssh-copy-id root@remotehost -p 22

Login ke remotehost Sekarang sudah dapat login ke remotehot tanpa memasukkan password

ssh root@remotehost

Jika anda berganti komputer dan membawa file id_rsa.pub atau file key lain bisa dengan

ssh -i /path/id_rsa.pub root@remotehost

* SSH Local Port Forwarding 
SSH -N root@IP -P 22 -L localhost:port:localhost:port 

* Anydesk 
Get Id : anydesk --get-id 
Set Password : echo your_password | anydesk --set-password

* Email Tester 
swaks -server your_mail_server:587 -tls --auth-user your_user_mail@mail.com --auth-password your_password_mail --to your_sender_to_mail@mail.com --from your_from_mail_sender@mail.com

* The following commands will get you the IP address list to find public IP addresses for your machine:

curl ifconfig.me
curl -4/-6 icanhazip.com
curl ipinfo.io/ip
curl api.ipify.org
curl checkip.dyndns.org
dig +short myip.opendns.com @resolver1.opendns.com
host myip.opendns.com resolver1.opendns.com
curl ident.me
curl bot.whatismyipaddress.com
curl ipecho.net/plain

* The following commands will get you the private IP address of your interfaces:

ifconfig -a
ip addr (ip a)
hostname -I | awk '{print $1}'
ip route get 1.2.3.4 | awk '{print $7}'
(Fedora) Wifi-Settings→ click the setting icon next to the Wifi name that you are connected to → Ipv4 and Ipv6 both can be seen
nmcli -p device show

* Hide command line history
1. Insert space before command
[space]echo "this is a top secret"
export HISTCONTROL = ignorespace

2. Disable the entire history for the current session
export HISTFILE=0

3. Erase the entire history after you’re done
history -cw

4. Turn off history only for the work you do
[space]set +o history

To re-enable the history, run the following command:
[Space]set -o history

5. Delete specific commands from history
[space]history | grep "part of command you want to remove"

history | grep echo 
history -d [num] ex. history -d 1

6. flush / clear history permanent
One annoying side-effect is that the history entries has a copy in the memory and it will flush back to the file when you log out.

cat /dev/null > ~/.bash_history && history -c && exit

or 

history -c && history -w

* Screen Linux 
screen --version
screen 
screen -ls
screen -S your_session_name_screen
screen -r your_session_name_screen or id screen

* Chown (Change Ownership of directory)
sudo chown -R user:group /parent_dir 
sudo chown -R 1001:1001 "your_folder_or_file"

* Find SUID
find / -perm -u=s -type f 2>/dev/null

* Find Word in dir 
find / -type f -exec grep -H 'text-to-find-here' {} \;

* Find where alias or command is based
grep -r 'sudo' ~

* Find directory
find . -name "dirname" -type d

* Find File more
find . -name testfile.txt
find /home -name *.jpg

* info where command is located
type commandname 
type rm

* SSH copy to remote
rsync -av dir/ user@domain.de:dir

* Mount 
lsblk
sudo mount /dev/your-drive-from-lsblk /your-dir-you-want-to-mount
sudo mount /dev/sda1 /mnt/ext-2-tb

* Unmount
- umount /dev/sda1

* Force Unmount
- umount -l /dev/sda1

* copy with progress status
rsync --progress -a sourceDirectory destinationDirectory

* move with rsync
rsync -a --progress --remove-source-files src/test/ dest

* rsync via SSH proxyjump (bandwidth limit 1MB)

rsync --bwlimit=1000 -azvP -e 'ssh -J username@server1:22' username@server2:/path/source/folder target/folder

* download file via curl
curl http://example.com --output my.file

* download and execute
bash <(curl -s http://mywebsite.com/myscript.txt)

* Change only year of machine
date --set="$(date +'2013%m%d %H:%M')"

* Taskmanager | show resources
top
htop

* Kill Port
lsof -t -i tcp:4000 | xargs kill

* This fuser 8080/tcp will print you PID of process bound on that port.
fuser -k 8080/tcp will kill that process.

* Free Swap Memory

#!/bin/bash

free_data="$(free)"
mem_data="$(echo "$free_data" | grep 'Mem:')"
free_mem="$(echo "$mem_data" | awk '{print $4}')"
buffers="$(echo "$mem_data" | awk '{print $6}')"
cache="$(echo "$mem_data" | awk '{print $7}')"
total_free=$((free_mem + buffers + cache))
used_swap="$(echo "$free_data" | grep 'Swap:' | awk '{print $3}')"

echo -e "Free memory:\t$total_free kB ($((total_free / 1024)) MB)\nUsed swap:\t$used_swap kB ($((used_swap / 1024)) MB)"
if [[ $used_swap -eq 0 ]]; then
    echo "Congratulations! No swap is in use."
elif [[ $used_swap -lt $total_free ]]; then
    echo "Freeing swap..."
    sudo swapoff -a
    sudo swapon -a
else
    echo "Not enough free memory. Exiting."
    exit 1
fi

## SSH CHEATSHEET
* SSH Permission denied (publickey) (Via Key Without Password)
1. client (your laptop/other machines)
ssh-keygen

cat ~/.ssh/id_rsa.pub 
ssh-rsa AAAAB3Nzkajskldjakldjklajdkljakldsjakljdkj1312k3j12k3j12kj3k12j3kj12k3j1k23jk1j23kj12k3j1kl23j9u9ua9ud9a9d89a8d98a9d89a898d9ada danigungun@dagun.local

theen save key.

2. login ssh server
add user 
sudo adduser deploy
sudo adduser deploy sudo

sudo nano /home/deploy/.ssh/authorized_keys
copy this key and save : 
ssh-rsa AAAAB3Nzkajskldjakldjklajdkljakldsjakljdkj1312k3j12k3j12kj3k12j3kj12k3j1k23jk1j23kj12k3j1kl23j9u9ua9ud9a9d89a8d98a9d89a898d9ada Danigunawan@DSC-Dani-Gunawan.local

sudo nano /etc/ssh/sshd_config
add :
AllowUsers user deploy
sudo service sshd restart

3. test again via ssh keygen (without password)

* SSH tunneling error: "channel 1: open failed: administratively prohibited: open failed"

ssh -N user@ip -L localhost:port:localhost:port

Solution : 
sudo nano /etc/ssh/sshd_config
AllowTcpForwarding yes

and 

PermitOpen is either not present, is commented out, or is set to any

sudo service sshd restart

## CRONTAB CHEATSHEET
- crontab -e
- crontab run program with sleep every 1 minutes 30 second

*/1 * * * * sleep 30; command 1 && sleep 30; command 2

- Every 5 seconds
script.sh

i=0

while [ $i -lt 12 ]; do # 12 five-second intervals in 1 minute
  command/to/run & #run your command
  sleep 5
  i=$(( i + 1 ))
done

/etc/crontab

* * * * * script.sh

## To copy a file from "Server 2" to your local laptop through "Server 1" using a single command, you can utilize SSH port forwarding and the scp command. Here's an example command:

scp -r -o ProxyJump=username@server1_ip username@server2_ip:/path/to/source/file /path/to/destination/on/laptop/

* Custom Ports
scp -r -o ProxyJump=username@server1_ip:15338 username@server2_ip:/path/to/source/file /path/to/destination/on/laptop/

Replace the following placeholders:

    username@server1_ip with the username and IP address of "Server 1."
    username@server2_ip with the username and IP address of "Server 2."
    /path/to/source/file with the file's location on "Server 2" that you want to copy.
    /path/to/destination/on/laptop/ with the destination location on your local laptop.

This command will establish an SSH tunnel through "Server 1" to connect to "Server 2" and copy the file from "Server 2" to your laptop. You might be prompted to enter the SSH passwords for both "Server 1" and "Server 2" during this process.

Make sure you have the appropriate permissions to access files on both servers, and replace the parameters with the correct information in the command above.

Referensi : 
https://www.linux.org/threads/massive-collection-of-linux-command-cheat-sheet-for-2022.38934/

Linux Command Cheat Sheet For 2022 : 
* The Linux Command Line: Download The Linx Command Line
* Command Line Cheat Sheet: Command Line Cheat Sheet
* Sed Stream Editor: Download Sed Stream Editor
* Archlinux Cheat Sheet: Archlinux Cheat Sheet
* Linux/Unix Command Line Cheat Sheet: Linux/Unix Command Line Cheat Sheet
* Unix/Linux Command Reference – FOSSwire: Unix/Linux Command Reference
* Set Operations In The Unix: Set Operations In The Unix
* Linux Quick Reference GuideDownload Linux Quick Reference Guide
* Linux Bash Shell Cheat Sheet: Download Linux Bash Shell Cheat Sheet
* Advanced Linux Commands Cheat Sheet from Red Hat: Advanced Linux Commands Cheat Sheet from Red Hat
* Linux Terminal Cheat Sheet: Linux Terminal Cheat Sheet
* Perf Cheat Sheet: Perf Cheat Sheet
* Linux Command Cheat Sheet From Cheatography: Cheat Sheet By Cheatography
* AWK command cheat sheet: AWK command cheat sheet
* Bash History Cheat Sheet: Bash History Cheat Sheet
* Bash Redirections Cheat Sheet: Bash Redirections Cheat Sheet
* FreeBSD Command Reference: FreeBSD Command Reference
* Linux Administrator’s Quick Reference Card: Quick Reference Card
* Linux & LPIC Quick Reference Guide: LPIC Quick Reference Guide
* Linux Networking Commands: Linux Networking Commands
* Linux Command Cheat Sheet By Loggly: Linux Command Cheat Sheet By Loggly
* UNIX/Linux Command Reference: UNIX/Linux Command Reference
* Ubuntu Cheat Sheet: Ubuntu Cheat Sheet
* Bash Scripting Cheat Sheet: Bash Scripting Cheat Sheet
* Ryans Tutorial Cheat Sheet: Ryans Linux Cheat Sheet
* Linux Server Step-by-Step Configuration Guide Cheat Sheet: Server Cheat Sheet
* Raspberry Pi Commands Cheat Sheet: Raspberry Pi commands cheat sheet
* Unix Command Cheat Sheets: Unix Command Cheat Sheets
* The Linux® Command-Line: The Linux Command Line
* Cheat Sheet: Advanced Linux Commands: Cheat Sheet: Advanced Linux Commands
* Set Operations in the Unix Shell: Set Operations in the Unix Shell
* MakeUseOf Linux Commands Reference: MakeUseOf Linux Commands Reference
* Red Hat Linux Commands Cheat Sheet: Red Hat Linux Commands Cheat Sheet
* Linoxide Linux Command Cheat Sheet Collection: Linoxide Linux Command Cheat Sheet
* UNIX Toolbox: UNIX Toolbox

soon

# add user to docker group
sudo usermod -aG docker $USER

# get access to group in current shell
newgrp docker

# Docker copy
docker cp container_name:/src_path dest_path

# Docker Tips: Clean Up Your Local Machine
- docker file system
docker system df 
- Clean build cache
docker builder prune

- Image prune 
docker image prune

- system prune
docker system prune 

- find img file docker
find /var/lib/docker -type f -name test.img

- Historical command
docker rm -f $(docker ps -aq)

- More recent command
docker container rm -f $(docker container ls -aq)

- Cleanup exited processes:
docker rm $(docker ps -q -f status=exited)

- Cleanup dangling volumes:
docker volume rm $(docker volume ls -qf dangling=true)

- Cleanup dangling or None images:
docker rmi $(docker images --filter "dangling=true" -q --no-trunc)
docker rmi $(docker images -a|grep "<none>"|awk '$1=="<none>" {print $3}')

- Docker run with bash
docker run --rm -it --entrypoint bash <image_or_id>
docker exec -it <container-name-or-id> bash

- Docker Inspect (All)
docker inspect <container_name_or_id>

- Docker Inspect (Only Command)
docker inspect --format="{.Config.Cmd}" <container_name_or_id>

- Docker Scan Vuln
docker scout quickview <images>

- error: RPC failed; 0r fatal: The remote end hung up unexpectedly

git config --global http.postBuffer 2147483648

- Check ip range on docker network list
for name in  $(docker network ls --format '' ) ; do echo $name ; docker inspect $name --format '' ; done

# Referensi : 
https://github.com/wsargent/docker-cheat-sheet

Soon