Quick Reference
- Admin:
- Reading logs:
- Authentication Logs:
sudo grep "Accepted" /var/log/auth.log*: show all successful login, even in past log rotationssudo grep "Failed password" /var/log/auth.log: list failed login attemptssudo tail -n 20 -f /var/log/auth.log: read most recent 20 entries in ssh/authentication logsudo grep "Failed password" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -nr | head: see top IPs attempting SSH attackssudo grep sshd /var/log/auth.log: show all SSH-related events in authentication logsudo tail -f /var/log/nginx/access.log: reading nginx logs livesudo tail -n 20 -f /var/log/nginx/access.log: show the most recent 20 entries in logsudo tail -f /var/log/nginx/error.log: reading logs livesudo tail -n 20 -f /var/log/nginx/error.log: show the most recent 20 entries in logcat /etc/passwd | sort: list all userswho: show all logged in usersgetent group sudo: see who has admin privileges- Users control:
sudo useradd -m [username]: add a new user and make a home directorysudo passwd [username]: set password for a usersudo usermod [username] sudo: add a user to the sudo groupsudo userdel -r [username]: delete user and their home directorysudo nano /etc/ssh/sshd_config: edit SSH access permission for usersAllowUsers [username1 username2 ...] deploy: allow certain users to ssh and deny everyone elseDenyUsers [username1 username2 ...] deploy: deny certain users ssh; Deny rules will override allow rulesAllowGroups [group ...] deployDenyGroups [group ...] deploy- Priority:
- DenyUsers
- AllowUsers
- DenyGroups
- AllowGroups
sudo systemctl restart ssh: restart ssh
- Setup:
ssh -i [private key] [user]@[host]: connect to a remote host using SSHq / exit: quit the current sessionCtrl + L: clear the terminal screensudo apt update && sudo apt upgrade -y: update and upgrade packagessudo apt install wget curl unzip git -y: install common utilities- wget: download files from the web through HTTP/HTTPS/FTP
wget [URL]- download a file from the specified URL- curl: testing REST APIs, sending POST/PUT requests
- unzip: extract
.zipfiles since Linux only handle.tar.gzfiles - git: version control system
VARIABLE=value: set an environment variableexport VARIABLE=value: export an environment variable to make it available to child processes/subshellssudo apt install nginx -y: install Nginx web server- setup reverse proxy and rate limiting rules, also ssh limit
- Navigation:
pwd: print current directorycd [directory]: change directorymkdir [directory]: create a new directorycp [source] [destination]: copy files or directoriesscp [source] [user]@[host]:[destination]: securely copy files between local and remote hostsscp -r [source] [user]@[host]:[destination]: securely copy directories recursivelyrsync -avz [source] [user]@[host]:[destination]: copying large files and synchronizing directoriesmv [source] [destination]: move or rename files or directoriesrm [file]: remove a filerm -r [directory]: remove a directory and its contents recursivelyprintenv | grep [variable]: search for environment variablesls: list directory contentsls -a -1f: list all files, one per line, with file type indicatorsls [directory]: list contents of a specific directorytree -a -L 2: display all files and directory structure up to 2 levels deepwhich [command]: display the path of the executable for a commandfind [directory] -name [filename]: search for a file in a directory and its subdirectoriesfind [directory/to/search] -type d -name [directory]: search for a folder in a directory and its subdirectories- File Edit, Extract/Compress, and Firewall:
cat -n [file]: display the contents of a file with line numberscat [file] | grep [pattern]: search for a pattern in a filecat [file1] [file2]> [combined file]: concatentate file1 and file2 into a combined filenano -l [file]: edit file with line numbers on leftCtrl + O: save the current fileCtrl + X: exit the editorCtrl + W: search within the fileCtrl + _: jump to specific line #tar: compress and extract.tar.gzfilestar -czf [archive.tar.gz] [/path/to/directory]: create a compressed archive of a directorytar -xf [archive.tar.gz]- extract a compressed archiveufw: Uncomplicated Firewallufw status- display the current status of the firewallsudo ufw allow from [hostname] to [remoteAddress/any] app [appname]- allow traffic from a specific host to all the ports listed by the app profilesudo ufw allow from [home] to any app OpenSSHufw app list- list available applicationsufw app info [appname]- display network information about a specific applicationufw delete [rule]- delete a specific rulesudo ufw allow [port #]/[tcp/udp]- allow traffic on a specific portsudo ufw deny [port #]/[tcp/udp]- deny traffic on a specific port- Port 22: SSH
- Port 80: HTTP/Nginx
- Port 443: HTTPS/Nginx
Linux Commands
- Basics:
- Format:
command -option /argument - Help Commands:
{command} --help- display help information for a commandman {command}- display the manual page for a commandinfo {command}- display detailed information about a command- Shortcuts:
- U: return to parent menu
- B: goes back to beginning of node
- Q: quit
- PageUp / PageDown: scroll through the manual
- Piping
command1 | command2: sends the output of command1 as input to command2 - Protecting:
- Single Quote: protect everything from being shell expansion
- Double Quote: allow variable expansion but protect spaces
- Good for protecting variables from being expanded into multiple variables because of spaces
- Backslash: escape the single following character and also used to split long commands to a separate line
- File Globbing
- * - matches any number of characters
- ? - matches a single character
- [abc] - matches any one of the characters a, b, or c
- [a-z] - matches any one character in the range a to z
Ctrl + L- clear the terminalCtrl + D- exit terminal- Directories:
pwd- print current directorycd /path/to/directory- change directorycd -- change to the previous directorycd .- stay in the current directorycd ..- change to the parent directorycd ~- change to the home directoryls- list files in the current directoryls -l filename- list detailed information about a specific filegetfacl filename- display the access control list (ACL) of a filefind /directory- list out whole hierarchy of directoryfind /path/to/directory -name "d*""- find a file matching a pattern in a directoryfind /course -perm 755- find files with specific permissions- Aliases:
alias cp='cp -i'- create an alias for a command; useful to change default command optionsln -s /path/to/original /path/to/link- create a symbolic link or alias for directory- Example:
ln -s /projects/androidand thencd android - Copy, Move/Rename, Create, Delete, Redirecting/Appending:
cp source destination- copy a file or directorycp -r source destination- copy a directory and its contents recursivelymv source destination- move/rename a file or directorymkdir directory- create a new directorymkdir -p /path/to/directory- create a directory and any necessary parent directoriesrm file- delete a filerm file[12]- delete multiple files matching a patternrm -r directory- delete a directory and its contents recursively>- redirect output to a file>>- append output to a file- Variable:
$variableName- define a variablePATH=$PATH:- create/add to the PATH variable (separated by colons)- History:
history- list past commands!# or !88- rerun 88th command in history!e- rerun last command that starts with eCtrl + R- search command history- Converting Case
tr '[:lower:]' '[:upper:]'- convert lowercase to uppercasetr '[:upper:]' '[:lower:]'- convert uppercase to lowercase${variableName^^}- convert variable value to uppercase${variableName^}- convert first character of variable to uppercase${variableName,,}- convert variable value to lowercase${variableName,}- convert first character of variable to lowercase- Command does not replace the value stored in the variable
- Hardware Management:
uptime: gives info about how busy the system is (number of users and load average)top: gives detailed info about how busy the system is, including load average and memories usage- Load average should be below number of CPU cores or else there is a queue in returning requests
uname: display system informationlscpu: display detailed info about the CPU architecturelspci: display detailed info about the motherboard, PCI buses, and deviceslsusb: display detailed info about USB buses and deviceslsmod: display loaded kernel moduleslsblk: display information about disks and partitions- Writing Scripts:
- Shebang: specifify the shell interpreter and what is used to run script
- Debug Tip: use
bash -x script.sh- run the script with debugging enabled to see the command and output together #!/bin/bash- example of a shebang for a Bash scriptchmod u+x script.sh- make a script executable./script.sh- run the script in a separate fork processsource script.sh- run the script in the current shell process$1- first positional parameter passed to the script$?- exit status of the last command executed; anything beside 0 means failure/warning- Conditionals:
test -z "$variable"- check if a variable is emptytest -z "$variable" && echo "Variable is empty"- check if a variable is empty and print a messagetest -n "$variable"- check if a variable is not emptytest "$variable" = "value"- check if a variable equals a value- test can be replaced with brackets:
[ -z "$variable" ] if [ -z "$variable" ]; then echo "Variable is empty"; fi- if statement block to check if a variable is empty and print a message- Loops:
for i in {1..5}; do echo "Iteration $i" done- for loop examplewhile [ condition ]; do # commands to execute done- while loop template- Prompts:
NAME="$1" # create a variable and assign it the value of the first positional parameter read -p "Enter your name: " NAME- prompt user for input and store in variable- Administration:
sudo command: run a command with superuser privilegessudo -i: start a root shellsu username: switch to another user accountgetent passwd: display all local usersgetent group: display all local groupsnewgrp groupname: switch to a new groupchgrp groupname file/directory: change the group ownership of a file/directorysudo chown username:groupname file/directory: change the owner and group of a file/directorysudo useradd -m username: add a new user with a home directory in a private groupsudo useradd -m -N username: add a new user with a home directory in the default groupsudo useradd -m -r username: add a new system user with a home directorysudo usermod username: modify a user accountusermod username -a -G groupname: add a user to a groupuseradd -d: shows the default options for creating a user account, including the default shell and home directory locationsudo groupadd groupname: add a new groupsudo groupmod groupname: modify a groupsudo groupdel groupname: delete a groupsudo gpasswd -a username groupname: add a user to a groupid: display user identity informationid -Gn: display the name of the current user's primary groupwhoorw: display who is logged inlastlog: display the last login of all users- Permissions:
ls -l file/directory: display detailed info about a file including permissions- Linux system will match the file permissions to the userID first, and if no match was found, then the groupID, and finally others
- Linux permissions are not cumulative so permission from one group does not affect the others
- Deleting a files has to do with the directory permissions and not the file permissions
- Symbolic Permissions
- r: read permission
- w: write permission
- x: execute permission
- Octal Permissions
- 7: read + write + execute
- 6: read + write
- 5: read + execute
- 4: read
- 2: write
- 1: execute
chmod permissions file/directory: change the permissions of a file or directorychmod u=r,g=rw,o=rwx file/directory: change permissions symbolically for user, group, and otherschmod u-w file/directory: remove write permission for the userchmod u+w file/directory: add write permission for the userchmod 755 file/directory: change permissions using octal notation- Networking:
ip a: display all network interfaces and their IP addressesifconfig/ipconfig:(deprecated) display all network interfaces and their IP addresses- For ipv4 address 127.0.0.1/8 address, the 127 is the network while 0.0.0.1 is the host with a mask of 8
- For ipv4 address 192.168.0.21/24 address, the 192.168.0 is the network while 21 is the host with a mask of 24
- For ipv6 address 2001:db8:abcd:0012::0/64 address, the 2001:db8:abcd:0012 is the network while 0 is the host with a mask of 64
arp -a: list all systems on the local network, ie the ARP cacheping hostname: send ICMP ECHO_REQUEST to network hoststo check connectivity- Example:
ping google.comorping 192.168.0.1 traceroute/tracert hostname: trace the path to a network hostroute: display or modify the IP routing tablegetent hosts: display IP address and hostname mappings in the local host filehost hostname: display IP address for a hostnamedig hostname: display DNS information for a hostnamenetstat: display all active network connections on the devicess: display socket & network statistics on Linux systemsss -t: shows active TCP socketsss -at: shows all TCP socketsss -atn: shows all TCP sockets with numeric port numbersss -atnp: shows all TCP sockets with numeric port numbers and process informationss -u: shows active UDP socketsnmap: scan remote device for opened ports; network exploration tool and security scannernmap -sT -sU localhost: shows the open TCP and UDP ports on the local machinenc: opens network connections for reading/writing data across network connections in raw text- The command is only available on Mac and Linux systems. But apps like PuTTY/Telnet can be used instead on Windows systems
telnet hostname portNumber: opens a Telnet connection to a remote host through a specified port- Firewall:
ufw: Uncomplicated Firewall, a user-friendly interface for managing firewall rules on Linux systemsufw enableufw status: will also list the current rules of the firewall; if no rules are listed then all inbound traffic will be blockedufw allow portNumber/tcp: allow incoming TCP traffic on a specific portsudo ufw allow from [hostname] to [remoteAddress/any] app [appname]- allow traffic from a specific host to all the ports listed by the app profileufw app list: list available applications for firewall rulesufw app info {appname}: display information about a specific applicationufw delete 2: delete the second rule on the list fromufw status
CMD Commands
| Task | macOS / Linux | Windows (PowerShell) | Example |
|---|---|---|---|
| Show current directory | pwd | Get-Location (alias: pwd) | pwd |
| List files | ls | Get-ChildItem (alias: ls) | ls -la |
| Change directory | cd | Set-Location (alias: cd) | cd projects |
| Move up one directory | cd .. | Set-Location (alias: cd ..) | cd .. projects |
| Make directory | mkdir | New-Item -ItemType Directory (alias: mkdir) | mkdir assets |
| Remove empty directory | rmdir | Remove-Item -Force (alias: rmdir) | rmdir old |
| Remove directory (recursive) | rm -r | Remove-Item -Recurse | rm -rf build |
| Copy file | cp | Copy-Item (alias: cp) | cp a.txt b.txt |
| Move/Rename | mv | Move-Item (alias: mv, ren) | mv app.js app.old.js |
| Delete file | rm | Remove-Item (alias: rm, del) | rm notes.tmp |
| View file (print) | cat | Get-Content (alias: cat, type) | cat README.md |
| Paged view | less / more | more | less big.log |
| Search in files | grep | Select-String (similar to grep) | grep -R "TODO" . |
| Find files by name | find | Get-ChildItem -Recurse | find . -name "*.js" |
| Show running processes | ps / top | Get-Process | ps aux |
| Kill process | kill / kill -9 | Stop-Process / taskkill.exe | kill -9 12345 |
| Show username | whoami | whoami (or $env:USERNAME) | whoami |
| Environment variables | printenv / export | Get-ChildItem Env: / $env:VAR= | printenv PATH |
| Make empty file | touch | New-Item file.txt (or > file.txt) | touch .gitignore |
| Download HTTP | curl / wget | Invoke-WebRequest (alias: curl, iwr) | curl -O https://example.com/file.zip |
| Archive (tar) | tar | tar (on recent Windows) / Compress-Archive | tar -czf site.tgz dist/ |
| Disk usage | du -sh | Get-ChildItem | Measure-Object -Sum Length | du -sh * |
| Free disk space | df -h | Get-PSDrive | df -h |
| Network config | ifconfig / ip | ipconfig | ipconfig |
| Ping host | ping | ping | ping example.com |
| Change file mode | chmod | (No direct equivalent; use file properties/ACLs) | chmod +x script.sh |
| Change owner | chown | (Use icacls / Set-Acl) | sudo chown user:group file |
| Print text | echo | Write-Output / echo | echo "Hello" |
| Show manual/help | man | Get-Help | man ls |
npm Commands
| Command | Alias | Purpose | Example | Notes |
|---|---|---|---|---|
npm init | — | Create a package.json | npm init -y | -y skips prompts with defaults. |
npm --version | npm -v | Check installed version of npm | ||
npm install <pkg> | npm i | Install a dependency | npm i react | Saved to dependencies by default. |
npm install --save-dev <pkg> | npm i -D | Install a dev dependency | npm i -D typescript | Saves under devDependencies. |
npm install | npm i | Install from package.json | npm install | Reads versions from package.json/package-lock.json. |
npm uninstall <pkg> | npm remove, npm rm | Remove a dependency | npm uninstall lodash | Updates package.json and lockfile. |
npm update | npm up | Update deps within semver ranges | npm up | Uses ranges in package.json. |
npm outdated | — | Show available updates | npm outdated | Compares current, wanted, latest. |
npm run <script> | — | Run a script from package.json | npm run build | Scripts are under "scripts". |
npm start | — | Run scripts.start | npm start | Shortcut for npm run start. |
npm test | npm t | Run scripts.test | npm test | Shortcut for npm run test. |
npm exec <bin> | npm x | Run a package binary | npm exec eslint . | Uses local node_modules/.bin if present. |
npx <bin> | — | Execute a package (no install) | npx create-vite@latest | Convenience tool bundled with npm. |
npm list | npm ls | List installed packages | npm ls --depth=0 | Add --depth=0 for top-level only. |
npm view <pkg> | npm v, npm info | Show package metadata | npm view react version | Great for checking latest versions. |
npm audit | — | Scan for vulnerabilities | npm audit | Use npm audit fix to apply fixes. |
npm cache clean --force | — | Clear npm cache | npm cache clean --force | --force required for cleaning. |
npm ci | — | Clean install from lockfile | npm ci | Faster, reproducible installs (CI). |
npm link | — | Symlink a package for local dev | npm link | Use in package & consumer repos. |
npm pack | — | Create a tarball of the package | npm pack | Useful to inspect what will publish. |
npm publish | — | Publish to the registry | npm publish --access public | Requires login & proper settings. |
npm login / logout | — | Authenticate with the registry | npm login | Stores credentials for publish, etc. |
npm version <type> | — | Bump version & tag | npm version patch | patch | minor | major or exact. |
npm prune | — | Remove extraneous packages | npm prune | Keeps only what’s in package.json. |
npm dedupe | npm ddp | Reduce duplicate dependencies | npm dedupe | Flattens dependency tree where possible. |
npm config get/set | — | Manage npm config | npm config set registry <url> | Use --global for global config. |
npm doctor | — | Diagnose common issues | npm doctor | Checks environment & configuration. |
npm fund | — | Show funding info | npm fund | Lists packages seeking funding. |
npm explain <pkg> | — | Explain why a pkg is installed | npm explain ansi-regex | Shows dependency path(s). |