ABDURROZAK
ABDURROZAK.MY.ID // EBOOK

BAB 17 - PERINTAH DASAR

KUASAI COMMAND LINE KALI LINUX
12 SUB-BAB ~100 MENIT BACA FASE 4 - PRAKTIK LEVEL: DASAR

PENGANTAR BAB

Di Bab 16, Anda telah mengenal Kali Linux - sistem operasi yang menjadi senjata utama praktisi cyber security. Sekarang, saatnya menguasai command line - antarmuka paling powerful di Linux.

Command line bukan sekadar cara lama berinteraksi dengan komputer. Ia adalah antarmuka profesional yang memberikan kontrol penuh atas sistem. Hampir semua tools security di Kali Linux dijalankan melalui terminal. Tanpa menguasai command line, Anda tidak akan bisa memanfaatkan potensi penuh Kali Linux.

Bab ini akan membawa Anda dari pemahaman dasar terminal hingga penguasaan 60+ perintah essential yang akan menjadi second nature Anda. Setiap perintah akan dijelaskan dengan sintaks, opsi, contoh, dan analogi untuk memudahkan pemahaman.

60+
COMMANDS YANG DIPELAJARI
Essential commands
12
SUB-BAB PRAKTIKAL
Step by step
100+
CONTOH PRAKTIK
Real-world examples
12
ANALOGI PEMAHAMAN
Konseptual
TUJUAN PEMBELAJARAN
  • Memahami perbedaan terminal dan shell
  • Memahami struktur file system Linux (FHS)
  • Menguasai navigasi file system (pwd, ls, cd)
  • Menguasai manipulasi file (mkdir, touch, cp, mv, rm)
  • Menguasai viewing file (cat, less, head, tail)
  • Menguasai pencarian (grep, find)
  • Memahami dan mengatur file permission
  • Mengelola user dan group
  • Menguasai privilege escalation dengan sudo
  • Mengelola process (ps, top, kill, bg, fg)
  • Menguasai network commands dasar
17.1

TERMINAL & SHELL

Konsep Dasar

Banyak orang menyamakan terminal dan shell, padahal keduanya berbeda. Memahami perbedaannya penting untuk memahami cara kerja command line.

KOMPONENDEFINISICONTOH
Terminal Program yang menyediakan antarmuka teks (emulator) GNOME Terminal, Konsole, xterm, XFCE Terminal
Shell Program yang menerjemahkan dan mengeksekusi perintah Bash, Zsh, Fish, Sh
ANIMASI: TERMINAL vs SHELL
USER TERMINAL Emulator (GUI window) SHELL Interpreter (bash/zsh) KERNEL User -> Terminal (GUI) -> Shell (bash) -> Kernel

Shell Populer di Linux

SHELLDESKRIPSIKELEBIHAN
Bash Bourne Again Shell - default di banyak distro Standar, kompatibel, dokumentasi lengkap
Zsh Z Shell - default di Kali Linux Auto-complete canggih, oh-my-zsh, customizable
Fish Friendly Interactive Shell User-friendly, syntax highlighting, auto-suggestions
Sh Bourne Shell - shell original Unix Minimalis, standar POSIX

Cek Shell yang Sedang Aktif

Bash - Check Current Shell
# Method 1: Check SHELL environment variable
$ echo $SHELL
/usr/bin/zsh

# Method 2: Check current process
$ ps -p $$
  PID TTY          TIME CMD
 1234 pts/0    00:00:00 zsh

# Method 3: Check process name
$ echo $0
zsh

# Switch shell temporarily
$ bash
$ fish

# Change default shell
$ chsh -s /bin/bash
$ chsh -s /bin/zsh
$ chsh -s /usr/bin/fish

Terminal Emulator di Kali

TERMINALDESKTOPKELEBIHAN
QTerminal Default di Kali (LXQt) Lightweight, fast
GNOME Terminal GNOME Feature-rich, profiles
Konsole KDE Highly customizable
XFCE Terminal Xfce Lightweight, stable
Terminator Any Multiple panes, tiling

Shortcut Terminal Penting

SHORTCUTFUNGSI
Ctrl + Shift + T Open new tab
Ctrl + Shift + W Close current tab
Ctrl + Page Up/Down Switch between tabs
Ctrl + Shift + C Copy selected text
Ctrl + Shift + V Paste from clipboard
Ctrl + Shift + F Find in terminal
Ctrl + Shift + + Increase font size
Ctrl + Shift + - Decrease font size
ANALOGI: TERMINAL & SHELL
  • Terminal = ruangan dengan meja dan kursi (tempat Anda duduk)
  • Shell = penerjemah yang duduk di meja (menerjemahkan perintah Anda)
  • Kernel = otak komputer yang mengeksekusi perintah

Anda bisa ganti penerjemah (shell) tanpa ganti ruangan (terminal). Begitu juga sebaliknya.

TIPS: PROMPT SHELL

Prompt adalah teks yang muncul sebelum Anda mengetik perintah. Di Kali Linux (Zsh), default prompt biasanya:

Shell Prompt
# Format prompt:
# user@hostname:current_directory$

# Contoh:
kali@kali:~$
# kali = username
# kali = hostname
# ~ = home directory
# $ = normal user (# untuk root)

# Setelah sudo:
root@kali:~#
# # menandakan root user
REFERENSI
  • GNU Bash Manual - Bash Reference Manual
  • Zsh Documentation - Zsh Manual
  • Linux Command Library - Linux commands reference
17.2

STRUKTUR FILE LINUX

Filesystem Hierarchy Standard (FHS)

Linux menggunakan standar FHS (Filesystem Hierarchy Standard) yang mengatur struktur direktori. Memahami struktur ini penting untuk navigasi dan troubleshooting.

ANIMASI: LINUX FILE SYSTEM HIERARCHY
/ /bin /boot /etc /home /usr binaries boot files configs users programs /var /tmp /opt /dev /proc logs, spool temp files optional devices process info

Direktori Penting di Linux

DIREKTORIFUNGSICONTOH ISI
/bin Essential user binaries (commands) ls, cp, mv, bash
/sbin System binaries (admin commands) fdisk, iptables, reboot
/boot Boot loader files vmlinuz, initrd, grub
/dev Device files sda, tty, null, random
/etc Configuration files passwd, hosts, fstab
/home User home directories /home/kali, /home/user
/root Root user home directory Root user files
/var Variable data (logs, spool) /var/log, /var/spool
/tmp Temporary files Temporary files (deleted on reboot)
/usr User programs and data /usr/bin, /usr/lib, /usr/share
/opt Optional software packages Third-party software
/proc Process and kernel information Virtual filesystem
/media Mount point for removable media USB drives, CDs
/mnt Temporary mount point Manual mounts
/srv Service data Web server files, FTP data

Eksplorasi File System

Bash - Explore File System
# List root directory
$ ls /
bin  boot  dev  etc  home  lib  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

# Check what's in /etc (configuration)
$ ls /etc | head -20
adduser.conf
adduser.conf.dpkg-old
adjtime
aliases
alternatives
...

# Check user home
$ ls -la /home/kali
total 44
drwxr-xr-x 17 kali kali 4096 Sep  9 10:00 .
drwxr-xr-x  3 root root 4096 Sep  9 09:00 ..
-rw-------  1 kali kali  128 Sep  9 10:00 .bash_history
-rw-r--r--  1 kali kali  220 Sep  9 09:00 .bash_logout
drwxr-xr-x  2 kali kali 4096 Sep  9 10:00 Desktop
drwxr-xr-x  2 kali kali 4096 Sep  9 10:00 Documents

# Check /var/log (system logs)
$ ls /var/log
alternatives.log  apt  auth.log  bootstrap.log  btmp  daemon.log

# Check /proc (process info)
$ ls /proc | head
1  10  100  1000  1001  1002  1003  1004  1005  1006

# Check device files
$ ls /dev | grep sd
sda  sda1  sda2  sda5
ANALOGI: FILE SYSTEM = KOTA
  • / = kota (root)
  • /bin, /sbin = pusat perkakas (toko perkakas)
  • /etc = kantor pemerintahan (konfigurasi)
  • /home = perumahan (rumah user)
  • /var = gudang logistik (log, spool)
  • /tmp = tempat sampah sementara
  • /dev = pabrik perangkat (device files)
  • /proc = kantor sensus (info proses)
TIPS: NAVIGASI CEPAT
Bash - Quick Navigation
# Go to home directory
$ cd ~
$ cd

# Go to previous directory
$ cd -

# Go up one level
$ cd ..

# Go up two levels
$ cd ../..

# Use absolute path
$ cd /etc/network

# Use relative path
$ cd ./Documents

# Tab completion
$ cd /etc/ne[TAB]
# Auto-completes to: cd /etc/network/
REFERENSI
  • Filesystem Hierarchy Standard - filesystem-hierarchy-standard.readthedocs.io
  • Linux Foundation - Linux Filesystem Hierarchy
  • Arch Wiki - File system hierarchy
17.3

pwd, ls & cd

Navigasi File System

Tiga perintah paling fundamental untuk navigasi di Linux: pwd (print working directory), ls (list), dan cd (change directory).

pwd - Print Working Directory

SINTAKS

pwd [OPTION]

Bash - pwd Examples
# Print current directory
$ pwd
/home/kali

# Change directory and check
$ cd /etc/network
$ pwd
/etc/network

# Physical path (resolve symlinks)
$ pwd -P
/etc/network

# Logical path (with symlinks)
$ pwd -L
/etc/network

ls - List Directory Contents

SINTAKS

ls [OPTION]... [FILE]...

Opsi Penting:

OPSIFUNGSICONTOH
-l Long format (detail) ls -l
-a Show all (include hidden) ls -a
-h Human-readable sizes ls -lh
-R Recursive (subdirectories) ls -R
-t Sort by time ls -lt
-S Sort by size ls -lS
-r Reverse order ls -lr
-i Show inode number ls -i
-d List directories only ls -d */
Bash - ls Examples
# Basic list
$ ls
Desktop  Documents  Downloads  Music  Pictures  Videos

# Long format
$ ls -l
total 32
drwxr-xr-x 2 kali kali 4096 Sep  9 10:00 Desktop
drwxr-xr-x 2 kali kali 4096 Sep  9 10:00 Documents
drwxr-xr-x 2 kali kali 4096 Sep  9 10:00 Downloads
-rw-r--r-- 1 kali kali  256 Sep  9 10:00 file.txt

# Show all (including hidden)
$ ls -a
.  ..  .bash_history  .bashrc  Desktop  Documents

# Long format with human-readable sizes
$ ls -lh
total 32K
drwxr-xr-x 2 kali kali 4.0K Sep  9 10:00 Desktop
-rw-r--r-- 1 kali kali  256 Sep  9 10:00 file.txt

# Sort by modification time (newest first)
$ ls -lt
-rw-r--r-- 1 kali kali  256 Sep  9 10:00 new.txt
-rw-r--r-- 1 kali kali  128 Sep  9 09:00 old.txt

# Sort by size (largest first)
$ ls -lS
-rw-r--r-- 1 kali kali 1024 Sep  9 10:00 large.txt
-rw-r--r-- 1 kali kali  256 Sep  9 10:00 small.txt

# Recursive listing
$ ls -R
.:
Desktop  Documents

./Desktop:
file1.txt  file2.txt

./Documents:
doc1.pdf  doc2.pdf

# List only directories
$ ls -d */
Desktop/  Documents/  Downloads/

# List with inode numbers
$ ls -i
1234567 Desktop  1234568 Documents  1234569 file.txt

# Combined options
$ ls -lah
total 44K
drwxr-xr-x 17 kali kali 4.0K Sep  9 10:00 .
drwxr-xr-x  3 root root 4.0K Sep  9 09:00 ..
-rw-------  1 kali kali  128 Sep  9 10:00 .bash_history

cd - Change Directory

SINTAKS

cd [DIRECTORY]

Bash - cd Examples
# Go to home directory
$ cd
$ cd ~

# Go to specific directory (absolute path)
$ cd /etc/network

# Go to relative directory
$ cd Documents

# Go up one level
$ cd ..

# Go up two levels
$ cd ../..

# Go to previous directory
$ cd -
/etc/network

# Go to root directory
$ cd /

# Go to user's directory
$ cd ~kali

# Navigate with tab completion
$ cd /etc/ne[TAB]
# Auto-completes to: cd /etc/network/

# Multiple directory navigation
$ cd /usr/local/bin
$ cd ../../../etc
# Goes to /etc

Kombinasi Perintah

Bash - Combined Commands
# List, change, and list again
$ ls -la && cd Documents && ls -la

# Check current directory after operations
$ cd /etc && pwd && ls | head

# Navigate and check disk usage
$ cd /var/log && du -sh *

# Find and navigate to directory
$ cd $(find / -name "network" -type d 2>/dev/null | head -1)

# Chain multiple commands
$ pwd && ls -la && cd .. && pwd
ANALOGI: NAVIGASI FILE SYSTEM
  • pwd = bertanya "Saya di mana?"
  • ls = melihat daftar ruangan di gedung
  • cd = masuk ke ruangan tertentu
  • cd .. = keluar dari ruangan
  • cd ~ = pulang ke rumah
  • cd - = kembali ke ruangan sebelumnya
TIPS: NAVIGATION SHORTCUTS
Bash - Navigation Tips
# Use $HOME instead of ~
$ cd $HOME

# Use environment variables
$ cd $HOME/Documents

# Use relative paths for efficiency
$ cd ../Documents/../Downloads

# Use pushd and popd for directory stack
$ pushd /etc
$ pushd /var
$ dirs
/var /etc ~
$ popd
/etc ~
$ popd
~

# Use CDPATH for quick navigation
$ export CDPATH=.:~:/etc:/var
$ cd network  # Goes to /etc/network
REFERENSI
  • GNU Coreutils Manual - pwd, ls, cd
  • Linux Command Library - Navigation commands
17.4

mkdir, touch & cp

mkdir - Make Directory

SINTAKS

mkdir [OPTION] DIRECTORY...

Opsi Penting:

OPSIFUNGSICONTOH
-p Create parent directories mkdir -p dir1/dir2/dir3
-m Set permissions mkdir -m 755 directory
-v Verbose (show what's done) mkdir -v directory
Bash - mkdir Examples
# Create single directory
$ mkdir project

# Create multiple directories
$ mkdir dir1 dir2 dir3

# Create nested directories
$ mkdir -p project/src/main/java

# Create with specific permissions
$ mkdir -m 700 private

# Create with verbose output
$ mkdir -v test
mkdir: created directory 'test'

# Create multiple nested directories
$ mkdir -p project/{src,tests,docs}/{main,test}

# Create directory tree
$ mkdir -p workspace/{project1,project2}/{src,bin,doc}

touch - Create Empty File or Update Timestamp

SINTAKS

touch [OPTION] FILE...

Opsi Penting:

OPSIFUNGSICONTOH
-a Change access time only touch -a file
-m Change modification time only touch -m file
-t Set specific timestamp touch -t 202301011200 file
-r Use reference file's timestamp touch -r ref_file file
-c Don't create if doesn't exist touch -c file
Bash - touch Examples
# Create empty file
$ touch file.txt

# Create multiple files
$ touch file1.txt file2.txt file3.txt

# Update timestamp of existing file
$ touch existing_file.txt

# Create file with specific timestamp
$ touch -t 202301011200 file.txt
# Format: YYYYMMDDHHMM

# Use reference file's timestamp
$ touch -r reference.txt new_file.txt

# Create multiple files with brace expansion
$ touch file{1..10}.txt
# Creates: file1.txt, file2.txt, ..., file10.txt

# Don't create if file doesn't exist
$ touch -c nonexistent.txt
# No file created, no error

# Create file in specific directory
$ touch /path/to/directory/file.txt

cp - Copy Files and Directories

SINTAKS

cp [OPTION] SOURCE DEST
cp [OPTION] SOURCE... DIRECTORY

Opsi Penting:

OPSIFUNGSICONTOH
-r, -R Copy directories recursively cp -r dir1 dir2
-i Prompt before overwrite cp -i file1 file2
-f Force overwrite cp -f file1 file2
-v Verbose output cp -v file1 file2
-p Preserve attributes cp -p file1 file2
-a Archive mode (preserve all) cp -a dir1 dir2
-u Copy only when source is newer cp -u file1 file2
-n No overwrite cp -n file1 file2
Bash - cp Examples
# Copy file
$ cp file.txt backup.txt

# Copy file to directory
$ cp file.txt /path/to/directory/

# Copy multiple files to directory
$ cp file1.txt file2.txt /path/to/directory/

# Copy directory recursively
$ cp -r dir1 dir2

# Copy with interactive prompt
$ cp -i file.txt existing.txt
cp: overwrite 'existing.txt'? y

# Copy with verbose output
$ cp -v file.txt backup.txt
'file.txt' -> 'backup.txt'

# Copy preserving attributes
$ cp -p file.txt backup.txt
# Preserves: mode, ownership, timestamps

# Copy archive mode (preserve all)
$ cp -a dir1 dir2
# Preserves: mode, ownership, timestamps, links

# Copy only newer files
$ cp -u file.txt /backup/

# Copy without overwriting
$ cp -n file.txt existing.txt

# Copy with wildcard
$ cp *.txt /backup/
$ cp *.log /var/log/archive/

# Copy and rename
$ cp file.txt /backup/new_name.txt

# Copy with backup
$ cp -b file.txt /backup/
# Creates backup.txt~ if backup.txt exists

# Copy with specific permissions
$ cp --preserve=mode,ownership file.txt /backup/
ANALOGI: FILE OPERATIONS
  • mkdir = membuat ruangan baru di gedung
  • touch = membuat dokumen kosong atau stempel waktu
  • cp = fotokopi dokumen
  • cp -r = fotokopi seluruh folder berisi dokumen
  • cp -p = fotokopi dengan mempertahankan semua properti asli
PERINGATAN: OVERWRITE

Perintah cp akan menimpa (overwrite) file tujuan tanpa peringatan kecuali Anda menggunakan opsi -i (interactive) atau -n (no-clobber). Selalu hati-hati saat menyalin file!

TIPS: EFFICIENT COPYING
Bash - Advanced cp Tips
# Copy with progress bar (using rsync)
$ rsync -ah --progress source/ destination/

# Copy only specific file types
$ find . -name "*.log" -exec cp {} /backup/ \;

# Copy and compress
$ tar -czf backup.tar.gz directory/

# Copy with exclude
$ rsync -av --exclude='*.tmp' source/ destination/

# Copy and change ownership
$ sudo cp -a file.txt /backup/ && sudo chown user:group /backup/file.txt

# Copy sparse files efficiently
$ cp --sparse=always sparse_file destination/
REFERENSI
  • GNU Coreutils Manual - mkdir, touch, cp
  • Linux Command Library - File operations
17.5

mv & rm

mv - Move or Rename Files

SINTAKS

mv [OPTION] SOURCE DEST
mv [OPTION] SOURCE... DIRECTORY

Opsi Penting:

OPSIFUNGSICONTOH
-i Prompt before overwrite mv -i file1 file2
-f Force (no prompt) mv -f file1 file2
-v Verbose output mv -v file1 file2
-n No overwrite mv -n file1 file2
-u Move only when newer mv -u file1 file2
-b Make backup mv -b file1 file2
Bash - mv Examples
# Rename file
$ mv old_name.txt new_name.txt

# Move file to directory
$ mv file.txt /path/to/directory/

# Move multiple files to directory
$ mv file1.txt file2.txt /path/to/directory/

# Move directory
$ mv dir1 /path/to/destination/

# Move with interactive prompt
$ mv -i file.txt existing.txt
mv: overwrite 'existing.txt'? y

# Move with verbose output
$ mv -v file.txt /backup/
renamed 'file.txt' -> '/backup/file.txt'

# Move without overwriting
$ mv -n file.txt existing.txt
# No move if file exists

# Move with backup
$ mv -b file.txt existing.txt
# Creates existing.txt~ backup

# Move only if source is newer
$ mv -u file.txt /backup/

# Move with wildcard
$ mv *.log /var/log/archive/

# Move and rename
$ mv file.txt /backup/new_name.txt

# Move multiple files with pattern
$ mv file{1..5}.txt /archive/

rm - Remove Files or Directories

SINTAKS

rm [OPTION] FILE...

PERINGATAN KERAS: PERINTAH BERBAHAYA

rm menghapus file permanen tanpa memindahkannya ke trash. File yang dihapus dengan rm TIDAK BISA dikembalikan kecuali dengan tools forensik khusus. Selalu berhati-hati!

Opsi Penting:

OPSIFUNGSICONTOH
-r, -R Remove directories recursively rm -r directory
-f Force (no prompt) rm -f file
-i Prompt before every removal rm -i file
-I Prompt once before removing 3+ files rm -I file*
-v Verbose output rm -v file
-d Remove empty directories rm -d directory
Bash - rm Examples
# Remove single file
$ rm file.txt

# Remove multiple files
$ rm file1.txt file2.txt file3.txt

# Remove with interactive prompt
$ rm -i file.txt
rm: remove regular file 'file.txt'? y

# Remove with verbose output
$ rm -v file.txt
removed 'file.txt'

# Remove directory (must be empty)
$ rmdir empty_directory
$ rm -d empty_directory

# Remove directory recursively
$ rm -r directory

# Force remove (no prompts)
$ rm -f file.txt
$ rm -rf directory

# WARNING: DANGEROUS COMMANDS
# rm -rf /          # DELETES EVERYTHING!
# rm -rf /*         # DELETES EVERYTHING!
# rm -rf ~          # DELETES HOME DIRECTORY!

# Remove with wildcard
$ rm *.tmp
$ rm *.log

# Remove files older than X days
$ find /path -type f -mtime +30 -delete

# Interactive removal of multiple files
$ rm -I file*
rm: remove 5 files? y

# Remove and show what's removed
$ rm -rv directory
removed 'directory/file1.txt'
removed 'directory/file2.txt'
removed directory 'directory'

Safe Deletion Practices

Bash - Safe Deletion
# Use trash-cli instead of rm (recoverable)
$ sudo apt install trash-cli
$ trash-put file.txt
$ trash-list
$ trash-restore

# Preview before deleting
$ ls *.tmp
$ rm -i *.tmp

# Use find to preview
$ find . -name "*.tmp" -print
$ find . -name "*.tmp" -delete

# Secure delete (overwrite before delete)
$ sudo apt install secure-delete
$ srm file.txt
$ sfill /path/to/mount

# Shred file (overwrite multiple times)
$ shred -v -n 3 -z file.txt
# -v: verbose
# -n 3: overwrite 3 times
# -z: add final zero overwrite

# Shred and remove
$ shred -u file.txt
ANALOGI: mv & rm
  • mv = memindahkan dokumen dari satu folder ke folder lain, atau mengganti nama dokumen
  • rm = membuang dokumen ke tempat sampah (tapi di Linux, langsung dibakar, tidak bisa diambil lagi!)
  • rm -r = membakar seluruh folder beserta isinya
  • rm -f = membakar tanpa konfirmasi
  • trash-put = memindahkan ke tempat sampah (bisa diambil lagi)
BEST PRACTICES
  • Selalu gunakan ls dulu untuk preview sebelum rm
  • Gunakan -i untuk interactive mode saat menghapus banyak file
  • Pertimbangkan menggunakan trash-cli untuk deletion yang recoverable
  • Jangan pernah menjalankan rm -rf / atau rm -rf /*
  • Backup sebelum operasi penghapusan massal
  • Gunakan shred untuk sensitive data
REFERENSI
  • GNU Coreutils Manual - mv, rm
  • Linux Command Library - File deletion
  • trash-cli - GitHub Documentation
17.6

cat, less, head & tail

cat - Concatenate and Display Files

SINTAKS

cat [OPTION] [FILE]...

Opsi Penting:

OPSIFUNGSICONTOH
-n Number all output lines cat -n file
-b Number non-blank lines cat -b file
-s Squeeze multiple blank lines cat -s file
-E Show $ at end of each line cat -E file
-T Show tabs as ^I cat -T file
-A Show all (equivalent to -vET) cat -A file
Bash - cat Examples
# Display file content
$ cat file.txt
Line 1
Line 2
Line 3

# Display with line numbers
$ cat -n file.txt
     1  Line 1
     2  Line 2
     3  Line 3

# Display multiple files
$ cat file1.txt file2.txt

# Concatenate files
$ cat file1.txt file2.txt > combined.txt

# Append to file
$ cat file1.txt >> combined.txt

# Show non-blank lines numbered
$ cat -b file.txt

# Show special characters
$ cat -A file.txt
Line 1$
Line 2^I$
Line 3$

# Squeeze blank lines
$ cat -s file.txt

# Create file with cat
$ cat > new_file.txt
# Type content, then Ctrl+D to save

# Read from stdin
$ echo "Hello" | cat
Hello

less - View Files Page by Page

SINTAKS

less [OPTION] FILE

Navigation Commands in less:

COMMANDFUNGSI
Space, f Scroll forward one page
b Scroll backward one page
Enter, j Scroll forward one line
k Scroll backward one line
g Go to first line
G Go to last line
/pattern Search forward
?pattern Search backward
n Repeat previous search
N Repeat search in reverse
q Quit less
h Help
Bash - less Examples
# View file with less
$ less large_file.txt

# View with line numbers
$ less -N file.txt

# View multiple files
$ less file1.txt file2.txt

# Search while viewing
$ less file.txt
# Then type: /pattern to search

# View with pattern highlight
$ less -p "pattern" file.txt

# View compressed file
$ less file.gz

# View with follow mode (like tail -f)
$ less +F log.txt

# Pipe to less
$ ls -la | less
$ cat file.txt | less

head - Display First Lines

SINTAKS

head [OPTION]... [FILE]...

Opsi Penting:

OPSIFUNGSICONTOH
-n NUM Print first NUM lines head -n 20 file
-c NUM Print first NUM bytes head -c 100 file
-q Quiet (no headers) head -q file1 file2
-v Verbose (print headers) head -v file1 file2
Bash - head Examples
# Display first 10 lines (default)
$ head file.txt

# Display first 20 lines
$ head -n 20 file.txt
$ head -20 file.txt

# Display first 100 bytes
$ head -c 100 file.txt

# Display first 5 lines of multiple files
$ head -n 5 file1.txt file2.txt

# Quiet mode (no file headers)
$ head -q file1.txt file2.txt

# Pipe with head
$ ls -la | head -10
$ cat large_file.txt | head -50

# Get first line
$ head -n 1 file.txt

tail - Display Last Lines

SINTAKS

tail [OPTION]... [FILE]...

Opsi Penting:

OPSIFUNGSICONTOH
-n NUM Print last NUM lines tail -n 20 file
-c NUM Print last NUM bytes tail -c 100 file
-f Follow (output appended data) tail -f log.txt
-F Follow with retry tail -F log.txt
-q Quiet (no headers) tail -q file1 file2
-v Verbose (print headers) tail -v file1 file2
-s SEC Sleep interval with -f tail -f -s 2 log.txt
Bash - tail Examples
# Display last 10 lines (default)
$ tail file.txt

# Display last 20 lines
$ tail -n 20 file.txt
$ tail -20 file.txt

# Follow file (real-time monitoring)
$ tail -f /var/log/syslog
# Press Ctrl+C to stop

# Follow with retry (useful for log rotation)
$ tail -F /var/log/syslog

# Follow with custom sleep interval
$ tail -f -s 2 log.txt

# Display last 100 bytes
$ tail -c 100 file.txt

# Display last 5 lines of multiple files
$ tail -n 5 file1.txt file2.txt

# Follow multiple files
$ tail -f log1.txt log2.txt

# Pipe with tail
$ ls -la | tail -10
$ cat large_file.txt | tail -50

# Get last line
$ tail -n 1 file.txt

# Combine head and tail
$ head -n 100 file.txt | tail -n 10
# Get lines 91-100

# Monitor log with grep
$ tail -f /var/log/syslog | grep --line-buffered "error"
ANALOGI: VIEWING COMMANDS
  • cat = membaca seluruh buku dari awal sampai akhir sekaligus
  • less = membaca buku halaman per halaman, bisa bolak-balik
  • head = membaca beberapa halaman pertama saja
  • tail = membaca beberapa halaman terakhir saja
  • tail -f = membaca halaman terakhir dan terus membaca halaman baru yang ditambahkan
TIPS: LOG MONITORING
Bash - Log Monitoring Tips
# Monitor multiple logs
$ tail -f /var/log/syslog /var/log/auth.log

# Monitor with color (using grep)
$ tail -f /var/log/syslog | grep --color "error"

# Monitor and filter
$ tail -f /var/log/syslog | grep -v "INFO"

# Monitor with timestamp
$ tail -f /var/log/syslog | ts

# Monitor last 100 lines and follow
$ tail -n 100 -f /var/log/syslog

# Monitor and save to file
$ tail -f /var/log/syslog | tee monitoring.log

# Monitor with line numbers
$ tail -f /var/log/syslog | nl

# Monitor specific process logs
$ tail -f /var/log/apache2/access.log | grep "192.168.1.100"
PERFORMANCE TIPS
  • Gunakan less untuk file besar (tidak load seluruh file ke memory)
  • Gunakan head atau tail untuk preview file
  • Hindari cat untuk file sangat besar
  • Gunakan tail -F (capital F) untuk log yang di-rotate
REFERENSI
  • GNU Coreutils Manual - cat, less, head, tail
  • Linux Command Library - File viewing
17.7

grep & find

grep - Search Text Patterns

SINTAKS

grep [OPTION] PATTERN [FILE...]
grep [OPTION] [-e PATTERN | -f FILE] [FILE...]

Opsi Penting:

OPSIFUNGSICONTOH
-i Case insensitive grep -i "error" file
-r, -R Recursive search grep -r "pattern" /dir
-n Show line numbers grep -n "pattern" file
-v Invert match grep -v "pattern" file
-c Count matches grep -c "pattern" file
-l List files with matches grep -l "pattern" *.txt
-w Match whole word grep -w "error" file
-E Extended regex grep -E "pattern1|pattern2"
-A NUM Show NUM lines after match grep -A 3 "error" file
-B NUM Show NUM lines before match grep -B 3 "error" file
-C NUM Show NUM lines context grep -C 3 "error" file
--color Highlight matches grep --color "pattern" file
Bash - grep Examples
# Basic search
$ grep "error" log.txt

# Case insensitive
$ grep -i "error" log.txt

# Show line numbers
$ grep -n "error" log.txt

# Recursive search
$ grep -r "error" /var/log/

# Invert match (show non-matching)
$ grep -v "info" log.txt

# Count matches
$ grep -c "error" log.txt

# List files with matches
$ grep -l "error" *.log

# Match whole word
$ grep -w "error" file.txt

# Extended regex (multiple patterns)
$ grep -E "error|warning|critical" log.txt

# Show context (3 lines before and after)
$ grep -C 3 "error" log.txt

# Show lines after match
$ grep -A 5 "error" log.txt

# Show lines before match
$ grep -B 5 "error" log.txt

# Colorized output
$ grep --color "error" log.txt

# Search for IP addresses
$ grep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}" log.txt

# Search for email addresses
$ grep -E "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" file.txt

# Search and count unique
$ grep "error" log.txt | sort | uniq -c

# Search with multiple files
$ grep "error" file1.txt file2.txt

# Search in specific file types
$ grep -r --include="*.log" "error" /var/log/

# Exclude file types
$ grep -r --exclude="*.bak" "pattern" /dir/

# Recursive with line numbers
$ grep -rn "error" /var/log/

# Case insensitive recursive
$ grep -ri "error" /var/log/

find - Search for Files

SINTAKS

find [PATH] [OPTION]... [EXPRESSION]

Opsi Penting:

OPSIFUNGSICONTOH
-name Search by name (case sensitive) find . -name "file.txt"
-iname Search by name (case insensitive) find . -iname "file.txt"
-type Search by type (f=file, d=dir) find . -type f
-size Search by size find . -size +10M
-mtime Modified time (days) find . -mtime -7
-atime Access time (days) find . -atime -1
-user Search by user find . -user kali
-group Search by group find . -group users
-perm Search by permissions find . -perm 755
-maxdepth Limit search depth find . -maxdepth 2
-exec Execute command on results find . -name "*.tmp" -exec rm {} \;
-delete Delete found files find . -name "*.tmp" -delete
Bash - find Examples
# Find file by name
$ find . -name "file.txt"

# Find case insensitive
$ find . -iname "file.txt"

# Find by pattern
$ find . -name "*.txt"
$ find . -name "*.log"

# Find directories only
$ find . -type d

# Find files only
$ find . -type f

# Find by size (greater than 10MB)
$ find . -size +10M

# Find by size (less than 1KB)
$ find . -size -1k

# Find files modified in last 7 days
$ find . -mtime -7

# Find files modified more than 30 days ago
$ find . -mtime +30

# Find files accessed in last 24 hours
$ find . -atime -1

# Find files by user
$ find . -user kali

# Find files by group
$ find . -group users

# Find files with specific permissions
$ find . -perm 755
$ find . -perm -u+r

# Limit search depth
$ find . -maxdepth 2 -name "*.txt"

# Find and execute command
$ find . -name "*.tmp" -exec rm {} \;
$ find . -name "*.log" -exec ls -lh {} \;

# Find and delete
$ find . -name "*.tmp" -delete

# Find empty files
$ find . -type f -empty

# Find empty directories
$ find . -type d -empty

# Find and display with details
$ find . -name "*.txt" -ls

# Find with multiple conditions
$ find . -name "*.log" -size +1M -mtime -7

# Find and count
$ find . -name "*.txt" | wc -l

# Find and copy
$ find . -name "*.txt" -exec cp {} /backup/ \;

# Find with OR condition
$ find . \( -name "*.txt" -o -name "*.log" \)

# Find with NOT condition
$ find . -not -name "*.tmp"

# Find and change permissions
$ find . -name "*.sh" -exec chmod +x {} \;

# Find large files and sort by size
$ find . -type f -exec ls -s {} \; | sort -n | tail -10

Kombinasi grep dan find

Bash - Combined grep and find
# Find files and search content
$ find . -name "*.log" -exec grep "error" {} \;

# Find files and search with line numbers
$ find . -name "*.log" -exec grep -n "error" {} \;

# Find and count matches
$ find . -name "*.log" -exec grep -c "error" {} \;

# Find files containing pattern
$ find . -name "*.log" -exec grep -l "error" {} \;

# Find and display with context
$ find . -name "*.log" -exec grep -C 2 "error" {} \;

# Find large files and search
$ find . -size +10M -name "*.log" -exec grep "error" {} \;

# Find recent files and search
$ find . -mtime -1 -name "*.log" -exec grep "error" {} \;

# Find and replace in files
$ find . -name "*.txt" -exec sed -i 's/old/new/g' {} \;

# Find and delete files with pattern
$ find . -name "*.tmp" -exec grep -l "pattern" {} \; | xargs rm

# Find and archive
$ find . -name "*.log" -exec tar -rvf logs.tar {} \;
ANALOGI: grep & find
  • find = mencari file berdasarkan nama, ukuran, tanggal, dll (seperti mencari dokumen di lemari arsip)
  • grep = mencari isi/konten di dalam file (seperti membaca isi dokumen untuk mencari kata tertentu)
  • find + grep = mencari dokumen tertentu, lalu membaca isinya
TIPS: EFFICIENT SEARCHING
Bash - Search Tips
# Use -print0 and xargs -0 for safe file handling
$ find . -name "*.txt" -print0 | xargs -0 grep "pattern"

# Use grep -r instead of find + grep for simple cases
$ grep -r "pattern" /path/

# Exclude directories
$ grep -r --exclude-dir=".git" "pattern" .

# Use find with -exec + for better performance
$ find . -name "*.log" -exec grep -H "error" {} +

# Use ripgrep (rg) for faster searching
$ sudo apt install ripgrep
$ rg "pattern" /path/

# Use fd for faster file finding
$ sudo apt install fd-find
$ fdfind "pattern" /path/
COMMON PITFALLS
  • find . -name "*.tmp" -exec rm {} \; - hati-hati, langsung menghapus!
  • Gunakan -print atau -ls dulu untuk preview sebelum aksi
  • Escape special characters dalam pattern
  • Gunakan quotes untuk pattern dengan spaces
REFERENSI
  • GNU Grep Manual - grep command
  • GNU Findutils Manual - find command
  • Linux Command Library - Searching files and content
17.8

FILE PERMISSION

Konsep Permission

Linux menggunakan sistem permission yang ketat untuk mengontrol akses ke file dan direktori. Memahami permission sangat penting untuk keamanan sistem.

Tiga Jenis Permission

PERMISSIONFILEDIRECTORYANGKA
Read (r) Melihat isi file Melihat isi direktori 4
Write (w) Memodifikasi file Membuat/menghapus file di direktori 2
Execute (x) Menjalankan file Masuk ke direktori (cd) 1

Tiga Kategori User

KATEGORISIMBOLDESKRIPSI
User/Owner (u) u Pemilik file
Group (g) g Group pemilik file
Others (o) o Semua user lain

Memahami Permission String

Permission String Format
# Format: [type][owner][group][others]
# Example: -rwxr-xr--

# Breakdown:
# -        = file type (- = file, d = directory, l = link)
# rwx      = owner permissions (read, write, execute)
# r-x      = group permissions (read, execute)
# r--      = others permissions (read only)

# Examples:
-rw-r--r--  file with rw for owner, r for group and others
-rwxr-xr-x  executable file
drwxr-xr-x  directory
-rwx------  executable, owner only
-rw-------  private file (owner read/write only)

chmod - Change File Permissions

SINTAKS

chmod [OPTION] MODE FILE...

Mode Formats:

FORMATCONTOHDESKRIPSI
Numeric (octal) chmod 755 file rwxr-xr-x
Symbolic chmod u+x file Add execute for owner

Numeric Values:

ANGKAPERMISSIONBINARY
0 --- 000
1 --x 001
2 -w- 010
3 -wx 011
4 r-- 100
5 r-x 101
6 rw- 110
7 rwx 111
Bash - chmod Examples
# Numeric mode
$ chmod 755 script.sh
# rwxr-xr-x (owner: rwx, group: r-x, others: r-x)

$ chmod 644 file.txt
# rw-r--r-- (owner: rw-, group: r--, others: r--)

$ chmod 600 private.txt
# rw------- (owner: rw-, group: ---, others: ---)

$ chmod 700 private_dir/
# rwx------ (owner: rwx, group: ---, others: ---)

# Symbolic mode
$ chmod u+x script.sh
# Add execute permission for owner

$ chmod g+w file.txt
# Add write permission for group

$ chmod o-r file.txt
# Remove read permission for others

$ chmod u=rwx,g=rx,o=r file.txt
# Set specific permissions

$ chmod a+r file.txt
# Add read for all (a = all)

$ chmod a-x script.sh
# Remove execute for all

# Recursive
$ chmod -R 755 directory/

# Common permission sets
$ chmod 755 directory/    # Standard directory
$ chmod 644 file.txt      # Standard file
$ chmod 700 ~/.ssh        # SSH directory
$ chmod 600 ~/.ssh/id_rsa # SSH private key
$ chmod 644 ~/.ssh/id_rsa.pub # SSH public key

# Copy permissions from another file
$ chmod --reference=file1.txt file2.txt

# Change permissions with verbose
$ chmod -v 755 script.sh
mode of 'script.sh' retained as 0755 (rwxr-xr-x)

# Change only if different
$ chmod -c 755 script.sh

chown - Change Owner and Group

SINTAKS

chown [OPTION] OWNER[:[GROUP]] FILE...

Bash - chown Examples
# Change owner
$ sudo chown user file.txt

# Change owner and group
$ sudo chown user:group file.txt

# Change group only
$ sudo chown :group file.txt

# Recursive
$ sudo chown -R user:group directory/

# Change owner to match another file
$ sudo chown --reference=file1.txt file2.txt

# Verbose
$ sudo chown -v user:group file.txt
changed ownership of 'file.txt' from root:root to user:group

# Change only if different
$ sudo chown -c user:group file.txt

# Recursive with verbose
$ sudo chown -Rv user:group directory/

chgrp - Change Group

Bash - chgrp Examples
# Change group
$ sudo chgrp group file.txt

# Recursive
$ sudo chgrp -R group directory/

# Verbose
$ sudo chgrp -v group file.txt

Special Permissions

PERMISSIONANGKADESKRIPSI
SetUID (u+s) 4 File dijalankan dengan permission owner
SetGID (g+s) 2 File dijalankan dengan permission group; directory inherits group
Sticky Bit (+t) 1 Only owner can delete files in directory
Bash - Special Permissions
# SetUID
$ chmod u+s file
$ chmod 4755 file

# SetGID
$ chmod g+s file
$ chmod 2755 file

# Sticky bit (commonly on /tmp)
$ chmod +t directory
$ chmod 1777 directory

# Remove special permissions
$ chmod u-s file
$ chmod g-s file
$ chmod -t directory

# Check special permissions
$ ls -l /usr/bin/passwd
-rwsr-xr-x 1 root root ... /usr/bin/passwd
# 's' indicates SetUID

$ ls -ld /tmp
drwxrwxrwt 1 root root ... /tmp
# 't' indicates sticky bit

umask - Default Permissions

Bash - umask Examples
# Check current umask
$ umask
0022

# umask symbolic
$ umask -S
u=rwx,g=rx,o=rx

# Set umask
$ umask 022
# Files: 644 (rw-r--r--)
# Directories: 755 (rwxr-xr-x)

$ umask 077
# Files: 600 (rw-------)
# Directories: 700 (rwx------)

# Set umask temporarily
$ umask 027

# Set umask permanently (add to ~/.bashrc)
$ echo "umask 027" >> ~/.bashrc

# Test new file creation
$ touch test.txt
$ ls -l test.txt
-rw-r----- 1 user group ... test.txt
ANALOGI: PERMISSIONS
  • Read (r) = boleh melihat isi dokumen
  • Write (w) = boleh mengedit dokumen
  • Execute (x) = boleh menjalankan program
  • Owner (u) = pemilik rumah
  • Group (g) = anggota keluarga
  • Others (o) = tamu/orang asing
  • SetUID = tamu menjalankan program dengan hak pemilik
  • Sticky bit = hanya pemilik yang boleh menghapus file di folder bersama
SECURITY BEST PRACTICES
  • Gunakan permission minimal yang dibutuhkan (least privilege)
  • Hindari chmod 777 kecuali sangat diperlukan
  • File sensitif: chmod 600 atau chmod 400
  • SSH private key: chmod 600
  • Script executable: chmod 755 atau chmod 700
  • Directory: chmod 755 atau chmod 700
  • Regular files: chmod 644 atau chmod 600
  • Gunakan umask 027 atau umask 077 untuk keamanan
REFERENSI
  • Linux Documentation - File Permissions
  • Linux Command Library - chmod, chown, chgrp
  • Arch Wiki - File permissions and attributes
17.9

USER & GROUP

Konsep User dan Group

Linux adalah sistem multi-user, memungkinkan banyak user menggunakan sistem secara bersamaan. Setiap user memiliki home directory, permission, dan resource sendiri. Group digunakan untuk mengelola permission secara kolektif.

File-file Penting

FILEFUNGSIISI
/etc/passwd User account information Username, UID, GID, home, shell
/etc/shadow Encrypted passwords Password hash, expiry
/etc/group Group information Group name, GID, members
/etc/gshadow Encrypted group passwords Group password hash

useradd - Add User

SINTAKS

useradd [OPTION] USERNAME

Opsi Penting:

OPSIFUNGSICONTOH
-m Create home directory useradd -m user
-s Set login shell useradd -s /bin/bash user
-g Set primary group useradd -g group user
-G Add to supplementary groups useradd -G group1,group2 user
-d Set home directory useradd -d /home/dir user
-c Set comment (GECOS) useradd -c "Full Name" user
-e Set account expiry date useradd -e 2024-12-31 user
-D Set defaults useradd -D -s /bin/bash
Bash - useradd Examples
# Basic user creation
$ sudo useradd -m username

# Create with specific shell
$ sudo useradd -m -s /bin/bash username

# Create with full name
$ sudo useradd -m -c "John Doe" username

# Create with specific group
$ sudo useradd -m -g users username

# Create with multiple groups
$ sudo useradd -m -G sudo,docker username

# Create with specific home directory
$ sudo useradd -m -d /custom/home username

# Create with expiry date
$ sudo useradd -m -e 2024-12-31 username

# Create system user (no home, no login)
$ sudo useradd -r -s /sbin/nologin serviceuser

# Create and set password
$ sudo useradd -m username
$ sudo passwd username

# View defaults
$ useradd -D
GROUP=100
HOME=/home
INACTIVE=-1
EXPIRE=
SHELL=/bin/sh
SKEL=/etc/skel
CREATE_MAIL_SPOOL=yes

# Change defaults
$ sudo useradd -D -s /bin/bash
$ sudo useradd -D -b /custom/home

usermod - Modify User

SINTAKS

usermod [OPTION] USERNAME

Bash - usermod Examples
# Add user to group
$ sudo usermod -aG group username

# Add user to multiple groups
$ sudo usermod -aG group1,group2,group3 username

# Change primary group
$ sudo usermod -g group username

# Change shell
$ sudo usermod -s /bin/zsh username

# Change home directory
$ sudo usermod -d /new/home -m username

# Lock account
$ sudo usermod -L username

# Unlock account
$ sudo usermod -U username

# Set expiry date
$ sudo usermod -e 2024-12-31 username

# Remove expiry date
$ sudo usermod -e "" username

# Change username
$ sudo usermod -l newname oldname

# Add comment
$ sudo usermod -c "New Full Name" username

# Lock and expire immediately
$ sudo usermod -L -e 1 username

userdel - Delete User

SINTAKS

userdel [OPTION] USERNAME

Bash - userdel Examples
# Delete user (keep home directory)
$ sudo userdel username

# Delete user and home directory
$ sudo userdel -r username

# Force delete (even if logged in)
$ sudo userdel -f username

# Delete user and remove from mail spool
$ sudo userdel -r username

# Check if user exists before delete
$ id username && sudo userdel -r username

groupadd, groupmod, groupdel

Bash - Group Management
# Add group
$ sudo groupadd groupname

# Add group with specific GID
$ sudo groupadd -g 1500 groupname

# Add system group
$ sudo groupadd -r systemgroup

# Modify group name
$ sudo groupmod -n newname oldname

# Modify group GID
$ sudo groupmod -g 2000 groupname

# Delete group
$ sudo groupdel groupname

# List groups
$ groups
$ groups username

# View group members
$ cat /etc/group | grep groupname
$ getent group groupname

# Add user to group (alternative)
$ sudo gpasswd -a username groupname

# Remove user from group
$ sudo gpasswd -d username groupname

# Set group administrator
$ sudo gpasswd -A admin groupname

# Set group password
$ sudo gpasswd groupname

Informasi User

Bash - User Information Commands
# Current user info
$ whoami
$ id
uid=1000(kali) gid=1000(kali) groups=1000(kali),... 

# Specific user info
$ id username
$ id -u username    # UID only
$ id -g username    # GID only
$ id -G username    # All groups
$ id -n username    # Names instead of numbers

# Who is logged in
$ who
kali     tty1         2024-01-15 09:00
kali     pts/0        2024-01-15 09:05

# Detailed who
$ who -u
kali     tty1         2024-01-15 09:00 00:05  1234

# Who is logged in (short)
$ w
 09:10:00 up 10 min,  2 users,  load average: 0.00, 0.00, 0.00
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
kali     tty1     -                09:00    5:00   0.00s  0.00s -bash

# Last login
$ last
$ last username
$ last -10    # Last 10 logins

# Failed login attempts
$ lastb
$ sudo lastb

# User password info
$ sudo chage -l username
Last password change                                    : Jan 15, 2024
Password expires                                        : never
Password inactive                                       : never
Account expires                                         : never

# Change password aging
$ sudo chage -M 90 username      # Max days
$ sudo chage -m 7 username       # Min days
$ sudo chage -E 2024-12-31 username  # Expiry date
$ sudo chage -d 0 username       # Force password change
ANALOGI: USER & GROUP
  • User = orang dengan ID card unik
  • Group = departemen atau tim
  • UID = nomor ID card
  • GID = nomor departemen
  • Home directory = ruangan pribadi
  • Shell = bahasa yang digunakan untuk berkomunikasi
  • Root (UID 0) = administrator dengan akses penuh
SECURITY BEST PRACTICES
  • Gunakan password yang kuat untuk semua user
  • Gunakan sudo daripada login sebagai root
  • Disable root login via SSH
  • Gunakan SSH keys daripada password
  • Lock atau delete akun yang tidak digunakan
  • Set password expiry policy
  • Monitor failed login attempts
  • Gunakan group untuk mengelola permission
REFERENSI
  • Linux Documentation - User Management
  • Linux Command Library - useradd, usermod, userdel
  • Arch Wiki - Users and groups
17.10

sudo

Konsep sudo

sudo (superuser do) memungkinkan user menjalankan command dengan privilege user lain (biasanya root). Ini lebih aman daripada login langsung sebagai root karena:

  • Memberikan audit trail (siapa melakukan apa)
  • Membatasi command yang bisa dijalankan
  • Tidak perlu share root password
  • Timeout otomatis setelah periode tidak aktif

Penggunaan Dasar sudo

Bash - sudo Basics
# Run command as root
$ sudo command

# Run command as specific user
$ sudo -u username command

# Run shell as root
$ sudo -i
# # Now in root shell

# Run shell as root (alternative)
$ sudo -s

# Run command with environment preserved
$ sudo -E command

# Run command without password (if configured)
$ sudo -n command

# List allowed commands
$ sudo -l

# Edit sudoers file safely
$ sudo visudo

# Edit specific user's sudoers
$ sudo visudo -f /etc/sudoers.d/username

# Validate sudoers file
$ sudo visudo -c

Konfigurasi sudoers

Bash - sudoers Configuration
# Edit sudoers file
$ sudo visudo

# Basic format:
# user  host=(runas)  commands

# Examples:

# Allow user to run all commands as root
username ALL=(ALL:ALL) ALL

# Allow user to run all commands without password
username ALL=(ALL) NOPASSWD: ALL

# Allow user to run specific commands
username ALL=(ALL) /usr/bin/apt, /usr/bin/systemctl

# Allow group to run commands
%groupname ALL=(ALL) ALL

# Allow group without password
%sudo ALL=(ALL:ALL) NOPASSWD: ALL

# Complex example
username ALL=(root) NOPASSWD: /usr/bin/systemctl restart nginx, \
                              /usr/bin/systemctl status nginx

# Host-specific
username server1=(ALL) ALL

# Command aliases
Cmnd_Alias SERVICES = /usr/bin/systemctl start *, \
                                 /usr/bin/systemctl stop *, \
                                 /usr/bin/systemctl restart *
username ALL=(ALL) SERVICES

# User aliases
User_Alias ADMINS = user1, user2, user3
ADMINS ALL=(ALL) ALL

# Defaults
Defaults:username timestamp_timeout=30
Defaults:username logfile=/var/log/sudo-username.log

sudo History dan Logging

Bash - sudo Logging
# View sudo log
$ sudo grep sudo /var/log/auth.log
$ sudo grep sudo /var/log/secure  # RHEL/CentOS

# View recent sudo commands
$ sudo grep "COMMAND=" /var/log/auth.log | tail

# View sudo commands by user
$ sudo grep "username" /var/log/auth.log | grep "COMMAND="

# Configure sudo logging
$ sudo visudo
# Add: Defaults logfile="/var/log/sudo.log"

# View sudo log
$ sudo tail -f /var/log/sudo.log

sudo Best Practices

BEST PRACTICES
  • Gunakan sudo daripada login sebagai root
  • Batasi command yang bisa dijalankan dengan sudo
  • Gunakan NOPASSWD hanya jika diperlukan
  • Set timestamp_timeout yang sesuai
  • Log semua aktivitas sudo
  • Gunakan group untuk mengelola akses sudo
  • Review sudoers file secara berkala
  • Gunakan visudo untuk edit sudoers (mencegah syntax error)
ANALOGI: sudo
  • sudo = meminjam kunci master untuk sementara
  • sudo -u user = meminjam kunci ruangan orang lain
  • sudoers file = daftar siapa yang boleh pinjam kunci master
  • NOPASSWD = tidak perlu minta izin setiap kali pinjam
  • timestamp_timeout = berapa lama kunci bisa dipakai sebelum harus dikembalikan
PERINGATAN
  • Jangan berikan akses sudo penuh ke user yang tidak dipercaya
  • Jangan gunakan NOPASSWD: ALL kecuali sangat diperlukan
  • Selalu gunakan visudo untuk edit sudoers
  • Test konfigurasi sudoers sebelum apply
  • Monitor log sudo secara berkala
REFERENSI
  • sudo Manual - sudo man page
  • sudoers Manual - sudoers man page
  • Linux Command Library - sudo, sudoers
17.11

PROCESS MANAGEMENT

Konsep Process

Process adalah instance dari program yang sedang dijalankan. Setiap process memiliki PID (Process ID), status, resource usage, dan parent process. Linux memungkinkan banyak process berjalan secara bersamaan (multitasking).

Melihat Process

Bash - Process Viewing Commands
# ps - Report process status
$ ps
  PID TTY          TIME CMD
 1234 pts/0    00:00:00 bash
 5678 pts/0    00:00:00 ps

# ps with all processes
$ ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root         1  0.0  0.1 169432 11520 ?        Ss   09:00   0:01 /sbin/init
root       456  0.0  0.2 274532 18432 ?        Ssl  09:00   0:00 /usr/lib/systemd/systemd-journald

# ps with forest view
$ ps auxf
root         1  0.0  0.1 169432 11520 ?        Ss   09:00   0:01 /sbin/init
root       456  0.0  0.2 274532 18432 ?        Ssl  09:00   0:00  \_ /usr/lib/systemd/systemd-journald

# ps with specific user
$ ps -u username

# ps with specific PID
$ ps -p 1234

# ps with custom format
$ ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem

# top - Dynamic process viewer
$ top

# top with specific user
$ top -u username

# top with specific PID
$ top -p 1234

# htop - Enhanced top (if installed)
$ htop

# pgrep - Search processes by name
$ pgrep firefox
1234
5678

# pgrep with details
$ pgrep -a firefox
1234 /usr/lib/firefox/firefox

# pidof - Get PID of running program
$ pidof firefox
1234 5678

# pstree - Display process tree
$ pstree
systemd─┬─ModemManager───2*[{ModemManager}]
        ├─NetworkManager───2*[{NetworkManager}]

# pstree with PIDs
$ pstree -p

# pstree for specific user
$ pstree -u username

Menghentikan Process

Bash - Process Control Commands
# kill - Send signal to process
$ kill PID

# kill with signal
$ kill -SIGTERM PID
$ kill -15 PID

# kill force
$ kill -SIGKILL PID
$ kill -9 PID

# killall - Kill by name
$ killall firefox

# killall with signal
$ killall -9 firefox

# pkill - Kill by pattern
$ pkill firefox

# pkill with signal
$ pkill -9 firefox

# pkill by user
$ pkill -u username

# pkill by parent
$ pkill -P PPID

# Signals:
# 1  (SIGHUP)  - Hangup
# 2  (SIGINT)  - Interrupt (Ctrl+C)
# 9  (SIGKILL) - Kill (cannot be caught)
# 15 (SIGTERM) - Terminate (default)
# 18 (SIGCONT) - Continue
# 19 (SIGSTOP) - Stop (cannot be caught)

# List all signals
$ kill -l

Background dan Foreground

Bash - Background/Foreground Control
# Run command in background
$ command &
[1] 1234

# Run long-running command in background
$ sleep 3600 &
[1] 5678

# List background jobs
$ jobs
[1]+  Running                 sleep 3600 &

# Bring job to foreground
$ fg %1
$ fg 1

# Send foreground to background
# Press Ctrl+Z to suspend
# Then:
$ bg %1

# Suspend foreground process
# Press Ctrl+Z
[1]+  Stopped                 command

# Resume suspended job in background
$ bg

# Resume suspended job in foreground
$ fg

# Run command immune to hangups
$ nohup command &
$ nohup command > output.log 2>&1 &

# Run command with nice (priority)
$ nice -n 10 command
$ nice -n -5 command  # Higher priority (requires root)

# Change priority of running process
$ renice -n 10 -p PID

# Run command in subshell
$ (command1; command2; command3)

# Run command and discard output
$ command > /dev/null 2>&1

Resource Monitoring

Bash - Resource Monitoring
# System uptime
$ uptime
 09:15:00 up 15 min,  2 users,  load average: 0.00, 0.01, 0.00

# Memory usage
$ free -h
              total        used        free      shared  buff/cache   available
Mem:          7.7Gi       1.2Gi       5.1Gi       128Mi       1.4Gi       6.2Gi
Swap:         2.0Gi          0B       2.0Gi

# Disk usage
$ df -h
Filesystem      Size  Used Avail Use% Mounted on
/dev/sda1        50G   15G   33G  32% /
/dev/sda2       100G   45G   50G  48% /home

# Disk usage by directory
$ du -sh /var/log/
256M    /var/log/

# Disk usage with details
$ du -sh /var/log/*
64M     /var/log/apt
128M    /var/log/syslog

# CPU info
$ lscpu
Architecture:          x86_64
CPU(s):                4
Thread(s) per core:    2

# Block devices
$ lsblk
NAME   MAJ:MIN RM  SIZE RO TYPE MOUNTPOINT
sda      8:0    0   50G  0 disk
└─sda1   8:1    0   50G  0 part /

# PCI devices
$ lspci

# USB devices
$ lsusb

# System information
$ uname -a
Linux kali 5.15.0-kali3-amd64 #1 SMP Debian 5.15.15-2kali1

# Kernel messages
$ dmesg
$ dmesg | tail

# System logs
$ journalctl
$ journalctl -u ssh
$ journalctl --since "1 hour ago"
ANALOGI: PROCESS MANAGEMENT
  • Process = pekerja yang sedang melakukan tugas
  • PID = nomor ID pekerja
  • ps = daftar semua pekerja yang sedang bekerja
  • top = monitor real-time semua pekerja
  • kill = memecat pekerja
  • kill -9 = memecat pekerja secara paksa
  • bg/fg = menyuruh pekerja bekerja di belakang/depan
  • nice = mengatur prioritas pekerja
BEST PRACTICES
  • Gunakan SIGTERM (15) sebelum SIGKILL (9)
  • Monitor resource usage secara berkala
  • Gunakan nice untuk proses yang tidak kritis
  • Gunakan nohup untuk proses long-running
  • Monitor log sistem untuk troubleshooting
  • Gunakan systemctl untuk manage services
REFERENSI
  • Linux Documentation - Process Management
  • Linux Command Library - ps, top, kill
  • Arch Wiki - Process management
17.12

NETWORK COMMANDS

Network Commands Overview

Linux menyediakan banyak command untuk network troubleshooting, monitoring, dan configuration. Menguasai command-command ini essential untuk network administration dan security analysis.

Network Configuration

Bash - Network Configuration Commands
# ip - Show/manipulate routing, devices, policy routing
$ ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN
    inet 127.0.0.1/8 scope host lo
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500
    inet 192.168.1.100/24 brd 192.168.1.255 scope global eth0

# ip with brief output
$ ip -br addr
lo               UNKNOWN        127.0.0.1/8
eth0             UP             192.168.1.100/24

# Show routing table
$ ip route
default via 192.168.1.1 dev eth0
192.168.1.0/24 dev eth0 proto kernel scope link src 192.168.1.100

# Show link status
$ ip link
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500

# Show statistics
$ ip -s link

# Legacy commands (still used)
$ ifconfig
$ route -n
$ netstat -rn

Connectivity Testing

Bash - Connectivity Testing
# ping - Send ICMP echo requests
$ ping google.com
PING google.com (142.250.195.78) 56(84) bytes of data.
64 bytes from sof04s07-in-f14.1e100.net: icmp_seq=1 ttl=117 time=15.2 ms

# ping with count
$ ping -c 4 google.com

# ping with interval
$ ping -i 2 google.com

# ping with specific packet size
$ ping -s 1000 google.com

# traceroute - Trace route to host
$ traceroute google.com
traceroute to google.com (142.250.195.78), 30 hops max
 1  192.168.1.1  1.234 ms  1.123 ms  1.098 ms
 2  10.0.0.1  5.678 ms  5.456 ms  5.234 ms

# traceroute with ICMP
$ traceroute -I google.com

# traceroute with specific port
$ traceroute -p 80 google.com

# mtr - Combined ping and traceroute
$ mtr google.com

# mtr with report
$ mtr -r google.com

# mtr with specific count
$ mtr -c 10 google.com

# dig - DNS lookup
$ dig google.com
;google.com.                   IN      A
google.com.            123     IN      A       142.250.195.78

# dig with specific record type
$ dig google.com MX
$ dig google.com NS
$ dig google.com TXT

# dig short output
$ dig +short google.com

# nslookup (legacy)
$ nslookup google.com

# host (simple)
$ host google.com

# Reverse DNS lookup
$ dig -x 142.250.195.78
$ host 142.250.195.78

Port dan Connection Monitoring

Bash - Port and Connection Monitoring
# netstat - Network statistics
$ netstat
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address   Foreign Address  State
tcp        0      0 192.168.1.100:22 192.168.1.50:54321 ESTABLISHED

# netstat with listening ports
$ netstat -l
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address   State
tcp        0      0 0.0.0.0:22      LISTEN

# netstat with process info
$ netstat -tulpn
Proto Recv-Q Send-Q Local Address   PID/Program name
tcp        0      0 0.0.0.0:22      1234/sshd

# netstat with statistics
$ netstat -s

# netstat with routing table
$ netstat -r

# ss - Socket statistics (modern replacement)
$ ss
Netid State  Recv-Q Send-Q Local Address:Port  Peer Address:Port
tcp   ESTAB  0      0      192.168.1.100:22   192.168.1.50:54321

# ss with listening
$ ss -l
Netid State  Recv-Q Send-Q Local Address:Port
tcp   LISTEN 0      128    0.0.0.0:22

# ss with process info
$ ss -tulpn
Netid State  Recv-Q Send-Q Local Address:Port  Process
tcp   LISTEN 0      128    0.0.0.0:22      users:(("sshd",pid=1234,fd=3))

# ss with all sockets
$ ss -a

# ss with statistics
$ ss -s

# lsof - List open files (including network)
$ lsof -i
COMMAND  PID USER   FD   TYPE  DEVICE SIZE/OFF NODE NAME
sshd    1234 root    3u  IPv4  12345      0t0  TCP *:ssh (LISTEN)

# lsof with specific port
$ lsof -i :22

# lsof with specific protocol
$ lsof -i tcp
$ lsof -i udp

# lsof with specific user
$ lsof -u username

# lsof with specific process
$ lsof -p PID

Download dan Transfer

Bash - Download and Transfer Commands
# wget - Download files
$ wget https://example.com/file.txt

# wget with output filename
$ wget -O output.txt https://example.com/file.txt

# wget with continue
$ wget -c https://example.com/largefile.iso

# wget with background
$ wget -b https://example.com/file.txt

# wget with quiet mode
$ wget -q https://example.com/file.txt

# wget with recursive
$ wget -r https://example.com/directory/

# wget with specific depth
$ wget -r -l 2 https://example.com/

# curl - Transfer data
$ curl https://example.com

# curl with output
$ curl -o output.txt https://example.com/file.txt

# curl with headers
$ curl -I https://example.com

# curl with verbose
$ curl -v https://example.com

# curl with POST
$ curl -X POST -d "data=value" https://example.com/api

# curl with JSON
$ curl -X POST -H "Content-Type: application/json" \
       -d '{"key":"value"}' https://example.com/api

# curl with authentication
$ curl -u username:password https://example.com

# curl with silent mode
$ curl -s https://example.com

# curl with progress bar
$ curl -# -O https://example.com/file.txt

# scp - Secure copy
$ scp file.txt user@remote:/path/

# scp from remote
$ scp user@remote:/path/file.txt .

# scp recursive
$ scp -r directory user@remote:/path/

# rsync - Efficient file transfer
$ rsync -avh source/ user@remote:/path/

# rsync with delete
$ rsync -avh --delete source/ user@remote:/path/

# rsync with progress
$ rsync -avh --progress source/ user@remote:/path/

# rsync dry run
$ rsync -avhn source/ user@remote:/path/

Network Security Commands

Bash - Network Security Commands
# nmap - Network scanner
$ nmap 192.168.1.1

# nmap with specific ports
$ nmap -p 80,443 192.168.1.1

# nmap with port range
$ nmap -p 1-1000 192.168.1.1

# nmap with service detection
$ nmap -sV 192.168.1.1

# nmap with OS detection
$ nmap -O 192.168.1.1

# nmap with all
$ nmap -A 192.168.1.1

# nmap with aggressive scan
$ nmap -T4 -A 192.168.1.1

# nmap with output to file
$ nmap -oN output.txt 192.168.1.1

# tcpdump - Packet analyzer
$ sudo tcpdump

# tcpdump with interface
$ sudo tcpdump -i eth0

# tcpdump with filter
$ sudo tcpdump -i eth0 port 80

# tcpdump with host
$ sudo tcpdump -i eth0 host 192.168.1.100

# tcpdump with write to file
$ sudo tcpdump -i eth0 -w capture.pcap

# tcpdump with read from file
$ tcpdump -r capture.pcap

# tcpdump with verbose
$ sudo tcpdump -i eth0 -vv

# tcpdump with count
$ sudo tcpdump -i eth0 -c 100

# iptables - Firewall
$ sudo iptables -L
$ sudo iptables -L -n
$ sudo iptables -L -v

# iptables add rule
$ sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# iptables delete rule
$ sudo iptables -D INPUT 1

# iptables save
$ sudo iptables-save > /etc/iptables/rules.v4

# iptables restore
$ sudo iptables-restore < /etc/iptables/rules.v4

# ufw - Uncomplicated Firewall
$ sudo ufw status
$ sudo ufw enable
$ sudo ufw disable

# ufw allow
$ sudo ufw allow 22
$ sudo ufw allow 80/tcp
$ sudo ufw allow from 192.168.1.0/24

# ufw delete
$ sudo ufw delete allow 22
ANALOGI: NETWORK COMMANDS
  • ping = memanggil seseorang untuk memastikan dia ada
  • traceroute = melacak rute surat dari pengirim ke penerima
  • netstat/ss = melihat siapa yang sedang berkomunikasi dengan siapa
  • tcpdump = merekam semua percakapan di jaringan
  • nmap = mendata semua rumah di lingkungan dan apa yang ada di dalamnya
  • iptables = satpam yang mengatur siapa yang boleh masuk/keluar
BEST PRACTICES
  • Gunakan ss daripada netstat (lebih modern)
  • Gunakan ip daripada ifconfig (lebih modern)
  • Gunakan dig daripada nslookup (lebih lengkap)
  • Gunakan rsync untuk transfer file besar (efisien)
  • Gunakan tcpdump dengan filter untuk efisiensi
  • Backup konfigurasi firewall sebelum mengubah
  • Test aturan firewall secara bertahap
REFERENSI
  • Linux Documentation - Network Configuration
  • Linux Command Library - Network commands
  • Arch Wiki - Network configuration
  • Nmap Documentation - Nmap Reference Guide
Q

DIAGNOSTIK KOMPETENSI

Uji pemahaman Anda tentang Bab 17! Target minimal: 70% untuk melanjutkan ke Bab 18.

PETUNJUK
  • Total 10 pertanyaan pilihan ganda
  • Klik opsi untuk menjawab - feedback langsung
  • Benar = HIJAU, salah = MAGENTA
  • Penjelasan muncul setelah menjawab
  • Klik "LIHAT HASIL AKHIR" untuk skor final
SKOR ANDA
0/ 10
-

-

REFERENSI BAB 17 SECARA KESELURUHAN
  • Linux Documentation Project - Linux Command Guide
  • GNU Manuals - Coreutils, Bash, etc.
  • Arch Wiki - Linux commands reference
  • Linux Command Library - Comprehensive command reference
  • OverTheWire Bandit - Linux command practice wargame
ABDURROZAK.MY.ID // JARINGAN SOSIAL
Dibuat dengan oleh Abdur Rozak, S.Kom. - abdurrozak.my.id