Operating systems
$ sudo ss -tulpn
LinuxLinux commands for files, packages, services, networking, firewalls and more, with versions for Debian and Ubuntu, Red Hat and Fedora, and Alpine.168 commands
$ ipconfig /all
Windows CMDWindows Command Prompt (cmd.exe) commands for files, networking, users, services, disks, firewalls, system information and troubleshooting.274 commands
$ Get-Process | Sort CPU
PowerShellPowerShell commands for files, text, the pipeline, processes, services, networking, users and Active Directory, remoting, execution policy and more.329 commands
$ brew upgrade
macOSmacOS Terminal commands for Homebrew, settings, Spotlight, launchd, networking, disks, Time Machine, power, Gatekeeper and more.240 commands
$ vim +42 app.log
VimVim commands and keys for opening, saving and quitting, moving around, editing, copy and paste, search and replace, visual mode, windows and tabs, diffs, macros and settings.278 commands
$ bash -x backup.sh
Bash scriptingBash scripting for Linux, macOS and Windows (Git Bash or WSL): script templates, variables, arguments and options, conditions, loops, functions, strings, arrays, redirection, error handling, traps and handy snippets.168 commands
Networking
$ traceroute example.com
NetworkingNetworking commands for Linux, macOS and Windows side by side: IP addresses, ping and traceroute, ports, DNS, routes, ARP, curl, packet capture and SSH tunnels.133 commands
$ show ip int brief
Cisco IOSCisco IOS commands for switches and routers: setup, interfaces, VLANs and trunks, spanning tree, routing, OSPF, ACLs, NAT, DHCP, SSH, AAA and troubleshooting.249 commands
$ show vpc brief
Cisco NX-OSCisco NX-OS commands for Nexus switches: features, interfaces, VLANs, port channels and vPC, VRFs, routing, OSPF, BGP, checkpoints and rollback, ACLs and troubleshooting.188 commands
$ show vsx status
HPE Aruba AOS-CXHPE Aruba Networking AOS-CX commands for CX switches: setup and management, interfaces, VLANs and trunks, LAGs, VSX, spanning tree, VRFs, OSPF, BGP, ACLs, AAA, 802.1X and MAC authentication, checkpoints, troubleshooting and upgrades.173 commands
$ show interfaces terse
Juniper JunosJuniper Junos OS commands for EX switches, SRX firewalls and MX routers: the CLI and commit model, filtering output, setup, interfaces, VLANs, LAGs, spanning tree, routing, OSPF, BGP, firewall filters, SRX zones, policies and NAT, logging and troubleshooting.206 commands
Security
$ fw ctl zdebug + drop
Check PointCheck Point Gaia and Quantum Security Gateway commands: Clish and Expert mode, Gaia setup, interfaces and bonds, status and health, policy, connections and SAM blocks, fw monitor and zdebug, ClusterXL, site-to-site VPN, mgmt_cli, CPUSE upgrades, backups and snapshots.143 commands
$ show session all filter source 10.0.0.5
Palo AltoPalo Alto Networks PAN-OS firewall commands: operational and configuration mode, commit, setup, interfaces, zones and routing, security and NAT rules, policy tests, sessions and counters, packet capture, logs, HA, IPsec VPN, User-ID and upgrades.132 commands
$ diagnose debug flow trace start 100
FortinetFortinet FortiGate FortiOS commands: get, show and config blocks, setup, interfaces, routing, OSPF and BGP, SD-WAN, policies and VIPs, security profiles, users and LDAP/RADIUS, DHCP, VDOMs, sessions, sniffer and debug flow, HA, IPsec VPN, logging and firmware.138 commands
$ packet-tracer input inside tcp 10.0.0.5 12345 8.8.8.8 443
Cisco ASA and FTDCisco Secure Firewall ASA and Firewall Threat Defense (FTD) commands: setup, interfaces and routing, objects, access lists and NAT, packet-tracer and captures, connections, logging, failover, VPN, upgrades, and the FTD CLI for registration, Snort tracing and the diagnostic CLI.110 commands
$ pfctl -ss | grep 192.168.1.25
pfSensepfSense shell commands: the console menu, pfctl rules, states and tables, EasyRule, recovery, logs, tcpdump, Kea DHCP leases, the Unbound resolver, CARP, limiters, restarting services, VPN status, config.xml backups, boot environments, packages and upgrades.100 commands
$ pluginctl -s unbound restart
OPNsenseOPNsense shell commands: the console menu, configctl and pluginctl services, pfctl rules, states and tables, logs, tcpdump and pflog, routing, Unbound and Dnsmasq, VPN status, CARP, password and config recovery, opnsense-update, opnsense-revert and plugins.84 commands
$ ipa hbactest --user=jsmith --host=web01.example.com --service=sshd
FreeIPAFreeIPA and Red Hat IdM commands: installing servers, replicas and clients, Kerberos tickets, users, groups, hosts and services, keytabs, HBAC access rules, sudo rules, password policy and OTP, certificates and certmonger, DNS, replication topology, Active Directory trusts and ID views, health checks, SSSD troubleshooting and backups.193 commands
Cybersecurity
$ nmap -sV 10.0.0.0/24
nmapnmap commands for scanning your own networks: host discovery, port and service scans, OS detection, timing, output formats and NSE scripts.157 commands
$ stats count by host
SplunkSplunk SPL searches and CLI commands: search basics, time ranges, stats and charts, eval, rex, lookups, tstats, security hunts for logins, Windows changes and network traffic, and forwarder setup.157 commands
DevOps
$ qm list
ProxmoxProxmox VE commands for VMs with qm, containers with pct, storage, ZFS, backups and restores, templates and cloud-init, clusters, HA and troubleshooting.161 commands
$ git switch -c fix
GitGit commands for setting up, committing, branching, merging, working with GitHub, undoing mistakes and searching history.116 commands
$ docker compose up -d
DockerDocker commands for running and managing containers, images, builds, volumes, networks, Compose stacks, clean-up, remote hosts and Swarm.159 commands
$ terraform plan
TerraformTerraform commands for setting up a project, formatting and validating, planning, applying and destroying, working with state, workspaces, tests, automation and debugging.129 commands
$ ansible all -m ping
AnsibleAnsible commands for setup and docs, inventory and host patterns, ad hoc commands, running playbooks, Vault, Galaxy collections and roles, linting and Molecule, Windows hosts, network devices and troubleshooting.147 commands
$ kubectl get pods -A
kubectlkubectl commands for Kubernetes: contexts and kubeconfig, viewing resources, creating and applying YAML, deployments and rollouts, logs, shells and port-forwarding, ConfigMaps and Secrets, services, nodes, RBAC, storage and troubleshooting.176 commands
Cloud
$ aws s3 ls
AWS CLIAWS CLI commands for signing in and profiles, output and queries, S3, EC2, VPCs and security groups, EBS, IAM, Lambda, CloudWatch, Systems Manager, secrets, containers, CloudFormation, Route 53, databases, costs and troubleshooting.298 commands
$ az vm list -o table
Azure CLIAzure CLI commands for signing in and subscriptions, output and queries, resource groups, VMs, disks, networking, storage, Entra ID and roles, Key Vault, App Service, containers and AKS, databases, monitoring, Bicep deployments, policy and cost, and troubleshooting.283 commands
$ gcloud config list
Google Cloud CLIGoogle Cloud CLI (gcloud) commands for signing in and configurations, output and filters, projects and IAM, Compute Engine, disks, VPC networking, Cloud Storage, service accounts, secrets, Cloud Run and Functions, GKE, Cloud SQL, logging, billing, BigQuery and troubleshooting.246 commands
Tools
$ 192.168.1.10/24
Subnet calculatorWork out the network, mask, host range and broadcast for any IPv4 or IPv6 address, split it into subnets, and plan subnets by host count.Tool
$ /24 = 254 hosts
Subnet cheat sheetEvery IPv4 prefix from /0 to /32 with its netmask, wildcard mask, addresses and usable hosts, including AWS, Azure and Google Cloud, plus common IPv6 prefix sizes.Tool
$ summary 10.0.0.0/22
Summarise networksPaste a list of IPv4 or IPv6 networks or address ranges to get the one network that covers them all, the shortest exact summary, and any that overlap.Tool
$ /26 = ? hosts
Subnetting practicePractise IPv4 subnetting with quick questions at three levels, marked as you go, with the working shown for every answer.Tool
$ openssl rand -hex 32
Password and key generatorMake passwords, passphrases and pre-shared keys in your browser. Nothing is sent anywhere or saved.Tool
$ 443/tcp https
Port referenceCommon TCP and UDP ports with the service and what each is for, searchable by number or name, with links to the matching commands.Tool
$ docker compose up -d
Docker run to ComposePaste a docker run command and get the matching Compose file, with a list of anything that couldn't be converted. Runs in your browser.Tool
$ chmod 755 deploy.sh
chmod calculatorTick read, write and run for the owner, group and everyone else to get the chmod number and letters, or type 755, u+x or -rwxr-xr-x to see what it means. With the command to copy.Tool
$ 0 9 * * 1-5
Cron expression builderBuild a cron schedule from plain choices, or paste one to see what it means in plain English and when it runs next. With the crontab line to copy.Tool
Linux: Files and folders
-
List files, including hidden ones, with sizesLinux, macOS
ls -lah -
Show the current folderLinux, macOS
pwd -
Go to your home folderLinux, macOS
cd ~ -
Create a folder and any missing parent foldersLinux, macOS
mkdir -p projects/site/assets -
Copy a folder and everything in itLinux, macOS
cp -r source/ backup/ -
Move or rename a fileLinux, macOS
mv old-name.txt new-name.txt -
Delete a fileLinux, macOS
rm file.txt -
Delete a folder and everything in itLinux, macOS
rm -rf folder/Warning: Deletes without asking and can't be undone. Check the path before you run it.
-
Create a shortcut (symbolic link) to a fileLinux, macOS
ln -s /path/to/target link-name -
Show a file's permissions, size and timestampsLinux, macOS
stat file.txt -
Find files by nameLinux, macOS
find . -name "*.log" -
Find files changed in the last dayLinux, macOS
find . -type f -mtime -1 -
Find files larger than 100 MBLinux, macOS
find / -type f -size +100M 2>/dev/null
Linux: Text
-
Show a file's contentsLinux, macOS
cat file.txt -
Scroll through a long fileLinux, macOS
less file.txt -
Show the first 20 lines of a fileLinux, macOS
head -n 20 file.txt -
Show the last 50 lines of a fileLinux, macOS
tail -n 50 file.txt -
Search for text in a folderLinux, macOS
grep -rn "error" . -
Search for text, ignoring caseLinux, macOS
grep -i "error" app.log -
Show lines that don't contain some textLinux, macOS
grep -v "debug" app.log -
Replace text in a fileLinux
sed -i 's/old/new/g' file.txtWarning: Changes the file straight away, with no backup.
-
Count lines in a fileLinux, macOS
wc -l file.txt -
Sort lines and remove duplicatesLinux, macOS
sort file.txt | uniq -
Count how often each line appearsLinux, macOS
sort file.txt | uniq -c | sort -rn -
Print the first column of each lineLinux, macOS
awk '{print $1}' access.log -
Compare two filesLinux, macOS
diff -u old.txt new.txt -
Edit a file in the terminalLinux
nano file.txt
Linux: Permissions
-
Make a script runnableLinux, macOS
chmod +x script.sh -
Let only the owner read and write a fileLinux, macOS
chmod 600 secrets.env -
Set standard folder permissionsLinux, macOS
chmod 755 folder/ -
Change a file's owner and groupLinux, macOS
sudo chown alice:alice file.txt -
Change the owner of a folder and everything in itLinux, macOS
sudo chown -R alice:alice folder/ -
Show your user ID and groupsLinux, macOS
id -
Open a shell as the root userLinux, macOS
sudo -i
Linux: Users and groups
-
Show which user you areLinux, macOS
whoami -
Show who is logged inLinux, macOS
who -
Create a user with a home folderDebian, Ubuntu
sudo adduser aliceRed Hat, Fedorasudo useradd -m alice && sudo passwd aliceAlpineadduser alice -
Change a user's passwordLinux
sudo passwd alice -
Give a user admin rightsDebian, Ubuntu
sudo usermod -aG sudo aliceRed Hat, Fedorasudo usermod -aG wheel aliceAlpineaddgroup alice wheel -
Add a user to a groupDebian, Ubuntu, Red Hat, Fedora
sudo usermod -aG docker aliceAlpineaddgroup alice docker -
Show a user's groupsLinux, macOS
groups alice -
Delete a user and their home folderDebian, Ubuntu
sudo deluser --remove-home aliceRed Hat, Fedorasudo userdel -r aliceAlpinedeluser --remove-home aliceWarning: Deletes the user's files and can't be undone.
Linux: Packages
-
Refresh the list of available packagesDebian, Ubuntu
sudo apt updateRed Hat, Fedorasudo dnf check-updateAlpineapk update -
Install a packageDebian, Ubuntu
sudo apt install nginxRed Hat, Fedorasudo dnf install nginxAlpineapk add nginx -
Update all installed packagesDebian, Ubuntu
sudo apt update && sudo apt upgradeRed Hat, Fedorasudo dnf upgradeAlpineapk update && apk upgrade -
Remove a packageDebian, Ubuntu
sudo apt remove nginxRed Hat, Fedorasudo dnf remove nginxAlpineapk del nginx -
Search for a packageDebian, Ubuntu
apt search nginxRed Hat, Fedoradnf search nginxAlpineapk search nginx -
List installed packagesDebian, Ubuntu
apt list --installedRed Hat, Fedoradnf list --installedAlpineapk info -
Find which package a file came fromDebian, Ubuntu
dpkg -S /usr/bin/curlRed Hat, Fedoradnf provides /usr/bin/curlAlpineapk info --who-owns /usr/bin/curl -
Remove packages that are no longer neededDebian, Ubuntu
sudo apt autoremoveRed Hat, Fedorasudo dnf autoremove
Linux: Services
-
Check a service's statusDebian, Ubuntu, Red Hat, Fedora
systemctl status nginxAlpinerc-service nginx status -
Start a serviceDebian, Ubuntu, Red Hat, Fedora
sudo systemctl start nginxAlpinerc-service nginx start -
Stop a serviceDebian, Ubuntu, Red Hat, Fedora
sudo systemctl stop nginxAlpinerc-service nginx stop -
Restart a serviceDebian, Ubuntu, Red Hat, Fedora
sudo systemctl restart nginxAlpinerc-service nginx restart -
Start a service now and at every bootDebian, Ubuntu, Red Hat, Fedora
sudo systemctl enable --now nginxAlpinerc-update add nginx default && rc-service nginx start -
Stop a service starting at bootDebian, Ubuntu, Red Hat, Fedora
sudo systemctl disable nginxAlpinerc-update del nginx default -
List running servicesDebian, Ubuntu, Red Hat, Fedora
systemctl list-units --type=service --state=runningAlpinerc-status -
Reload service files after editing themDebian, Ubuntu, Red Hat, Fedora
sudo systemctl daemon-reload
Linux: Processes
-
Show all running processesLinux, macOS
ps aux -
Find a process by nameLinux
pgrep -a nginx -
Watch CPU and memory use liveLinux, macOS
top -
Stop a process by IDLinux, macOS
kill 1234 -
Force a process to stopLinux, macOS
kill -9 1234Warning: The process can't clean up, so unsaved data may be lost.
-
Stop every process with a nameLinux, macOS
pkill nginx -
Keep a command running after you log outLinux, macOS
nohup ./script.sh & -
Show what is using a portLinux, macOS
sudo lsof -i :443
Linux: Logs
-
Follow a log file as it growsLinux, macOS
tail -f app.log -
Read a service's recent logsDebian, Ubuntu, Red Hat, Fedora
journalctl -u nginx -n 50 -
Follow a service's logs liveDebian, Ubuntu, Red Hat, Fedora
journalctl -u nginx -f -
Show logs since the last bootDebian, Ubuntu, Red Hat, Fedora
journalctl -b -
Show errors since the last bootDebian, Ubuntu, Red Hat, Fedora
journalctl -p err -b -
Read the system logAlpine
tail -n 100 /var/log/messages -
Show recent kernel messagesLinux
sudo dmesg | tail -n 50
Linux: System
-
Show which distro and version is installedLinux
cat /etc/os-release -
Show the kernel versionLinux, macOS
uname -r -
Show how long the system has been runningLinux, macOS
uptime -
Show memory useLinux
free -h -
Show CPU detailsLinux
lscpu -
Show the hostnameLinux, macOS
hostname -
Change the hostnameDebian, Ubuntu, Red Hat, Fedora
sudo hostnamectl set-hostname web01 -
Show the date, time and time zoneDebian, Ubuntu, Red Hat, Fedora
timedatectl -
Set the time zoneDebian, Ubuntu, Red Hat, Fedora
sudo timedatectl set-timezone Europe/Dublin -
Restart the systemLinux
sudo rebootWarning: Disconnects everyone and stops running services.
Linux: Storage
-
Check free disk spaceLinux, macOS
df -h -
See what is using disk spaceLinux, macOS
du -sh * | sort -h -
Find the biggest folders on the systemLinux, macOS
sudo du -h -d 1 / 2>/dev/null | sort -h -
List disks and partitionsLinux
lsblk -
Show disk IDs and filesystem typesLinux
sudo blkid -
Mount a partitionLinux
sudo mount /dev/sdb1 /mnt/data -
Unmount a partitionLinux
sudo umount /mnt/data -
List mounted filesystemsLinux
findmnt -
Format a partition as ext4Linux
sudo mkfs.ext4 /dev/sdb1Warning: Erases everything on the partition. Check the device name with lsblk first.
Linux: Network
-
Show this machine's IP addressesLinux
ip -br addr -
Show the routing tableLinux
ip route -
List listening portsLinux
sudo ss -tulpn -
Check whether a host is reachableLinux, macOS
ping -c 4 example.com -
Trace the route to a hostLinux, macOS
traceroute example.com -
Look up a domain's IP addressLinux, macOS
dig +short example.com -
Look up a domain's mail serversLinux, macOS
dig +short MX example.com -
Show the DNS resolver settingsLinux
cat /etc/resolv.conf -
See only the response headers from a siteLinux, macOS
curl -I https://example.com -
Download a fileLinux, macOS
curl -LO https://example.com/file.tar.gz -
Test whether a port is openLinux, macOS
nc -zv example.com 443 -
Show your public IP addressLinux, macOS
curl -s https://ifconfig.me -
Show network connectionsRed Hat, Fedora
nmcli connection show -
Restart networkingAlpine
rc-service networking restart
Linux: Firewall
-
Show the firewall rulesDebian, Ubuntu
sudo ufw status verboseRed Hat, Fedorasudo firewall-cmd --list-all -
Allow SSH through the firewallDebian, Ubuntu
sudo ufw allow OpenSSHRed Hat, Fedorasudo firewall-cmd --permanent --add-service=ssh && sudo firewall-cmd --reload -
Allow a portDebian, Ubuntu
sudo ufw allow 443/tcpRed Hat, Fedorasudo firewall-cmd --permanent --add-port=443/tcp && sudo firewall-cmd --reload -
Remove a port ruleDebian, Ubuntu
sudo ufw delete allow 443/tcpRed Hat, Fedorasudo firewall-cmd --permanent --remove-port=443/tcp && sudo firewall-cmd --reload -
Turn on the firewallDebian, Ubuntu
sudo ufw enableRed Hat, Fedorasudo systemctl enable --now firewalldWarning: Allow SSH first if you're connected remotely, or you'll lock yourself out.
Linux: SSH
-
Connect to a serverLinux, macOS
ssh user@host -
Connect on a custom portLinux, macOS
ssh -p 2222 user@host -
Run one command on a serverLinux, macOS
ssh user@host 'uptime' -
Create a new SSH keyLinux, macOS
ssh-keygen -t ed25519 -C "label" -
Copy your key to a serverLinux, macOS
ssh-copy-id user@host -
Copy a file to a serverLinux, macOS
scp file.txt user@host:/tmp/ -
Copy a file from a serverLinux, macOS
scp user@host:/var/log/app.log . -
Sync a folder to a serverLinux, macOS
rsync -avz dist/ user@host:/var/www/site/ -
Reach a server's port through SSHLinux, macOS
ssh -L 8080:localhost:80 user@host -
Check the SSH server config for errorsLinux
sudo sshd -t -
Restart the SSH serverDebian, Ubuntu
sudo systemctl restart sshRed Hat, Fedorasudo systemctl restart sshdAlpinerc-service sshd restart
Linux: Archives
-
Compress a folderLinux, macOS
tar -czf backup.tar.gz folder/ -
Extract a .tar.gz archiveLinux, macOS
tar -xzf backup.tar.gz -
Extract a .tar.gz archive into a folderLinux, macOS
tar -xzf backup.tar.gz -C /path/to/folder -
List what is inside a .tar.gz archiveLinux, macOS
tar -tzf backup.tar.gz -
Create a zip fileLinux, macOS
zip -r archive.zip folder/ -
Extract a zip fileLinux, macOS
unzip archive.zip
Linux: Scheduled tasks
-
Edit your scheduled tasksLinux, macOS
crontab -e -
List your scheduled tasksLinux, macOS
crontab -l -
Run a script every day at 2am (add this line with crontab -e)Linux, macOS
0 2 * * * /home/alice/backup.sh -
List scheduled systemd timersDebian, Ubuntu, Red Hat, Fedora
systemctl list-timers
Windows CMD: Getting around
-
Show the current folderWindows
cd -
Go to a folderWindows
cd C:\Projects -
Go up one folderWindows
cd .. -
Switch to another driveWindows
D: -
Change drive and folder in one goWindows
cd /d D:\Backups -
Go to your user folderWindows
cd %USERPROFILE% -
List all built-in commandsWindows
help -
Show help for a commandWindows
ipconfig /? -
Clear the screenWindows
cls -
Show the commands you've typed in this windowWindows
doskey /history -
Find where a program is installedWindows
where python -
Open File Explorer in the current folderWindows
start . -
Open a new Command Prompt windowWindows
start cmd -
Open a file with its default appWindows
start report.pdf
Windows CMD: Files and folders
-
List files and foldersWindows
dir -
List files, including hidden and system onesWindows
dir /a -
List files in this folder and all subfoldersWindows
dir /s -
Find files by name in all subfoldersWindows
dir /s /b *.log -
List files by date, newest firstWindows
dir /o-d -
List files by size, largest firstWindows
dir /o-s -
Show the folder tree with filesWindows
tree /f -
Create a folder and any missing parent foldersWindows
mkdir projects\site\assets -
Create an empty fileWindows
type nul > notes.txt -
Copy a fileWindows
copy report.docx D:\Backup\ -
Copy a folder and everything in itWindows
xcopy source backup /e /i /h -
Copy a folder with RobocopyWindows
robocopy C:\Source D:\Backup /e -
Copy a folder to a share, with retries and a logWindows
robocopy C:\Source \\server01\share /e /z /r:3 /w:5 /log:copy.log -
Make a folder an exact mirror of anotherWindows
robocopy C:\Source D:\Backup /mirWarning: Deletes files in the destination that aren't in the source.
-
Move a file to another folderWindows
move report.docx D:\Archive\ -
Rename a fileWindows
ren old-name.txt new-name.txt -
Change the extension of every .txt fileWindows
ren *.txt *.bak -
Delete a fileWindows
del file.txt -
Delete matching files in all subfolders without askingWindows
del /s /q *.tmpWarning: Deletes without asking and skips the Recycle Bin.
-
Delete an empty folderWindows
rmdir old-folder -
Delete a folder and everything in itWindows
rmdir /s /q old-folderWarning: Deletes without asking, skips the Recycle Bin and can't be undone.
-
Compare two filesWindows
fc file1.txt file2.txt -
Show a file's attributesWindows
attrib file.txt -
Hide a fileWindows
attrib +h file.txt -
Unhide a file and remove read-onlyWindows
attrib -h -r file.txt -
Show a file's SHA-256 hashWindows
certutil -hashfile setup.exe SHA256 -
Create a shortcut (symbolic link) to a file (as admin)Windows
mklink link.txt C:\Data\target.txt -
Create a link to a folder (junction)Windows
mklink /j Docs C:\Users\me\Documents -
Give a folder its own drive letterWindows
subst X: C:\Projects -
Remove a drive letter made with substWindows
subst X: /d
Windows CMD: Text and output
-
Show a file's contentsWindows
type notes.txt -
Show a long file one page at a timeWindows
more app.log -
Print textWindows
echo Hello -
Search for text in a fileWindows
findstr "error" app.log -
Search for text in all files in subfolders, ignoring caseWindows
findstr /s /i "error" *.log -
Show lines that don't contain some textWindows
findstr /v "DEBUG" app.log -
Count lines that contain some textWindows
find /c "error" app.log -
Sort the lines of a fileWindows
sort names.txt -
Sort a file and save the resultWindows
sort names.txt /o sorted.txt -
Save a command's output to a fileWindows
ipconfig /all > network.txt -
Add a command's output to the end of a fileWindows
echo Backup done >> log.txt -
Save output and errors to the same fileWindows
dir C:\missing > out.txt 2>&1 -
Hide a command's outputWindows
ping 8.8.8.8 > nul -
Copy a command's output to the clipboardWindows
ipconfig | clip -
Run a second command only if the first worksWindows
mkdir build && cd build -
Run a second command only if the first failsWindows
ping -n 1 server01 || echo Server is down
Windows CMD: Variables and batch files
-
Show all environment variablesWindows
set -
Show one variableWindows
echo %PATH% -
Set a variable for this window onlyWindows
set APP_ENV=dev -
Set a variable permanently for your accountWindows
setx APP_ENV dev -
Set a variable permanently for everyone (as admin)Windows
setx APP_ENV prod /m -
Show today's date and the timeWindows
echo %date% %time% -
Ask the user to type somethingWindows
set /p NAME=Enter your name: -
Do some arithmeticWindows
set /a 5*4 -
Run a command for each fileWindows
for %f in (*.txt) do echo %f -
Run a command for each number in a rangeWindows
for /l %i in (1,1,5) do echo %i -
Run a command for each line in a fileWindows
for /f "tokens=*" %l in (servers.txt) do ping -n 1 %l -
Do something only if a file existsWindows
if exist config.ini echo Found -
Show the exit code of the last commandWindows
echo %errorlevel% -
Run another batch file and come backWindows
call setup.bat -
Wait 10 secondsWindows
timeout /t 10 -
Wait for a key pressWindows
pause -
Stop a batch file showing each commandWindows
@echo off -
Change the window titleWindows
title Build server -
Change the window coloursWindows
color 0a
Windows CMD: System information
-
Show detailed system informationWindows
systeminfo -
Show when the computer last startedWindows
systeminfo | find "System Boot Time" -
Show the Windows versionWindows
ver -
Show the computer nameWindows
hostname -
Show the current userWindows
whoami -
Show your groups and privilegesWindows
whoami /all -
Show today's dateWindows
date /t -
Show the current timeWindows
time /t -
List installed driversWindows
driverquery -
Show Windows licence and activation detailsWindows
slmgr /dli -
Show which Group Policies apply to youWindows
gpresult /r -
Apply Group Policy changes nowWindows
gpupdate /force -
Create a battery health reportWindows
powercfg /batteryreport -
Open System InformationWindows
msinfo32
Windows CMD: Processes
-
List running processesWindows
tasklist -
Find a process by nameWindows
tasklist /fi "imagename eq chrome.exe" -
Show the services running in each processWindows
tasklist /svc -
End a process by nameWindows
taskkill /im notepad.exe -
End a process by its IDWindows
taskkill /pid 1234 -
Force a process and its child processes to endWindows
taskkill /f /t /im chrome.exeWarning: The program can't clean up, so unsaved work may be lost.
-
Start a programWindows
start notepad -
Start a program and wait for it to finishWindows
start /wait setup.exe -
Run a program as another userWindows
runas /user:Administrator cmd -
Open Task ManagerWindows
taskmgr -
Open Resource MonitorWindows
resmon
Windows CMD: Services
-
List running servicesWindows
sc query -
List all services, including stopped onesWindows
sc query state= all -
Show a service's statusWindows
sc query spooler -
Show a service's settingsWindows
sc qc spooler -
Start a service (as admin)Windows
net start spooler -
Stop a service (as admin)Windows
net stop spooler -
Restart a service (as admin)Windows
net stop spooler && net start spooler -
Make a service start automatically (as admin)Windows
sc config spooler start= auto -
Disable a service (as admin)Windows
sc config spooler start= disabled -
Open the Services consoleWindows
services.msc
Windows CMD: Users and groups
-
List local usersWindows
net user -
Show a user's detailsWindows
net user alice -
Show a domain user's detailsWindows
net user alice /domain -
Create a local user (asks for the password) (as admin)Windows
net user alice * /add -
Change a user's password (as admin)Windows
net user alice * -
Disable a user (as admin)Windows
net user alice /active:no -
Enable a user (as admin)Windows
net user alice /active:yes -
Delete a local user (as admin)Windows
net user alice /deleteWarning: Deletes the account and can't be undone.
-
List local groupsWindows
net localgroup -
List the members of the Administrators groupWindows
net localgroup Administrators -
Add a user to the Administrators group (as admin)Windows
net localgroup Administrators alice /add -
Remove a user from the Administrators group (as admin)Windows
net localgroup Administrators alice /delete -
Show password and lockout settingsWindows
net accounts -
Show who is signed inWindows
query user -
Lock the computerWindows
rundll32.exe user32.dll,LockWorkStation
Windows CMD: Network
-
Show your IP addressWindows
ipconfig -
Show full network details, including DNS servers and MAC addressesWindows
ipconfig /all -
Release your IP addressWindows
ipconfig /release -
Get a new IP addressWindows
ipconfig /renew -
Clear the DNS cacheWindows
ipconfig /flushdns -
Show the DNS cacheWindows
ipconfig /displaydns -
Show MAC addressesWindows
getmac /v -
Check you can reach a hostWindows
ping 8.8.8.8 -
Ping a host until you press Ctrl+CWindows
ping -t 8.8.8.8 -
Ping a host 10 timesWindows
ping -n 10 8.8.8.8 -
Trace the route to a hostWindows
tracert google.com -
Trace the route without looking up namesWindows
tracert -d google.com -
Find where packets are being lostWindows
pathping google.com -
Look up a domain's IP addressWindows
nslookup example.com -
Look up a domain using a specific DNS serverWindows
nslookup example.com 1.1.1.1 -
Look up a domain's mail (MX) recordsWindows
nslookup -type=mx example.com -
Look up the name for an IP addressWindows
nslookup 8.8.8.8 -
List connections and listening ports with process IDsWindows
netstat -ano -
List listening portsWindows
netstat -ano | findstr LISTENING -
Find what's using a portWindows
netstat -ano | findstr :8080 -
Show the program behind each connection (as admin)Windows
netstat -b -
Show network traffic totalsWindows
netstat -e -
Show the routing tableWindows
route print -
Add a route (as admin)Windows
route add 10.0.0.0 mask 255.0.0.0 192.168.1.1 -
Show the ARP tableWindows
arp -a -
Test whether a TCP port is openWindows
curl -v telnet://server01:443 -
Show your public IP addressWindows
curl ifconfig.me -
Download a fileWindows
curl -o file.zip https://example.com/file.zip -
Connect to a server over SSHWindows
-
Copy a file to a server over SSHWindows
scp file.txt [email protected]:/home/user/ -
Connect to a computer with Remote DesktopWindows
mstsc /v:server01
Windows CMD: Network adapters and Wi-Fi
-
List network adaptersWindows
netsh interface show interface -
Show each adapter's IP settingsWindows
netsh interface ipv4 show config -
Set a static IP address (as admin)Windows
netsh interface ipv4 set address name="Ethernet" static 192.168.1.50 255.255.255.0 192.168.1.1 -
Switch an adapter back to DHCP (as admin)Windows
netsh interface ipv4 set address name="Ethernet" source=dhcp -
Set an adapter's DNS server (as admin)Windows
netsh interface ipv4 set dnsservers name="Ethernet" static 1.1.1.1 primary -
Disable a network adapter (as admin)Windows
netsh interface set interface "Ethernet" disable -
Enable a network adapter (as admin)Windows
netsh interface set interface "Ethernet" enable -
Show your current Wi-Fi connection and signalWindows
netsh wlan show interfaces -
List Wi-Fi networks in rangeWindows
netsh wlan show networks mode=bssid -
List saved Wi-Fi networksWindows
netsh wlan show profiles -
Show a saved Wi-Fi network's password (as admin)Windows
netsh wlan show profile name="HomeWiFi" key=clear -
Show proxy settingsWindows
netsh winhttp show proxy -
Reset TCP/IP settings (as admin)Windows
netsh int ip resetWarning: Resets your network settings. Restart afterwards.
-
Reset Winsock (as admin)Windows
netsh winsock resetWarning: Resets network settings, which can affect VPN and security software. Restart afterwards.
Windows CMD: Firewall
-
Show the firewall status for each profileWindows
netsh advfirewall show allprofiles -
Turn the firewall on (as admin)Windows
netsh advfirewall set allprofiles state on -
Turn the firewall off (as admin)Windows
netsh advfirewall set allprofiles state offWarning: Leaves the computer unprotected. Turn it back on when you're done.
-
Allow incoming traffic on a port (as admin)Windows
netsh advfirewall firewall add rule name="Allow 8080" dir=in action=allow protocol=TCP localport=8080 -
Allow incoming ping (as admin)Windows
netsh advfirewall firewall add rule name="Allow ping" protocol=icmpv4:8,any dir=in action=allow -
Block a program from the internet (as admin)Windows
netsh advfirewall firewall add rule name="Block app" dir=out action=block program="C:\Apps\app.exe" -
Show a firewall ruleWindows
netsh advfirewall firewall show rule name="Allow 8080" -
Delete a firewall rule (as admin)Windows
netsh advfirewall firewall delete rule name="Allow 8080" -
Reset the firewall to its defaults (as admin)Windows
netsh advfirewall resetWarning: Removes every rule you've added.
Windows CMD: Disks and storage
-
Show free space on a driveWindows
fsutil volume diskfree C: -
Check a drive for errors without fixing themWindows
chkdsk C: -
Check a drive and fix errors (as admin)Windows
chkdsk C: /f -
Check a drive, fix errors and recover bad sectors (as admin)Windows
chkdsk C: /r -
Format a drive (as admin)Windows
format E: /fs:NTFS /q /v:BackupWarning: Erases everything on the drive.
-
Change a drive's nameWindows
label E: Backup -
List volumes and where they're mountedWindows
mountvol -
Check whether a drive needs optimising (as admin)Windows
defrag C: /a -
Optimise a drive (as admin)Windows
defrag C: /o -
Show BitLocker status for each drive (as admin)Windows
manage-bde -status -
Open Disk CleanupWindows
cleanmgr -
Open Disk ManagementWindows
diskmgmt.msc
Windows CMD: DiskPart
-
Open DiskPart (as admin)Windows
diskpart -
In DiskPart, list disksWindows
list disk -
In DiskPart, choose a disk to work onWindows
select disk 1 -
In DiskPart, list the chosen disk's partitionsWindows
list partition -
In DiskPart, list volumesWindows
list volume -
In DiskPart, wipe the chosen diskWindows
cleanWarning: Erases every partition on the chosen disk. Check the disk number with list disk first.
-
In DiskPart, create a partition using the whole diskWindows
create partition primary -
In DiskPart, quick-format the new partitionWindows
format fs=ntfs quick label=Backup -
In DiskPart, give the partition a drive letterWindows
assign letter=E -
In DiskPart, close DiskPartWindows
exit
Windows CMD: Permissions
-
Show a folder's permissionsWindows
icacls C:\Projects -
Give a user modify access to a folder and everything in itWindows
icacls C:\Projects /grant alice:(OI)(CI)M -
Remove a user's permissions from a folderWindows
icacls C:\Projects /remove alice -
Back up a folder's permissionsWindows
icacls C:\Projects /save perms.txt /t -
Restore permissions from a backupWindows
icacls C:\ /restore perms.txt -
Reset permissions to the inherited defaultsWindows
icacls C:\Projects /reset /tWarning: Removes every permission set directly on the folder and its contents.
-
Take ownership of a folder and everything in it (as admin)Windows
takeown /f C:\Projects /r /d y
Windows CMD: Registry
-
Show the programs that start when you sign inWindows
reg query "HKCU\Software\Microsoft\Windows\CurrentVersion\Run" -
Add or change a registry valueWindows
reg add "HKCU\Software\MyApp" /v Mode /t REG_SZ /d dev -
Delete a registry valueWindows
reg delete "HKCU\Software\MyApp" /v Mode /fWarning: Deletes without asking. Export the key first if you might need it back.
-
Back up a registry key to a fileWindows
reg export "HKCU\Software\MyApp" myapp.reg -
Restore a registry key from a fileWindows
reg import myapp.reg -
Open Registry EditorWindows
regedit
Windows CMD: Apps and Windows features
-
List installed appsWindows
winget list -
Search for an app to installWindows
winget search vscode -
Install an appWindows
winget install Microsoft.VisualStudioCode -
See which apps have updatesWindows
winget upgrade -
Update all appsWindows
winget upgrade --all -
Uninstall an appWindows
winget uninstall Microsoft.VisualStudioCode -
List optional Windows features (as admin)Windows
dism /online /get-features /format:table -
Turn on a Windows feature (as admin)Windows
dism /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all -
Install WSL and Ubuntu (as admin)Windows
wsl --install -
List WSL distros and their versionsWindows
wsl -l -v -
Open SettingsWindows
start ms-settings: -
Open Control PanelWindows
control
Windows CMD: Repair and troubleshooting
-
Scan and repair Windows system files (as admin)Windows
sfc /scannow -
Check whether the Windows image is marked as damaged (as admin)Windows
DISM /Online /Cleanup-Image /CheckHealth -
Scan the Windows image for damage (as admin)Windows
DISM /Online /Cleanup-Image /ScanHealth -
Repair the Windows image (as admin)Windows
DISM /Online /Cleanup-Image /RestoreHealth -
Clean up old Windows update files (as admin)Windows
DISM /Online /Cleanup-Image /StartComponentCleanup -
Show the 20 most recent system errorsWindows
wevtutil qe System /c:20 /rd:true /f:text /q:"*[System[(Level=2)]]" -
Clear an event log (as admin)Windows
wevtutil cl ApplicationWarning: Deletes the log's entries and can't be undone.
-
Open Event ViewerWindows
eventvwr -
Open Device ManagerWindows
devmgmt.msc -
Open Reliability MonitorWindows
perfmon /rel -
Test your computer's memory on the next restartWindows
mdsched -
Show the boot configuration (as admin)Windows
bcdedit -
Show what's stopping the computer from sleeping (as admin)Windows
powercfg /requests -
Show what last woke the computerWindows
powercfg /lastwake -
List devices that can wake the computerWindows
powercfg /devicequery wake_armed
Windows CMD: Shut down and restart
-
Shut down nowWindows
shutdown /s /t 0 -
Restart nowWindows
shutdown /r /t 0 -
Shut down in one hourWindows
shutdown /s /t 3600 -
Cancel a scheduled shutdownWindows
shutdown /a -
Sign outWindows
shutdown /l -
HibernateWindows
shutdown /h -
Restart into advanced startup optionsWindows
shutdown /r /o /t 0 -
Restart into the BIOS or UEFI settings (as admin)Windows
shutdown /r /fw /t 0 -
Restart another computerWindows
shutdown /r /m \\server01 /t 0 -
List power plansWindows
powercfg /list -
Turn off hibernation (as admin)Windows
powercfg /h off
Windows CMD: Scheduled tasks
-
List scheduled tasksWindows
schtasks /query -
Show a scheduled task's detailsWindows
schtasks /query /tn "Backup" /v /fo list -
Run a script every day at 2amWindows
schtasks /create /tn "Backup" /tr "C:\Scripts\backup.bat" /sc daily /st 02:00 -
Run a script when you sign inWindows
schtasks /create /tn "Startup script" /tr "C:\Scripts\start.bat" /sc onlogon -
Run a scheduled task nowWindows
schtasks /run /tn "Backup" -
Disable a scheduled taskWindows
schtasks /change /tn "Backup" /disable -
Delete a scheduled taskWindows
schtasks /delete /tn "Backup" /f -
Open Task SchedulerWindows
taskschd.msc
PowerShell: Getting started and help
-
Show the PowerShell versionLinux, macOS, Windows
$PSVersionTable.PSVersion -
Install PowerShell 7Windows
winget install Microsoft.PowerShell -
Start PowerShell 7 from another shellLinux, macOS, Windows
pwsh -
Get help for a commandLinux, macOS, Windows
Get-Help Get-Process -Detailed -
Show examples for a commandLinux, macOS, Windows
Get-Help Get-Process -Examples -
Open a command's help page in your browserLinux, macOS, Windows
Get-Help Get-Process -Online -
Download the latest help files (PowerShell 7)Linux, macOS, Windows
Update-Help -Scope CurrentUser -
Find commands by nameLinux, macOS, Windows
Get-Command *service* -
Find commands that work with somethingLinux, macOS, Windows
Get-Command -Noun Process -
Show the properties and methods a command's output hasLinux, macOS, Windows
Get-Process | Get-Member -
Find out what an alias stands forLinux, macOS, Windows
Get-Alias ls -
Show the commands you've typed in this sessionLinux, macOS, Windows
Get-History -
Search commands from earlier sessionsLinux, macOS, Windows
Get-Content (Get-PSReadLineOption).HistorySavePath | Select-String "docker" -
Clear the screenLinux, macOS, Windows
Clear-Host -
Create your profile script if it doesn't existLinux, macOS, Windows
if (!(Test-Path $PROFILE)) { New-Item -Path $PROFILE -ItemType File -Force } -
Edit your profile scriptWindows
notepad $PROFILE -
Reload your profile scriptLinux, macOS, Windows
. $PROFILE
PowerShell: Files and folders
-
Show the current folderLinux, macOS, Windows
Get-Location -
Go to a folderLinux, macOS, Windows
Set-Location ~/Projects -
List files and foldersLinux, macOS, Windows
Get-ChildItem -
List files, including hidden onesLinux, macOS, Windows
Get-ChildItem -Force -
List only foldersLinux, macOS, Windows
Get-ChildItem -Directory -
Find files by name in all subfoldersLinux, macOS, Windows
Get-ChildItem -Recurse -Filter *.log -
List files by size, largest firstLinux, macOS, Windows
Get-ChildItem -File | Sort-Object Length -Descending -
Find the 10 largest files in all subfoldersLinux, macOS, Windows
Get-ChildItem -Recurse -File | Sort-Object Length -Descending | Select-Object -First 10 FullName, Length -
Find files changed in the last 7 daysLinux, macOS, Windows
Get-ChildItem -Recurse -File | Where-Object LastWriteTime -gt (Get-Date).AddDays(-7) -
Show a folder's total size in GBLinux, macOS, Windows
(Get-ChildItem -Recurse -File | Measure-Object Length -Sum).Sum / 1GB -
Create a folder and any missing parent foldersLinux, macOS, Windows
New-Item -ItemType Directory -Path projects/site/assets -Force -
Create an empty fileLinux, macOS, Windows
New-Item -ItemType File -Path notes.txt -
Check whether a file or folder existsLinux, macOS, Windows
Test-Path notes.txt -
Show all of a file's propertiesLinux, macOS, Windows
Get-Item notes.txt | Format-List * -
Copy a fileLinux, macOS, Windows
Copy-Item report.docx backup/ -
Copy a folder and everything in itLinux, macOS, Windows
Copy-Item source -Destination backup -Recurse -
Move a file to another folderLinux, macOS, Windows
Move-Item report.docx archive/ -
Rename a fileLinux, macOS, Windows
Rename-Item old-name.txt new-name.txt -
Change the extension of every .txt fileLinux, macOS, Windows
Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace '\.txt$', '.bak' } -
Delete a fileLinux, macOS, Windows
Remove-Item file.txt -
Preview what a delete would removeLinux, macOS, Windows
Remove-Item *.tmp -WhatIf -
Delete matching files in all subfoldersLinux, macOS, Windows
Get-ChildItem -Recurse -Filter *.tmp | Remove-ItemWarning: Deletes without asking and skips the Recycle Bin.
-
Delete a folder and everything in itLinux, macOS, Windows
Remove-Item old-folder -Recurse -ForceWarning: Deletes without asking, skips the Recycle Bin and can't be undone.
-
Show a file's SHA-256 hashLinux, macOS, Windows
Get-FileHash setup.exe -
Compare the files in two foldersLinux, macOS, Windows
Compare-Object (Get-ChildItem folder1) (Get-ChildItem folder2) -Property Name -
Zip a folderLinux, macOS, Windows
Compress-Archive -Path site/* -DestinationPath site.zip -
Unzip a fileLinux, macOS, Windows
Expand-Archive site.zip -DestinationPath site -
Create a symbolic linkLinux, macOS, Windows
New-Item -ItemType SymbolicLink -Path link.txt -Target target.txt -
Open the current folder in File ExplorerWindows
Invoke-Item .
PowerShell: Reading and searching text
-
Show a file's contentsLinux, macOS, Windows
Get-Content notes.txt -
Show the first 10 lines of a fileLinux, macOS, Windows
Get-Content app.log -TotalCount 10 -
Show the last 20 lines of a fileLinux, macOS, Windows
Get-Content app.log -Tail 20 -
Follow a log file as it growsLinux, macOS, Windows
Get-Content app.log -Wait -Tail 20 -
Search for text in a fileLinux, macOS, Windows
Select-String -Path app.log -Pattern "error" -
Search for text in all files in subfoldersLinux, macOS, Windows
Get-ChildItem -Recurse -Filter *.log | Select-String "error" -
Search for text, matching caseLinux, macOS, Windows
Select-String -Path app.log -Pattern "Error" -CaseSensitive -
Show lines that don't contain some textLinux, macOS, Windows
Select-String -Path app.log -Pattern "DEBUG" -NotMatch -
Show 2 lines either side of each matchLinux, macOS, Windows
Select-String -Path app.log -Pattern "error" -Context 2,2 -
Count the matches in a fileLinux, macOS, Windows
(Select-String -Path app.log -Pattern "error").Count -
Count the lines, words and characters in a fileLinux, macOS, Windows
Get-Content notes.txt | Measure-Object -Line -Word -Character -
Replace a file's contents with some textLinux, macOS, Windows
"Hello" | Set-Content notes.txt -
Add a line to the end of a fileLinux, macOS, Windows
Add-Content log.txt "Backup done" -
Save a command's output to a fileLinux, macOS, Windows
Get-Process | Out-File processes.txt -
Replace text in a fileLinux, macOS, Windows
(Get-Content config.txt) -replace 'old', 'new' | Set-Content config.txtWarning: Changes the file straight away, with no backup.
-
Show a file's unique lines, sortedLinux, macOS, Windows
Get-Content names.txt | Sort-Object -Unique -
Compare two filesLinux, macOS, Windows
Compare-Object (Get-Content file1.txt) (Get-Content file2.txt) -
Copy a command's output to the clipboardWindows
Get-Process | Set-Clipboard -
Show what's on the clipboardWindows
Get-Clipboard
PowerShell: Pipeline, filtering and formatting
-
Keep only items that match a conditionLinux, macOS, Windows
Get-Process | Where-Object CPU -gt 100 -
Keep only items that match several conditionsLinux, macOS, Windows
Get-Process | Where-Object { $_.CPU -gt 10 -and $_.WorkingSet64 -gt 200MB } -
Choose which properties to showLinux, macOS, Windows
Get-Process | Select-Object Name, Id, CPU -
Show just the values of one propertyLinux, macOS, Windows
(Get-Process).Name -
Show the unique values of a propertyLinux, macOS, Windows
Get-Process | Select-Object -ExpandProperty Name -Unique -
Sort and show the top 5Linux, macOS, Windows
Get-Process | Sort-Object CPU -Descending | Select-Object -First 5 -
Group items and count each groupLinux, macOS, Windows
Get-Process | Group-Object Name | Sort-Object Count -Descending -
Count itemsLinux, macOS, Windows
(Get-Process).Count -
Show the total, average and largest of a propertyLinux, macOS, Windows
Get-ChildItem -File | Measure-Object Length -Sum -Average -Maximum -
Run something for each itemLinux, macOS, Windows
Get-ChildItem *.log | ForEach-Object { $_.Name.ToUpper() } -
Run something for each item in parallel (PowerShell 7)Linux, macOS, Windows
1..5 | ForEach-Object -Parallel { Start-Sleep 1; $_ } -ThrottleLimit 5 -
Add a calculated columnLinux, macOS, Windows
Get-ChildItem -File | Select-Object Name, @{Name='SizeMB'; Expression={[math]::Round($_.Length / 1MB, 2)}} -
Show output as a tableLinux, macOS, Windows
Get-Process | Format-Table Name, Id, CPU -AutoSize -
Show every property as a listLinux, macOS, Windows
Get-Process -Id $PID | Format-List * -
Show output and save it to a file at the same timeLinux, macOS, Windows
Get-Process | Tee-Object -FilePath processes.txt -
Show output in a sortable, filterable windowWindows
Get-Process | Out-GridView
PowerShell: Variables, objects and scripting
-
Set a variableLinux, macOS, Windows
$name = "Gerard" -
List all environment variablesLinux, macOS, Windows
Get-ChildItem Env: -
Show an environment variableLinux, macOS, Windows
$env:PATH -
Set an environment variable for this sessionLinux, macOS, Windows
$env:APP_ENV = "dev" -
Set an environment variable permanently for your accountWindows
[Environment]::SetEnvironmentVariable("APP_ENV", "dev", "User") -
Ask the user to type somethingLinux, macOS, Windows
$name = Read-Host "Enter your name" -
Ask for a password without showing itLinux, macOS, Windows
$secret = Read-Host "Password" -AsSecureString -
Ask for a username and passwordLinux, macOS, Windows
$cred = Get-Credential -
Create a list (array)Linux, macOS, Windows
$servers = @("web01", "web02", "db01") -
Create a hashtableLinux, macOS, Windows
$config = @{ Name = "web"; Port = 8080 } -
Create a custom objectLinux, macOS, Windows
[PSCustomObject]@{ Name = "web01"; Status = "Up" } -
Loop through a listLinux, macOS, Windows
foreach ($s in $servers) { Test-Connection $s -Count 1 } -
Loop through a range of numbersLinux, macOS, Windows
1..5 | ForEach-Object { "Server $_" } -
Do something only if a file existsLinux, macOS, Windows
if (Test-Path config.json) { "Found" } else { "Missing" } -
Catch an errorLinux, macOS, Windows
try { Get-Item missing.txt -ErrorAction Stop } catch { "Error: $_" } -
Check whether the last command workedLinux, macOS, Windows
$? -
Show the exit code of the last programLinux, macOS, Windows
$LASTEXITCODE -
Show the date and timeLinux, macOS, Windows
Get-Date -
Show the date in a custom formatLinux, macOS, Windows
Get-Date -Format "yyyy-MM-dd HH:mm" -
Get the date 30 days agoLinux, macOS, Windows
(Get-Date).AddDays(-30) -
Time how long a command takesLinux, macOS, Windows
Measure-Command { Get-ChildItem -Recurse } -
Wait 10 secondsLinux, macOS, Windows
Start-Sleep -Seconds 10 -
Print a message in colourLinux, macOS, Windows
Write-Host "Done" -ForegroundColor Green -
Run a script in the current folderLinux, macOS, Windows
./backup.ps1 -
Run a script with parametersLinux, macOS, Windows
./backup.ps1 -Path ~/Documents -
Record everything in this session to a fileLinux, macOS, Windows
Start-Transcript -Path session.log -
Stop recording the sessionLinux, macOS, Windows
Stop-Transcript -
Generate a GUIDLinux, macOS, Windows
New-Guid -
Generate a random 16-character passwordLinux, macOS, Windows
-join ((48..57) + (65..90) + (97..122) | Get-Random -Count 16 | ForEach-Object { [char]$_ })
PowerShell: CSV, JSON and other formats
-
Read a CSV fileLinux, macOS, Windows
Import-Csv users.csv -
Save output as a CSV fileLinux, macOS, Windows
Get-Process | Select-Object Name, Id, CPU | Export-Csv processes.csv -NoTypeInformation -
Read a JSON fileLinux, macOS, Windows
Get-Content config.json -Raw | ConvertFrom-Json -
Convert output to JSONLinux, macOS, Windows
Get-Process | Select-Object Name, Id | ConvertTo-Json -
Save an object as a JSON fileLinux, macOS, Windows
$config | ConvertTo-Json -Depth 5 | Set-Content config.json -
Read an XML fileLinux, macOS, Windows
[xml]$xml = Get-Content config.xml -
Save output as an HTML reportLinux, macOS, Windows
Get-Process | Select-Object Name, CPU | ConvertTo-Html | Out-File report.html -
Save objects to a file exactly as they areLinux, macOS, Windows
Get-Process | Export-Clixml processes.xml -
Load objects saved with Export-ClixmlLinux, macOS, Windows
Import-Clixml processes.xml
PowerShell: Processes and jobs
-
List running processesLinux, macOS, Windows
Get-Process -
Find a process by nameLinux, macOS, Windows
Get-Process -Name chrome -
Show the 10 processes using the most memoryLinux, macOS, Windows
Get-Process | Sort-Object WorkingSet64 -Descending | Select-Object -First 10 Name, Id, @{Name='MemoryMB'; Expression={[math]::Round($_.WorkingSet64 / 1MB)}} -
Show the 10 processes using the most CPULinux, macOS, Windows
Get-Process | Sort-Object CPU -Descending | Select-Object -First 10 -
Show where a running program is installedLinux, macOS, Windows
Get-Process -Name code | Select-Object Name, Path -
Stop a process by nameLinux, macOS, Windows
Stop-Process -Name notepad -
Stop a process by its IDLinux, macOS, Windows
Stop-Process -Id 1234 -
Force a process to stopLinux, macOS, Windows
Stop-Process -Name chrome -ForceWarning: The program can't clean up, so unsaved work may be lost.
-
Wait for a process to finishLinux, macOS, Windows
Wait-Process -Name setup -
Start a programWindows
Start-Process notepad -
Start a program and wait for it to finishWindows
Start-Process setup.exe -Wait -
Open PowerShell as administratorWindows
Start-Process pwsh -Verb RunAs -
Run a command in the backgroundLinux, macOS, Windows
Start-Job { Get-ChildItem -Recurse ~ } -
Run a command in the background with & (PowerShell 7)Linux, macOS, Windows
Get-ChildItem -Recurse ~ & -
List background jobsLinux, macOS, Windows
Get-Job -
Wait for a background job to finishLinux, macOS, Windows
Wait-Job -Id 1 -
Get a background job's outputLinux, macOS, Windows
Receive-Job -Id 1 -Keep -
Remove finished background jobsLinux, macOS, Windows
Get-Job -State Completed | Remove-Job
PowerShell: Services
-
List servicesWindows
Get-Service -
List running servicesWindows
Get-Service | Where-Object Status -eq Running -
Show a service's statusWindows
Get-Service -Name spooler -
Find services by display nameWindows
Get-Service -DisplayName *update* -
Show the services that depend on a serviceWindows
Get-Service spooler -DependentServices -
Show a service's account and program pathWindows
Get-CimInstance Win32_Service -Filter "Name='spooler'" | Select-Object Name, StartName, PathName -
Start a service (as admin)Windows
Start-Service spooler -
Stop a service (as admin)Windows
Stop-Service spooler -
Restart a service (as admin)Windows
Restart-Service spooler -
Make a service start automatically (as admin)Windows
Set-Service spooler -StartupType Automatic -
Disable a service (as admin)Windows
Set-Service spooler -StartupType Disabled
PowerShell: System information
-
Show the computer nameLinux, macOS, Windows
[System.Net.Dns]::GetHostName() -
Show the current userLinux, macOS, Windows
[Environment]::UserName -
Show how long the computer has been running (PowerShell 7)Linux, macOS, Windows
Get-Uptime -
Show the time zoneLinux, macOS, Windows
Get-TimeZone -
Change the time zone (as admin)Windows
Set-TimeZone -Id "GMT Standard Time" -
Show a full system summaryWindows
Get-ComputerInfo -
Show the Windows version and buildWindows
Get-CimInstance Win32_OperatingSystem | Select-Object Caption, Version, BuildNumber -
Show when the computer last startedWindows
(Get-CimInstance Win32_OperatingSystem).LastBootUpTime -
Show the serial numberWindows
(Get-CimInstance Win32_BIOS).SerialNumber -
Show the CPU and core countWindows
Get-CimInstance Win32_Processor | Select-Object Name, NumberOfCores, NumberOfLogicalProcessors -
Show the installed memory in GBWindows
(Get-CimInstance Win32_ComputerSystem).TotalPhysicalMemory / 1GB -
List installed updates, newest firstWindows
Get-HotFix | Sort-Object InstalledOn -Descending -
List installed programsWindows
Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion | Sort-Object DisplayName -
List drivers and their versionsWindows
Get-CimInstance Win32_PnPSignedDriver | Select-Object DeviceName, DriverVersion -
List devices that have a problemWindows
Get-PnpDevice -Status ERROR
PowerShell: Network
-
Check you can reach a hostLinux, macOS, Windows
Test-Connection 8.8.8.8 -Count 4 -
Test whether a TCP port is open (PowerShell 7)Linux, macOS, Windows
Test-Connection server01 -TcpPort 443 -
Show your public IP addressLinux, macOS, Windows
Invoke-RestMethod https://api.ipify.org -
Show your IP addressesWindows
Get-NetIPAddress -AddressFamily IPv4 -
Show each adapter's IP, gateway and DNS settingsWindows
Get-NetIPConfiguration -
List network adaptersWindows
Get-NetAdapter -
Test a port and show connection detailsWindows
Test-NetConnection server01 -Port 443 -
Trace the route to a hostWindows
Test-NetConnection google.com -TraceRoute -
Look up a domain's IP addressWindows
Resolve-DnsName example.com -
Look up a domain's mail (MX) recordsWindows
Resolve-DnsName example.com -Type MX -
Look up a domain using a specific DNS serverWindows
Resolve-DnsName example.com -Server 1.1.1.1 -
Show the DNS cacheWindows
Get-DnsClientCache -
Clear the DNS cache (as admin)Windows
Clear-DnsClientCache -
Show your DNS serversWindows
Get-DnsClientServerAddress -AddressFamily IPv4 -
Set an adapter's DNS servers (as admin)Windows
Set-DnsClientServerAddress -InterfaceAlias "Ethernet" -ServerAddresses 1.1.1.1, 8.8.8.8 -
Set a static IP address (as admin)Windows
New-NetIPAddress -InterfaceAlias "Ethernet" -IPAddress 192.168.1.50 -PrefixLength 24 -DefaultGateway 192.168.1.1 -
Switch an adapter to DHCP (as admin)Windows
Set-NetIPInterface -InterfaceAlias "Ethernet" -Dhcp Enabled -
List listening portsWindows
Get-NetTCPConnection -State Listen -
List open connectionsWindows
Get-NetTCPConnection -State Established -
Find which program is using a portWindows
Get-NetTCPConnection -LocalPort 8080 | Select-Object LocalPort, OwningProcess, @{Name='Process'; Expression={(Get-Process -Id $_.OwningProcess).Name}} -
Show the routing tableWindows
Get-NetRoute -
Show the ARP tableWindows
Get-NetNeighbor -
Restart a network adapter (as admin)Windows
Restart-NetAdapter -Name "Ethernet" -
Disable a network adapter (as admin)Windows
Disable-NetAdapter -Name "Wi-Fi" -Confirm:$false -
Enable a network adapter (as admin)Windows
Enable-NetAdapter -Name "Wi-Fi" -
Show whether each network is public or privateWindows
Get-NetConnectionProfile -
Set a network to private (as admin)Windows
Set-NetConnectionProfile -InterfaceAlias "Ethernet" -NetworkCategory Private
PowerShell: Web requests and APIs
-
Download a fileLinux, macOS, Windows
Invoke-WebRequest https://example.com/file.zip -OutFile file.zip -
Check a website's status codeLinux, macOS, Windows
(Invoke-WebRequest https://example.com).StatusCode -
Show a website's response headersLinux, macOS, Windows
(Invoke-WebRequest https://example.com -Method Head).Headers -
Call a REST APILinux, macOS, Windows
Invoke-RestMethod https://api.github.com/repos/PowerShell/PowerShell -
Send JSON to an APILinux, macOS, Windows
Invoke-RestMethod -Uri https://api.example.com/items -Method Post -Body (@{ name = "test" } | ConvertTo-Json) -ContentType "application/json" -
Call an API with a tokenLinux, macOS, Windows
Invoke-RestMethod https://api.example.com/me -Headers @{ Authorization = "Bearer $token" } -
Call a site with a self-signed certificate (PowerShell 7)Linux, macOS, Windows
Invoke-RestMethod https://192.168.1.50:8006/api2/json/version -SkipCertificateCheckWarning: Turns off certificate checks. Only use it on your own servers.
PowerShell: Local users and groups
-
List local usersWindows
Get-LocalUser -
Show a local user's detailsWindows
Get-LocalUser alice | Format-List * -
Create a local user (asks for the password) (as admin)Windows
New-LocalUser -Name alice -Password (Read-Host -AsSecureString "Password") -
Change a local user's password (as admin)Windows
Set-LocalUser -Name alice -Password (Read-Host -AsSecureString "Password") -
Disable a local user (as admin)Windows
Disable-LocalUser alice -
Enable a local user (as admin)Windows
Enable-LocalUser alice -
Delete a local user (as admin)Windows
Remove-LocalUser aliceWarning: Deletes the account and can't be undone.
-
List local groupsWindows
Get-LocalGroup -
List the members of the Administrators groupWindows
Get-LocalGroupMember Administrators -
Add a user to the Administrators group (as admin)Windows
Add-LocalGroupMember -Group Administrators -Member alice -
Remove a user from the Administrators group (as admin)Windows
Remove-LocalGroupMember -Group Administrators -Member alice
PowerShell: Active Directory
-
Install the Active Directory module on Windows 11 (as admin)Windows
Add-WindowsCapability -Online -Name Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0 -
Load the Active Directory moduleWindows
Import-Module ActiveDirectory -
Show a user's detailsWindows
Get-ADUser alice -Properties * -
Find users by nameWindows
Get-ADUser -Filter "Name -like '*smith*'" -
List locked-out usersWindows
Search-ADAccount -LockedOut -
Unlock a userWindows
Unlock-ADAccount alice -
List disabled usersWindows
Search-ADAccount -AccountDisabled -UsersOnly -
List users who haven't signed in for 90 daysWindows
Search-ADAccount -AccountInactive -TimeSpan 90.00:00:00 -UsersOnly -
List users whose password has expiredWindows
Search-ADAccount -PasswordExpired -
Reset a user's passwordWindows
Set-ADAccountPassword alice -Reset -NewPassword (Read-Host -AsSecureString "New password") -
Make a user change their password at next sign-inWindows
Set-ADUser alice -ChangePasswordAtLogon $true -
Create a userWindows
New-ADUser -Name "Alice Smith" -SamAccountName alice -UserPrincipalName [email protected] -AccountPassword (Read-Host -AsSecureString "Password") -Enabled $true -
Disable a userWindows
Disable-ADAccount alice -
Delete a userWindows
Remove-ADUser aliceWarning: Deletes the account and can't be undone unless the AD Recycle Bin is turned on.
-
List the groups a user is inWindows
Get-ADPrincipalGroupMembership alice | Select-Object Name -
List a group's membersWindows
Get-ADGroupMember "IT Staff" -
Add a user to a groupWindows
Add-ADGroupMember "IT Staff" -Members alice -
Remove a user from a groupWindows
Remove-ADGroupMember "IT Staff" -Members alice -Confirm:$false -
Show a computer's detailsWindows
Get-ADComputer server01 -Properties * -
List the computers in an OUWindows
Get-ADComputer -Filter * -SearchBase "OU=Servers,DC=corp,DC=example,DC=com" -
List domain controllersWindows
Get-ADDomainController -Filter * -
Show domain detailsWindows
Get-ADDomain
PowerShell: Remoting
-
Turn on PowerShell remoting (as admin)Windows
Enable-PSRemoting -Force -
Check remoting works on another computerWindows
Test-WSMan server01 -
Trust a computer that isn't in your domain (as admin)Windows
Set-Item WSMan:\localhost\Client\TrustedHosts -Value "192.168.1.50" -Concatenate -Force -
Open a session on another computerWindows
Enter-PSSession -ComputerName server01 -
Open a session as another userWindows
Enter-PSSession -ComputerName server01 -Credential (Get-Credential) -
Open a session over SSH (PowerShell 7)Linux, macOS, Windows
Enter-PSSession -HostName user@server01 -
Leave a remote sessionLinux, macOS, Windows
Exit-PSSession -
Run a command on another computerWindows
Invoke-Command -ComputerName server01 -ScriptBlock { Get-Service spooler } -
Run a command on several computersWindows
Invoke-Command -ComputerName web01, web02, db01 -ScriptBlock { (Get-CimInstance Win32_OperatingSystem).LastBootUpTime } -
Run a local script on another computerWindows
Invoke-Command -ComputerName server01 -FilePath ./check.ps1 -
Create a session you can reuseWindows
$s = New-PSSession -ComputerName server01 -
Copy a file to a remote sessionWindows
Copy-Item ./setup.msi -Destination C:\Temp\ -ToSession $s -
Copy a file from a remote sessionWindows
Copy-Item C:\Logs\app.log -Destination . -FromSession $s -
Close all remote sessionsLinux, macOS, Windows
Get-PSSession | Remove-PSSession
PowerShell: Execution policy and security
-
Show the execution policyWindows
Get-ExecutionPolicy -
Show the execution policy for each scopeWindows
Get-ExecutionPolicy -List -
Allow local scripts and signed downloaded ones for your accountWindows
Set-ExecutionPolicy RemoteSigned -Scope CurrentUser -
Allow all scripts in this window onlyWindows
Set-ExecutionPolicy Bypass -Scope ProcessWarning: Lets any script run in this window, including ones you didn't write.
-
Run one script without changing the policyWindows
pwsh -ExecutionPolicy Bypass -File ./script.ps1 -
Unblock a script you downloadedWindows
Unblock-File ./script.ps1 -
Check a script's digital signatureWindows
Get-AuthenticodeSignature ./script.ps1 -
Show Microsoft Defender statusWindows
Get-MpComputerStatus -
Run a Defender quick scanWindows
Start-MpScan -ScanType QuickScan -
Update Defender's virus definitionsWindows
Update-MpSignature -
Show threats Defender has foundWindows
Get-MpThreatDetection -
Show BitLocker status for each drive (as admin)Windows
Get-BitLockerVolume
PowerShell: Modules
-
List loaded modulesLinux, macOS, Windows
Get-Module -
List installed modulesLinux, macOS, Windows
Get-Module -ListAvailable -
Search the PowerShell Gallery for modulesLinux, macOS, Windows
Find-Module *azure* -
Install a module for your accountLinux, macOS, Windows
Install-Module Az -Scope CurrentUser -
Install a module with PSResourceGet (PowerShell 7)Linux, macOS, Windows
Install-PSResource Az -Scope CurrentUser -
Update a moduleLinux, macOS, Windows
Update-Module Az -
Load a moduleLinux, macOS, Windows
Import-Module Az.Accounts -
List the commands in a moduleLinux, macOS, Windows
Get-Command -Module Microsoft.PowerShell.Archive -
Uninstall a moduleLinux, macOS, Windows
Uninstall-Module Az
PowerShell: Event logs
-
List event logs that have entriesWindows
Get-WinEvent -ListLog * | Where-Object RecordCount -gt 0 -
Show the 20 latest System eventsWindows
Get-WinEvent -LogName System -MaxEvents 20 -
Show System errors from the last 24 hoursWindows
Get-WinEvent -FilterHashtable @{ LogName = 'System'; Level = 2; StartTime = (Get-Date).AddDays(-1) } -
Show recent failed sign-ins (as admin)Windows
Get-WinEvent -FilterHashtable @{ LogName = 'Security'; Id = 4625 } -MaxEvents 20 -
Show recent startups and shutdownsWindows
Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = 6005, 6006 } -MaxEvents 10 -
Show unexpected shutdowns and power lossesWindows
Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = 41 } -
Save events to a CSV fileWindows
Get-WinEvent -LogName Application -MaxEvents 500 | Export-Csv app-events.csv -NoTypeInformation -
Clear an event log (as admin)Windows
[System.Diagnostics.Eventing.Reader.EventLogSession]::GlobalSession.ClearLog("Application")Warning: Deletes the log's entries and can't be undone.
PowerShell: Registry
-
List the keys under a registry keyWindows
Get-ChildItem HKCU:\Software -
Show the programs that start when you sign inWindows
Get-ItemProperty "HKCU:\Software\Microsoft\Windows\CurrentVersion\Run" -
Show one registry valueWindows
Get-ItemPropertyValue "HKCU:\Control Panel\Desktop" -Name WallPaper -
Check whether a registry key existsWindows
Test-Path "HKCU:\Software\MyApp" -
Create a registry keyWindows
New-Item -Path "HKCU:\Software\MyApp" -
Set a registry valueWindows
Set-ItemProperty -Path "HKCU:\Software\MyApp" -Name Mode -Value dev -
Create a number (DWORD) registry valueWindows
New-ItemProperty -Path "HKCU:\Software\MyApp" -Name Port -Value 8080 -PropertyType DWord -
Delete a registry valueWindows
Remove-ItemProperty -Path "HKCU:\Software\MyApp" -Name ModeWarning: Deletes the value without a backup.
-
Delete a registry key and everything in itWindows
Remove-Item -Path "HKCU:\Software\MyApp" -RecurseWarning: Deletes the key and all its values without a backup.
PowerShell: Disks and storage
-
Show drives and their free spaceLinux, macOS, Windows
Get-PSDrive -PSProvider FileSystem -
List volumesWindows
Get-Volume -
List disksWindows
Get-Disk -
List partitionsWindows
Get-Partition -
Show each disk's type and healthWindows
Get-PhysicalDisk | Select-Object FriendlyName, MediaType, HealthStatus, Size -
Show disk temperature, wear and errors (as admin)Windows
Get-PhysicalDisk | Get-StorageReliabilityCounter | Select-Object DeviceId, Temperature, Wear, ReadErrorsTotal -
Set up a new disk with one NTFS partition (as admin)Windows
Initialize-Disk -Number 1 -PartitionStyle GPT; New-Partition -DiskNumber 1 -UseMaximumSize -AssignDriveLetter | Format-Volume -FileSystem NTFS -NewFileSystemLabel BackupWarning: Check the disk number with Get-Disk first.
-
Format a volume (as admin)Windows
Format-Volume -DriveLetter E -FileSystem NTFS -NewFileSystemLabel BackupWarning: Erases everything on the volume.
-
Wipe a disk (as admin)Windows
Clear-Disk -Number 1 -RemoveDataWarning: Erases every partition on the disk. Check the disk number with Get-Disk first.
-
Change a volume's name (as admin)Windows
Set-Volume -DriveLetter E -NewFileSystemLabel Backup -
Change a drive letter (as admin)Windows
Set-Partition -DriveLetter E -NewDriveLetter F -
Check a volume for errors (as admin)Windows
Repair-Volume -DriveLetter C -Scan -
Fix errors on a volume (as admin)Windows
Repair-Volume -DriveLetter C -OfflineScanAndFix -
Optimise a drive (as admin)Windows
Optimize-Volume -DriveLetter C -
Mount an ISO fileWindows
Mount-DiskImage -ImagePath C:\ISOs\windows.iso -
Unmount an ISO fileWindows
Dismount-DiskImage -ImagePath C:\ISOs\windows.iso
PowerShell: Firewall
-
Show whether the firewall is on for each profileWindows
Get-NetFirewallProfile | Select-Object Name, Enabled -
Turn the firewall on (as admin)Windows
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True -
Turn the firewall off (as admin)Windows
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled FalseWarning: Leaves the computer unprotected. Turn it back on when you're done.
-
List enabled rules that allow incoming trafficWindows
Get-NetFirewallRule -Direction Inbound -Enabled True -Action Allow -
Allow incoming traffic on a port (as admin)Windows
New-NetFirewallRule -DisplayName "Allow 8080" -Direction Inbound -Protocol TCP -LocalPort 8080 -Action Allow -
Allow incoming ping (as admin)Windows
New-NetFirewallRule -DisplayName "Allow ping" -Direction Inbound -Protocol ICMPv4 -IcmpType 8 -Action Allow -
Block a program from the internet (as admin)Windows
New-NetFirewallRule -DisplayName "Block app" -Direction Outbound -Program "C:\Apps\app.exe" -Action Block -
Show the ports a firewall rule coversWindows
Get-NetFirewallRule -DisplayName "Allow 8080" | Get-NetFirewallPortFilter -
Disable a firewall rule (as admin)Windows
Disable-NetFirewallRule -DisplayName "Allow 8080" -
Delete a firewall rule (as admin)Windows
Remove-NetFirewallRule -DisplayName "Allow 8080"
PowerShell: Scheduled tasks
-
List scheduled tasksWindows
Get-ScheduledTask -
List scheduled tasks that aren't Microsoft'sWindows
Get-ScheduledTask | Where-Object { $_.TaskPath -notlike '\Microsoft\*' } -
Show when a task last ran and its resultWindows
Get-ScheduledTaskInfo -TaskName "Backup" -
Run a PowerShell script every day at 2amWindows
$action = New-ScheduledTaskAction -Execute "pwsh.exe" -Argument "-File C:\Scripts\backup.ps1"; $trigger = New-ScheduledTaskTrigger -Daily -At 2am; Register-ScheduledTask -TaskName "Backup" -Action $action -Trigger $trigger -
Run a scheduled task nowWindows
Start-ScheduledTask -TaskName "Backup" -
Disable a scheduled taskWindows
Disable-ScheduledTask -TaskName "Backup" -
Delete a scheduled taskWindows
Unregister-ScheduledTask -TaskName "Backup" -Confirm:$false
PowerShell: Restart and shut down
-
Restart the computerWindows
Restart-Computer -
Force the computer to restartWindows
Restart-Computer -ForceWarning: Closes apps without saving.
-
Shut down the computerWindows
Stop-Computer -
Restart another computerWindows
Restart-Computer -ComputerName server01 -Force -
Restart another computer and wait until it's backWindows
Restart-Computer -ComputerName server01 -Wait -For PowerShell -Timeout 300 -
Rename the computer and restart (as admin)Windows
Rename-Computer -NewName web01 -Restart -
Join a domain and restart, in Windows PowerShell 5.1 (as admin)Windows
Add-Computer -DomainName corp.example.com -Credential (Get-Credential) -Restart
macOS: System information
-
Show the macOS version and buildmacOS
sw_vers -
Show just the macOS version numbermacOS
sw_vers -productVersion -
Show the Mac model, chip, memory and serial numbermacOS
system_profiler SPHardwareDataType -
Show the processor namemacOS
sysctl -n machdep.cpu.brand_string -
Check whether the Mac is Apple silicon or IntelmacOS
uname -m -
Show how long the Mac has been runningmacOS
uptime -
Show the Mac's namemacOS
scutil --get ComputerName -
Change the Mac's namemacOS
sudo scutil --set ComputerName "Gerard's Mac" -
Change the Mac's local network namemacOS
sudo scutil --set LocalHostName gerards-mac -
Install the Xcode command line toolsmacOS
xcode-select --install -
Install Rosetta for Intel apps on Apple siliconmacOS
softwareupdate --install-rosetta --agree-to-license
macOS: Homebrew
-
Install HomebrewmacOS
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" -
Search for a packagemacOS
brew search wget -
Show a package's detailsmacOS
brew info wget -
Install a command-line toolmacOS
brew install wget -
Install an appmacOS
brew install --cask visual-studio-code -
List installed packagesmacOS
brew list -
See which packages have updatesmacOS
brew outdated -
Update Homebrew's package listmacOS
brew update -
Upgrade all packagesmacOS
brew upgrade -
Upgrade one packagemacOS
brew upgrade wget -
Upgrade apps, including ones that update themselvesmacOS
brew upgrade --cask --greedy -
Stop a package from being upgradedmacOS
brew pin node -
Show which installed packages depend on a packagemacOS
brew uses --installed wget -
Uninstall a packagemacOS
brew uninstall wget -
Remove old versions and cached downloadsmacOS
brew cleanup -
Check Homebrew for problemsmacOS
brew doctor -
Save a list of your packages to a BrewfilemacOS
brew bundle dump -
Install everything in a BrewfilemacOS
brew bundle -
List background services installed with HomebrewmacOS
brew services list -
Start a Homebrew service and run it at loginmacOS
brew services start postgresql@16 -
Stop a Homebrew servicemacOS
brew services stop postgresql@16
macOS: Software updates
-
List available macOS updatesmacOS
softwareupdate --list -
Install all macOS updatesmacOS
sudo softwareupdate --install --all -
Install all macOS updates and restartmacOS
sudo softwareupdate --install --all --restart -
List full macOS installers you can downloadmacOS
softwareupdate --list-full-installers -
Download a full macOS installermacOS
softwareupdate --fetch-full-installer --full-installer-version 15.1 -
Install the Mac App Store command-line toolmacOS
brew install mas -
List apps installed from the App StoremacOS
mas list -
Update App Store appsmacOS
mas upgrade
macOS: Finder and files
-
Open a file with its default appmacOS
open report.pdf -
Open the current folder in FindermacOS
open . -
Open a folder in a specific appmacOS
open -a "Visual Studio Code" . -
Show a file in FindermacOS
open -R report.pdf -
Open a web page in your default browsermacOS
open https://commandguide.com -
Preview a file with Quick LookmacOS
qlmanage -p photo.png -
Copy a folder, keeping all Mac metadatamacOS
ditto source/ backup/ -
Zip a folder the same way Finder doesmacOS
ditto -c -k --keepParent folder folder.zip -
Create a compressed disk image from a foldermacOS
hdiutil create -volname Projects -srcfolder ~/Projects -ov -format UDZO projects.dmg -
Open a disk imagemacOS
hdiutil attach app.dmg -
Eject a disk imagemacOS
hdiutil detach /Volumes/App -
Hide a file in FindermacOS
chflags hidden file.txt -
Unhide a file in FindermacOS
chflags nohidden file.txt -
Lock a file so it can't be changedmacOS
chflags uchg file.txt -
Unlock a filemacOS
chflags nouchg file.txt -
Show a file's extended attributesmacOS
xattr -l app.dmg -
Convert a HEIC photo to JPEGmacOS
sips -s format jpeg photo.heic --out photo.jpg -
Resize an image so its longest side is 1200 pixelsmacOS
sips -Z 1200 photo.jpgWarning: Changes the image straight away, with no backup.
-
Convert a Word document to plain textmacOS
textutil -convert txt report.docx -
Print a filemacOS
lpr report.pdf
macOS: Clipboard, screenshots and speech
-
Copy a command's output to the clipboardmacOS
ls | pbcopy -
Copy a file's contents to the clipboardmacOS
pbcopy < notes.txt -
Paste the clipboardmacOS
pbpaste -
Save the clipboard to a filemacOS
pbpaste > notes.txt -
Take a screenshot of the whole screenmacOS
screencapture screen.png -
Take a screenshot of an area or window you choosemacOS
screencapture -i shot.png -
Take a screenshot after 5 secondsmacOS
screencapture -T 5 screen.png -
Take a screenshot and copy it to the clipboardmacOS
screencapture -c -
Record the screenmacOS
screencapture -v recording.mov -
Change where screenshots are savedmacOS
defaults write com.apple.screencapture location ~/Pictures/Screenshots && killall SystemUIServer -
Save screenshots as JPEGmacOS
defaults write com.apple.screencapture type jpg && killall SystemUIServer -
Remove the shadow from window screenshotsmacOS
defaults write com.apple.screencapture disable-shadow -bool true && killall SystemUIServer -
Speak some textmacOS
say "Build finished" -
Save spoken text to an audio filemacOS
say -o hello.aiff "Hello" -
Show a notificationmacOS
osascript -e 'display notification "Build finished" with title "Terminal"'
macOS: Spotlight
-
Search for files with SpotlightmacOS
mdfind "invoice" -
Find files by namemacOS
mdfind -name report.pdf -
Search inside one foldermacOS
mdfind -onlyin ~/Documents "invoice" -
Find files larger than 1 GBmacOS
mdfind "kMDItemFSSize > 1000000000" -
List every app on the MacmacOS
mdfind "kMDItemContentType == 'com.apple.application-bundle'" -
Show a file's Spotlight metadata, including where it was downloaded frommacOS
mdls report.pdf -
Check whether Spotlight is indexing a drivemacOS
mdutil -s / -
Rebuild the Spotlight indexmacOS
sudo mdutil -E / -
Stop Spotlight indexing a drivemacOS
sudo mdutil -i off /Volumes/Backup
macOS: Settings with defaults
-
Show all of an app's settingsmacOS
defaults read com.apple.dock -
Show one settingmacOS
defaults read com.apple.dock autohide -
Search all settings for a wordmacOS
defaults find autohide -
List the apps that have settingsmacOS
defaults domains -
Reset one setting to its defaultmacOS
defaults delete com.apple.dock autohide -
Back up an app's settings to a filemacOS
defaults export com.apple.dock dock.plist -
Restore an app's settings from a filemacOS
defaults import com.apple.dock dock.plist -
Show a settings (plist) file in readable formmacOS
plutil -p ~/Library/Preferences/com.apple.dock.plist -
Check a plist file for errorsmacOS
plutil -lint settings.plist -
Convert a plist file to XMLmacOS
plutil -convert xml1 settings.plist -
Show hidden files in FindermacOS
defaults write com.apple.finder AppleShowAllFiles -bool true && killall Finder -
Hide hidden files in Finder againmacOS
defaults write com.apple.finder AppleShowAllFiles -bool false && killall Finder -
Show the path bar in FindermacOS
defaults write com.apple.finder ShowPathbar -bool true && killall Finder -
Show all file extensionsmacOS
defaults write NSGlobalDomain AppleShowAllExtensions -bool true && killall Finder -
Stop Finder making .DS_Store files on network drivesmacOS
defaults write com.apple.desktopservices DSDontWriteNetworkStores -bool true -
Save new documents to the Mac instead of iCloudmacOS
defaults write NSGlobalDomain NSDocumentSaveNewDocumentsToCloud -bool false -
Open save dialogs fully expandedmacOS
defaults write NSGlobalDomain NSNavPanelExpandedStateForSaveMode -bool true -
Make keys repeat faster (sign out to apply)macOS
defaults write NSGlobalDomain KeyRepeat -int 2 -
Repeat keys when held instead of showing accentsmacOS
defaults write NSGlobalDomain ApplePressAndHoldEnabled -bool false
macOS: Dock
-
Hide the Dock automaticallymacOS
defaults write com.apple.dock autohide -bool true && killall Dock -
Show a hidden Dock instantlymacOS
defaults write com.apple.dock autohide-delay -float 0 && killall Dock -
Change the Dock's icon sizemacOS
defaults write com.apple.dock tilesize -int 48 && killall Dock -
Stop showing recent apps in the DockmacOS
defaults write com.apple.dock show-recents -bool false && killall Dock -
Add a gap between Dock appsmacOS
defaults write com.apple.dock persistent-apps -array-add '{"tile-type"="spacer-tile";}' && killall Dock -
Reset the DockmacOS
defaults delete com.apple.dock && killall DockWarning: Removes every app you've added to the Dock and all Dock settings.
macOS: Apps and processes
-
Open an appmacOS
open -a Safari -
Open another copy of an appmacOS
open -na "Google Chrome" -
Quit an app normallymacOS
osascript -e 'quit app "Safari"' -
Force an app to quitmacOS
killall SafariWarning: The app can't save, so unsaved work may be lost.
-
Show an app's bundle IDmacOS
osascript -e 'id of app "Safari"' -
Show processes by CPU usemacOS
top -o cpu -
Restart FindermacOS
killall Finder -
Restart the DockmacOS
killall Dock -
Restart the menu barmacOS
killall SystemUIServer -
Keep the Mac awake while a command runsmacOS
caffeinate -i make build -
Keep the Mac awake for an hourmacOS
caffeinate -t 3600 -
Keep the display on until you press Ctrl+CmacOS
caffeinate -d
macOS: launchd and background jobs
-
List your background jobsmacOS
launchctl list -
Find a background job by namemacOS
launchctl list | grep docker -
Show a background job's detailsmacOS
launchctl print gui/$(id -u)/com.example.backup -
Load a launch agentmacOS
launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.example.backup.plist -
Unload a launch agentmacOS
launchctl bootout gui/$(id -u) ~/Library/LaunchAgents/com.example.backup.plist -
Restart a background jobmacOS
launchctl kickstart -k gui/$(id -u)/com.example.backup -
Restart a system servicemacOS
sudo launchctl kickstart -k system/com.openssh.sshd -
Stop a background job starting automaticallymacOS
launchctl disable gui/$(id -u)/com.example.backup -
Let a disabled background job start againmacOS
launchctl enable gui/$(id -u)/com.example.backup -
List login items and background itemsmacOS
sudo sfltool dumpbtm
macOS: Logs and diagnostics
-
Watch the system log for one processmacOS
log stream --predicate 'process == "sshd"' -
Search the last hour of logs for errorsmacOS
log show --last 1h --predicate 'eventMessage CONTAINS "error"' -
Save the last hour of logs to a filemacOS
sudo log collect --last 1h -
Open the folder of crash reportsmacOS
open ~/Library/Logs/DiagnosticReports -
Collect a full diagnostics report for ApplemacOS
sudo sysdiagnose
macOS: Network
-
List network services, such as Wi-Fi and EthernetmacOS
networksetup -listallnetworkservices -
List network ports and their device namesmacOS
networksetup -listallhardwareports -
Show a network service's IP settingsmacOS
networksetup -getinfo Wi-Fi -
Show the IP address of an interfacemacOS
ipconfig getifaddr en0 -
Show an interface's MAC addressmacOS
ifconfig en0 ether -
Show the default gatewaymacOS
route -n get default -
Show the DNS servers in usemacOS
scutil --dns -
Show a network service's DNS serversmacOS
networksetup -getdnsservers Wi-Fi -
Set a network service's DNS serversmacOS
sudo networksetup -setdnsservers Wi-Fi 1.1.1.1 8.8.8.8 -
Go back to the DNS servers from DHCPmacOS
sudo networksetup -setdnsservers Wi-Fi empty -
Clear the DNS cachemacOS
sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder -
Set a static IP addressmacOS
sudo networksetup -setmanual Ethernet 192.168.1.50 255.255.255.0 192.168.1.1 -
Switch a network service to DHCPmacOS
sudo networksetup -setdhcp Ethernet -
Renew the DHCP leasemacOS
sudo ipconfig set en0 DHCP -
Show the order network services are used inmacOS
networksetup -listnetworkserviceorder -
Show proxy settingsmacOS
scutil --proxy -
Test your internet speed and responsivenessmacOS
networkQuality -
List listening portsmacOS
sudo lsof -iTCP -sTCP:LISTEN -n -P -
Find what's using a portmacOS
lsof -i :8080 -
Turn on Remote Login (SSH)macOS
sudo systemsetup -setremotelogin on
macOS: Wi-Fi
-
Turn Wi-Fi offmacOS
networksetup -setairportpower en0 off -
Turn Wi-Fi onmacOS
networksetup -setairportpower en0 on -
Join a Wi-Fi networkmacOS
networksetup -setairportnetwork en0 HomeWiFiWarning: Your Wi-Fi password is saved in your shell history.
-
Show Wi-Fi details, including nearby networksmacOS
system_profiler SPAirPortDataType -
Show detailed Wi-Fi diagnosticsmacOS
sudo wdutil info -
Show a saved Wi-Fi network's passwordmacOS
security find-generic-password -wa "HomeWiFi"
macOS: Firewall
-
Check whether the firewall is onmacOS
/usr/libexec/ApplicationFirewall/socketfilterfw --getglobalstate -
Turn the firewall onmacOS
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate on -
Turn the firewall offmacOS
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate offWarning: Leaves the Mac unprotected. Turn it back on when you're done.
-
Turn on stealth modemacOS
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode on -
List apps and whether they're allowedmacOS
/usr/libexec/ApplicationFirewall/socketfilterfw --listapps -
Allow an app through the firewallmacOS
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --add /Applications/MyApp.app -
Block an app's incoming connectionsmacOS
sudo /usr/libexec/ApplicationFirewall/socketfilterfw --blockapp /Applications/MyApp.app -
Show the packet filter (pf) statusmacOS
sudo pfctl -s info
macOS: Disks
-
List disks and volumesmacOS
diskutil list -
Show a disk's detailsmacOS
diskutil info disk2 -
Check a disk's SMART statusmacOS
diskutil info disk0 | grep SMART -
List APFS containers and volumesmacOS
diskutil apfs list -
Check a volume for errorsmacOS
diskutil verifyVolume / -
Repair a volumemacOS
sudo diskutil repairVolume /Volumes/Backup -
Mount a volumemacOS
diskutil mount disk2s1 -
Unmount a volumemacOS
diskutil unmount /Volumes/Backup -
Eject a diskmacOS
diskutil eject disk2 -
Rename a volumemacOS
diskutil rename /Volumes/Untitled Backup -
Add an APFS volume to a containermacOS
diskutil apfs addVolume disk3 APFS Projects -
Erase a disk as APFSmacOS
diskutil eraseDisk APFS Backup disk2Warning: Erases everything on the disk. Check the disk name with diskutil list first.
-
Erase a disk as exFAT for Mac and WindowsmacOS
diskutil eraseDisk ExFAT USB GPT disk2Warning: Erases everything on the disk. Check the disk name with diskutil list first.
-
Make a bootable macOS installer on a USB drivemacOS
sudo /Applications/Install\ macOS\ Sequoia.app/Contents/Resources/createinstallmedia --volume /Volumes/USBWarning: Erases everything on the USB drive.
macOS: Time Machine
-
Show Time Machine's statusmacOS
tmutil status -
Start a backup nowmacOS
tmutil startbackup -
Show the backup drive's detailsmacOS
tmutil destinationinfo -
Show the latest backupmacOS
tmutil latestbackup -
List all backupsmacOS
tmutil listbackups -
Leave a folder out of backupsmacOS
tmutil addexclusion ~/Downloads -
Check whether a folder is left out of backupsmacOS
tmutil isexcluded ~/Downloads -
List local snapshotsmacOS
tmutil listlocalsnapshots /
macOS: Power and sleep
-
Show power settingsmacOS
pmset -g -
Show battery chargemacOS
pmset -g batt -
Show battery health and cycle countmacOS
system_profiler SPPowerDataType -
Show what's stopping the Mac from sleepingmacOS
pmset -g assertions -
Show recent sleep and wake timesmacOS
pmset -g log | grep -E "Sleep|Wake" -
Put the Mac to sleepmacOS
pmset sleepnow -
Turn the display offmacOS
pmset displaysleepnow -
Turn the display off after 10 minutes on the chargermacOS
sudo pmset -c displaysleep 10 -
Never sleep on the chargermacOS
sudo pmset -c sleep 0 -
Turn on Low Power ModemacOS
sudo pmset -a lowpowermode 1 -
Wake or start the Mac at 7am on weekdaysmacOS
sudo pmset repeat wakeorpoweron MTWRF 07:00:00 -
Cancel scheduled wake and start timesmacOS
sudo pmset repeat cancel -
Restart nowmacOS
sudo shutdown -r now -
Shut down nowmacOS
sudo shutdown -h now -
Shut down in 30 minutesmacOS
sudo shutdown -h +30 -
Sign outmacOS
osascript -e 'tell application "System Events" to log out'
macOS: Security and Gatekeeper
-
Check whether Gatekeeper is onmacOS
spctl --status -
Check whether Gatekeeper will let an app openmacOS
spctl --assess --verbose /Applications/MyApp.app -
Show who signed an appmacOS
codesign -dv --verbose=4 /Applications/MyApp.app -
Check an app's signature is intactmacOS
codesign --verify --deep --strict /Applications/MyApp.app -
Remove the downloaded-from-internet flag from an appmacOS
xattr -d com.apple.quarantine /Applications/MyApp.appWarning: Skips Gatekeeper's check. Only do it for apps you trust.
-
Check whether System Integrity Protection is onmacOS
csrutil status -
Check whether FileVault is onmacOS
fdesetup status -
Turn on FileVaultmacOS
sudo fdesetup enable -
Reset an app's privacy permissionsmacOS
tccutil reset All com.example.app -
List code-signing certificatesmacOS
security find-identity -v -p codesigning
macOS: Keychain
-
Save a password in the keychain (asks for it)macOS
security add-generic-password -a "$USER" -s "MyService" -w -
Show a saved passwordmacOS
security find-generic-password -s "MyService" -w -
Delete a saved passwordmacOS
security delete-generic-password -s "MyService" -
List keychainsmacOS
security list-keychains -
Lock the login keychainmacOS
security lock-keychain ~/Library/Keychains/login.keychain-db
macOS: Users and groups
-
List user accountsmacOS
dscl . list /Users | grep -v '^_' -
Show your account's detailsmacOS
dscl . read /Users/$USER -
List the groups you're inmacOS
id -Gn -
List administratorsmacOS
dscl . read /Groups/admin GroupMembership -
Create a user (asks for the password)macOS
sudo sysadminctl -addUser alice -fullName "Alice Smith" -password - -
Make a user an administratormacOS
sudo dseditgroup -o edit -a alice -t user admin -
Remove a user's administrator rightsmacOS
sudo dseditgroup -o edit -d alice -t user admin -
Change your passwordmacOS
passwd -
Check whether the guest account is onmacOS
sudo sysadminctl -guestAccount status -
Delete a user and their home foldermacOS
sudo sysadminctl -deleteUser aliceWarning: Deletes the user's files and can't be undone.
macOS: Automation
-
Run an AppleScript commandmacOS
osascript -e 'tell application "Music" to play' -
List your ShortcutsmacOS
shortcuts list -
Run a ShortcutmacOS
shortcuts run "Resize Image" -
Set the volume to 50%macOS
osascript -e 'set volume output volume 50' -
Mute the soundmacOS
osascript -e 'set volume output muted true' -
Switch between light and dark modemacOS
osascript -e 'tell application "System Events" to tell appearance preferences to set dark mode to not dark mode' -
Empty the TrashmacOS
osascript -e 'tell application "Finder" to empty trash'Warning: Deletes everything in the Trash and can't be undone.
Vim: Install and start
-
Check which version of Vim is installedLinux, macOS, Windows
vim --version -
Install VimDebian, Ubuntu
sudo apt install vimRed Hat, Fedorasudo dnf install vim-enhancedAlpineapk add vim -
Install Vim with Homebrew, newer than the one macOS includesmacOS
brew install vim -
Install Vim on WindowsWindows
winget install vim.vim -
Install a Vim that can copy to the system clipboardDebian, Ubuntu
sudo apt install vim-gtk3 -
Check Vim can use the system clipboard (look for +clipboard)Linux, macOS
vim --version | grep clipboard -
Open a file, or create it if it doesn't existLinux, macOS, Windows
vim notes.txt -
Open a file at line 42Linux, macOS, Windows
vim +42 notes.txt -
Open a file at the last lineLinux, macOS, Windows
vim + app.log -
Open a file at the first match of a wordLinux, macOS, Windows
vim +/error app.log -
Open a file read-onlyLinux, macOS, Windows
vim -R notes.txt -
Open two files side by sideLinux, macOS, Windows
vim -O a.txt b.txt -
Open several files in tabsLinux, macOS, Windows
vim -p a.txt b.txt -
Edit a system file as root, keeping your own Vim settingsLinux, macOS
sudoedit /etc/ssh/sshd_config -
Recover a file after Vim or the computer crashedLinux, macOS, Windows
vim -r notes.txt -
Start Vim without your settings or pluginsLinux, macOS, Windows
vim --clean -
Make Vim the editor Git uses for commit messagesLinux, macOS, Windows
git config --global core.editor vim -
Make Vim the default editor for crontab, sudoedit and other toolsLinux, macOS
export EDITOR=vim -
Start the built-in 30-minute Vim tutorialLinux, macOS, Windows
vimtutor
Vim: Modes, quitting and saving
-
Go back to normal mode, whatever you were doingLinux, macOS, Windows
Esc -
Quit VimLinux, macOS, Windows
:q -
Exit Vim without saving changesLinux, macOS, Windows
:q!Warning: Throws away every change since you last saved.
-
Save and quit VimLinux, macOS, Windows
:wq -
Save only if there are changes, then quit VimLinux, macOS, Windows
:x -
Save and quit Vim from normal mode, without typing a colonLinux, macOS, Windows
ZZ -
Exit Vim without saving, from normal modeLinux, macOS, Windows
ZQWarning: Throws away every change since you last saved.
-
Quit every window and tabLinux, macOS, Windows
:qa -
Exit everything without saving any changesLinux, macOS, Windows
:qa!Warning: Throws away the unsaved changes in every open file.
-
Save the fileLinux, macOS, Windows
:w -
Save a copy under a new name and keep editing the originalLinux, macOS, Windows
:w backup.txt -
Save under a new name and carry on editing the new fileLinux, macOS, Windows
:saveas notes-v2.txt -
Save every changed fileLinux, macOS, Windows
:wa -
Save and quit every fileLinux, macOS, Windows
:wqa -
Save a file you opened without sudoLinux, macOS
:w !sudo tee % > /dev/nullWarning: Works in Vim but not in Neovim. Use sudoedit next time.
-
Save only lines 10 to 20 to another fileLinux, macOS, Windows
:10,20w part.txt -
Start typing before the cursor (insert mode)Linux, macOS, Windows
i -
Start typing after the cursorLinux, macOS, Windows
a -
Start typing at the start of the lineLinux, macOS, Windows
I -
Start typing at the end of the lineLinux, macOS, Windows
A -
Open a new line below and start typingLinux, macOS, Windows
o -
Open a new line above and start typingLinux, macOS, Windows
O -
Type over the existing text (replace mode)Linux, macOS, Windows
R -
Run one normal-mode command without leaving insert modeLinux, macOS, Windows
Ctrl-o -
Show the file name, line number and how far through you areLinux, macOS, Windows
Ctrl-g
Vim: Open and switch files
-
Open another fileLinux, macOS, Windows
:e config.yaml -
Reload the file from disk, throwing away your changesLinux, macOS, Windows
:e!Warning: Throws away every change since you last saved.
-
Browse the files in the current folderLinux, macOS, Windows
:Explore -
Open the file whose name is under the cursorLinux, macOS, Windows
gf -
Insert another file's contents below the cursorLinux, macOS, Windows
:r header.txt -
Insert the output of a command below the cursorLinux, macOS
:r !date -
List open files (buffers)Linux, macOS, Windows
:ls -
Switch to buffer 2Linux, macOS, Windows
:b 2 -
Switch to an open file by part of its nameLinux, macOS, Windows
:b conf -
Go to the next or previous open fileLinux, macOS, Windows
:bn :bp -
Go back to the file you were in beforeLinux, macOS, Windows
Ctrl-^ -
Close the current file but keep Vim openLinux, macOS, Windows
:bd -
Find a file by name in this folder or below, and open itLinux, macOS, Windows
:set path+=** :find settings.py -
Change Vim's working folderLinux, macOS, Windows
:cd ~/projects/site -
Show Vim's working folderLinux, macOS, Windows
:pwd
Vim: Moving around
-
Move left, down, up and rightLinux, macOS, Windows
h j k l -
Move down 5 linesLinux, macOS, Windows
5j -
Jump to the next word, or back a wordLinux, macOS, Windows
w b -
Jump to the end of the wordLinux, macOS, Windows
e -
Jump by words separated only by spaces, skipping punctuationLinux, macOS, Windows
W B E -
Go to the start of the lineLinux, macOS, Windows
0 -
Go to the first character of the line that isn't a spaceLinux, macOS, Windows
^ -
Go to the end of the lineLinux, macOS, Windows
$ -
Go to the top of the fileLinux, macOS, Windows
gg -
Go to the bottom of the fileLinux, macOS, Windows
G -
Go to line 42Linux, macOS, Windows
:42 -
Go halfway through the fileLinux, macOS, Windows
50% -
Go to column 20 of the lineLinux, macOS, Windows
20| -
Scroll down or up half a screenLinux, macOS, Windows
Ctrl-d Ctrl-u -
Scroll down or up a whole screenLinux, macOS, Windows
Ctrl-f Ctrl-b -
Move to the top, middle or bottom of the screenLinux, macOS, Windows
H M L -
Scroll so the cursor's line is in the middle of the screenLinux, macOS, Windows
zz -
Scroll so the cursor's line is at the top or bottom of the screenLinux, macOS, Windows
zt zb -
Jump to the matching bracketLinux, macOS, Windows
% -
Jump to the next or previous paragraphLinux, macOS, Windows
} { -
Jump to the next x on the lineLinux, macOS, Windows
fx -
Jump to just before the next x on the lineLinux, macOS, Windows
tx -
Repeat the last f or t jump, forwards or backwardsLinux, macOS, Windows
; , -
Go back to where you were before a jump, or forward againLinux, macOS, Windows
Ctrl-o Ctrl-i -
Go back to where you last changed somethingLinux, macOS, Windows
g;
Vim: Marks
-
Set mark a at the cursorLinux, macOS, Windows
ma -
Jump to the line with mark aLinux, macOS, Windows
'a -
Jump to the exact spot of mark aLinux, macOS, Windows
`a -
Set a mark you can jump to from any file (capital letter)Linux, macOS, Windows
mA -
Go back to the line you were on before the last jumpLinux, macOS, Windows
'' -
Go to the spot of the last changeLinux, macOS, Windows
`. -
List all marksLinux, macOS, Windows
:marks -
Delete mark aLinux, macOS, Windows
:delmarks a
Vim: Editing
-
Delete the character under the cursorLinux, macOS, Windows
x -
Delete the lineLinux, macOS, Windows
dd -
Delete 3 linesLinux, macOS, Windows
3dd -
Delete to the end of the wordLinux, macOS, Windows
dw -
Delete to the end of the lineLinux, macOS, Windows
D -
Delete to the end of the fileLinux, macOS, Windows
dG -
Delete the text inside quotesLinux, macOS, Windows
di" -
Delete the text inside bracketsLinux, macOS, Windows
di( -
Delete the brackets and everything in themLinux, macOS, Windows
da( -
Delete the text inside an HTML or XML tagLinux, macOS, Windows
dit -
Change a word (delete it and start typing)Linux, macOS, Windows
cw -
Change the whole word the cursor is inLinux, macOS, Windows
ciw -
Change the whole lineLinux, macOS, Windows
cc -
Change to the end of the lineLinux, macOS, Windows
C -
Change the text inside quotesLinux, macOS, Windows
ci" -
Replace the character under the cursor with xLinux, macOS, Windows
rx -
Join the next line onto this oneLinux, macOS, Windows
J -
Switch the case of the character under the cursorLinux, macOS, Windows
~ -
Make the line lowercase or UPPERCASELinux, macOS, Windows
guu gUU -
Indent the line, or take the indent offLinux, macOS, Windows
>> << -
Fix the indentation of the whole fileLinux, macOS, Windows
gg=G -
Add 1 to the number under the cursor, or take 1 awayLinux, macOS, Windows
Ctrl-a Ctrl-x -
Repeat the last changeLinux, macOS, Windows
. -
Swap this line with the one belowLinux, macOS, Windows
ddp -
Swap two charactersLinux, macOS, Windows
xp -
Delete lines 10 to 20Linux, macOS, Windows
:10,20d -
Delete every line that contains a wordLinux, macOS, Windows
:g/DEBUG/dWarning: Check the pattern with a search first. Undo with u if it takes too much.
-
Delete every line that doesn't contain a wordLinux, macOS, Windows
:v/ERROR/dWarning: Check the pattern with a search first. Undo with u if it takes too much.
-
Delete empty lines, including ones with only spacesLinux, macOS, Windows
:g/^\s*$/d -
Remove spaces and tabs from the ends of linesLinux, macOS, Windows
:%s/\s\+$//e -
Sort the linesLinux, macOS, Windows
:sort -
Sort the lines and remove duplicatesLinux, macOS, Windows
:sort u -
Sort lines by the number at the startLinux, macOS, Windows
:sort n -
Reverse the order of the linesLinux, macOS, Windows
:g/^/m0 -
Wrap long lines in a paragraph to the text widthLinux, macOS, Windows
gqip -
Insert a character by its Unicode number, such as an en dashLinux, macOS, Windows
Ctrl-v u2013
Vim: Undo and redo
-
UndoLinux, macOS, Windows
u -
RedoLinux, macOS, Windows
Ctrl-r -
Undo every change on the line you just editedLinux, macOS, Windows
U -
Go back to how the file was 10 minutes agoLinux, macOS, Windows
:earlier 10m -
Go forward in time againLinux, macOS, Windows
:later 10m -
Go back to how the file was when you last savedLinux, macOS, Windows
:earlier 1f -
Keep undo history after you close the fileLinux, macOS, Windows
:set undofile
Vim: Copy and paste
-
Copy (yank) the lineLinux, macOS, Windows
yy -
Copy 3 linesLinux, macOS, Windows
3yy -
Copy the wordLinux, macOS, Windows
yiw -
Copy to the end of the lineLinux, macOS, Windows
y$ -
Copy the whole fileLinux, macOS, Windows
:%y -
Paste after the cursor, or below the lineLinux, macOS, Windows
p -
Paste before the cursor, or above the lineLinux, macOS, Windows
P -
Paste the last thing you copied, not the last thing you deletedLinux, macOS, Windows
"0p -
Copy the line into register aLinux, macOS, Windows
"ayy -
Paste from register aLinux, macOS, Windows
"ap -
Copy the line to the system clipboardLinux, macOS, Windows
"+yy -
Copy the selection to the system clipboardLinux, macOS, Windows
"+y -
Paste from the system clipboardLinux, macOS, Windows
"+p -
Copy the whole file to the system clipboardLinux, macOS, Windows
:%y + -
Paste while typing, without leaving insert modeLinux, macOS, Windows
Ctrl-r " -
Show what's in every registerLinux, macOS, Windows
:registers -
Copy lines 5 to 10 to below line 20Linux, macOS, Windows
:5,10t 20 -
Move lines 5 to 10 to below line 20Linux, macOS, Windows
:5,10m 20 -
Move the current line to the top of the fileLinux, macOS, Windows
:m 0
Vim: Search
-
Search forwardsLinux, macOS, Windows
/error -
Search backwardsLinux, macOS, Windows
?error -
Go to the next or previous matchLinux, macOS, Windows
n N -
Search for the word under the cursor, forwards or backwardsLinux, macOS, Windows
* # -
Search for a whole word onlyLinux, macOS, Windows
/\<error\> -
Search ignoring case, just this onceLinux, macOS, Windows
/error\c -
Search for either of two wordsLinux, macOS, Windows
/error\|warning -
Turn off the search highlighting until the next searchLinux, macOS, Windows
:noh -
Count how many times a word appearsLinux, macOS, Windows
:%s/error//gn -
Highlight matches and show them as you typeLinux, macOS, Windows
:set hlsearch incsearch -
Ignore case in searches unless you type a capitalLinux, macOS, Windows
:set ignorecase smartcase -
Search every Python file below this folderLinux, macOS, Windows
:vimgrep /TODO/ **/*.py -
Open the list of matches from vimgrepLinux, macOS, Windows
:copen -
Go to the next or previous match in the listLinux, macOS, Windows
:cnext :cprev -
List every line in the file that matchesLinux, macOS, Windows
:g/error/p
Vim: Find and replace
-
Replace the first match on the lineLinux, macOS, Windows
:s/old/new/ -
Replace every match on the lineLinux, macOS, Windows
:s/old/new/g -
Replace every match in the fileLinux, macOS, Windows
:%s/old/new/g -
Replace every match in the file, asking each timeLinux, macOS, Windows
:%s/old/new/gc -
Replace in lines 10 to 20Linux, macOS, Windows
:10,20s/old/new/g -
Replace in the lines you've selectedLinux, macOS, Windows
:'<,'>s/old/new/g -
Replace whole words onlyLinux, macOS, Windows
:%s/\<old\>/new/g -
Replace, ignoring caseLinux, macOS, Windows
:%s/old/new/gi -
Replace text containing slashes, such as a pathLinux, macOS, Windows
:%s#/var/www#/srv/www#g -
Replace with the last word you searched forLinux, macOS, Windows
:%s//new/g -
Put each comma-separated item on its own lineLinux, macOS, Windows
:%s/,/\r/g -
Put the matched text back in the replacementLinux, macOS, Windows
:%s/v[0-9]\+/release &/g -
Swap two words using groupsLinux, macOS, Windows
:%s/\(\w\+\) \(\w\+\)/\2 \1/ -
Repeat the last replace on this lineLinux, macOS, Windows
& -
Repeat the last replace on every lineLinux, macOS, Windows
g& -
Replace in every .conf file below this folder, and save themLinux, macOS, Windows
:args **/*.conf :argdo %s/old/new/ge | updateWarning: Saves every file it changes. Commit or back up first.
Vim: Visual mode (selecting)
-
Select charactersLinux, macOS, Windows
v -
Select whole linesLinux, macOS, Windows
V -
Select a block (columns)Linux, macOS, Windows
Ctrl-v -
Select everythingLinux, macOS, Windows
ggVG -
Select the paragraphLinux, macOS, Windows
vip -
Select inside brackets or bracesLinux, macOS, Windows
vi( vi{ -
Select inside quotesLinux, macOS, Windows
vi" -
Select the last selection againLinux, macOS, Windows
gv -
Jump to the other end of the selectionLinux, macOS, Windows
o -
Copy, delete or change the selectionLinux, macOS, Windows
y d c -
Indent the selection, or take the indent offLinux, macOS, Windows
> < -
Make the selection UPPERCASE or lowercaseLinux, macOS, Windows
U u -
Add # to the start of several linesLinux, macOS, Windows
Ctrl-v jj I# Esc -
Add ; to the end of several linesLinux, macOS, Windows
Ctrl-v jj $A; Esc -
Run a normal-mode command on every selected lineLinux, macOS, Windows
:'<,'>norm A; -
Sort the selected linesLinux, macOS, Windows
:'<,'>sort
Vim: Windows and tabs
-
Split the window and open a file aboveLinux, macOS, Windows
:split other.txt -
Split the window and open a file alongsideLinux, macOS, Windows
:vsplit other.txt -
Move to the next windowLinux, macOS, Windows
Ctrl-w w -
Move to the window left, below, above or rightLinux, macOS, Windows
Ctrl-w h Ctrl-w j Ctrl-w k Ctrl-w l -
Make all windows the same sizeLinux, macOS, Windows
Ctrl-w = -
Make the window 20 lines tallLinux, macOS, Windows
:resize 20 -
Make the window 80 columns wideLinux, macOS, Windows
:vertical resize 80 -
Close the windowLinux, macOS, Windows
:close -
Close every window except this oneLinux, macOS, Windows
:only -
Open a file in a new tabLinux, macOS, Windows
:tabnew other.txt -
Go to the next or previous tabLinux, macOS, Windows
gt gT -
Close the tabLinux, macOS, Windows
:tabclose -
Open a terminal inside VimLinux, macOS, Windows
:terminal
Vim: Compare files (diff)
-
Compare two files side by sideLinux, macOS, Windows
vim -d old.conf new.conf -
Jump to the next or previous differenceLinux, macOS, Windows
]c [c -
Take the other file's version of this differenceLinux, macOS, Windows
do -
Send this version to the other fileLinux, macOS, Windows
dp -
Recalculate the differences after editingLinux, macOS, Windows
:diffupdate -
Compare two windows you already have open (run in each)Linux, macOS, Windows
:diffthis -
Stop comparingLinux, macOS, Windows
:diffoff! -
See what you've changed since you last savedLinux, macOS
:w !diff % -
Vim: Macros
-
Start recording a macro into register aLinux, macOS, Windows
qa -
Stop recordingLinux, macOS, Windows
q -
Play macro aLinux, macOS, Windows
@a -
Play the last macro againLinux, macOS, Windows
@@ -
Play macro a 10 timesLinux, macOS, Windows
10@a -
Play macro a on lines 5 to 20Linux, macOS, Windows
:5,20norm @a -
Play macro a on every selected lineLinux, macOS, Windows
:'<,'>norm @a -
See what's in macro aLinux, macOS, Windows
:reg a
Vim: Folding
-
Fold by indentationLinux, macOS, Windows
:set foldmethod=indent -
Fold a paragraph you chooseLinux, macOS, Windows
zfap -
Open or close the fold under the cursorLinux, macOS, Windows
za -
Open every foldLinux, macOS, Windows
zR -
Close every foldLinux, macOS, Windows
zM -
Delete the fold under the cursor, keeping the textLinux, macOS, Windows
zd
Vim: Settings
-
Show line numbersLinux, macOS, Windows
:set number -
Show line numbers relative to the cursorLinux, macOS, Windows
:set relativenumber -
Hide line numbersLinux, macOS, Windows
:set nonumber norelativenumber -
Turn on syntax highlightingLinux, macOS, Windows
:syntax on -
Tell Vim what kind of file it is, for highlightingLinux, macOS, Windows
:set filetype=yaml -
Use 4 spaces when you press TabLinux, macOS, Windows
:set expandtab tabstop=4 shiftwidth=4 -
Turn the tabs in the file into spacesLinux, macOS, Windows
:retab -
Show tabs and spaces at the ends of linesLinux, macOS, Windows
:set list -
Stop long lines wrappingLinux, macOS, Windows
:set nowrap -
Let the mouse move the cursor and select textLinux, macOS, Windows
:set mouse=a -
Show what you're typing in normal mode, at the bottom rightLinux, macOS, Windows
:set showcmd -
Turn on spell checking in British EnglishLinux, macOS, Windows
:set spell spelllang=en_gb -
Jump to the next misspelt wordLinux, macOS, Windows
]s -
Show spelling suggestions for the wordLinux, macOS, Windows
z= -
Change the colour schemeLinux, macOS, Windows
:colorscheme desert -
Check what a setting is set toLinux, macOS, Windows
:set tabstop? -
See which file last changed a settingLinux, macOS, Windows
:verbose set tabstop? -
Turn a setting back to Vim's defaultLinux, macOS, Windows
:set tabstop& -
Save the file with Unix line endings, from Windows onesLinux, macOS, Windows
:set fileformat=unix :w -
Open your settings file (vimrc)Linux, macOS, Windows
:e $MYVIMRC -
Create your settings fileLinux, macOS
vim ~/.vimrcWindowsvim ~/_vimrc -
Reload your settings without restarting VimLinux, macOS, Windows
:source $MYVIMRC -
Good starter settings for your vimrcLinux, macOS, Windows
set number syntax on filetype plugin indent on set expandtab tabstop=4 shiftwidth=4 set ignorecase smartcase incsearch hlsearch set showcmd -
Use the space bar as your leader key (add to vimrc)Linux, macOS, Windows
let mapleader = " " -
Make Space then w save the file (add to vimrc)Linux, macOS, Windows
nnoremap <leader>w :w<CR> -
Install a plugin with Vim's built-in packagesLinux, macOS
git clone https://github.com/tpope/vim-surround ~/.vim/pack/plugins/start/vim-surround
Vim: Help and shell commands
-
Open Vim's helpLinux, macOS, Windows
:help -
Get help on a commandLinux, macOS, Windows
:help :wq -
Get help on a keyLinux, macOS, Windows
:help dd -
Search all of the helpLinux, macOS, Windows
:helpgrep undo -
Follow a link in the help, and come backLinux, macOS, Windows
Ctrl-] Ctrl-o -
Run a shell command without leaving VimLinux, macOS
:!lsWindows:!dir -
Drop to a shell, then type exit to come backLinux, macOS, Windows
:sh -
Sort the whole file with the system sort commandLinux, macOS
:%!sort -
Format a JSON file neatly (needs jq installed)Linux, macOS, Windows
:%!jq . -
Count the words, lines and characters in the fileLinux, macOS, Windows
g Ctrl-g -
Show the last error messages againLinux, macOS, Windows
:messages -
Find out why Vim starts slowlyLinux, macOS, Windows
vim --startuptime startup.log
Bash scripting: Start a script
-
Get bash on Windows with Git Bash (run in PowerShell)Windows
winget install --id Git.Git -e -
Get a full Linux with bash on Windows using WSL (run in PowerShell as admin)Windows
wsl --install -
Start a script with the bash shebang lineLinux, macOS, Windows
#!/usr/bin/env bash -
Stop the script on errors, unset variables and failed pipesLinux, macOS, Windows
set -euo pipefail -
A good starting template for a new scriptLinux, macOS, Windows
#!/usr/bin/env bash set -euo pipefail script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" main() { echo "Running from $script_dir" } main "$@" -
Make a script executableLinux, macOS
chmod +x backup.sh -
Run a script in the current folderLinux, macOS, Windows
./backup.sh -
Run a script without making it executableLinux, macOS, Windows
bash backup.sh -
Run a script in the current shell, so its variables stay setLinux, macOS, Windows
source ./env.sh -
Check a script for syntax errors without running itLinux, macOS, Windows
bash -n backup.sh -
Show each command as the script runs it, to debugLinux, macOS, Windows
bash -x backup.sh -
Turn on debugging for just part of a scriptLinux, macOS, Windows
set -x cp "$src" "$dest" set +x -
Check a script for common mistakes with ShellCheckLinux, macOS, Windows
shellcheck backup.sh -
Install ShellCheckDebian, Ubuntu
sudo apt install shellcheckRed Hat, Fedorasudo dnf install ShellCheckAlpineapk add shellcheckmacOSbrew install shellcheckWindowswinget install --id koalaman.shellcheck -
Check which version of bash you haveLinux, macOS, Windows
bash --version -
Install a current bash on macOS, which includes bash 3.2macOS
brew install bash -
Get the folder the script is in, wherever it's run fromLinux, macOS, Windows
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -
Add a commentLinux, macOS, Windows
# Rotate logs older than 7 days
Bash scripting: Variables
-
Set a variable (no spaces around the =)Linux, macOS, Windows
name="web01" -
Use a variableLinux, macOS, Windows
echo "Connecting to $name" -
Use a variable right next to other textLinux, macOS, Windows
echo "${name}_backup.tar.gz" -
Quote variables so spaces in names don't break commandsLinux, macOS, Windows
cp "$file" "$dest" -
Save a command's output in a variableLinux, macOS, Windows
today=$(date +%F) -
Use a default value if a variable is empty or unsetLinux, macOS, Windows
port="${PORT:-8080}" -
Stop with an error if a variable isn't setLinux, macOS, Windows
: "${API_TOKEN:?API_TOKEN must be set}" -
Make a variable available to programs the script runsLinux, macOS, Windows
export AWS_PROFILE=prod -
Make a variable read-onlyLinux, macOS, Windows
readonly CONFIG=/etc/app.conf -
Delete a variableLinux, macOS, Windows
unset name -
Ask the user for a valueLinux, macOS, Windows
read -rp "Hostname: " host -
Ask for a password without showing itLinux, macOS, Windows
read -rsp "Password: " password echo -
Load settings from a file of KEY=value linesLinux, macOS, Windows
source ./config.env -
Get the exit code of the last command (0 means success)Linux, macOS, Windows
echo $? -
Get the script's name, its process ID and the last background job's IDLinux, macOS, Windows
echo "$0 $$ $!" -
Get the user, home folder and host nameLinux, macOS
echo "$USER $HOME $HOSTNAME"
Bash scripting: Arguments and options
-
Use the first and second argumentsLinux, macOS, Windows
src="$1" dest="$2" -
Pass on all the arguments, keeping each one wholeLinux, macOS, Windows
"$@" -
Count the argumentsLinux, macOS, Windows
echo $# -
Show usage and stop if an argument is missingLinux, macOS, Windows
if [[ $# -lt 1 ]]; then echo "Usage: $0 <host>" >&2 exit 1 fi -
Use a default if an argument isn't givenLinux, macOS, Windows
host="${1:-localhost}" -
Loop over every argumentLinux, macOS, Windows
for arg in "$@"; do echo "$arg" done -
Drop the first argument and move the rest downLinux, macOS, Windows
shift -
Read short options such as -v and -o file with getoptsLinux, macOS, Windows
verbose=false output=out.txt while getopts ":vo:" opt; do case $opt in v) verbose=true ;; o) output="$OPTARG" ;; *) echo "Usage: $0 [-v] [-o file]" >&2; exit 1 ;; esac done shift $((OPTIND - 1)) -
Read long options such as --dry-run and --env prodLinux, macOS, Windows
while [[ $# -gt 0 ]]; do case $1 in --dry-run) dry_run=true; shift ;; --env) env="$2"; shift 2 ;; -h|--help) echo "Usage: $0 [--dry-run] [--env name]"; exit 0 ;; *) echo "Unknown option: $1" >&2; exit 1 ;; esac done
Bash scripting: Conditions
-
If, elif and elseLinux, macOS, Windows
if [[ $count -gt 100 ]]; then echo "high" elif [[ $count -gt 10 ]]; then echo "medium" else echo "low" fi -
Check a file existsLinux, macOS, Windows
if [[ -f "$file" ]]; then echo "found" fi -
Check a folder existsLinux, macOS, Windows
if [[ -d "$dir" ]]; then echo "found" fi -
Do something only if a file or folder doesn't existLinux, macOS, Windows
if [[ ! -e "$path" ]]; then mkdir -p "$path" fi -
Check a file isn't emptyLinux, macOS, Windows
[[ -s "$file" ]] -
Check a file can be read, written or runLinux, macOS, Windows
[[ -r "$file" ]] [[ -w "$file" ]] [[ -x "$file" ]] -
Check one file is newer than anotherLinux, macOS, Windows
[[ "$src" -nt "$backup" ]] -
Check two strings are the same, or differentLinux, macOS, Windows
[[ "$env" == "prod" ]] [[ "$env" != "prod" ]] -
Check a string is empty, or not emptyLinux, macOS, Windows
[[ -z "$name" ]] [[ -n "$name" ]] -
Check a string matches a patternLinux, macOS, Windows
[[ "$file" == *.log ]] -
Check a string contains a wordLinux, macOS, Windows
[[ "$line" == *error* ]] -
Check a string matches a regular expressionLinux, macOS, Windows
if [[ "$ip" =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}$ ]]; then echo "looks like an IPv4 address" fi -
Compare numbersLinux, macOS, Windows
(( count > 10 )) [[ $count -gt 10 ]] -
Combine checks with and, orLinux, macOS, Windows
[[ -f "$file" && -r "$file" ]] [[ "$env" == dev || "$env" == test ]] -
Run a command only if the one before it workedLinux, macOS, Windows
mkdir -p backup && cp app.conf backup/ -
Run a command only if the one before it failedLinux, macOS
ping -c 1 web01 >/dev/null || echo "web01 is down" -
Check a command is installedLinux, macOS, Windows
if ! command -v jq >/dev/null; then echo "Install jq first" >&2 exit 1 fi -
Stop unless the script is run as rootLinux, macOS
if [[ $EUID -ne 0 ]]; then echo "Run this as root" >&2 exit 1 fi -
Check whether a command workedLinux, macOS, Windows
if grep -q "error" app.log; then echo "errors found" fi -
Choose between several values with caseLinux, macOS, Windows
case "$1" in start) start_app ;; stop) stop_app ;; restart) stop_app; start_app ;; *) echo "Usage: $0 {start|stop|restart}" >&2; exit 1 ;; esac -
Ask yes or no before carrying onLinux, macOS, Windows
read -rp "Continue? [y/N] " answer [[ "$answer" == [yY] ]] || exit 1
Bash scripting: Loops
-
Loop over a list of valuesLinux, macOS, Windows
for host in web01 web02 db01; do echo "$host" done -
Loop over filesLinux, macOS, Windows
for file in *.log; do gzip "$file" done -
Skip the loop when no files match, instead of using the pattern itselfLinux, macOS, Windows
shopt -s nullglob -
Loop over a range of numbersLinux, macOS, Windows
for i in {1..10}; do echo "$i" done -
Loop with a counterLinux, macOS, Windows
for ((i = 0; i < 5; i++)); do echo "$i" done -
Read a file line by lineLinux, macOS, Windows
while IFS= read -r line; do echo "$line" done < hosts.txt -
Loop over a command's output line by lineLinux, macOS
while IFS= read -r user; do echo "$user" done < <(cut -d: -f1 /etc/passwd) -
Loop over files from find, even with spaces in their namesLinux, macOS, Windows
while IFS= read -r -d '' file; do echo "$file" done < <(find . -name "*.conf" -print0) -
Loop while something is trueLinux, macOS, Windows
while [[ ! -f /tmp/ready ]]; do sleep 2 done -
Loop until a server answersLinux, macOS
until ping -c 1 web01 >/dev/null; do sleep 5 done -
Loop forever, every 60 secondsLinux, macOS, Windows
while true; do df -h / sleep 60 done -
Skip to the next item, or stop the loopLinux, macOS, Windows
continue break -
Retry a command up to 5 timesLinux, macOS, Windows
for attempt in {1..5}; do curl -fsS https://example.com && break echo "Attempt $attempt failed" >&2 sleep 5 done
Bash scripting: Functions
-
Write a function and call itLinux, macOS, Windows
greet() { echo "Hello $1" } greet web01 -
Keep a variable inside a functionLinux, macOS, Windows
count_lines() { local file="$1" wc -l < "$file" } -
Get a value back from a functionLinux, macOS, Windows
count_files() { find "$1" -type f | wc -l } total=$(count_files /var/log) -
Return success or failure from a functionLinux, macOS
is_up() { ping -c 1 "$1" >/dev/null 2>&1 } if is_up web01; then echo "up" fi -
Print timestamped log messagesLinux, macOS, Windows
log() { echo "$(date +"%F %T") $*" } log "Backup started" -
Print an error and stopLinux, macOS, Windows
die() { echo "Error: $*" >&2 exit 1 } [[ -f "$config" ]] || die "No config file" -
List the functions defined in the current shellLinux, macOS, Windows
declare -F
Bash scripting: Strings
-
Get the length of a stringLinux, macOS, Windows
echo "${#name}" -
Get part of a string (from position 0, 5 characters)Linux, macOS, Windows
echo "${name:0:5}" -
Replace the first match in a stringLinux, macOS, Windows
echo "${path/old/new}" -
Replace every match in a stringLinux, macOS, Windows
echo "${path//old/new}" -
Get the file name from a pathLinux, macOS, Windows
echo "${path##*/}" -
Get the folder from a pathLinux, macOS, Windows
echo "${path%/*}" -
Remove the extension from a file nameLinux, macOS, Windows
echo "${file%.*}" -
Get the extension of a file nameLinux, macOS, Windows
echo "${file##*.}" -
Remove text from the start of a stringLinux, macOS, Windows
echo "${version#v}" -
Make a string UPPERCASE or lowercase (bash 4 or later)Linux, macOS, Windows
echo "${name^^}" echo "${name,,}" -
Split a string on commas into an arrayLinux, macOS, Windows
IFS=, read -ra parts <<< "$csv" -
Print text in neat columnsLinux, macOS, Windows
printf '%-15s %5s\n' "$host" "$status" -
Print coloured textLinux, macOS, Windows
red=$'\e[31m' reset=$'\e[0m' echo "${red}Failed${reset}" -
Repeat a character to make a lineLinux, macOS, Windows
printf '%.0s-' {1..40}; echo
Bash scripting: Arrays
-
Make an arrayLinux, macOS, Windows
hosts=(web01 web02 db01) -
Add an item to an arrayLinux, macOS, Windows
hosts+=(db02) -
Get every item, each kept wholeLinux, macOS, Windows
"${hosts[@]}" -
Get one item (counting from 0)Linux, macOS, Windows
echo "${hosts[0]}" -
Count the itemsLinux, macOS, Windows
echo "${#hosts[@]}" -
Loop over an arrayLinux, macOS, Windows
for host in "${hosts[@]}"; do echo "$host" done -
Get a slice of an array (2 items from position 1)Linux, macOS, Windows
echo "${hosts[@]:1:2}" -
Remove an itemLinux, macOS, Windows
unset 'hosts[1]' -
Read a file's lines into an array (bash 4 or later)Linux, macOS, Windows
mapfile -t hosts < hosts.txt -
Join an array with commasLinux, macOS, Windows
(IFS=,; echo "${hosts[*]}") -
Make a key and value array (bash 4 or later)Linux, macOS, Windows
declare -A ports=([ssh]=22 [http]=80 [https]=443) -
Get a value by its keyLinux, macOS, Windows
echo "${ports[ssh]}" -
Loop over keys and valuesLinux, macOS, Windows
for service in "${!ports[@]}"; do echo "$service ${ports[$service]}" done
Bash scripting: Arithmetic
-
Do whole-number mathsLinux, macOS, Windows
total=$(( used + free )) -
Add 1 to a counterLinux, macOS, Windows
(( count++ )) -
Get the remainder of a divisionLinux, macOS, Windows
echo $(( 17 % 5 )) -
Raise to a powerLinux, macOS, Windows
echo $(( 2 ** 10 )) -
Do maths with decimalsLinux, macOS
echo "scale=2; 10 / 3" | bc -
Get a random number from 0 to 99Linux, macOS, Windows
echo $(( RANDOM % 100 )) -
Work out a percentageLinux, macOS, Windows
pct=$(( used * 100 / total ))
Bash scripting: Output and redirection
-
Write output to a file, replacing itLinux, macOS, Windows
echo "started" > run.log -
Add output to the end of a fileLinux, macOS, Windows
echo "finished" >> run.log -
Send errors to a fileLinux, macOS, Windows
./backup.sh 2> errors.log -
Send output and errors to the same fileLinux, macOS, Windows
./backup.sh > run.log 2>&1 -
Throw away all outputLinux, macOS, Windows
./backup.sh >/dev/null 2>&1 -
Print a message as an errorLinux, macOS, Windows
echo "Disk almost full" >&2 -
Show output on screen and save it to a fileLinux, macOS, Windows
./backup.sh | tee run.log -
Send everything the script prints to a log file as wellLinux, macOS, Windows
exec > >(tee -a /var/log/backup.log) 2>&1 -
Write a file from a block of text (here document)Linux, macOS, Windows
cat > app.conf <<EOF host=$host port=$port EOF -
Write a block of text without filling in variablesLinux, macOS, Windows
cat > run.sh <<'EOF' echo "$HOME is not expanded here" EOF -
Write to a file that needs rootLinux, macOS
echo "10.0.0.5 web01" | sudo tee -a /etc/hosts >/dev/null -
Pass a string to a command as its inputLinux, macOS, Windows
grep -c "," <<< "$csv" -
Compare the output of two commandsLinux, macOS, Windows
diff <(sort old.txt) <(sort new.txt)
Bash scripting: Errors, exit codes and cleanup
-
Stop the script with success, or with an error codeLinux, macOS, Windows
exit 0 exit 1 -
Let one command fail without stopping a set -e scriptLinux, macOS, Windows
rm old.tmp || true -
Get the exit code of each command in a pipeLinux, macOS, Windows
curl -s "$url" | jq .name echo "${PIPESTATUS[@]}" -
Make a temporary fileLinux, macOS, Windows
tmp=$(mktemp) -
Make a temporary folderLinux, macOS, Windows
tmpdir=$(mktemp -d) -
Always clean up when the script ends, even after an errorLinux, macOS, Windows
tmp=$(mktemp) trap 'rm -f "$tmp"' EXIT -
Run something when Ctrl-C is pressedLinux, macOS, Windows
trap 'echo "Stopped"; exit 130' INT -
Show the line number when a command failsLinux, macOS, Windows
trap 'echo "Failed at line $LINENO" >&2' ERR -
Stop a command if it runs longer than 30 secondsLinux, Windows
timeout 30 curl -s https://example.com -
Stop the script running twice at the same timeLinux
exec 9>/tmp/backup.lock flock -n 9 || { echo "Already running" >&2; exit 1; }
Bash scripting: Dates and times
-
Get today's date as 2026-11-19Linux, macOS, Windows
date +%F -
Put a timestamp in a file nameLinux, macOS, Windows
tar czf "backup-$(date +%Y%m%d-%H%M%S).tar.gz" /etc -
Get the time in seconds since 1970 (Unix time)Linux, macOS, Windows
date +%s -
Get yesterday's dateLinux, Windows
date -d yesterday +%FmacOSdate -v-1d +%F -
Show how long the script tookLinux, macOS, Windows
echo "Took ${SECONDS}s" -
Time a single commandLinux, macOS, Windows
time ./backup.sh -
Wait 5 secondsLinux, macOS, Windows
sleep 5
Bash scripting: Background jobs and parallel tasks
-
Run a command in the backgroundLinux, macOS, Windows
./backup.sh & -
Run several commands at once, then wait for them allLinux, macOS
rsync -a /data web01:/data & rsync -a /data web02:/data & wait -
Wait for one background job and get its exit codeLinux, macOS, Windows
./backup.sh & pid=$! wait "$pid" echo "Exit code $?" -
Run a command on several servers over SSHLinux, macOS, Windows
for host in web01 web02; do ssh "$host" "uptime" done -
Wait until a port is openLinux, macOS
until nc -z localhost 5432; do sleep 1 done -
Keep a script running after you log outLinux, macOS
nohup ./long-job.sh > job.log 2>&1 & -
Run a script every night at 2am with cron (add with crontab -e)Linux, macOS
0 2 * * * /opt/scripts/backup.sh >> /var/log/backup.log 2>&1
Bash scripting: Handy script snippets
-
Back up a file with the date before changing itLinux, macOS, Windows
cp "$file" "$file.$(date +%F).bak" -
Delete files older than 7 daysLinux, macOS, Windows
find /var/backups -name "*.tar.gz" -mtime +7 -deleteWarning: Run it without -delete first to see what it would remove.
-
Warn when the root disk is over 90% fullLinux
usage=$(df --output=pcent / | tail -1 | tr -dc '0-9') if (( usage > 90 )); then echo "Disk is ${usage}% full" >&2 fi -
Check a website answers with HTTP 200Linux, macOS, Windows
code=$(curl -s -o /dev/null -w "%{http_code}" https://example.com) [[ "$code" == 200 ]] || echo "Site returned $code" -
Read a value from a JSON API with jqLinux, macOS, Windows
name=$(curl -s https://api.github.com/repos/vim/vim | jq -r .full_name) -
Check a list of hosts and report which are downLinux, macOS
while IFS= read -r host; do ping -c 1 "$host" >/dev/null || echo "$host is down" done < hosts.txt -
Make a passwordLinux, macOS, Windows
openssl rand -base64 24 -
Rename every .txt file to .mdLinux, macOS, Windows
for file in *.txt; do mv -- "$file" "${file%.txt}.md" done
Networking: Your connection
-
Show your IP addressesLinux
ip -br addrmacOSipconfig getifaddr en0Windowsipconfig -
Show full details for every network interfaceLinux
ip addr showmacOSifconfigWindowsipconfig /all -
Show MAC addressesLinux
ip link showmacOSifconfig en0 etherWindowsgetmac /v -
Show the default gatewayLinux
ip route show defaultmacOSroute -n get defaultWindowsipconfig | findstr /i "Gateway" -
Show the DNS servers in useLinux
resolvectl statusmacOSscutil --dns | grep nameserverWindowsipconfig /all | findstr /i /c:"DNS Servers" -
Show your public IP addressLinux, macOS, Windows
curl ifconfig.me -
Get a new IP address from DHCPmacOS
sudo ipconfig set en0 DHCPWindowsipconfig /release && ipconfig /renew -
Show traffic and error counts for each interfaceLinux
ip -s linkmacOSnetstat -iWindowsnetstat -e -
Show the link speed of each adapterLinux
ethtool eth0Windowspowershell -c "Get-NetAdapter | Select-Object Name, LinkSpeed"
Networking: Ping and traceroute
-
Check you can reach a hostLinux, macOS
ping -c 4 8.8.8.8Windowsping 8.8.8.8 -
Ping a host until you press Ctrl+CLinux, macOS
ping 8.8.8.8Windowsping -t 8.8.8.8 -
Ping over IPv6Linux
ping -6 -c 4 google.commacOSping6 -c 4 google.comWindowsping -6 google.com -
Ping with larger packetsLinux, macOS
ping -c 4 -s 1400 8.8.8.8Windowsping -l 1400 8.8.8.8 -
Find the largest packet that gets through without splitting (MTU)Linux
ping -M do -s 1472 -c 4 8.8.8.8macOSping -D -s 1472 -c 4 8.8.8.8Windowsping -f -l 1472 8.8.8.8 -
Trace the route to a hostLinux, macOS
traceroute 8.8.8.8Windowstracert 8.8.8.8 -
Trace the route without looking up namesLinux, macOS
traceroute -n 8.8.8.8Windowstracert -d 8.8.8.8 -
Trace the route over TCP to get past firewalls that block pingLinux
sudo traceroute -T -p 443 example.com -
Find where packets are being lost along the routeLinux, macOS
mtr 8.8.8.8Windowspathping 8.8.8.8
Networking: Ports and connections
-
Test whether a TCP port is openLinux, macOS
nc -zv example.com 443Windowspowershell -c "Test-NetConnection example.com -Port 443" -
List listening ports and the programs using themLinux
sudo ss -tulpnmacOSsudo lsof -iTCP -sTCP:LISTEN -n -PWindowsnetstat -ano | findstr LISTENING -
Find what's using a portLinux, macOS
sudo lsof -i :8080Windowsnetstat -ano | findstr :8080 -
List all connectionsLinux
ss -tunamacOS, Windowsnetstat -an -
Show connection statisticsLinux
ss -smacOS, Windowsnetstat -s -
Watch live network useLinux
sudo iftop -i eth0macOSnettopWindowsresmon -
Start a bandwidth test serverLinux, macOS, Windows
iperf3 -s -
Test bandwidth to an iperf3 serverLinux, macOS, Windows
iperf3 -c 192.168.1.10
Networking: DNS
-
Look up a domain's IP addressLinux, macOS
dig example.com +shortWindowsnslookup example.com -
Show the full DNS answerLinux, macOS
dig example.comWindowspowershell -c "Resolve-DnsName example.com" -
Look up a domain's mail (MX) recordsLinux, macOS
dig example.com MX +shortWindowsnslookup -type=mx example.com -
Look up a domain's TXT records, such as SPFLinux, macOS
dig example.com TXT +shortWindowsnslookup -type=txt example.com -
Look up a domain's name serversLinux, macOS
dig example.com NS +shortWindowsnslookup -type=ns example.com -
Look up a domain's IPv6 (AAAA) addressLinux, macOS
dig example.com AAAA +shortWindowsnslookup -type=aaaa example.com -
Look up where a name points (CNAME)Linux, macOS
dig www.example.com CNAME +shortWindowsnslookup -type=cname www.example.com -
Look up a domain using a specific DNS serverLinux, macOS
dig @1.1.1.1 example.com +shortWindowsnslookup example.com 1.1.1.1 -
Look up the name for an IP addressLinux, macOS
dig -x 8.8.8.8 +shortWindowsnslookup 8.8.8.8 -
Follow a lookup from the root servers downLinux, macOS
dig example.com +trace -
Clear the DNS cacheLinux
sudo resolvectl flush-cachesmacOSsudo dscacheutil -flushcache; sudo killall -HUP mDNSResponderWindowsipconfig /flushdns -
Show the DNS cacheWindows
ipconfig /displaydns -
Edit the hosts fileLinux, macOS
sudo nano /etc/hostsWindowsnotepad C:\Windows\System32\drivers\etc\hosts
Networking: Routes and ARP
-
Show the routing tableLinux
ip routemacOSnetstat -rnWindowsroute print -
Show which route an address usesLinux
ip route get 8.8.8.8macOSroute -n get 8.8.8.8Windowspowershell -c "Find-NetRoute -RemoteIPAddress 8.8.8.8" -
Add a routeLinux
sudo ip route add 10.20.0.0/16 via 192.168.1.254macOSsudo route -n add -net 10.20.0.0/16 192.168.1.254Windowsroute add 10.20.0.0 mask 255.255.0.0 192.168.1.254 -
Add a route that stays after a restartWindows
route -p add 10.20.0.0 mask 255.255.0.0 192.168.1.254 -
Delete a routeLinux
sudo ip route del 10.20.0.0/16macOSsudo route -n delete -net 10.20.0.0/16Windowsroute delete 10.20.0.0 -
Show the ARP tableLinux
ip neighmacOS, Windowsarp -a -
Clear the ARP cacheLinux
sudo ip neigh flush allmacOSsudo arp -a -dWindowsnetsh interface ip delete arpcache
Networking: Wi-Fi
-
Show your current Wi-Fi connectionLinux
nmcli device wifi showmacOSsystem_profiler SPAirPortDataTypeWindowsnetsh wlan show interfaces -
List Wi-Fi networks in rangeLinux
nmcli device wifi listWindowsnetsh wlan show networks mode=bssid
Networking: Web requests with curl
-
Check a website responds and show its headersLinux, macOS, Windows
curl -I https://example.com -
Follow redirectsLinux, macOS, Windows
curl -L https://example.com -
Download a fileLinux, macOS, Windows
curl -LO https://example.com/file.zip -
Download a file under a different nameLinux, macOS, Windows
curl -L -o setup.zip https://example.com/file.zip -
Time how long a request takesLinux, macOS
curl -o /dev/null -s -w "%{time_total}\n" https://example.comWindowscurl -o NUL -s -w "%{time_total}\n" https://example.com -
Test your download speedLinux, macOS
curl -o /dev/null https://speed.cloudflare.com/__down?bytes=100000000Windowscurl -o NUL https://speed.cloudflare.com/__down?bytes=100000000 -
Send JSON to an APILinux, macOS
curl -X POST -H "Content-Type: application/json" -d '{"name":"test"}' https://api.example.com/itemsWindowscurl -X POST -H "Content-Type: application/json" -d "{\"name\":\"test\"}" https://api.example.com/items -
Call an API with a tokenLinux, macOS
curl -H "Authorization: Bearer $TOKEN" https://api.example.com/meWindowscurl -H "Authorization: Bearer %TOKEN%" https://api.example.com/me -
Test a site on a new IP address before changing DNSLinux, macOS, Windows
curl --resolve example.com:443:203.0.113.10 https://example.com -
Show the TLS handshake and certificateLinux, macOS, Windows
curl -vI https://example.com -
Show when a site's certificate expiresLinux, macOS
echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -enddate
Networking: Packet capture
-
Capture packets on an interfaceLinux
sudo tcpdump -i eth0macOSsudo tcpdump -i en0Windowspktmon start --capture -
Capture packets to one host and portLinux
sudo tcpdump -i any host 192.168.1.20 and port 443macOSsudo tcpdump -i en0 host 192.168.1.20 and port 443 -
Save a capture to open in WiresharkLinux
sudo tcpdump -i eth0 -w capture.pcapmacOSsudo tcpdump -i en0 -w capture.pcapWindowspktmon stop && pktmon etl2pcap PktMon.etl --out capture.pcapng
Networking: SSH tunnels
-
Reach a remote service through SSH on a local portLinux, macOS, Windows
ssh -L 8080:localhost:80 user@server01 -
Share a local service on a port of the remote serverLinux, macOS, Windows
ssh -R 9000:localhost:3000 user@server01 -
Use a server as a SOCKS proxyLinux, macOS, Windows
ssh -D 1080 user@server01 -
Connect through a jump hostLinux, macOS, Windows
ssh -J [email protected] user@server01
Cisco IOS: Modes and getting around
-
Enter privileged EXEC modeCisco IOS · User EXEC (>)
enable -
Leave privileged EXEC modeCisco IOS · Privileged EXEC (#)
disable -
Enter global configuration modeCisco IOS · Privileged EXEC (#)
configure terminal -
Go back one levelCisco IOS · Global config (config)#
exit -
Go straight back to privileged EXEC modeCisco IOS · Global config (config)#
end -
Run a show command without leaving config modeCisco IOS · Global config (config)#
do show ip interface brief -
List the commands you can use hereCisco IOS · Privileged EXEC (#)
? -
List the options for a commandCisco IOS · Privileged EXEC (#)
show ? -
Show the commands you've typedCisco IOS · Privileged EXEC (#)
show history -
Stop long output pausing at every pageCisco IOS · Privileged EXEC (#)
terminal length 0 -
Show log messages in an SSH sessionCisco IOS · Privileged EXEC (#)
terminal monitor -
Stop log messages interrupting what you typeCisco IOS · Global config (config)#
line console 0 logging synchronous -
Stop mistyped commands being looked up as hostnamesCisco IOS · Global config (config)#
no ip domain-lookup -
Remove a setting by putting no in front of itCisco IOS · Global config (config)#
no banner motd
Cisco IOS: Filtering output
-
Show only lines that contain some textCisco IOS · Privileged EXEC (#)
show running-config | include hostname -
Hide lines that contain some textCisco IOS · Privileged EXEC (#)
show ip interface brief | exclude unassigned -
Show output from the first match onwardsCisco IOS · Privileged EXEC (#)
show running-config | begin line vty -
Show one section of the configCisco IOS · Privileged EXEC (#)
show running-config | section interface -
Show one interface's configCisco IOS · Privileged EXEC (#)
show running-config interface GigabitEthernet0/1
Cisco IOS: Basic setup
-
Set the device's nameCisco IOS · Global config (config)#
hostname SW1 -
Set the enable passwordCisco IOS · Global config (config)#
enable secret MyEnablePassword -
Create a local admin userCisco IOS · Global config (config)#
username admin privilege 15 secret MyPassword -
Hide plain-text passwords in the configCisco IOS · Global config (config)#
service password-encryption -
Set a login bannerCisco IOS · Global config (config)#
banner motd # Authorised access only # -
Require a local login on the console, with a 10-minute timeoutCisco IOS · Global config (config)#
line console 0 login local exec-timeout 10 0 logging synchronous -
Set the domain nameCisco IOS · Global config (config)#
ip domain-name corp.example.com -
Set a DNS serverCisco IOS · Global config (config)#
ip name-server 1.1.1.1 -
Give a switch a management IP addressCisco IOS · Global config (config)#
interface Vlan1 ip address 192.168.1.10 255.255.255.0 no shutdown -
Set a switch's default gatewayCisco IOS · Global config (config)#
ip default-gateway 192.168.1.1 -
Set the time zoneCisco IOS · Global config (config)#
clock timezone GMT 0 -
Turn on Irish summer timeCisco IOS · Global config (config)#
clock summer-time IST recurring last Sun Mar 1:00 last Sun Oct 2:00 -
Get the time from an NTP serverCisco IOS · Global config (config)#
ntp server 0.pool.ntp.org -
Set the clock by handCisco IOS · Privileged EXEC (#)
clock set 14:30:00 13 November 2026 -
Show the timeCisco IOS · Privileged EXEC (#)
show clock -
Show whether the clock is synced with NTPCisco IOS · Privileged EXEC (#)
show ntp status -
Show NTP servers and their stateCisco IOS · Privileged EXEC (#)
show ntp associations
Cisco IOS: Save and back up the config
-
Save the running configCisco IOS · Privileged EXEC (#)
copy running-config startup-config -
Save the running config (short version)Cisco IOS · Privileged EXEC (#)
write memory -
Show the running configCisco IOS · Privileged EXEC (#)
show running-config -
Show the saved configCisco IOS · Privileged EXEC (#)
show startup-config -
Show what's changed since the last saveCisco IOS · Privileged EXEC (#)
show archive config differences nvram:startup-config system:running-config -
Back up the config to a TFTP serverCisco IOS · Privileged EXEC (#)
copy running-config tftp://192.168.1.5/SW1.cfg -
Back up the config to flashCisco IOS · Privileged EXEC (#)
copy running-config flash:SW1-backup.cfg -
Load a config from a TFTP serverCisco IOS · Privileged EXEC (#)
copy tftp://192.168.1.5/SW1.cfg running-configWarning: Merges with the current config rather than replacing it.
-
Replace the running config with a saved oneCisco IOS · Privileged EXEC (#)
configure replace flash:SW1-backup.cfgWarning: Removes anything not in the saved file, which can cut off your connection.
-
Keep an archive of the config every time you saveCisco IOS · Global config (config)#
archive path flash:archive write-memory time-period 1440 -
List archived configsCisco IOS · Privileged EXEC (#)
show archive -
Erase the saved configCisco IOS · Privileged EXEC (#)
write eraseWarning: The device starts with a blank config next time it reloads.
-
Delete a switch's VLAN databaseCisco IOS · Privileged EXEC (#)
delete flash:vlan.datWarning: Removes every VLAN when the switch reloads.
Cisco IOS: Reload and files
-
Reload in 10 minutes unless you cancelCisco IOS · Privileged EXEC (#)
reload in 10 -
Cancel a scheduled reloadCisco IOS · Privileged EXEC (#)
reload cancel -
Reload nowCisco IOS · Privileged EXEC (#)
reloadWarning: Drops all traffic through the device while it restarts.
-
List the files in flashCisco IOS · Privileged EXEC (#)
dir flash: -
Show a file's contentsCisco IOS · Privileged EXEC (#)
more flash:SW1-backup.cfg -
Delete a file from flashCisco IOS · Privileged EXEC (#)
delete flash:old.cfgWarning: Deletes the file and can't be undone.
-
Copy a software image from a TFTP serverCisco IOS · Privileged EXEC (#)
copy tftp://192.168.1.5/image.bin flash: -
Check a software image's MD5 hashCisco IOS · Privileged EXEC (#)
verify /md5 flash:image.bin -
Boot from a specific imageCisco IOS · Global config (config)#
boot system flash:image.bin -
Let the device receive files over SCPCisco IOS · Global config (config)#
ip scp server enable
Cisco IOS: Show and verify
-
Show the model, software version and uptimeCisco IOS · Privileged EXEC (#)
show version -
Show interfaces, IP addresses and statusCisco IOS · Privileged EXEC (#)
show ip interface brief -
Show switch ports, VLANs, speed and duplexCisco IOS · Privileged EXEC (#)
show interfaces status -
Show one interface's details and countersCisco IOS · Privileged EXEC (#)
show interfaces GigabitEthernet0/1 -
Show interface descriptionsCisco IOS · Privileged EXEC (#)
show interfaces description -
Show interface error countersCisco IOS · Privileged EXEC (#)
show interfaces counters errors -
Show hardware, modules and serial numbersCisco IOS · Privileged EXEC (#)
show inventory -
Show CPU use, busiest processes firstCisco IOS · Privileged EXEC (#)
show processes cpu sorted -
Show CPU use over timeCisco IOS · Privileged EXEC (#)
show processes cpu history -
Show memory useCisco IOS · Privileged EXEC (#)
show memory statistics -
Show temperature, fans and power suppliesCisco IOS · Privileged EXEC (#)
show environment all -
Show the logCisco IOS · Privileged EXEC (#)
show logging -
Show neighbouring Cisco devicesCisco IOS · Privileged EXEC (#)
show cdp neighbors -
Show neighbouring Cisco devices in detail, with IP addressesCisco IOS · Privileged EXEC (#)
show cdp neighbors detail -
Show neighbouring devices using LLDPCisco IOS · Privileged EXEC (#)
show lldp neighbors -
Show the MAC address tableCisco IOS · Privileged EXEC (#)
show mac address-table -
Find the port a MAC address is onCisco IOS · Privileged EXEC (#)
show mac address-table address aabb.cc00.0100 -
Show the MAC addresses on a portCisco IOS · Privileged EXEC (#)
show mac address-table interface GigabitEthernet0/1 -
Show the ARP tableCisco IOS · Privileged EXEC (#)
show ip arp -
Find the IP address for a MAC addressCisco IOS · Privileged EXEC (#)
show ip arp | include aabb.cc00.0100 -
Show who's logged inCisco IOS · Privileged EXEC (#)
show users -
Show the licence summaryCisco IOS · Privileged EXEC (#)
show license summary -
Collect everything for a support caseCisco IOS · Privileged EXEC (#)
show tech-support
Cisco IOS: Interfaces
-
Add a description to an interfaceCisco IOS · Global config (config)#
interface GigabitEthernet0/1 description Uplink to core -
Turn an interface onCisco IOS · Global config (config)#
interface GigabitEthernet0/1 no shutdown -
Turn an interface offCisco IOS · Global config (config)#
interface GigabitEthernet0/1 shutdownWarning: Disconnects whatever is plugged into the port.
-
Turn an interface off and on againCisco IOS · Global config (config)#
interface GigabitEthernet0/1 shutdown no shutdown -
Configure several interfaces at onceCisco IOS · Global config (config)#
interface range GigabitEthernet0/1 - 24 description User ports -
Set an interface's speed and duplexCisco IOS · Global config (config)#
interface GigabitEthernet0/1 speed 1000 duplex full -
Give a router interface an IP addressCisco IOS · Global config (config)#
interface GigabitEthernet0/0 ip address 192.168.1.1 255.255.255.0 no shutdown -
Get an interface's IP address from DHCPCisco IOS · Global config (config)#
interface GigabitEthernet0/0 ip address dhcp no shutdown -
Add a second IP address to an interfaceCisco IOS · Global config (config)#
interface GigabitEthernet0/0 ip address 10.0.0.1 255.255.255.0 secondary -
Create a loopback interfaceCisco IOS · Global config (config)#
interface Loopback0 ip address 10.255.255.1 255.255.255.255 -
Reset an interface to its defaultsCisco IOS · Global config (config)#
default interface GigabitEthernet0/1Warning: Removes all of the interface's settings.
-
Reset an interface's countersCisco IOS · Privileged EXEC (#)
clear counters GigabitEthernet0/1 -
List ports shut down by an error (err-disabled)Cisco IOS · Privileged EXEC (#)
show interfaces status err-disabled -
Bring err-disabled ports back automatically after 5 minutesCisco IOS · Global config (config)#
errdisable recovery cause all errdisable recovery interval 300 -
Show Power over Ethernet use per portCisco IOS · Privileged EXEC (#)
show power inline -
Turn off Power over Ethernet on a portCisco IOS · Global config (config)#
interface GigabitEthernet1/0/1 power inline never
Cisco IOS: VLANs and trunks
-
Create a VLAN and name itCisco IOS · Global config (config)#
vlan 10 name Users -
List VLANs and their portsCisco IOS · Privileged EXEC (#)
show vlan brief -
Delete a VLANCisco IOS · Global config (config)#
no vlan 10Warning: Ports in the VLAN stop passing traffic until you move them.
-
Make a port an access port in a VLANCisco IOS · Global config (config)#
interface GigabitEthernet0/1 switchport mode access switchport access vlan 10 -
Add a voice VLAN for an IP phoneCisco IOS · Global config (config)#
interface GigabitEthernet0/1 switchport mode access switchport access vlan 10 switchport voice vlan 20 -
Make a port a trunk carrying some VLANsCisco IOS · Global config (config)#
interface GigabitEthernet0/24 switchport mode trunk switchport trunk allowed vlan 10,20,30Warning: Replaces the trunk's allowed VLAN list. Use add to include one more without removing the others.
-
Set trunk encapsulation on switches that ask for itCisco IOS · Global config (config)#
interface GigabitEthernet0/24 switchport trunk encapsulation dot1q -
Add a VLAN to a trunkCisco IOS · Global config (config)#
interface GigabitEthernet0/24 switchport trunk allowed vlan add 40 -
Remove a VLAN from a trunkCisco IOS · Global config (config)#
interface GigabitEthernet0/24 switchport trunk allowed vlan remove 40 -
Change a trunk's native VLANCisco IOS · Global config (config)#
interface GigabitEthernet0/24 switchport trunk native vlan 99 -
Stop a port negotiating trunking (DTP)Cisco IOS · Global config (config)#
interface GigabitEthernet0/24 switchport nonegotiate -
Show trunk ports and their VLANsCisco IOS · Privileged EXEC (#)
show interfaces trunk -
Show a port's VLAN and trunk settingsCisco IOS · Privileged EXEC (#)
show interfaces GigabitEthernet0/1 switchport -
Route between VLANs on a Layer 3 switchCisco IOS · Global config (config)#
ip routing interface Vlan10 ip address 192.168.10.1 255.255.255.0 no shutdown -
Route between VLANs on a router (router on a stick)Cisco IOS · Global config (config)#
interface GigabitEthernet0/0.10 encapsulation dot1Q 10 ip address 192.168.10.1 255.255.255.0 -
Park unused ports in an unused VLAN and shut themCisco IOS · Global config (config)#
interface range GigabitEthernet0/20 - 23 switchport mode access switchport access vlan 999 shutdown -
Stop the switch sharing VLANs with VTPCisco IOS · Global config (config)#
vtp mode transparent -
Show VTP settingsCisco IOS · Privileged EXEC (#)
show vtp status
Cisco IOS: Spanning tree
-
Show spanning treeCisco IOS · Privileged EXEC (#)
show spanning-tree -
Show spanning tree for one VLANCisco IOS · Privileged EXEC (#)
show spanning-tree vlan 10 -
Show a spanning tree summaryCisco IOS · Privileged EXEC (#)
show spanning-tree summary -
Use Rapid PVST+Cisco IOS · Global config (config)#
spanning-tree mode rapid-pvst -
Make this switch the root for a VLANCisco IOS · Global config (config)#
spanning-tree vlan 10 root primary -
Set a switch's spanning tree priority for a VLANCisco IOS · Global config (config)#
spanning-tree vlan 10 priority 4096 -
Turn on PortFast for a port with a PC or server on itCisco IOS · Global config (config)#
interface GigabitEthernet0/1 spanning-tree portfast -
Turn on BPDU guard for a portCisco IOS · Global config (config)#
interface GigabitEthernet0/1 spanning-tree bpduguard enable -
Turn on PortFast for every access portCisco IOS · Global config (config)#
spanning-tree portfast default -
Turn on BPDU guard for every PortFast portCisco IOS · Global config (config)#
spanning-tree portfast bpduguard default -
Stop a port becoming the path to a new root (root guard)Cisco IOS · Global config (config)#
interface GigabitEthernet0/24 spanning-tree guard root
Cisco IOS: EtherChannel
-
Bundle two ports with LACPCisco IOS · Global config (config)#
interface range GigabitEthernet0/23 - 24 channel-group 1 mode active -
Make a port-channel a trunkCisco IOS · Global config (config)#
interface Port-channel1 switchport mode trunk -
Balance traffic by source and destination IPCisco IOS · Global config (config)#
port-channel load-balance src-dst-ip -
Show EtherChannel statusCisco IOS · Privileged EXEC (#)
show etherchannel summary -
Show LACP neighboursCisco IOS · Privileged EXEC (#)
show lacp neighbor
Cisco IOS: Switch security
-
Allow up to 2 MAC addresses on a port and remember themCisco IOS · Global config (config)#
interface GigabitEthernet0/1 switchport mode access switchport port-security switchport port-security maximum 2 switchport port-security violation restrict switchport port-security mac-address sticky -
Show port security for every portCisco IOS · Privileged EXEC (#)
show port-security -
Show port security for one portCisco IOS · Privileged EXEC (#)
show port-security interface GigabitEthernet0/1 -
Turn on DHCP snooping and trust the uplinkCisco IOS · Global config (config)#
ip dhcp snooping ip dhcp snooping vlan 10 interface GigabitEthernet0/24 ip dhcp snooping trust -
Show DHCP snooping bindingsCisco IOS · Privileged EXEC (#)
show ip dhcp snooping binding -
Turn on Dynamic ARP Inspection and trust the uplinkCisco IOS · Global config (config)#
ip arp inspection vlan 10 interface GigabitEthernet0/24 ip arp inspection trust -
Limit broadcast traffic on a portCisco IOS · Global config (config)#
interface GigabitEthernet0/1 storm-control broadcast level 5.00 -
Stop sending CDP on a portCisco IOS · Global config (config)#
interface GigabitEthernet0/1 no cdp enable -
Turn off CDP everywhereCisco IOS · Global config (config)#
no cdp run -
Turn on LLDPCisco IOS · Global config (config)#
lldp run -
Turn off the web interfaceCisco IOS · Global config (config)#
no ip http server no ip http secure-server
Cisco IOS: Static routing
-
Turn on routing on a Layer 3 switchCisco IOS · Global config (config)#
ip routing -
Add a static routeCisco IOS · Global config (config)#
ip route 10.20.0.0 255.255.0.0 192.168.1.254 -
Add a default routeCisco IOS · Global config (config)#
ip route 0.0.0.0 0.0.0.0 203.0.113.1 -
Add a backup default route used only if the main one failsCisco IOS · Global config (config)#
ip route 0.0.0.0 0.0.0.0 198.51.100.1 250 -
Drop traffic to a networkCisco IOS · Global config (config)#
ip route 10.99.0.0 255.255.0.0 Null0 -
Remove a static routeCisco IOS · Global config (config)#
no ip route 10.20.0.0 255.255.0.0 192.168.1.254 -
Show the routing tableCisco IOS · Privileged EXEC (#)
show ip route -
Show static routesCisco IOS · Privileged EXEC (#)
show ip route static -
Show which route a destination usesCisco IOS · Privileged EXEC (#)
show ip route 10.20.1.5 -
Show which routing protocols are runningCisco IOS · Privileged EXEC (#)
show ip protocols
Cisco IOS: IPv6
-
Turn on IPv6 routingCisco IOS · Global config (config)#
ipv6 unicast-routing -
Give an interface an IPv6 addressCisco IOS · Global config (config)#
interface GigabitEthernet0/0 ipv6 address 2001:db8:1::1/64 -
Add an IPv6 default routeCisco IOS · Global config (config)#
ipv6 route ::/0 2001:db8::1 -
Show IPv6 interfacesCisco IOS · Privileged EXEC (#)
show ipv6 interface brief -
Show the IPv6 routing tableCisco IOS · Privileged EXEC (#)
show ipv6 route
Cisco IOS: OSPF
-
Start OSPF and add a network to area 0Cisco IOS · Global config (config)#
router ospf 1 router-id 1.1.1.1 network 192.168.1.0 0.0.0.255 area 0 -
Turn on OSPF on an interfaceCisco IOS · Global config (config)#
interface GigabitEthernet0/0 ip ospf 1 area 0 -
Stop OSPF on all interfaces except the ones you nameCisco IOS · Global config (config)#
router ospf 1 passive-interface default no passive-interface GigabitEthernet0/0 -
Advertise a default route into OSPFCisco IOS · Global config (config)#
router ospf 1 default-information originate -
Set an interface's OSPF costCisco IOS · Global config (config)#
interface GigabitEthernet0/0 ip ospf cost 10 -
Treat a link as point-to-point in OSPFCisco IOS · Global config (config)#
interface GigabitEthernet0/0 ip ospf network point-to-point -
Turn on OSPF authentication on an interfaceCisco IOS · Global config (config)#
interface GigabitEthernet0/0 ip ospf authentication message-digest ip ospf message-digest-key 1 md5 MyOspfKey -
Show OSPF neighboursCisco IOS · Privileged EXEC (#)
show ip ospf neighbor -
Show OSPF interfacesCisco IOS · Privileged EXEC (#)
show ip ospf interface brief -
Show routes learned from OSPFCisco IOS · Privileged EXEC (#)
show ip route ospf -
Show the OSPF databaseCisco IOS · Privileged EXEC (#)
show ip ospf database -
Restart OSPFCisco IOS · Privileged EXEC (#)
clear ip ospf processWarning: Drops every OSPF neighbour while they reconnect.
Cisco IOS: BGP
-
Start BGP and add a neighbourCisco IOS · Global config (config)#
router bgp 65001 neighbor 203.0.113.1 remote-as 65000 -
Advertise a network in BGPCisco IOS · Global config (config)#
router bgp 65001 network 198.51.100.0 mask 255.255.255.0 -
Show BGP neighbours and their stateCisco IOS · Privileged EXEC (#)
show ip bgp summary -
Show the BGP tableCisco IOS · Privileged EXEC (#)
show ip bgp -
Refresh routes from a BGP neighbour without dropping itCisco IOS · Privileged EXEC (#)
clear ip bgp 203.0.113.1 soft
Cisco IOS: Gateway redundancy (HSRP)
-
Share a gateway address between two switchesCisco IOS · Global config (config)#
interface Vlan10 standby 1 ip 192.168.10.1 standby 1 priority 110 standby 1 preempt -
Show HSRP statusCisco IOS · Privileged EXEC (#)
show standby brief
Cisco IOS: Access lists
-
Create a standard ACL that allows a networkCisco IOS · Global config (config)#
access-list 10 permit 192.168.1.0 0.0.0.255 -
Create an ACL that blocks Telnet and allows everything elseCisco IOS · Global config (config)#
ip access-list extended BLOCK-TELNET deny tcp any any eq 23 permit ip any any -
Create an ACL that only allows web traffic to a serverCisco IOS · Global config (config)#
ip access-list extended WEB-IN permit tcp any host 192.168.1.20 eq 443 permit tcp any host 192.168.1.20 eq 80 deny ip any any log -
Apply an ACL to traffic coming into an interfaceCisco IOS · Global config (config)#
interface GigabitEthernet0/0 ip access-group WEB-IN inWarning: Anything the ACL doesn't permit is blocked. Make sure you have another way in, such as the console, before you apply it over SSH.
-
Remove an ACL from an interfaceCisco IOS · Global config (config)#
interface GigabitEthernet0/0 no ip access-group WEB-IN in -
Only allow SSH from the management networkCisco IOS · Global config (config)#
access-list 10 permit 192.168.1.0 0.0.0.255 line vty 0 15 access-class 10 inWarning: Make sure you have another way in, such as the console, before you apply it over SSH.
-
Insert a line into an ACL at a set positionCisco IOS · Global config (config)#
ip access-list extended WEB-IN 15 permit tcp any host 192.168.1.20 eq 8443 -
Delete one line from an ACLCisco IOS · Global config (config)#
ip access-list extended WEB-IN no 15 -
Renumber an ACL's lines in steps of 10Cisco IOS · Global config (config)#
ip access-list resequence WEB-IN 10 10 -
Show ACLs and how many packets each line matchedCisco IOS · Privileged EXEC (#)
show ip access-lists -
Show which ACLs are applied to an interfaceCisco IOS · Privileged EXEC (#)
show ip interface GigabitEthernet0/0 | include access list -
Reset ACL match countersCisco IOS · Privileged EXEC (#)
clear ip access-list counters
Cisco IOS: NAT
-
Mark the inside and outside interfaces for NATCisco IOS · Global config (config)#
interface GigabitEthernet0/1 ip nat inside interface GigabitEthernet0/0 ip nat outside -
Share one public IP address with the inside network (PAT)Cisco IOS · Global config (config)#
access-list 1 permit 192.168.1.0 0.0.0.255 ip nat inside source list 1 interface GigabitEthernet0/0 overload -
Map a public IP address to an inside serverCisco IOS · Global config (config)#
ip nat inside source static 192.168.1.20 203.0.113.10 -
Forward a port to an inside serverCisco IOS · Global config (config)#
ip nat inside source static tcp 192.168.1.20 443 interface GigabitEthernet0/0 443 -
Show NAT translationsCisco IOS · Privileged EXEC (#)
show ip nat translations -
Show NAT statisticsCisco IOS · Privileged EXEC (#)
show ip nat statistics -
Clear all NAT translationsCisco IOS · Privileged EXEC (#)
clear ip nat translation *Warning: Drops connections that are using NAT right now.
Cisco IOS: DHCP server and relay
-
Keep some addresses out of DHCPCisco IOS · Global config (config)#
ip dhcp excluded-address 192.168.1.1 192.168.1.20 -
Create a DHCP poolCisco IOS · Global config (config)#
ip dhcp pool USERS network 192.168.1.0 255.255.255.0 default-router 192.168.1.1 dns-server 1.1.1.1 8.8.8.8 lease 7 -
Always give a device the same addressCisco IOS · Global config (config)#
ip dhcp pool PRINTER host 192.168.1.50 255.255.255.0 hardware-address aabb.cc00.0100 -
Forward DHCP requests to a server on another networkCisco IOS · Global config (config)#
interface Vlan10 ip helper-address 192.168.1.5 -
Show DHCP leasesCisco IOS · Privileged EXEC (#)
show ip dhcp binding -
Show DHCP pools and how full they areCisco IOS · Privileged EXEC (#)
show ip dhcp pool -
Show DHCP address conflictsCisco IOS · Privileged EXEC (#)
show ip dhcp conflict -
Clear all DHCP leasesCisco IOS · Privileged EXEC (#)
clear ip dhcp binding *
Cisco IOS: SSH and remote access
-
Set up SSH from scratchCisco IOS · Global config (config)#
hostname SW1 ip domain-name corp.example.com crypto key generate rsa modulus 2048 ip ssh version 2 username admin privilege 15 secret MyPassword line vty 0 15 login local transport input ssh -
Only allow SSH, not TelnetCisco IOS · Global config (config)#
line vty 0 15 transport input ssh -
Log out idle remote sessions after 10 minutesCisco IOS · Global config (config)#
line vty 0 15 exec-timeout 10 0 -
Limit SSH login attempts and timeCisco IOS · Global config (config)#
ip ssh authentication-retries 3 ip ssh time-out 60 -
Block logins for 2 minutes after 5 failures in a minuteCisco IOS · Global config (config)#
login block-for 120 attempts 5 within 60 -
Show SSH settingsCisco IOS · Privileged EXEC (#)
show ip ssh -
Show current SSH sessionsCisco IOS · Privileged EXEC (#)
show ssh -
SSH from this device to anotherCisco IOS · Privileged EXEC (#)
ssh -l admin 192.168.1.20 -
Disconnect a remote sessionCisco IOS · Privileged EXEC (#)
clear line vty 0
Cisco IOS: AAA, RADIUS and TACACS+
-
Turn on AAA with local usersCisco IOS · Global config (config)#
aaa new-model aaa authentication login default local aaa authorization exec default localWarning: Changes how everyone logs in. Create a local user first and keep a session open while you test.
-
Add a RADIUS serverCisco IOS · Global config (config)#
radius server NPS1 address ipv4 192.168.1.5 auth-port 1812 acct-port 1813 key MyRadiusKey -
Log in with RADIUS, falling back to local usersCisco IOS · Global config (config)#
aaa authentication login default group radius local -
Add a TACACS+ serverCisco IOS · Global config (config)#
tacacs server ISE1 address ipv4 192.168.1.6 key MyTacacsKey -
Log in with TACACS+, falling back to local usersCisco IOS · Global config (config)#
aaa authentication login default group tacacs+ local -
Log every admin command to TACACS+Cisco IOS · Global config (config)#
aaa accounting commands 15 default start-stop group tacacs+ -
Test a login against RADIUSCisco IOS · Privileged EXEC (#)
test aaa group radius admin MyPassword new-code -
Show AAA servers and their stateCisco IOS · Privileged EXEC (#)
show aaa servers
Cisco IOS: Logging and SNMP
-
Send logs to a syslog serverCisco IOS · Global config (config)#
logging host 192.168.1.5 logging trap informational -
Keep more log messages on the deviceCisco IOS · Global config (config)#
logging buffered 64000 -
Add the date and time to log messagesCisco IOS · Global config (config)#
service timestamps log datetime msec localtime show-timezone -
Clear the logCisco IOS · Privileged EXEC (#)
clear logging -
Set up SNMPv3 with authentication and encryptionCisco IOS · Global config (config)#
snmp-server group MONITOR v3 priv snmp-server user monitor MONITOR v3 auth sha MyAuthPass priv aes 128 MyPrivPass -
Set up read-only SNMPv2cCisco IOS · Global config (config)#
snmp-server community MyReadOnlyString ROWarning: SNMPv2c sends the community string in plain text. Use SNMPv3 where you can.
-
Set the SNMP location and contactCisco IOS · Global config (config)#
snmp-server location Dublin office snmp-server contact [email protected] -
Show SNMP settings and countersCisco IOS · Privileged EXEC (#)
show snmp
Cisco IOS: Troubleshooting
-
Check you can reach an addressCisco IOS · Privileged EXEC (#)
ping 192.168.1.1 -
Ping from a specific interfaceCisco IOS · Privileged EXEC (#)
ping 8.8.8.8 source GigabitEthernet0/1 -
Ping 100 timesCisco IOS · Privileged EXEC (#)
ping 8.8.8.8 repeat 100 -
Trace the route to an addressCisco IOS · Privileged EXEC (#)
traceroute 8.8.8.8 -
Test whether a TCP port is openCisco IOS · Privileged EXEC (#)
telnet 192.168.1.20 443 -
Find interfaces that went up or downCisco IOS · Privileged EXEC (#)
show logging | include UPDOWN -
Test a copper cableCisco IOS · Privileged EXEC (#)
test cable-diagnostics tdr interface GigabitEthernet1/0/1 -
Show the cable test resultCisco IOS · Privileged EXEC (#)
show cable-diagnostics tdr interface GigabitEthernet1/0/1 -
Copy a port's traffic to another port (SPAN)Cisco IOS · Global config (config)#
monitor session 1 source interface GigabitEthernet0/1 monitor session 1 destination interface GigabitEthernet0/24Warning: The destination port stops passing its normal traffic.
-
Show port mirroring sessionsCisco IOS · Privileged EXEC (#)
show monitor session 1 -
Debug ping trafficCisco IOS · Privileged EXEC (#)
debug ip icmpWarning: Debug output can overload a busy device. Turn it off with undebug all.
-
Show which debugs are onCisco IOS · Privileged EXEC (#)
show debugging -
Turn off all debuggingCisco IOS · Privileged EXEC (#)
undebug all
Cisco IOS: Switch stacks
-
Show stack members and their rolesCisco IOS · Privileged EXEC (#)
show switch -
Make a stack member more likely to be the active switchCisco IOS · Global config (config)#
switch 1 priority 15 -
Change a stack member's numberCisco IOS · Global config (config)#
switch 2 renumber 3Warning: Takes effect when the member reloads, and its ports are renamed.
Cisco IOS: Password recovery (routers)
-
In ROMMON, skip the saved config on next bootCisco IOS · ROMMON (rommon>)
confreg 0x2142 -
In ROMMON, restart the routerCisco IOS · ROMMON (rommon>)
reset -
After recovery, boot normally againCisco IOS · Global config (config)#
config-register 0x2102 -
Show the config registerCisco IOS · Privileged EXEC (#)
show version | include register
Cisco NX-OS: Modes and getting around
-
Enter config modeCisco NX-OS · EXEC (#)
configure terminal -
Leave config modeCisco NX-OS · Global config (config)#
end -
Run a show command from config mode (no do needed)Cisco NX-OS · Global config (config)#
show ip interface brief -
See which mode and context you're inCisco NX-OS · EXEC (#)
where detail -
List the commands you've typedCisco NX-OS · EXEC (#)
show cli history -
Stop output pausing at each screenCisco NX-OS · EXEC (#)
terminal length 0 -
Make a short alias for a long commandCisco NX-OS · Global config (config)#
cli alias name wr copy running-config startup-config
Cisco NX-OS: Filtering output
-
Show only the lines that contain a wordCisco NX-OS · EXEC (#)
show running-config | include hostname -
Search output with grep, ignoring caseCisco NX-OS · EXEC (#)
show interface status | grep -i connected -
Show one section of the configCisco NX-OS · EXEC (#)
show running-config | section bgp -
Show output without pagingCisco NX-OS · EXEC (#)
show running-config | no-more -
Get output as JSONCisco NX-OS · EXEC (#)
show interface brief | json-pretty -
Show the config including default settingsCisco NX-OS · EXEC (#)
show running-config all
Cisco NX-OS: Features
-
List features and whether they're onCisco NX-OS · EXEC (#)
show feature -
Turn on VLAN interfaces (SVIs)Cisco NX-OS · Global config (config)#
feature interface-vlan -
Turn on LACP for port channelsCisco NX-OS · Global config (config)#
feature lacp -
Turn on vPCCisco NX-OS · Global config (config)#
feature vpc -
Turn on OSPFCisco NX-OS · Global config (config)#
feature ospf -
Turn on BGPCisco NX-OS · Global config (config)#
feature bgp -
Turn on HSRPCisco NX-OS · Global config (config)#
feature hsrp -
Turn on LLDPCisco NX-OS · Global config (config)#
feature lldp -
Turn on the DHCP relay and snooping featureCisco NX-OS · Global config (config)#
feature dhcp -
Turn on TACACS+Cisco NX-OS · Global config (config)#
feature tacacs+ -
Let other devices copy files to this switch with SCPCisco NX-OS · Global config (config)#
feature scp-server -
Turn off TelnetCisco NX-OS · Global config (config)#
no feature telnet
Cisco NX-OS: Basic setup
-
Set the hostnameCisco NX-OS · Global config (config)#
hostname N9K-1 -
Create an admin userCisco NX-OS · Global config (config)#
username admin password MyPassword role network-admin -
Create a read-only userCisco NX-OS · Global config (config)#
username ops password MyPassword role network-operator -
Give the management port an IP addressCisco NX-OS · Global config (config)#
interface mgmt0 ip address 192.168.1.10/24 -
Set the default gateway for management trafficCisco NX-OS · Global config (config)#
vrf context management ip route 0.0.0.0/0 192.168.1.1 -
Set the domain nameCisco NX-OS · Global config (config)#
ip domain-name corp.example.com -
Set a DNS server, reached through the management VRFCisco NX-OS · Global config (config)#
ip name-server 1.1.1.1 use-vrf management -
Set an NTP server, reached through the management VRFCisco NX-OS · Global config (config)#
ntp server 192.168.1.5 use-vrf management -
Set the time zoneCisco NX-OS · Global config (config)#
clock timezone GMT 0 0 -
Show a login bannerCisco NX-OS · Global config (config)#
banner motd # Authorised access only # -
Log out idle SSH sessions after 10 minutesCisco NX-OS · Global config (config)#
line vty exec-timeout 10 -
Log out an idle console session after 10 minutesCisco NX-OS · Global config (config)#
line console exec-timeout 10
Cisco NX-OS: Save, back up and roll back
-
Save the running configCisco NX-OS · EXEC (#)
copy running-config startup-config -
Show what's changed since the last saveCisco NX-OS · EXEC (#)
show running-config diff -
Show the saved configCisco NX-OS · EXEC (#)
show startup-config -
Copy the config to a file on the switchCisco NX-OS · EXEC (#)
copy running-config bootflash:N9K-1-backup.cfg -
Back up the config to a TFTP serverCisco NX-OS · EXEC (#)
copy running-config tftp://192.168.1.5/N9K-1-backup.cfg vrf management -
Back up the config to a server with SCPCisco NX-OS · EXEC (#)
copy running-config scp://[email protected]/N9K-1-backup.cfg vrf management -
Take a checkpoint before a changeCisco NX-OS · EXEC (#)
checkpoint before-change -
List checkpointsCisco NX-OS · EXEC (#)
show checkpoint summary -
Show what rolling back to a checkpoint would changeCisco NX-OS · EXEC (#)
show diff rollback-patch checkpoint before-change running-config -
Roll back to a checkpointCisco NX-OS · EXEC (#)
rollback running-config checkpoint before-changeWarning: Replaces the running config with the checkpoint. Check the rollback-patch diff first.
-
Delete a checkpointCisco NX-OS · EXEC (#)
no checkpoint before-change -
See who changed the config and whenCisco NX-OS · EXEC (#)
show accounting log -
List files on the switchCisco NX-OS · EXEC (#)
dir bootflash: -
Show the contents of a fileCisco NX-OS · EXEC (#)
show file bootflash:N9K-1-backup.cfg -
Delete a fileCisco NX-OS · EXEC (#)
delete bootflash:N9K-1-backup.cfgWarning: Deleted files can't be recovered.
-
Erase the saved configCisco NX-OS · EXEC (#)
write eraseWarning: Wipes the startup config. The switch comes up unconfigured after the next reload.
-
Restart the switchCisco NX-OS · EXEC (#)
reloadWarning: Restarts the switch and drops all traffic through it. Save the config first.
Cisco NX-OS: Show and verify
-
Show the software version and uptimeCisco NX-OS · EXEC (#)
show version -
Show modules and their statusCisco NX-OS · EXEC (#)
show module -
Show serial numbers and hardwareCisco NX-OS · EXEC (#)
show inventory -
Show fans, power supplies and temperatureCisco NX-OS · EXEC (#)
show environment -
Show CPU and memory useCisco NX-OS · EXEC (#)
show system resources -
Show the busiest processesCisco NX-OS · EXEC (#)
show processes cpu sort -
Show how long the switch has been upCisco NX-OS · EXEC (#)
show system uptime -
Show why the switch last restartedCisco NX-OS · EXEC (#)
show system reset-reason -
Show every interface in one tableCisco NX-OS · EXEC (#)
show interface brief -
Show port status, VLAN, speed and duplexCisco NX-OS · EXEC (#)
show interface status -
Show one interface in detailCisco NX-OS · EXEC (#)
show interface Ethernet1/1 -
Show interface descriptionsCisco NX-OS · EXEC (#)
show interface description -
Show interface error countersCisco NX-OS · EXEC (#)
show interface counters errors -
Show an optic's type and light levelsCisco NX-OS · EXEC (#)
show interface Ethernet1/1 transceiver details -
Show IP addresses in the default VRFCisco NX-OS · EXEC (#)
show ip interface brief -
Show IP addresses in every VRFCisco NX-OS · EXEC (#)
show ip interface brief vrf all -
Show neighbours seen with CDPCisco NX-OS · EXEC (#)
show cdp neighbors -
Show neighbours seen with LLDPCisco NX-OS · EXEC (#)
show lldp neighbors -
Show the MAC address tableCisco NX-OS · EXEC (#)
show mac address-table -
Find which port a MAC address is onCisco NX-OS · EXEC (#)
show mac address-table address aabb.cc00.0100 -
Show the ARP tableCisco NX-OS · EXEC (#)
show ip arp -
Show who's logged inCisco NX-OS · EXEC (#)
show users -
Show the last 50 log messagesCisco NX-OS · EXEC (#)
show logging last 50 -
Show the whole log fileCisco NX-OS · EXEC (#)
show logging logfile
Cisco NX-OS: Interfaces
-
Describe an interfaceCisco NX-OS · Global config (config)#
interface Ethernet1/1 description Uplink to core -
Turn an interface onCisco NX-OS · Global config (config)#
interface Ethernet1/1 no shutdown -
Turn an interface offCisco NX-OS · Global config (config)#
interface Ethernet1/1 shutdown -
Configure several interfaces at onceCisco NX-OS · Global config (config)#
interface Ethernet1/1-4 description Server ports -
Make a port a routed (Layer 3) port with an IP addressCisco NX-OS · Global config (config)#
interface Ethernet1/1 no switchport ip address 10.0.0.1/30 no shutdown -
Make a routed port a switch port againCisco NX-OS · Global config (config)#
interface Ethernet1/1 switchport -
Create a loopback interfaceCisco NX-OS · Global config (config)#
interface loopback0 ip address 10.255.255.1/32 -
Set the speed of a portCisco NX-OS · Global config (config)#
interface Ethernet1/1 speed 10000 -
Allow jumbo frames on a portCisco NX-OS · Global config (config)#
interface Ethernet1/1 mtu 9216 -
Reset an interface to its default configCisco NX-OS · Global config (config)#
default interface Ethernet1/1Warning: Removes all config from the interface.
-
Split a 40G or 100G port into fourCisco NX-OS · Global config (config)#
interface breakout module 1 port 49 map 10g-4xWarning: Removes the config on that port. Supported ports and speeds depend on the model.
-
Clear an interface's countersCisco NX-OS · EXEC (#)
clear counters interface Ethernet1/1
Cisco NX-OS: VLANs and trunks
-
Create a VLAN and name itCisco NX-OS · Global config (config)#
vlan 10 name Users -
Delete a VLANCisco NX-OS · Global config (config)#
no vlan 10 -
List VLANs and their portsCisco NX-OS · EXEC (#)
show vlan brief -
Make a port an access port in a VLANCisco NX-OS · Global config (config)#
interface Ethernet1/1 switchport switchport mode access switchport access vlan 10 -
Make a port a trunk carrying some VLANsCisco NX-OS · Global config (config)#
interface Ethernet1/48 switchport switchport mode trunk switchport trunk allowed vlan 10,20,30Warning: Replaces the trunk's allowed VLAN list. Use add to include one more without removing the others.
-
Add a VLAN to a trunkCisco NX-OS · Global config (config)#
interface Ethernet1/48 switchport trunk allowed vlan add 40 -
Remove a VLAN from a trunkCisco NX-OS · Global config (config)#
interface Ethernet1/48 switchport trunk allowed vlan remove 40 -
Change a trunk's native VLANCisco NX-OS · Global config (config)#
interface Ethernet1/48 switchport trunk native vlan 99 -
List trunk ports and their VLANsCisco NX-OS · EXEC (#)
show interface trunk -
Show a port's VLAN and trunk settingsCisco NX-OS · EXEC (#)
show interface Ethernet1/1 switchport -
Give a VLAN an IP address (SVI)Cisco NX-OS · Global config (config)#
feature interface-vlan interface Vlan10 ip address 192.168.10.1/24 no shutdown
Cisco NX-OS: Port channels
-
Bundle ports into a port channel with LACPCisco NX-OS · Global config (config)#
feature lacp interface Ethernet1/47-48 channel-group 10 mode active -
Make a port channel a trunkCisco NX-OS · Global config (config)#
interface port-channel10 switchport mode trunk -
Show port channels and their member portsCisco NX-OS · EXEC (#)
show port-channel summary -
Show the LACP partner on each portCisco NX-OS · EXEC (#)
show lacp neighbor
Cisco NX-OS: vPC
-
Create a vPC domain and its keepalive linkCisco NX-OS · Global config (config)#
feature vpc vpc domain 1 peer-keepalive destination 192.168.1.2 source 192.168.1.1 vrf management -
Make a port channel the vPC peer linkCisco NX-OS · Global config (config)#
interface port-channel1 switchport mode trunk vpc peer-link -
Make a port channel a vPC to another deviceCisco NX-OS · Global config (config)#
interface port-channel10 vpc 10 -
Turn on the usual vPC domain optionsCisco NX-OS · Global config (config)#
vpc domain 1 peer-switch peer-gateway auto-recovery ip arp synchronize -
Choose which switch is the vPC primaryCisco NX-OS · Global config (config)#
vpc domain 1 role priority 1000 -
Show vPC statusCisco NX-OS · EXEC (#)
show vpc -
Show which switch is primaryCisco NX-OS · EXEC (#)
show vpc role -
Show the keepalive link's statusCisco NX-OS · EXEC (#)
show vpc peer-keepalive -
Check both switches' settings matchCisco NX-OS · EXEC (#)
show vpc consistency-parameters global
Cisco NX-OS: Spanning tree
-
Show spanning treeCisco NX-OS · EXEC (#)
show spanning-tree -
Show spanning tree for one VLANCisco NX-OS · EXEC (#)
show spanning-tree vlan 10 -
Show a spanning tree summaryCisco NX-OS · EXEC (#)
show spanning-tree summary -
Make this switch the root for a VLANCisco NX-OS · Global config (config)#
spanning-tree vlan 10 root primary -
Set the spanning tree priority for a VLANCisco NX-OS · Global config (config)#
spanning-tree vlan 10 priority 4096 -
Mark a port as an edge port (a server or PC)Cisco NX-OS · Global config (config)#
interface Ethernet1/1 spanning-tree port type edge -
Mark a trunk to a server as an edge portCisco NX-OS · Global config (config)#
interface Ethernet1/1 spanning-tree port type edge trunk -
Turn on BPDU guard for a portCisco NX-OS · Global config (config)#
interface Ethernet1/1 spanning-tree bpduguard enable -
Turn on BPDU guard for every edge portCisco NX-OS · Global config (config)#
spanning-tree port type edge bpduguard default -
Stop a port becoming the path to a new root (root guard)Cisco NX-OS · Global config (config)#
interface Ethernet1/48 spanning-tree guard root
Cisco NX-OS: VRFs
-
Create a VRFCisco NX-OS · Global config (config)#
vrf context TENANT-A description Tenant A -
Put an interface in a VRFCisco NX-OS · Global config (config)#
interface Ethernet1/1 vrf member TENANT-AWarning: Removes the interface's IP address, so set the address again afterwards.
-
List VRFsCisco NX-OS · EXEC (#)
show vrf -
Show which interfaces are in each VRFCisco NX-OS · EXEC (#)
show vrf interface -
Show a VRF's routing tableCisco NX-OS · EXEC (#)
show ip route vrf TENANT-A -
Ping through the management VRFCisco NX-OS · EXEC (#)
ping 192.168.1.1 vrf management -
Trace a route through the management VRFCisco NX-OS · EXEC (#)
traceroute 8.8.8.8 vrf management -
SSH to another device through the management VRFCisco NX-OS · EXEC (#)
ssh [email protected] vrf management -
Run the commands that follow in one VRFCisco NX-OS · EXEC (#)
routing-context vrf management
Cisco NX-OS: Static routing
-
Add a static routeCisco NX-OS · Global config (config)#
ip route 10.20.0.0/16 192.168.1.254 -
Add a default routeCisco NX-OS · Global config (config)#
ip route 0.0.0.0/0 203.0.113.1 -
Add a static route in a VRFCisco NX-OS · Global config (config)#
vrf context TENANT-A ip route 10.20.0.0/16 192.168.1.254 -
Remove a static routeCisco NX-OS · Global config (config)#
no ip route 10.20.0.0/16 192.168.1.254 -
Show the routing tableCisco NX-OS · EXEC (#)
show ip route -
Show static routesCisco NX-OS · EXEC (#)
show ip route static -
Show which route a destination usesCisco NX-OS · EXEC (#)
show ip route 10.20.1.5
Cisco NX-OS: OSPF
-
Start OSPF and set the router IDCisco NX-OS · Global config (config)#
feature ospf router ospf 1 router-id 1.1.1.1 -
Turn on OSPF on an interfaceCisco NX-OS · Global config (config)#
interface Ethernet1/1 ip router ospf 1 area 0.0.0.0 -
Stop OSPF sending hellos on an interfaceCisco NX-OS · Global config (config)#
interface Vlan10 ip ospf passive-interface -
Treat a link as point-to-point in OSPFCisco NX-OS · Global config (config)#
interface Ethernet1/1 ip ospf network point-to-point -
Set an interface's OSPF costCisco NX-OS · Global config (config)#
interface Ethernet1/1 ip ospf cost 10 -
Show OSPF neighboursCisco NX-OS · EXEC (#)
show ip ospf neighbors -
Show which interfaces run OSPFCisco NX-OS · EXEC (#)
show ip ospf interface brief -
Show routes learned from OSPFCisco NX-OS · EXEC (#)
show ip route ospf-1
Cisco NX-OS: BGP
-
Start BGP and set the router IDCisco NX-OS · Global config (config)#
feature bgp router bgp 65001 router-id 1.1.1.1 -
Add a BGP neighbourCisco NX-OS · Global config (config)#
router bgp 65001 neighbor 203.0.113.1 remote-as 65000 address-family ipv4 unicast -
Advertise a network in BGPCisco NX-OS · Global config (config)#
router bgp 65001 address-family ipv4 unicast network 198.51.100.0/24 -
Show BGP neighbours and their stateCisco NX-OS · EXEC (#)
show bgp ipv4 unicast summary -
Show the BGP tableCisco NX-OS · EXEC (#)
show bgp ipv4 unicast -
Show the routes you're sending to a neighbourCisco NX-OS · EXEC (#)
show bgp ipv4 unicast neighbors 203.0.113.1 advertised-routes -
Ask a neighbour to resend its routes without dropping the sessionCisco NX-OS · EXEC (#)
clear bgp ipv4 unicast 203.0.113.1 soft in
Cisco NX-OS: Gateway redundancy (HSRP)
-
Share a gateway address between two switchesCisco NX-OS · Global config (config)#
feature hsrp feature interface-vlan interface Vlan10 hsrp 10 ip 192.168.10.1 priority 110 preempt -
Show HSRP groups and which switch is activeCisco NX-OS · EXEC (#)
show hsrp brief
Cisco NX-OS: Access lists
-
Create an ACL that only allows web traffic to a serverCisco NX-OS · Global config (config)#
ip access-list WEB-IN permit tcp any host 192.168.1.20 eq 443 deny ip any any log -
Count how many packets hit each line of an ACLCisco NX-OS · Global config (config)#
ip access-list WEB-IN statistics per-entry -
Apply an ACL to traffic coming into a routed interfaceCisco NX-OS · Global config (config)#
interface Ethernet1/1 ip access-group WEB-IN inWarning: Anything the ACL doesn't permit is blocked. Make sure you have another way in, such as the console, before you apply it over SSH.
-
Apply an ACL to traffic coming into a switch portCisco NX-OS · Global config (config)#
interface Ethernet1/1 ip port access-group WEB-IN inWarning: Anything the ACL doesn't permit is blocked.
-
Only allow SSH from addresses in an ACLCisco NX-OS · Global config (config)#
line vty access-class MGMT inWarning: Make sure you have another way in, such as the console, before you apply it over SSH.
-
Show ACLs and their hit countsCisco NX-OS · EXEC (#)
show ip access-lists
Cisco NX-OS: TACACS+, logging and SNMP
-
Add a TACACS+ serverCisco NX-OS · Global config (config)#
feature tacacs+ tacacs-server host 192.168.1.6 key MyTacacsKey aaa group server tacacs+ TACACS server 192.168.1.6 use-vrf management -
Log in with TACACS+, falling back to local usersCisco NX-OS · Global config (config)#
aaa authentication login default group TACACS local -
List local users and their rolesCisco NX-OS · EXEC (#)
show user-account -
Show what each role is allowed to doCisco NX-OS · EXEC (#)
show role -
Show the SSH server's settingsCisco NX-OS · EXEC (#)
show ssh server -
Send logs to a syslog server through the management VRFCisco NX-OS · Global config (config)#
logging server 192.168.1.5 6 use-vrf management -
Clear the log fileCisco NX-OS · EXEC (#)
clear logging logfile -
Set a read-only SNMP communityCisco NX-OS · Global config (config)#
snmp-server community MyReadOnlyString group network-operator -
Create an SNMPv3 userCisco NX-OS · Global config (config)#
snmp-server user monitor network-operator auth sha MyAuthPass priv aes-128 MyPrivPass -
Check the time and NTP syncCisco NX-OS · EXEC (#)
show ntp peer-status
Cisco NX-OS: Troubleshooting
-
Ping an addressCisco NX-OS · EXEC (#)
ping 192.168.1.1 -
Ping 100 times from a chosen source addressCisco NX-OS · EXEC (#)
ping 8.8.8.8 source 10.0.0.1 count 100 -
Trace the route to an addressCisco NX-OS · EXEC (#)
traceroute 8.8.8.8 -
Capture traffic to and from the switch itself on the management portCisco NX-OS · EXEC (#)
ethanalyzer local interface mgmt limit-captured-frames 50 -
Copy a port's traffic to another port (SPAN)Cisco NX-OS · Global config (config)#
interface Ethernet1/48 switchport switchport monitor monitor session 1 source interface Ethernet1/1 both destination interface Ethernet1/48 no shut -
Show SPAN sessionsCisco NX-OS · EXEC (#)
show monitor session all -
List crash filesCisco NX-OS · EXEC (#)
show cores -
Gather everything Cisco support asks forCisco NX-OS · EXEC (#)
show tech-support details
Cisco NX-OS: Upgrades and automation
-
Show which image the switch bootsCisco NX-OS · EXEC (#)
show boot -
Check what an upgrade would do before running itCisco NX-OS · EXEC (#)
show install all impact nxos bootflash:nxos64-cs.10.3.4a.M.bin -
Upgrade NX-OSCisco NX-OS · EXEC (#)
install all nxos bootflash:nxos64-cs.10.3.4a.M.binWarning: Reloads the switch unless the upgrade can be done without disruption. Check the impact first and save the config.
-
Turn on the NX-API for scripts and toolsCisco NX-OS · Global config (config)#
feature nxapi -
Allow the Linux shell on the switchCisco NX-OS · Global config (config)#
feature bash-shell -
Open a Linux shell on the switchCisco NX-OS · EXEC (#)
run bash -
Run a Linux shell commandCisco NX-OS · EXEC (#)
run bash df -h
HPE Aruba AOS-CX: Modes and getting around
-
Go from operator mode to manager modeHPE Aruba AOS-CX · Operator (>)
enable -
Enter global config modeHPE Aruba AOS-CX · Manager (#)
configure terminal -
Go back up one levelHPE Aruba AOS-CX · Global config (config)#
exit -
Go straight back to manager modeHPE Aruba AOS-CX · Global config (config)#
end -
Run a show command without leaving config modeHPE Aruba AOS-CX · Global config (config)#
do show interface brief -
Show the config of the context you're inHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 show running-config current-context -
Turn off paging for this sessionHPE Aruba AOS-CX · Manager (#)
no page -
Show the commands you've typedHPE Aruba AOS-CX · Manager (#)
show history
HPE Aruba AOS-CX: Filtering output
-
Show only the lines that contain a wordHPE Aruba AOS-CX · Manager (#)
show running-config | include hostname -
Hide the lines that contain a wordHPE Aruba AOS-CX · Manager (#)
show interface brief | exclude down -
Start the output at the first line with a wordHPE Aruba AOS-CX · Manager (#)
show running-config | begin vlan -
Show the config for one interfaceHPE Aruba AOS-CX · Manager (#)
show running-config interface 1/1/1 -
Show the config as JSONHPE Aruba AOS-CX · Manager (#)
show running-config json
HPE Aruba AOS-CX: Basic setup
-
Set the hostnameHPE Aruba AOS-CX · Global config (config)#
hostname SW-CORE-1 -
Add a local admin userHPE Aruba AOS-CX · Global config (config)#
user netadmin group administrators password plaintext MyPasswordWarning: The password shows in plain text as you type it. Leave off plaintext and the password to be asked for it instead. admin can't be used as a new user name.
-
Add a read-only userHPE Aruba AOS-CX · Global config (config)#
user helpdesk group operators password plaintext MyPassword -
Change a user's passwordHPE Aruba AOS-CX · Global config (config)#
user admin password -
List the local usersHPE Aruba AOS-CX · Manager (#)
show user-list -
Set the time zoneHPE Aruba AOS-CX · Global config (config)#
clock timezone europe/dublinWarning: Time zones are IANA names. Type clock timezone and press Tab to see how your switch spells them.
-
Get the time from an NTP server over the management portHPE Aruba AOS-CX · Global config (config)#
ntp server pool.ntp.org iburst ntp enable ntp vrf mgmt -
Show the date and timeHPE Aruba AOS-CX · Manager (#)
show clock -
Check NTP is in syncHPE Aruba AOS-CX · Manager (#)
show ntp status -
Set the DNS server and domainHPE Aruba AOS-CX · Global config (config)#
ip dns server-address 1.1.1.1 ip dns domain-name corp.example.com -
Log idle sessions out after 30 minutesHPE Aruba AOS-CX · Global config (config)#
session-timeout 30
HPE Aruba AOS-CX: Management access
-
Give the management port a static addressHPE Aruba AOS-CX · Global config (config)#
interface mgmt no shutdown ip static 10.0.0.10/24 default-gateway 10.0.0.1 nameserver 1.1.1.1 -
Get the management port's address from DHCPHPE Aruba AOS-CX · Global config (config)#
interface mgmt no shutdown ip dhcp -
Show the management portHPE Aruba AOS-CX · Manager (#)
show interface mgmt -
Turn on SSH on the management portHPE Aruba AOS-CX · Global config (config)#
ssh server vrf mgmt -
Turn on SSH on the data portsHPE Aruba AOS-CX · Global config (config)#
ssh server vrf default -
Turn on the web interface and REST API on the management portHPE Aruba AOS-CX · Global config (config)#
https-server vrf mgmt
HPE Aruba AOS-CX: Save, back up and roll back
-
Save the configHPE Aruba AOS-CX · Manager (#)
write memory -
Save the config, the long wayHPE Aruba AOS-CX · Manager (#)
copy running-config startup-config -
Show the saved configHPE Aruba AOS-CX · Manager (#)
show startup-config -
See what's changed since the last saveHPE Aruba AOS-CX · Manager (#)
checkpoint diff startup-config running-config -
Save a named checkpoint before a changeHPE Aruba AOS-CX · Manager (#)
copy running-config checkpoint before-change -
List the checkpointsHPE Aruba AOS-CX · Manager (#)
show checkpoint -
Roll back to a checkpointHPE Aruba AOS-CX · Manager (#)
checkpoint rollback before-change -
Try changes that undo themselves unless you confirm themHPE Aruba AOS-CX · Manager (#)
checkpoint auto 10Warning: If you don't run checkpoint auto confirm within 10 minutes, the switch puts the old config back. Handy when a change might cut off your own access.
-
Keep the changes made in auto checkpoint modeHPE Aruba AOS-CX · Manager (#)
checkpoint auto confirm -
Back up the config to a TFTP serverHPE Aruba AOS-CX · Manager (#)
copy running-config tftp://10.0.0.5/SW-CORE-1.json json vrf mgmt -
Back up the config as plain CLI textHPE Aruba AOS-CX · Manager (#)
copy running-config tftp://10.0.0.5/SW-CORE-1.cfg cli vrf mgmt -
Back up the config over SFTPHPE Aruba AOS-CX · Manager (#)
copy running-config sftp://[email protected]/SW-CORE-1.json json vrf mgmt -
Restore a config from a TFTP serverHPE Aruba AOS-CX · Manager (#)
copy tftp://10.0.0.5/SW-CORE-1.json running-config json vrf mgmtWarning: A restore needs a backup saved in JSON format. Save it with write memory afterwards.
-
Reset the switch to factory defaultsHPE Aruba AOS-CX · Manager (#)
erase all zeroizeWarning: Wipes the config and all user data, then reboots. It can take several minutes to an hour. Back up first.
HPE Aruba AOS-CX: Show and verify
-
Show the software versionHPE Aruba AOS-CX · Manager (#)
show version -
Show the model, serial number and uptimeHPE Aruba AOS-CX · Manager (#)
show system -
Show CPU and memory useHPE Aruba AOS-CX · Manager (#)
show system resource-utilization -
Show the fansHPE Aruba AOS-CX · Manager (#)
show environment fan -
Show the power suppliesHPE Aruba AOS-CX · Manager (#)
show environment power-supply -
Show the temperaturesHPE Aruba AOS-CX · Manager (#)
show environment temperature -
Show the modules and line cardsHPE Aruba AOS-CX · Manager (#)
show module -
Show the running configHPE Aruba AOS-CX · Manager (#)
show running-config -
Show the system logHPE Aruba AOS-CX · Manager (#)
show logging -
Show the event logHPE Aruba AOS-CX · Manager (#)
show events -
Show every port's statusHPE Aruba AOS-CX · Manager (#)
show interface brief -
Show what's plugged in, with LLDPHPE Aruba AOS-CX · Manager (#)
show lldp neighbor-info -
Show LLDP details for one portHPE Aruba AOS-CX · Manager (#)
show lldp neighbor-info 1/1/1 -
Show the MAC address tableHPE Aruba AOS-CX · Manager (#)
show mac-address-table -
Find which port a MAC address is onHPE Aruba AOS-CX · Manager (#)
show mac-address-table address aa:bb:cc:dd:ee:ff -
Show the ARP tableHPE Aruba AOS-CX · Manager (#)
show arp -
Show IP addresses on interfacesHPE Aruba AOS-CX · Manager (#)
show ip interface brief -
Show the routing tableHPE Aruba AOS-CX · Manager (#)
show ip route -
Collect everything for a support caseHPE Aruba AOS-CX · Manager (#)
show techWarning: The output is very long. Run no page first, and log it to a file in your terminal app.
HPE Aruba AOS-CX: Interfaces
-
Turn a port on and describe itHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 description Uplink to core no shutdown -
Shut a port downHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 shutdown -
Turn on a range of portsHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1-1/1/24 no shutdown -
Show one port in detailHPE Aruba AOS-CX · Manager (#)
show interface 1/1/1 -
Show how busy each port isHPE Aruba AOS-CX · Manager (#)
show interface utilization -
Show the transceivers (SFPs)HPE Aruba AOS-CX · Manager (#)
show interface transceiver -
Use jumbo frames on a portHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 mtu 9198 -
Test a copper cableHPE Aruba AOS-CX · Manager (#)
diag cable-diagnostic test 1/1/1Warning: The port drops its link for a few seconds while it tests.
-
Show the cable test resultHPE Aruba AOS-CX · Manager (#)
diag cable-diagnostic show 1/1/1 -
Make a port a routed (Layer 3) portHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 routing ip address 192.168.10.1/24Warning: Not on 4100i, 6000, 6100 or 6200 switches, which can't route on their ports. Use a VLAN interface instead.
-
Make a port a switched (Layer 2) portHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 no routing -
Turn off PoE on a portHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 no power-over-ethernet -
Turn PoE back on for a portHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 power-over-ethernet -
Show PoE power useHPE Aruba AOS-CX · Manager (#)
show power-over-ethernet
HPE Aruba AOS-CX: VLANs and trunks
-
Create a VLAN and name itHPE Aruba AOS-CX · Global config (config)#
vlan 10 name Users -
Create several VLANs at onceHPE Aruba AOS-CX · Global config (config)#
vlan 10,20,30 -
Delete a VLANHPE Aruba AOS-CX · Global config (config)#
no vlan 10 -
Show the VLANsHPE Aruba AOS-CX · Manager (#)
show vlan -
Show one VLAN and its portsHPE Aruba AOS-CX · Manager (#)
show vlan 10 -
Make a port an access port in a VLANHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 vlan access 10 -
Make a port a trunkHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 vlan trunk native 1 vlan trunk allowed 10,20,30 -
Allow every VLAN on a trunkHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 vlan trunk allowed all -
Remove a VLAN from a trunkHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 no vlan trunk allowed 10 -
Tag the native VLAN on a trunkHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 vlan trunk native 1 tag -
Give a VLAN an IP addressHPE Aruba AOS-CX · Global config (config)#
interface vlan 10 ip address 192.168.10.1/24 no shutdown -
Relay DHCP requests on a VLAN to a serverHPE Aruba AOS-CX · Global config (config)#
interface vlan 10 ip helper-address 10.0.0.5
HPE Aruba AOS-CX: Link aggregation (LAG)
-
Create a LACP trunk LAGHPE Aruba AOS-CX · Global config (config)#
interface lag 10 no shutdown vlan trunk native 1 vlan trunk allowed 10,20,30 lacp mode active -
Add ports to a LAGHPE Aruba AOS-CX · Global config (config)#
interface 1/1/49-1/1/50 no shutdown lag 10 -
Use fast LACP timersHPE Aruba AOS-CX · Global config (config)#
interface lag 10 lacp rate fast -
Show the LAGsHPE Aruba AOS-CX · Manager (#)
show lacp aggregates -
Show LACP on each portHPE Aruba AOS-CX · Manager (#)
show lacp interfaces
HPE Aruba AOS-CX: VSX
-
Create the inter-switch link (ISL) LAGHPE Aruba AOS-CX · Global config (config)#
interface lag 256 no shutdown no routing vlan trunk native 1 tag vlan trunk allowed all lacp mode active -
Set up VSX on the primary switchHPE Aruba AOS-CX · Global config (config)#
vsx system-mac 02:00:00:00:01:00 inter-switch-link lag 256 role primary keepalive peer 192.168.255.2 source 192.168.255.1 vrf KA -
Set up VSX on the secondary switchHPE Aruba AOS-CX · Global config (config)#
vsx system-mac 02:00:00:00:01:00 inter-switch-link lag 256 role secondary keepalive peer 192.168.255.1 source 192.168.255.2 vrf KA -
Sync global settings to the peerHPE Aruba AOS-CX · Global config (config)#
vsx vsx-sync vsx-global -
Make a LAG that spans both switchesHPE Aruba AOS-CX · Global config (config)#
interface lag 10 multi-chassis no shutdown no routing vlan trunk native 1 vlan trunk allowed 10,20,30 lacp mode active -
Share a default gateway across the pairHPE Aruba AOS-CX · Global config (config)#
interface vlan 10 ip address 192.168.10.2/24 active-gateway ip mac 12:00:00:00:01:00 active-gateway ip 192.168.10.1 -
Show VSX statusHPE Aruba AOS-CX · Manager (#)
show vsx status -
Show VSX in briefHPE Aruba AOS-CX · Manager (#)
show vsx brief -
Check both switches' configs matchHPE Aruba AOS-CX · Manager (#)
show vsx config-consistency
HPE Aruba AOS-CX: Spanning tree
-
Turn on spanning tree (MSTP)HPE Aruba AOS-CX · Global config (config)#
spanning-tree -
Use Rapid PVST+ instead of MSTPHPE Aruba AOS-CX · Global config (config)#
spanning-tree mode rpvst -
Make this switch the root bridgeHPE Aruba AOS-CX · Global config (config)#
spanning-tree priority 0 -
Mark a port as an edge portHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 spanning-tree port-type admin-edge -
Shut a port if it receives a BPDUHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 spanning-tree bpdu-guard -
Stop a port becoming the root portHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 spanning-tree root-guard -
Shut a port if it sees its own traffic loop backHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 loop-protect -
Show spanning treeHPE Aruba AOS-CX · Manager (#)
show spanning-tree
HPE Aruba AOS-CX: Static routing and VRFs
-
Add a default routeHPE Aruba AOS-CX · Global config (config)#
ip route 0.0.0.0/0 192.168.1.254 -
Add a static routeHPE Aruba AOS-CX · Global config (config)#
ip route 10.20.0.0/16 192.168.1.254 -
Create a VRFHPE Aruba AOS-CX · Global config (config)#
vrf TENANT-A -
Put a VLAN interface in a VRFHPE Aruba AOS-CX · Global config (config)#
interface vlan 10 vrf attach TENANT-A ip address 192.168.10.1/24 -
Add a static route in a VRFHPE Aruba AOS-CX · Global config (config)#
ip route 10.20.0.0/16 192.168.1.254 vrf TENANT-A -
Show the VRFsHPE Aruba AOS-CX · Manager (#)
show vrf -
Show a VRF's routing tableHPE Aruba AOS-CX · Manager (#)
show ip route vrf TENANT-A -
Create a loopback interfaceHPE Aruba AOS-CX · Global config (config)#
interface loopback 0 ip address 10.255.0.1/32
HPE Aruba AOS-CX: OSPF
-
Start OSPFHPE Aruba AOS-CX · Global config (config)#
router ospf 1 router-id 1.1.1.1 area 0.0.0.0 -
Run OSPF on an interfaceHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 ip ospf 1 area 0.0.0.0 -
Treat a link as point-to-pointHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 ip ospf network point-to-point -
Stop sending OSPF hellos on an interfaceHPE Aruba AOS-CX · Global config (config)#
interface vlan 10 ip ospf passive -
Show OSPF neighboursHPE Aruba AOS-CX · Manager (#)
show ip ospf neighbors -
Show OSPF interfacesHPE Aruba AOS-CX · Manager (#)
show ip ospf interface
HPE Aruba AOS-CX: BGP
-
Start BGP and add a neighbourHPE Aruba AOS-CX · Global config (config)#
router bgp 65001 bgp router-id 1.1.1.1 neighbor 203.0.113.1 remote-as 65000 -
Turn on a neighbour and advertise a networkHPE Aruba AOS-CX · Global config (config)#
router bgp 65001 address-family ipv4 unicast neighbor 203.0.113.1 activate network 10.20.0.0/16 -
Show BGP neighboursHPE Aruba AOS-CX · Manager (#)
show bgp ipv4 unicast summary -
Show BGP routesHPE Aruba AOS-CX · Manager (#)
show bgp ipv4 unicast
HPE Aruba AOS-CX: Access lists
-
Create an ACL that only allows SSH from one networkHPE Aruba AOS-CX · Global config (config)#
access-list ip MGMT-IN 10 permit tcp 10.0.0.0/24 any eq 22 20 deny any any any -
Apply an ACL to traffic coming into a portHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 apply access-list ip MGMT-IN in -
Take an ACL off a portHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 no apply access-list ip MGMT-IN in -
Show the ACLsHPE Aruba AOS-CX · Manager (#)
show access-list
HPE Aruba AOS-CX: AAA, logging and SNMP
-
Add a RADIUS serverHPE Aruba AOS-CX · Global config (config)#
radius-server host 10.0.0.5 key plaintext MySharedKey vrf mgmt -
Add a TACACS+ serverHPE Aruba AOS-CX · Global config (config)#
tacacs-server host 10.0.0.5 key plaintext MySharedKey vrf mgmt -
Log in with TACACS+, falling back to local usersHPE Aruba AOS-CX · Global config (config)#
aaa authentication login default group tacacs local -
Log in with RADIUS, falling back to local usersHPE Aruba AOS-CX · Global config (config)#
aaa authentication login default group radius local -
Show how logins are checkedHPE Aruba AOS-CX · Manager (#)
show aaa authentication -
Show the RADIUS serversHPE Aruba AOS-CX · Manager (#)
show radius-server detail -
Show the TACACS+ serversHPE Aruba AOS-CX · Manager (#)
show tacacs-server detail -
Send logs to a syslog serverHPE Aruba AOS-CX · Global config (config)#
logging 10.0.0.5 vrf mgmt -
Turn on SNMP with a read-only communityHPE Aruba AOS-CX · Global config (config)#
snmp-server vrf mgmt snmp-server community MyReadOnlyStringWarning: SNMP v1 and v2c send the community string unencrypted. Use SNMPv3 where you can.
HPE Aruba AOS-CX: 802.1X and MAC authentication
-
Put the RADIUS servers for 802.1X in a groupHPE Aruba AOS-CX · Global config (config)#
radius-server host 10.0.0.5 key plaintext MySharedKey aaa group server radius NAC-RADIUS server 10.0.0.5Warning: Port access talks to RADIUS over the default VRF. Add vrf mgmt to the radius-server host line only if the server is reached through the management port.
-
Turn on 802.1X for the switchHPE Aruba AOS-CX · Global config (config)#
aaa authentication port-access dot1x authenticator radius server-group NAC-RADIUS enable -
Turn on MAC authentication for the switchHPE Aruba AOS-CX · Global config (config)#
aaa authentication port-access mac-auth radius server-group NAC-RADIUS enable -
Turn on 802.1X on a portHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 aaa authentication port-access dot1x authenticator enableWarning: Once enabled, nothing on the port gets on the network until it authenticates. Test on one port before rolling it out.
-
Turn on MAC authentication on a portHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 aaa authentication port-access mac-auth enable -
Try MAC authentication before 802.1X on a portHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 aaa authentication port-access auth-precedence mac-auth dot1x -
Let more than one device authenticate on a portHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 aaa authentication port-access client-limit 2Warning: The default is 1, so a phone with a PC behind it needs at least 2.
-
Re-authenticate clients on a scheduleHPE Aruba AOS-CX · Global config (config)#
interface 1/1/1 aaa authentication port-access dot1x authenticator reauth reauth-period 3600 -
Send port-access accounting to RADIUSHPE Aruba AOS-CX · Global config (config)#
aaa accounting port-access start-stop interim 300 group NAC-RADIUS -
Let the RADIUS server change or end sessions (CoA)HPE Aruba AOS-CX · Global config (config)#
radius dyn-authorization client 10.0.0.5 secret-key plaintext MySharedKey radius dyn-authorization enable -
Force every client on a port to re-authenticateHPE Aruba AOS-CX · Manager (#)
port-access reauthenticate interface 1/1/1 -
Show the authenticated clientsHPE Aruba AOS-CX · Manager (#)
show port-access clients -
Show the clients in detailHPE Aruba AOS-CX · Manager (#)
show port-access clients detail -
Show 802.1X status and why a client failedHPE Aruba AOS-CX · Manager (#)
show aaa authentication port-access dot1x authenticator interface all client-status -
Show MAC authentication statusHPE Aruba AOS-CX · Manager (#)
show aaa authentication port-access mac-auth interface all client-status -
Show 802.1X counters on a portHPE Aruba AOS-CX · Manager (#)
show aaa authentication port-access dot1x authenticator interface 1/1/1 port-statistics -
Show the CoA settingsHPE Aruba AOS-CX · Manager (#)
show radius dyn-authorization
HPE Aruba AOS-CX: Troubleshooting
-
Ping from the management portHPE Aruba AOS-CX · Manager (#)
ping 10.20.1.5 vrf mgmt -
Ping from the data portsHPE Aruba AOS-CX · Manager (#)
ping 10.20.1.5 -
Trace the route to an addressHPE Aruba AOS-CX · Manager (#)
traceroute 10.20.1.5 -
Copy a port's traffic to another portHPE Aruba AOS-CX · Global config (config)#
mirror session 1 source interface 1/1/1 both destination interface 1/1/48 enable -
Show the mirror sessionsHPE Aruba AOS-CX · Manager (#)
show mirror -
Clear the ARP tableHPE Aruba AOS-CX · Manager (#)
clear arp -
Show the stack members (VSF)HPE Aruba AOS-CX · Manager (#)
show vsf -
Show how the stack is cabled (VSF)HPE Aruba AOS-CX · Manager (#)
show vsf topology
HPE Aruba AOS-CX: Upgrades
-
Show the installed software imagesHPE Aruba AOS-CX · Manager (#)
show images -
Download new software into the secondary slotHPE Aruba AOS-CX · Manager (#)
copy tftp://10.0.0.5/ArubaOS-CX_6300-6400_10_16_1010.swi secondary vrf mgmt -
Restart from the secondary imageHPE Aruba AOS-CX · Manager (#)
boot system secondaryWarning: Reboots the switch. Save the config first.
-
Make an image the one it starts fromHPE Aruba AOS-CX · Manager (#)
boot set-default secondary -
Copy the primary image to the secondary slotHPE Aruba AOS-CX · Manager (#)
copy primary secondary -
Show past restartsHPE Aruba AOS-CX · Manager (#)
show boot-history
Juniper Junos: Modes and getting around
-
Start the Junos CLI after logging in as rootJuniper Junos · Shell (%)
cli -
Go into configuration modeJuniper Junos · Operational mode (>)
configure -
Edit your own copy of the config, so other people's uncommitted changes aren't mixed inJuniper Junos · Operational mode (>)
configure private -
Edit the config and stop anyone else changing itJuniper Junos · Operational mode (>)
configure exclusive -
Show who else is editing the configJuniper Junos · Configuration mode (#)
status -
Move into part of the config, so commands are shorterJuniper Junos · Configuration mode (#)
edit interfaces ge-0/0/0 -
Go up one levelJuniper Junos · Configuration mode (#)
up -
Go back to the top of the configJuniper Junos · Configuration mode (#)
top -
Run an operational command from configuration modeJuniper Junos · Configuration mode (#)
run show interfaces terse -
Leave configuration modeJuniper Junos · Configuration mode (#)
exit -
Show the words that can come nextJuniper Junos · Operational mode (>)
show interfaces ? -
Stop output pausing at the end of each screenJuniper Junos · Operational mode (>)
set cli screen-length 0 -
Show times in your local time zoneJuniper Junos · Operational mode (>)
set cli timestamp
Juniper Junos: Filtering output
-
Show the config as set commandsJuniper Junos · Operational mode (>)
show configuration | display set -
Show only lines that match some textJuniper Junos · Operational mode (>)
show interfaces terse | match ge-0/0/ -
Show lines that match one of several wordsJuniper Junos · Operational mode (>)
show interfaces terse | match "ge-0/0/|lo0" -
Hide lines that match some textJuniper Junos · Operational mode (>)
show interfaces terse | except down -
Count the matching linesJuniper Junos · Operational mode (>)
show interfaces terse | match up | count -
Start the output at the first matchJuniper Junos · Operational mode (>)
show configuration | find protocols -
Show the last linesJuniper Junos · Operational mode (>)
show log messages | last 50 -
Show everything without pausingJuniper Junos · Operational mode (>)
show configuration | no-more -
Show output as JSONJuniper Junos · Operational mode (>)
show interfaces terse | display json -
Show output as XML, with the RPC to get it in scriptsJuniper Junos · Operational mode (>)
show interfaces terse | display xml rpc -
Save the output to a fileJuniper Junos · Operational mode (>)
show configuration | save /var/tmp/backup.conf -
Rerun a command every few secondsJuniper Junos · Operational mode (>)
show interfaces terse | refresh 2 -
Show where a setting came from, including groupsJuniper Junos · Configuration mode (#)
show interfaces | display inheritance
Juniper Junos: Commit, compare and roll back
-
Check the changes without applying themJuniper Junos · Configuration mode (#)
commit check -
Apply the changesJuniper Junos · Configuration mode (#)
commit -
Apply the changes, and undo them in a few minutes unless you confirmJuniper Junos · Configuration mode (#)
commit confirmed 5Warning: If you lose access, it rolls back by itself. Run commit (or commit check) before the time is up to keep the changes.
-
Apply the changes with a note in the historyJuniper Junos · Configuration mode (#)
commit comment "Add VLAN 20 for printers" -
Apply the changes and leave configuration modeJuniper Junos · Configuration mode (#)
commit and-quit -
Apply on both Routing Engines, or every Virtual Chassis memberJuniper Junos · Configuration mode (#)
commit synchronize -
See the changes you haven't committedJuniper Junos · Configuration mode (#)
show | compare -
Compare the config with an earlier commitJuniper Junos · Configuration mode (#)
show | compare rollback 1 -
Throw away the changes you haven't committedJuniper Junos · Configuration mode (#)
rollback 0 -
Load an earlier commit, ready to commit againJuniper Junos · Configuration mode (#)
rollback 1Warning: Replaces every uncommitted change. Check it with show | compare, then commit.
-
List the commit historyJuniper Junos · Operational mode (>)
show system commit -
Show what changed between two earlier commitsJuniper Junos · Operational mode (>)
show system rollback 1 compare 0 -
Save the current config as the rescue configJuniper Junos · Operational mode (>)
request system configuration rescue save -
Load the rescue config, ready to commitJuniper Junos · Configuration mode (#)
rollback rescue -
Save the config to a fileJuniper Junos · Configuration mode (#)
save /var/tmp/backup.conf -
Merge config from a fileJuniper Junos · Configuration mode (#)
load merge /var/tmp/backup.conf -
Paste in set commands (finish with Ctrl+D)Juniper Junos · Configuration mode (#)
load set terminal -
Paste in config in curly-brace format (finish with Ctrl+D)Juniper Junos · Configuration mode (#)
load merge terminal -
Replace the whole config from a fileJuniper Junos · Configuration mode (#)
load override /var/tmp/backup.confWarning: Everything not in the file is removed when you commit. Use commit confirmed.
-
Delete part of the configJuniper Junos · Configuration mode (#)
delete interfaces ge-0/0/0 unit 0Warning: Takes effect at the next commit. Check with show | compare first.
-
Turn part of the config off without deleting itJuniper Junos · Configuration mode (#)
deactivate interfaces ge-0/0/0 -
Turn it back onJuniper Junos · Configuration mode (#)
activate interfaces ge-0/0/0 -
Copy one interface's config to anotherJuniper Junos · Configuration mode (#)
copy interfaces ge-0/0/0 to ge-0/0/1
Juniper Junos: Basic setup
-
Set the hostnameJuniper Junos · Configuration mode (#)
set system host-name ex-sw1 -
Set the domain nameJuniper Junos · Configuration mode (#)
set system domain-name example.com -
Set the DNS serversJuniper Junos · Configuration mode (#)
set system name-server 192.0.2.53 -
Set the time zoneJuniper Junos · Configuration mode (#)
set system time-zone Europe/Dublin -
Set an NTP serverJuniper Junos · Configuration mode (#)
set system ntp server 192.0.2.123 -
Set the root password (you're asked for it)Juniper Junos · Configuration mode (#)
set system root-authentication plain-text-password -
Add an admin user (you're asked for the password)Juniper Junos · Configuration mode (#)
set system login user admin class super-user authentication plain-text-password -
Add a read-only userJuniper Junos · Configuration mode (#)
set system login user admin class read-only authentication plain-text-password -
Add an SSH key for a userJuniper Junos · Configuration mode (#)
set system login user admin authentication ssh-ed25519 "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExample admin@laptop" -
Set a login bannerJuniper Junos · Configuration mode (#)
set system login message "Authorised access only" -
Stop root logging in over SSHJuniper Junos · Configuration mode (#)
set system services ssh root-login deny -
Turn off TelnetJuniper Junos · Configuration mode (#)
delete system services telnet -
Turn on NETCONF over SSH, for Ansible and other automationJuniper Junos · Configuration mode (#)
set system services netconf ssh -
Set the management interface's address (fxp0 on MX and SRX)Juniper Junos · Configuration mode (#)
set interfaces fxp0 unit 0 family inet address 192.0.2.10/24 -
Set the management interface's address (me0 on EX)Juniper Junos · Configuration mode (#)
set interfaces me0 unit 0 family inet address 192.0.2.10/24 -
Set a default routeJuniper Junos · Configuration mode (#)
set routing-options static route 0.0.0.0/0 next-hop 192.168.1.1 -
Disconnect after failed login attemptsJuniper Junos · Configuration mode (#)
set system login retry-options tries-before-disconnect 3
Juniper Junos: Show and verify
-
Show the Junos version and modelJuniper Junos · Operational mode (>)
show version -
Show the model, version and Junos familyJuniper Junos · Operational mode (>)
show system information -
List the hardware, with serial numbersJuniper Junos · Operational mode (>)
show chassis hardware -
Show chassis alarms (fans, power, temperature)Juniper Junos · Operational mode (>)
show chassis alarms -
Show system alarms (licences, rescue config, partitions)Juniper Junos · Operational mode (>)
show system alarms -
Show temperatures, fans and power suppliesJuniper Junos · Operational mode (>)
show chassis environment -
Show the Routing Engine's CPU, memory and uptimeJuniper Junos · Operational mode (>)
show chassis routing-engine -
Show how long it's been up, and the last commitJuniper Junos · Operational mode (>)
show system uptime -
Show who's logged inJuniper Junos · Operational mode (>)
show system users -
Show disk spaceJuniper Junos · Operational mode (>)
show system storage -
List interfaces with their status and addressesJuniper Junos · Operational mode (>)
show interfaces terse -
Show one interface in full, with errors and countersJuniper Junos · Operational mode (>)
show interfaces ge-0/0/0 extensive -
List interface descriptionsJuniper Junos · Operational mode (>)
show interfaces descriptions -
Show optic light levelsJuniper Junos · Operational mode (>)
show interfaces diagnostics optics ge-0/0/0 -
List LLDP neighboursJuniper Junos · Operational mode (>)
show lldp neighbors -
Show the ARP table, without looking up namesJuniper Junos · Operational mode (>)
show arp no-resolve -
Show one part of the configJuniper Junos · Operational mode (>)
show configuration interfaces ge-0/0/0 -
Show licencesJuniper Junos · Operational mode (>)
show system license
Juniper Junos: Interfaces
-
Set a descriptionJuniper Junos · Configuration mode (#)
set interfaces ge-0/0/0 description "Uplink to core" -
Set an IPv4 addressJuniper Junos · Configuration mode (#)
set interfaces ge-0/0/0 unit 0 family inet address 192.168.10.1/24 -
Set an IPv6 addressJuniper Junos · Configuration mode (#)
set interfaces ge-0/0/0 unit 0 family inet6 address 2001:db8:10::1/64 -
Get an address by DHCPJuniper Junos · Configuration mode (#)
set interfaces ge-0/0/0 unit 0 family inet dhcp -
Shut an interface downJuniper Junos · Configuration mode (#)
set interfaces ge-0/0/0 disable -
Bring an interface back upJuniper Junos · Configuration mode (#)
delete interfaces ge-0/0/0 disable -
Set the MTUJuniper Junos · Configuration mode (#)
set interfaces ge-0/0/0 mtu 9192 -
Set a loopback addressJuniper Junos · Configuration mode (#)
set interfaces lo0 unit 0 family inet address 10.255.255.1/32 -
Add a tagged subinterface for a VLAN (routers and SRX)Juniper Junos · Configuration mode (#)
set interfaces ge-0/0/0 vlan-tagging set interfaces ge-0/0/0 unit 10 vlan-id 10 set interfaces ge-0/0/0 unit 10 family inet address 192.168.10.1/24 -
Group several ports so you can configure them onceJuniper Junos · Configuration mode (#)
set interfaces interface-range ACCESS-PORTS member-range ge-0/0/0 to ge-0/0/23 -
Clear an interface's countersJuniper Junos · Operational mode (>)
clear interfaces statistics ge-0/0/0 -
Watch an interface's traffic and errors liveJuniper Junos · Operational mode (>)
monitor interface ge-0/0/0 -
Watch traffic on every interfaceJuniper Junos · Operational mode (>)
monitor interface traffic
Juniper Junos: VLANs and switching (EX and QFX)
-
Make a VLANJuniper Junos · Configuration mode (#)
set vlans USERS vlan-id 10 -
Make a port an access port in a VLANJuniper Junos · Configuration mode (#)
set interfaces ge-0/0/0 unit 0 family ethernet-switching interface-mode access vlan members USERS -
Make a port a trunk carrying some VLANsJuniper Junos · Configuration mode (#)
set interfaces ge-0/0/0 unit 0 family ethernet-switching interface-mode trunk vlan members [ USERS SERVERS ] -
Carry every VLAN on a trunkJuniper Junos · Configuration mode (#)
set interfaces ge-0/0/0 unit 0 family ethernet-switching interface-mode trunk vlan members all -
Set a trunk's native (untagged) VLANJuniper Junos · Configuration mode (#)
set interfaces ge-0/0/0 native-vlan-id 10 -
Put a range of ports in a VLANJuniper Junos · Configuration mode (#)
set interfaces interface-range ACCESS-PORTS unit 0 family ethernet-switching interface-mode access vlan members USERS -
Give a VLAN a gateway address (IRB)Juniper Junos · Configuration mode (#)
set interfaces irb unit 10 family inet address 192.168.10.1/24 set vlans USERS l3-interface irb.10 -
List VLANs and their portsJuniper Junos · Operational mode (>)
show vlans -
Show the MAC address tableJuniper Junos · Operational mode (>)
show ethernet-switching table -
Find which port a MAC address is onJuniper Junos · Operational mode (>)
show ethernet-switching table | match aa:bb:cc:00:01:00 -
Show each port's mode and VLANsJuniper Junos · Operational mode (>)
show ethernet-switching interface -
Clear the MAC address tableJuniper Junos · Operational mode (>)
clear ethernet-switching table
Juniper Junos: Link aggregation (LAG)
-
Allow aggregated interfaces (ae)Juniper Junos · Configuration mode (#)
set chassis aggregated-devices ethernet device-count 2 -
Add a port to a LAG (EX and QFX)Juniper Junos · Configuration mode (#)
set interfaces ge-0/0/0 ether-options 802.3ad ae0 -
Add a port to a LAG (MX and SRX)Juniper Junos · Configuration mode (#)
set interfaces ge-0/0/0 gigether-options 802.3ad ae0 -
Turn on LACP for a LAGJuniper Junos · Configuration mode (#)
set interfaces ae0 aggregated-ether-options lacp active -
Make a LAG a trunk (EX and QFX)Juniper Junos · Configuration mode (#)
set interfaces ae0 unit 0 family ethernet-switching interface-mode trunk vlan members all -
Show LACP state for each LAGJuniper Junos · Operational mode (>)
show lacp interfaces -
Show a LAG and its member portsJuniper Junos · Operational mode (>)
show interfaces ae0 extensive
Juniper Junos: Spanning tree (EX and QFX)
-
Run RSTP on every portJuniper Junos · Configuration mode (#)
set protocols rstp interface all -
Make a port an edge port (to a host, not a switch)Juniper Junos · Configuration mode (#)
set protocols rstp interface ge-0/0/0 edge -
Shut edge ports that receive BPDUsJuniper Junos · Configuration mode (#)
set protocols rstp bpdu-block-on-edge -
Make this switch the root bridgeJuniper Junos · Configuration mode (#)
set protocols rstp bridge-priority 4k -
Show the root bridge and this switch's priorityJuniper Junos · Operational mode (>)
show spanning-tree bridge -
Show each port's spanning tree role and stateJuniper Junos · Operational mode (>)
show spanning-tree interface -
Re-enable a port shut by a BPDUJuniper Junos · Operational mode (>)
clear error bpdu interface ge-0/0/0
Juniper Junos: Static routing and routing instances
-
Add a static routeJuniper Junos · Configuration mode (#)
set routing-options static route 10.20.0.0/16 next-hop 192.168.1.254 -
Add a backup static route that's only used if the main one failsJuniper Junos · Configuration mode (#)
set routing-options static route 10.20.0.0/16 qualified-next-hop 192.168.1.253 preference 200 -
Drop traffic for a range (a discard route)Juniper Junos · Configuration mode (#)
set routing-options static route 10.20.0.0/16 discard -
Make a routing instance (like a VRF without MPLS)Juniper Junos · Configuration mode (#)
set routing-instances CUSTOMER-A instance-type virtual-router set routing-instances CUSTOMER-A interface ge-0/0/0.0 -
Show the routing tableJuniper Junos · Operational mode (>)
show route -
Show the route to an addressJuniper Junos · Operational mode (>)
show route 192.168.1.20 -
Show static routesJuniper Junos · Operational mode (>)
show route protocol static -
Show a routing instance's tableJuniper Junos · Operational mode (>)
show route table CUSTOMER-A.inet.0 -
Show how many routes there are, by protocolJuniper Junos · Operational mode (>)
show route summary -
Show the forwarding table entry for an addressJuniper Junos · Operational mode (>)
show route forwarding-table destination 192.168.1.20
Juniper Junos: OSPF
-
Set the router IDJuniper Junos · Configuration mode (#)
set routing-options router-id 10.255.255.1 -
Run OSPF on an interfaceJuniper Junos · Configuration mode (#)
set protocols ospf area 0.0.0.0 interface ge-0/0/0.0 -
Advertise the loopback without sending hellos on itJuniper Junos · Configuration mode (#)
set protocols ospf area 0.0.0.0 interface lo0.0 passive -
Set an OSPF interface to point-to-pointJuniper Junos · Configuration mode (#)
set protocols ospf area 0.0.0.0 interface ge-0/0/0.0 interface-type p2p -
List OSPF neighboursJuniper Junos · Operational mode (>)
show ospf neighbor -
List OSPF interfacesJuniper Junos · Operational mode (>)
show ospf interface -
Show the OSPF databaseJuniper Junos · Operational mode (>)
show ospf database -
Show routes learned by OSPFJuniper Junos · Operational mode (>)
show route protocol ospf
Juniper Junos: BGP
-
Set the AS numberJuniper Junos · Configuration mode (#)
set routing-options autonomous-system 65001 -
Add an external (eBGP) neighbourJuniper Junos · Configuration mode (#)
set protocols bgp group TRANSIT type external set protocols bgp group TRANSIT peer-as 65002 set protocols bgp group TRANSIT neighbor 198.51.100.1 -
Write a policy that advertises a prefixJuniper Junos · Configuration mode (#)
set policy-options prefix-list OUR-PREFIXES 10.20.0.0/16 set policy-options policy-statement ALLOW-WEB term OURS from prefix-list OUR-PREFIXES set policy-options policy-statement ALLOW-WEB term OURS then accept -
Advertise with that policyJuniper Junos · Configuration mode (#)
set protocols bgp group TRANSIT export ALLOW-WEB -
Show BGP neighbours and how many prefixes each sendsJuniper Junos · Operational mode (>)
show bgp summary -
Show one neighbour in detailJuniper Junos · Operational mode (>)
show bgp neighbor 198.51.100.1 -
Show the routes a neighbour sends youJuniper Junos · Operational mode (>)
show route receive-protocol bgp 198.51.100.1 -
Show the routes you send a neighbourJuniper Junos · Operational mode (>)
show route advertising-protocol bgp 198.51.100.1 -
Ask a neighbour to send its routes again, without dropping the sessionJuniper Junos · Operational mode (>)
clear bgp neighbor 198.51.100.1 soft-inbound -
Reset a BGP sessionJuniper Junos · Operational mode (>)
clear bgp neighbor 198.51.100.1Warning: Drops the session and every route learned from it until it comes back up.
Juniper Junos: Firewall filters (ACLs)
-
Allow SSH only from a management range, to the switch or router itselfJuniper Junos · Configuration mode (#)
set firewall family inet filter PROTECT-RE term ALLOW-SSH from source-address 192.0.2.0/24 set firewall family inet filter PROTECT-RE term ALLOW-SSH from protocol tcp set firewall family inet filter PROTECT-RE term ALLOW-SSH from destination-port ssh set firewall family inet filter PROTECT-RE term ALLOW-SSH then accept set firewall family inet filter PROTECT-RE term BLOCK-SSH from protocol tcp set firewall family inet filter PROTECT-RE term BLOCK-SSH from destination-port ssh set firewall family inet filter PROTECT-RE term BLOCK-SSH then discard set firewall family inet filter PROTECT-RE term EVERYTHING-ELSE then accept -
Apply a filter to traffic for the device itself (lo0)Juniper Junos · Configuration mode (#)
set interfaces lo0 unit 0 family inet filter input PROTECT-REWarning: A mistake here can lock you out, including routing protocols. Apply it with commit confirmed.
-
Apply a filter to traffic coming in on an interfaceJuniper Junos · Configuration mode (#)
set interfaces ge-0/0/0 unit 0 family inet filter input PROTECT-RE -
Count matches on a termJuniper Junos · Configuration mode (#)
set firewall family inet filter PROTECT-RE term BLOCK-SSH then count blocked-ssh -
Show a filter's countersJuniper Junos · Operational mode (>)
show firewall filter PROTECT-RE -
Clear a filter's countersJuniper Junos · Operational mode (>)
clear firewall filter PROTECT-RE
Juniper Junos: SRX security: zones, policies and NAT
-
Put an interface in a security zoneJuniper Junos · Configuration mode (#)
set security zones security-zone trust interfaces ge-0/0/0.0 -
Allow ping and SSH to the SRX from a zoneJuniper Junos · Configuration mode (#)
set security zones security-zone trust host-inbound-traffic system-services ping set security zones security-zone trust host-inbound-traffic system-services ssh -
Add an address to a zone's address bookJuniper Junos · Configuration mode (#)
set security address-book global address MGMT-NET 192.0.2.0/24 -
Allow web traffic from one zone to anotherJuniper Junos · Configuration mode (#)
set security policies from-zone trust to-zone untrust policy ALLOW-WEB match source-address any set security policies from-zone trust to-zone untrust policy ALLOW-WEB match destination-address any set security policies from-zone trust to-zone untrust policy ALLOW-WEB match application [ junos-http junos-https ] set security policies from-zone trust to-zone untrust policy ALLOW-WEB then permit -
Log sessions that a policy allowsJuniper Junos · Configuration mode (#)
set security policies from-zone trust to-zone untrust policy ALLOW-WEB then log session-close -
Move a policy above anotherJuniper Junos · Configuration mode (#)
insert security policies from-zone trust to-zone untrust policy ALLOW-WEB before policy DENY-ALL -
Hide a zone behind the outside interface's address (source NAT)Juniper Junos · Configuration mode (#)
set security nat source rule-set TRUST-TO-UNTRUST from zone trust set security nat source rule-set TRUST-TO-UNTRUST to zone untrust set security nat source rule-set TRUST-TO-UNTRUST rule HIDE-TRUST match source-address 0.0.0.0/0 set security nat source rule-set TRUST-TO-UNTRUST rule HIDE-TRUST then source-nat interface -
List zones and their interfacesJuniper Junos · Operational mode (>)
show security zones -
List policies with how often each was hitJuniper Junos · Operational mode (>)
show security policies hit-count -
Find which policy would handle some trafficJuniper Junos · Operational mode (>)
show security match-policies from-zone trust to-zone untrust source-ip 192.168.1.20 destination-ip 203.0.113.80 source-port 50000 destination-port 443 protocol tcp -
Show how many sessions there areJuniper Junos · Operational mode (>)
show security flow session summary -
Show sessions to an addressJuniper Junos · Operational mode (>)
show security flow session destination-prefix 203.0.113.80 -
Show source NAT rules and how often each was usedJuniper Junos · Operational mode (>)
show security nat source rule all -
Clear every sessionJuniper Junos · Operational mode (>)
clear security flow session allWarning: Drops every connection through the SRX, including yours if you're connected through it.
Juniper Junos: AAA, logging and SNMP
-
Add a RADIUS serverJuniper Junos · Configuration mode (#)
set system radius-server 192.168.1.5 secret "MySharedSecret"Warning: The secret ends up in your command history. Junos stores it encrypted in the config.
-
Add a TACACS+ serverJuniper Junos · Configuration mode (#)
set system tacplus-server 192.168.1.5 secret "MySharedSecret"Warning: The secret ends up in your command history. Junos stores it encrypted in the config.
-
Try RADIUS first, then local accountsJuniper Junos · Configuration mode (#)
set system authentication-order [ radius password ] -
Send logs to a syslog serverJuniper Junos · Configuration mode (#)
set system syslog host 192.0.2.50 any notice -
Log config changes to their own fileJuniper Junos · Configuration mode (#)
set system syslog file interactive-commands interactive-commands any -
Set a read-only SNMP communityJuniper Junos · Configuration mode (#)
set snmp community MyCommunity authorization read-onlyWarning: SNMPv1 and v2c send the community in plain text. Limit it to your monitoring server with a client list, or use SNMPv3.
-
Show the main logJuniper Junos · Operational mode (>)
show log messages | last 50 -
Search the main logJuniper Junos · Operational mode (>)
show log messages | match ge-0/0/ -
Show who changed whatJuniper Junos · Operational mode (>)
show log interactive-commands | last 50 -
Follow the main log liveJuniper Junos · Operational mode (>)
monitor start messages -
Stop following logsJuniper Junos · Operational mode (>)
monitor stop
Juniper Junos: Troubleshooting
-
Ping an addressJuniper Junos · Operational mode (>)
ping 192.168.1.20 count 5 -
Ping fast, from a given source addressJuniper Junos · Operational mode (>)
ping 192.168.1.20 source 10.255.255.1 rapid count 100 -
Ping inside a routing instanceJuniper Junos · Operational mode (>)
ping 192.168.1.20 routing-instance CUSTOMER-A -
Trace the route to an addressJuniper Junos · Operational mode (>)
traceroute 192.168.1.20 -
Capture packets to and from the device itselfJuniper Junos · Operational mode (>)
monitor traffic interface ge-0/0/0 no-resolve -
Show the processes using the most CPUJuniper Junos · Operational mode (>)
show system processes extensive | no-more -
Show the messages from the last bootJuniper Junos · Operational mode (>)
show system boot-messages -
Show the state of the line cards and their portsJuniper Junos · Operational mode (>)
show chassis fpc pic-status -
Show core dumps from crashed processesJuniper Junos · Operational mode (>)
show system core-dumps -
Save support information for JTACJuniper Junos · Operational mode (>)
request support information | save /var/tmp/rsi.txt -
Open a Unix shellJuniper Junos · Operational mode (>)
start shellWarning: Changes made in the shell bypass the config and its history. Use it to look, not to fix.
Juniper Junos: Files, upgrades and reboots
-
List filesJuniper Junos · Operational mode (>)
file list /var/tmp -
Copy a file from a server over SCPJuniper Junos · Operational mode (>)
file copy scp://[email protected]/images/junos.tgz /var/tmp/ -
Delete a fileJuniper Junos · Operational mode (>)
file delete /var/tmp/backup.conf -
See what a storage clean-up would deleteJuniper Junos · Operational mode (>)
request system storage cleanup dry-run -
Free up disk space by deleting old logs and temporary filesJuniper Junos · Operational mode (>)
request system storage cleanup -
Install a Junos upgrade and rebootJuniper Junos · Operational mode (>)
request system software add /var/tmp/junos-install-ex.tgz rebootWarning: The device reboots and drops traffic. Save a rescue config first, and do it in a maintenance window.
-
RebootJuniper Junos · Operational mode (>)
request system rebootWarning: Drops traffic until it's back up.
-
Reboot in a few minutesJuniper Junos · Operational mode (>)
request system reboot in 5 -
Shut down so the power can be removedJuniper Junos · Operational mode (>)
request system power-off -
Wipe the config and reset to factory defaultsJuniper Junos · Operational mode (>)
request system zeroizeWarning: Erases the config and data, with no undo. You'll need console access afterwards.
Juniper Junos: Virtual Chassis (EX)
-
Show the members, their roles and serial numbersJuniper Junos · Operational mode (>)
show virtual-chassis -
Show the ports linking the membersJuniper Junos · Operational mode (>)
show virtual-chassis vc-port -
Open a session on another memberJuniper Junos · Operational mode (>)
request session member 1
Check Point: Clish, Expert mode and getting around
-
Go from Clish to Expert mode (bash)Check Point Gaia · Gaia Clish (>)
expert -
Go back to Clish from Expert modeCheck Point Gaia · Expert mode (#)
exit -
Run a Clish command from Expert modeCheck Point Gaia · Expert mode (#)
clish -c "show version all" -
Set the Expert mode passwordCheck Point Gaia · Gaia Clish (>)
set expert-password -
Take the config lock when Clish says someone else has itCheck Point Gaia · Gaia Clish (>)
lock database override -
Stop output pausing at the end of each screenCheck Point Gaia · Gaia Clish (>)
set clienv rows 0 -
Show the Gaia version, kernel and editionCheck Point Gaia · Gaia Clish (>)
show version all -
Show the Check Point software versionCheck Point Gaia · Expert mode (#)
fw ver -
List installed products and Jumbo hotfixesCheck Point Gaia · Expert mode (#)
cpinfo -y all -
Show the whole Gaia config as Clish commandsCheck Point Gaia · Gaia Clish (>)
show configuration -
Save the Clish changes so they survive a rebootCheck Point Gaia · Gaia Clish (>)
save config -
Save the Gaia config to a file in your home folderCheck Point Gaia · Gaia Clish (>)
save configuration gaia-config.txt -
Load Gaia config from a fileCheck Point Gaia · Gaia Clish (>)
load configuration gaia-config.txtWarning: Applies every command in the file. Check it first, then save config.
-
Open the Check Point configuration menu (licences, SIC, products)Check Point Gaia · Expert mode (#)
cpconfig -
Run the first-time setup wizard from the command lineCheck Point Gaia · Expert mode (#)
config_system
Check Point: Gaia setup
-
Set the hostnameCheck Point Gaia · Gaia Clish (>)
set hostname cp-gw1 -
Give an interface an IP addressCheck Point Gaia · Gaia Clish (>)
set interface eth1 ipv4-address 192.168.10.1 mask-length 24 -
Bring an interface upCheck Point Gaia · Gaia Clish (>)
set interface eth1 state on -
Add a description to an interfaceCheck Point Gaia · Gaia Clish (>)
set interface eth1 comments "Inside LAN" -
Add a VLAN interfaceCheck Point Gaia · Gaia Clish (>)
add interface eth1 vlan 10 -
Give a VLAN interface an IP addressCheck Point Gaia · Gaia Clish (>)
set interface eth1.10 ipv4-address 192.168.10.1 mask-length 24 -
Set the default routeCheck Point Gaia · Gaia Clish (>)
set static-route default nexthop gateway address 203.0.113.1 on -
Add a static routeCheck Point Gaia · Gaia Clish (>)
set static-route 10.20.0.0/16 nexthop gateway address 203.0.113.1 on -
Remove a static routeCheck Point Gaia · Gaia Clish (>)
set static-route 10.20.0.0/16 off -
Set the DNS serverCheck Point Gaia · Gaia Clish (>)
set dns primary 192.168.10.53 -
Set the NTP serverCheck Point Gaia · Gaia Clish (>)
set ntp server primary pool.ntp.org version 4 -
Turn NTP onCheck Point Gaia · Gaia Clish (>)
set ntp active on -
Show the date, time and time zoneCheck Point Gaia · Gaia Clish (>)
show clock -
Add an admin userCheck Point Gaia · Gaia Clish (>)
add user netadmin uid 0 homedir /home/netadmin -
Set a user's password (it asks for it)Check Point Gaia · Gaia Clish (>)
set user netadmin password -
Give a user the admin roleCheck Point Gaia · Gaia Clish (>)
add rba user netadmin roles adminRole -
Make Expert mode a user's login shellCheck Point Gaia · Gaia Clish (>)
set user netadmin shell /bin/bash -
Allow SSH and the Gaia Portal from one host onlyCheck Point Gaia · Gaia Clish (>)
add allowed-client host ipv4-address 192.168.10.50Warning: Once you add a host, only listed hosts can connect. Add your own address first, and delete any-host last.
-
List the hosts allowed to connectCheck Point Gaia · Gaia Clish (>)
show allowed-client all
Check Point: Interfaces, bonds and routes
-
Show every interface with its addresses and stateCheck Point Gaia · Gaia Clish (>)
show interfaces all -
Show one interfaceCheck Point Gaia · Gaia Clish (>)
show interface eth1 -
Show interfaces the firewall knows about, with addressesCheck Point Gaia · Expert mode (#)
fw getifs -
Show the routing tableCheck Point Gaia · Gaia Clish (>)
show route -
Show static routes onlyCheck Point Gaia · Gaia Clish (>)
show route static -
Show the routing table in Expert modeCheck Point Gaia · Expert mode (#)
netstat -rn -
Show the ARP tableCheck Point Gaia · Gaia Clish (>)
show arp dynamic all -
Create a bond (link aggregation)Check Point Gaia · Gaia Clish (>)
add bonding group 1 -
Add an interface to a bondCheck Point Gaia · Gaia Clish (>)
add bonding group 1 interface eth1Warning: The interface must have no IP address first.
-
Set a bond to LACP (802.3ad)Check Point Gaia · Gaia Clish (>)
set bonding group 1 mode 8023AD -
Show a bond's settings and membersCheck Point Gaia · Gaia Clish (>)
show bonding group 1 -
Show bond status on a cluster memberCheck Point Gaia · Gaia Clish (>)
show cluster bond all
Check Point: Status and health
-
Show the policy installed on the gateway, and whenCheck Point Gaia · Expert mode (#)
fw stat -
Show firewall status and countersCheck Point Gaia · Expert mode (#)
cpstat fw -
Show CPU useCheck Point Gaia · Expert mode (#)
cpstat os -f cpu -
Show memory useCheck Point Gaia · Expert mode (#)
cpstat os -f memory -
Show a live dashboard of CPU, traffic and connectionsCheck Point Gaia · Expert mode (#)
cpview -
List Check Point processes and how often they've restartedCheck Point Gaia · Expert mode (#)
cpwd_admin list -
List the blades turned onCheck Point Gaia · Expert mode (#)
enabled_blades -
Show licencesCheck Point Gaia · Expert mode (#)
cplic print -
Show SecureXL (acceleration) statusCheck Point Gaia · Expert mode (#)
fwaccel stat -
Show how much traffic is acceleratedCheck Point Gaia · Expert mode (#)
fwaccel stats -s -
Show CoreXL firewall instances and their connectionsCheck Point Gaia · Expert mode (#)
fw ctl multik stat -
Show which CPU cores handle interfaces and instancesCheck Point Gaia · Expert mode (#)
fw ctl affinity -l -
Show firewall kernel memory and connection statsCheck Point Gaia · Expert mode (#)
fw ctl pstat -
Show disk spaceCheck Point Gaia · Expert mode (#)
df -h -
Run the HealthCheck Point testsCheck Point Gaia · Expert mode (#)
hcp -r all
Check Point: Policy on the gateway
-
Reload the last policy the gateway hadCheck Point Gaia · Expert mode (#)
fw fetch local -
Fetch the policy from the management serverCheck Point Gaia · Expert mode (#)
fw fetch 192.168.10.5 -
Remove the policy from the gatewayCheck Point Gaia · Expert mode (#)
fw unloadlocalWarning: Leaves the gateway with no policy, so it stops filtering. Only on a console, and reinstall the policy straight after.
-
Stop Check Point servicesCheck Point Gaia · Expert mode (#)
cpstopWarning: Stops all traffic through the gateway.
-
Start Check Point servicesCheck Point Gaia · Expert mode (#)
cpstart -
Restart Check Point servicesCheck Point Gaia · Expert mode (#)
cprestartWarning: Interrupts traffic while services restart.
-
Test which rule a connection would matchCheck Point Gaia · Expert mode (#)
fw up_execute mode=access in_ifn=eth1 ipp=6 src=192.168.10.25 dst=198.51.100.10 dport=443
Check Point: Connections and blocking
-
Count the current connectionsCheck Point Gaia · Expert mode (#)
fw tab -t connections -s -
List connections in a readable formatCheck Point Gaia · Expert mode (#)
fw ctl conntab -
List connections from one addressCheck Point Gaia · Expert mode (#)
fw ctl conntab -sip=192.168.10.25 -
List connections to one portCheck Point Gaia · Expert mode (#)
fw ctl conntab -dport=443 -
Delete the connections from one addressCheck Point Gaia · Expert mode (#)
fw ctl conntab -x -sip=192.168.10.25Warning: Cuts those connections straight away. Check the list without -x first.
-
List accelerated connectionsCheck Point Gaia · Expert mode (#)
fwaccel conns -
Block an address for a while and close its connectionsCheck Point Gaia · Expert mode (#)
fw sam -t 3600 -J src 192.168.10.25 -
Remove that blockCheck Point Gaia · Expert mode (#)
fw sam -C -J src 192.168.10.25 -
List active blocksCheck Point Gaia · Expert mode (#)
fw sam -M -J all -
Remove every blockCheck Point Gaia · Expert mode (#)
fw sam -D
Check Point: Packet capture and debugging
-
Capture traffic to and from an address, accelerated or notCheck Point Gaia · Expert mode (#)
fw monitor -F "192.168.10.25,0,0,0,0" -F "0,0,192.168.10.25,0,0" -
Capture traffic between two hosts on one portCheck Point Gaia · Expert mode (#)
fw monitor -F "192.168.10.25,0,198.51.100.10,443,0" -F "198.51.100.10,443,192.168.10.25,0,0" -
Save a capture to open in WiresharkCheck Point Gaia · Expert mode (#)
fw monitor -F "192.168.10.25,0,0,0,0" -F "0,0,192.168.10.25,0,0" -o /var/log/capture.cap -
Capture on an interface with tcpdumpCheck Point Gaia · Expert mode (#)
tcpdump -nni eth1 host 192.168.10.25 -
Show dropped packets and whyCheck Point Gaia · Expert mode (#)
fw ctl zdebug + drop -
Show drops for one address onlyCheck Point Gaia · Expert mode (#)
fw ctl zdebug + drop | grep 192.168.10.25 -
Reset kernel debug flags to normalCheck Point Gaia · Expert mode (#)
fw ctl debug 0 -
Show the order of inspection modulesCheck Point Gaia · Expert mode (#)
fw ctl chain
Check Point: ClusterXL
-
Show cluster members and which is activeCheck Point Gaia · Gaia Clish (>)
show cluster state -
Show cluster members and which is active (Expert mode)Check Point Gaia · Expert mode (#)
cphaprob state -
Show cluster interfaces and their stateCheck Point Gaia · Expert mode (#)
cphaprob -a if -
Show critical devices that are reporting a problemCheck Point Gaia · Gaia Clish (>)
show cluster members pnotes problem -
Show all critical devicesCheck Point Gaia · Expert mode (#)
cphaprob -l list -
Show state sync statisticsCheck Point Gaia · Expert mode (#)
cphaprob syncstat -
Show failover historyCheck Point Gaia · Expert mode (#)
cphaprob show_failover -
Check the members run the same softwareCheck Point Gaia · Expert mode (#)
cphaprob release -
Fail over by taking this member downCheck Point Gaia · Expert mode (#)
clusterXL_admin downWarning: Moves traffic to another member. Run clusterXL_admin up to bring it back.
-
Bring this member back into the clusterCheck Point Gaia · Expert mode (#)
clusterXL_admin up
Check Point: Site-to-site VPN
-
Open the VPN tunnel menu (list and delete SAs)Check Point Gaia · Expert mode (#)
vpn tu -
List VPN tunnels with trafficCheck Point Gaia · Expert mode (#)
vpn tu tlist -
List tunnels to one peerCheck Point Gaia · Expert mode (#)
vpn tu tlist -p 198.51.100.200 -
List IKE SAs for one peerCheck Point Gaia · Expert mode (#)
vpn tu list peer_ike 198.51.100.200 -
List IPsec SAs for one peerCheck Point Gaia · Expert mode (#)
vpn tu list peer_ipsec 198.51.100.200 -
Show VPN status and countersCheck Point Gaia · Expert mode (#)
cpstat vpn -
Start IKE debugging with fresh log filesCheck Point Gaia · Expert mode (#)
vpn debug trunc -
Start IKE debuggingCheck Point Gaia · Expert mode (#)
vpn debug ikeon -
Stop VPN debuggingCheck Point Gaia · Expert mode (#)
vpn debug off -
Stop IKE debuggingCheck Point Gaia · Expert mode (#)
vpn debug ikeoff
Check Point: Management server and the API
-
Show management server statusCheck Point Gaia · Expert mode (#)
cpstat mg -
Check the management API is runningCheck Point Gaia · Expert mode (#)
api status -
Restart the management APICheck Point Gaia · Expert mode (#)
api restart -
Log in to the API and keep the session in a fileCheck Point Gaia · Expert mode (#)
mgmt_cli login -r true > id.txt -
Add a host objectCheck Point Gaia · Expert mode (#)
mgmt_cli add host name web-server-1 ip-address 192.168.10.1 -s id.txt -
Publish your changesCheck Point Gaia · Expert mode (#)
mgmt_cli publish -s id.txt -
Install a policy package on a gatewayCheck Point Gaia · Expert mode (#)
mgmt_cli install-policy policy-package "Standard" targets "cp-gw1" -s id.txt -
Log out of the APICheck Point Gaia · Expert mode (#)
mgmt_cli logout -s id.txt -
List gateways and serversCheck Point Gaia · Expert mode (#)
mgmt_cli -r true show gateways-and-servers -
Show a rulebase as JSONCheck Point Gaia · Expert mode (#)
mgmt_cli -r true show access-rulebase name "Network" --format json -
Find where an object is usedCheck Point Gaia · Expert mode (#)
mgmt_cli -r true where-used name web-server-1 -
Show the SIC trust state on a gatewayCheck Point Gaia · Expert mode (#)
cp_conf sic state -
Reset SIC on a gateway with a new activation keyCheck Point Gaia · Expert mode (#)
cp_conf sic init MyOneTimeKeyWarning: Breaks trust with the management server until you reset SIC on the gateway object in SmartConsole with the same key.
-
Export the management database for a migrationCheck Point Gaia · Expert mode (#)
$FWDIR/scripts/migrate_server export -v R82.10 /var/log/mgmt-export.tgz
Check Point: Upgrades and hotfixes (CPUSE)
-
Check for new packagesCheck Point Gaia · Gaia Clish (>)
installer check-for-updates -
List packages you can downloadCheck Point Gaia · Gaia Clish (>)
show installer packages available-for-download -
List installed packagesCheck Point Gaia · Gaia Clish (>)
show installer packages installed -
Download a package by its numberCheck Point Gaia · Gaia Clish (>)
installer download 1 -
Import a package you copied to the gatewayCheck Point Gaia · Gaia Clish (>)
installer import local /var/log/upload/Check_Point_R82_10_JUMBO_HF_Bundle_FULL.tgz -
List imported packagesCheck Point Gaia · Gaia Clish (>)
show installer packages imported -
Check a package can be installedCheck Point Gaia · Gaia Clish (>)
installer verify 1 -
Install a packageCheck Point Gaia · Gaia Clish (>)
installer install 1Warning: Most packages reboot the gateway. On a cluster, do one member at a time.
-
Upgrade to a new major versionCheck Point Gaia · Gaia Clish (>)
installer upgrade 1Warning: Reboots the gateway. Take a backup first, and upgrade the management server before its gateways.
-
Uninstall a packageCheck Point Gaia · Gaia Clish (>)
installer uninstall 1
Check Point: Backups and snapshots
-
Back up the system to the gatewayCheck Point Gaia · Gaia Clish (>)
add backup local -
Back up the system to an SCP serverCheck Point Gaia · Gaia Clish (>)
add backup scp ip 192.168.10.60 path /backups/ username backup interactive -
Show backup progressCheck Point Gaia · Gaia Clish (>)
show backup status -
List backupsCheck Point Gaia · Gaia Clish (>)
show backups -
Take a snapshot of the whole system and save it as a fileCheck Point Gaia · Gaia Clish (>)
add snapshot-onetime name before-upgrade description "Inside LAN" target local path /var/log/ -
Show a snapshot's date, description and sizeCheck Point Gaia · Gaia Clish (>)
show snapshot before-upgrade all
Check Point: Troubleshooting
-
Ping from the gatewayCheck Point Gaia · Gaia Clish (>)
ping 198.51.100.10 -
Trace the route to a hostCheck Point Gaia · Gaia Clish (>)
traceroute 198.51.100.10 -
Show the system log as it's writtenCheck Point Gaia · Expert mode (#)
tail -f /var/log/messages -
Show the firewall daemon logCheck Point Gaia · Expert mode (#)
tail -f $FWDIR/log/fwd.elg -
Show the busiest processesCheck Point Gaia · Expert mode (#)
top -
Collect diagnostics for Check Point supportCheck Point Gaia · Expert mode (#)
cpinfo -z -o /var/log/cpinfo-gw1.info -
List the log files on this machineCheck Point Gaia · Expert mode (#)
fw lslogs
Palo Alto: Modes and getting around
-
Go into configuration modePAN-OS · Operational mode (>)
configure -
Leave configuration modePAN-OS · Configuration mode (#)
exit -
Run an operational command from configuration modePAN-OS · Configuration mode (#)
run show system info -
Show the model, serial number, PAN-OS version and uptimePAN-OS · Operational mode (>)
show system info -
Stop output pausing at the end of each screenPAN-OS · Operational mode (>)
set cli pager off -
Show config as set commands instead of XML-style blocksPAN-OS · Operational mode (>)
set cli config-output-format set -
Find commands that contain a wordPAN-OS · Operational mode (>)
find command keyword session -
Show only lines that match some textPAN-OS · Operational mode (>)
show interface all | match session -
Show running and finished jobs (commits, downloads, installs)PAN-OS · Operational mode (>)
show jobs all -
Show one job's progressPAN-OS · Operational mode (>)
show jobs id 42 -
Show who is logged inPAN-OS · Operational mode (>)
show admins -
Show the date and timePAN-OS · Operational mode (>)
show clock
Palo Alto: Commit and configuration files
-
Show the changes you haven't committedPAN-OS · Operational mode (>)
show config diff -
Check the changes without applying themPAN-OS · Configuration mode (#)
validate full -
Apply the changesPAN-OS · Configuration mode (#)
commit -
Apply the changes with a descriptionPAN-OS · Configuration mode (#)
commit description "Allow web from inside" -
Throw away uncommitted changes by reloading the running configPAN-OS · Configuration mode (#)
load config from running-config.xml -
Show the running configPAN-OS · Operational mode (>)
show config running -
Show the candidate config (with your changes)PAN-OS · Operational mode (>)
show config candidate -
Save the candidate config to a named filePAN-OS · Configuration mode (#)
save config to before-change.xml -
Load a saved config file, ready to commitPAN-OS · Configuration mode (#)
load config from before-change.xmlWarning: Replaces the whole candidate config. Check it with show config diff, then commit.
-
Copy the running config to an SCP serverPAN-OS · Operational mode (>)
scp export configuration from running-config.xml to [email protected]:/backups -
Copy a config file in from an SCP serverPAN-OS · Operational mode (>)
scp import configuration from [email protected]:/backups/before-change.xml
Palo Alto: Basic setup
-
Set the hostnamePAN-OS · Configuration mode (#)
set deviceconfig system hostname pa-fw1 -
Set the management interface addressPAN-OS · Configuration mode (#)
set deviceconfig system ip-address 192.168.10.2 netmask 255.255.255.0 default-gateway 192.168.10.1Warning: Your session drops when you commit if you're connected to the old address.
-
Set the DNS serverPAN-OS · Configuration mode (#)
set deviceconfig system dns-setting servers primary 192.168.10.53 -
Set the NTP serverPAN-OS · Configuration mode (#)
set deviceconfig system ntp-servers primary-ntp-server ntp-server-address pool.ntp.org -
Set the time zonePAN-OS · Configuration mode (#)
set deviceconfig system timezone Europe/Dublin -
Allow management access only from one networkPAN-OS · Configuration mode (#)
set deviceconfig system permitted-ip 192.168.10.0/24Warning: Once one is set, only listed networks can reach the management interface. Add your own first.
-
Add an admin user with full rightsPAN-OS · Configuration mode (#)
set mgt-config users netadmin permissions role-based superuser yes -
Set an admin's password (it asks for it)PAN-OS · Configuration mode (#)
set mgt-config users netadmin password
Palo Alto: Interfaces, zones and routing
-
Give a Layer 3 interface an IP addressPAN-OS · Configuration mode (#)
set network interface ethernet ethernet1/1 layer3 ip 192.168.20.1/24 -
Allow ping and other management on an interfacePAN-OS · Configuration mode (#)
set network interface ethernet ethernet1/1 layer3 interface-management-profile allow-ping -
Add a VLAN subinterfacePAN-OS · Configuration mode (#)
set network interface ethernet ethernet1/1 layer3 units ethernet1/1.10 tag 10 -
Put an interface in a zonePAN-OS · Configuration mode (#)
set zone trust network layer3 ethernet1/1 -
Add an interface to the virtual routerPAN-OS · Configuration mode (#)
set network virtual-router default interface ethernet1/1 -
Add a default routePAN-OS · Configuration mode (#)
set network virtual-router default routing-table ip static-route default-route destination 0.0.0.0/0 nexthop ip-address 203.0.113.1 -
Show every interfacePAN-OS · Operational mode (>)
show interface all -
Show one interface's counters and settingsPAN-OS · Operational mode (>)
show interface ethernet1/1 -
Show the routing tablePAN-OS · Operational mode (>)
show routing route -
Show the forwarding tablePAN-OS · Operational mode (>)
show routing fib -
Show the routing table (Advanced Routing Engine)PAN-OS · Operational mode (>)
show advanced-routing route -
Find which route and interface an address usesPAN-OS · Operational mode (>)
test routing fib-lookup virtual-router default ip 198.51.100.10 -
Show the ARP tablePAN-OS · Operational mode (>)
show arp all
Palo Alto: Objects, security rules and NAT
-
Add an address objectPAN-OS · Configuration mode (#)
set address web-server-1 ip-netmask 192.168.20.10/32 -
Add an address groupPAN-OS · Configuration mode (#)
set address-group web-servers static [ web-server-1 ] -
Add a service (port) objectPAN-OS · Configuration mode (#)
set service tcp-8443 protocol tcp port 443 -
Add a security rulePAN-OS · Configuration mode (#)
set rulebase security rules allow-web from trust to untrust source any destination web-server-1 application [ ssl web-browsing ] service application-default action allow -
Move a rule to the topPAN-OS · Configuration mode (#)
move rulebase security rules allow-web top -
Move a rule above another onePAN-OS · Configuration mode (#)
move rulebase security rules allow-web before deny-all -
Turn a rule off without deleting itPAN-OS · Configuration mode (#)
set rulebase security rules allow-web disabled yes -
Delete a rulePAN-OS · Configuration mode (#)
delete rulebase security rules allow-web -
Add source NAT to the outside interface's addressPAN-OS · Configuration mode (#)
set rulebase nat rules outbound-nat from trust to untrust source any destination any service any source-translation dynamic-ip-and-port interface-address interface ethernet1/1 -
Test which security rule some traffic would matchPAN-OS · Operational mode (>)
test security-policy-match from trust to untrust source 192.168.20.25 destination 198.51.100.10 destination-port 443 protocol 6 -
Test which NAT rule some traffic would matchPAN-OS · Operational mode (>)
test nat-policy-match from trust to untrust source 192.168.20.25 destination 198.51.100.10 destination-port 443 protocol 6 -
Show the security rules the firewall is runningPAN-OS · Operational mode (>)
show running security-policy -
Show the NAT rules the firewall is runningPAN-OS · Operational mode (>)
show running nat-policy -
Show hit counts for every security rulePAN-OS · Operational mode (>)
show rule-hit-count vsys vsys-name vsys1 rule-base security rules all -
List security rules that haven't been usedPAN-OS · Operational mode (>)
show running rule-use rule-base security type unused vsys vsys1
Palo Alto: Sessions and counters
-
Show session table totalsPAN-OS · Operational mode (>)
show session info -
List sessions from an addressPAN-OS · Operational mode (>)
show session all filter source 192.168.20.25 -
List sessions to an address and portPAN-OS · Operational mode (>)
show session all filter destination 198.51.100.10 destination-port 443 -
Count active sessions on a rulePAN-OS · Operational mode (>)
show session all filter rule allow-web count yes -
Show one session in detailPAN-OS · Operational mode (>)
show session id 12345 -
Clear one sessionPAN-OS · Operational mode (>)
clear session id 12345 -
Clear every session from an addressPAN-OS · Operational mode (>)
clear session all filter source 192.168.20.25Warning: Cuts those connections straight away.
-
Show why packets are being dropped, since the last runPAN-OS · Operational mode (>)
show counter global filter delta yes severity drop -
Show CPU, memory and processes on the management planePAN-OS · Operational mode (>)
show system resources -
Show dataplane CPU and buffer usePAN-OS · Operational mode (>)
show running resource-monitor -
Show disk spacePAN-OS · Operational mode (>)
show system disk-space
Palo Alto: Packet capture and flow debugging
-
See the current capture and debug settingsPAN-OS · Operational mode (>)
debug dataplane packet-diag show setting -
Clear old capture and debug settings firstPAN-OS · Operational mode (>)
debug dataplane packet-diag clear all -
Match traffic from one address to anotherPAN-OS · Operational mode (>)
debug dataplane packet-diag set filter match source 192.168.20.25 destination 198.51.100.10 -
Match the return traffic tooPAN-OS · Operational mode (>)
debug dataplane packet-diag set filter match source 198.51.100.10 destination 192.168.20.25 -
Turn the filter onPAN-OS · Operational mode (>)
debug dataplane packet-diag set filter onWarning: Always turn the filter on before a capture or flow debug, or it captures everything.
-
Capture packets as they arrivePAN-OS · Operational mode (>)
debug dataplane packet-diag set capture stage receive file rx.pcap -
Capture dropped packetsPAN-OS · Operational mode (>)
debug dataplane packet-diag set capture stage drop file drop.pcap -
Start capturingPAN-OS · Operational mode (>)
debug dataplane packet-diag set capture on -
Stop capturingPAN-OS · Operational mode (>)
debug dataplane packet-diag set capture off -
Read a capture on the CLIPAN-OS · Operational mode (>)
view-pcap filter-pcap rx.pcap -
Log how the firewall handles matching packetsPAN-OS · Operational mode (>)
debug dataplane packet-diag set log feature flow basic -
Start flow loggingPAN-OS · Operational mode (>)
debug dataplane packet-diag set log on -
Stop flow loggingPAN-OS · Operational mode (>)
debug dataplane packet-diag set log off -
Capture on the management interfacePAN-OS · Operational mode (>)
tcpdump filter "host 192.168.20.25 and not port 22" -
Read the management interface capturePAN-OS · Operational mode (>)
view-pcap mgmt-pcap mgmt.pcap
Palo Alto: Logs
-
Show the newest traffic logsPAN-OS · Operational mode (>)
show log traffic direction equal backward -
Show traffic logs for one rulePAN-OS · Operational mode (>)
show log traffic rule equal allow-web -
Show the newest threat logsPAN-OS · Operational mode (>)
show log threat direction equal backward -
Show the newest system logsPAN-OS · Operational mode (>)
show log system direction equal backward -
Show the newest config change logsPAN-OS · Operational mode (>)
show log config direction equal backward -
Follow the management server logPAN-OS · Operational mode (>)
tail follow yes mp-log ms.log -
Read the authentication logPAN-OS · Operational mode (>)
less mp-log authd.log
Palo Alto: High availability
-
Show HA state and the peer's statePAN-OS · Operational mode (>)
show high-availability state -
Show all HA detailsPAN-OS · Operational mode (>)
show high-availability all -
Check session sync between the pairPAN-OS · Operational mode (>)
show high-availability state-synchronization -
Push this firewall's config to the peerPAN-OS · Operational mode (>)
request high-availability sync-to-remote running-configWarning: Overwrites the peer's config.
-
Fail over by suspending this firewallPAN-OS · Operational mode (>)
request high-availability state suspendWarning: Moves traffic to the peer. Run request high-availability state functional to bring it back.
-
Bring a suspended firewall backPAN-OS · Operational mode (>)
request high-availability state functional
Palo Alto: IPsec VPN and GlobalProtect
-
Show IKE phase 1 SAsPAN-OS · Operational mode (>)
show vpn ike-sa -
Show IKE SAs for one gatewayPAN-OS · Operational mode (>)
show vpn ike-sa gateway branch-gw -
Show IPsec phase 2 SAsPAN-OS · Operational mode (>)
show vpn ipsec-sa -
Show tunnels with packet and byte countersPAN-OS · Operational mode (>)
show vpn flow -
Start IKE phase 1 with a gatewayPAN-OS · Operational mode (>)
test vpn ike-sa gateway branch-gw -
Start IPsec phase 2 for a tunnelPAN-OS · Operational mode (>)
test vpn ipsec-sa tunnel branch-tunnel -
Reset phase 1 with a gatewayPAN-OS · Operational mode (>)
clear vpn ike-sa gateway branch-gw -
Reset phase 2 for a tunnelPAN-OS · Operational mode (>)
clear vpn ipsec-sa tunnel branch-tunnel -
Read the IKE logPAN-OS · Operational mode (>)
less mp-log ikemgr.log -
List users connected to GlobalProtectPAN-OS · Operational mode (>)
show global-protect-gateway current-user
Palo Alto: User-ID
-
List IP-to-user mappingsPAN-OS · Operational mode (>)
show user ip-user-mapping all -
Show the user mapped to one addressPAN-OS · Operational mode (>)
show user ip-user-mapping ip 192.168.20.25 -
List groups the firewall knowsPAN-OS · Operational mode (>)
show user group list -
List members of a groupPAN-OS · Operational mode (>)
show user group name "cn=it-staff,ou=groups,dc=example,dc=com" -
Show group mapping statusPAN-OS · Operational mode (>)
show user group-mapping state all -
Check the built-in User-ID agent is connectedPAN-OS · Operational mode (>)
show user server-monitor state all -
Clear one address's user mappingPAN-OS · Operational mode (>)
clear user-cache ip 192.168.20.25/32
Palo Alto: Software, content and licences
-
Check for PAN-OS versionsPAN-OS · Operational mode (>)
request system software check -
List PAN-OS versions available and downloadedPAN-OS · Operational mode (>)
request system software info -
Download a PAN-OS versionPAN-OS · Operational mode (>)
request system software download version 12.1.4 -
Install a PAN-OS versionPAN-OS · Operational mode (>)
request system software install version 12.1.4Warning: Takes effect after a reboot. On an HA pair, upgrade one firewall at a time.
-
Reboot the firewallPAN-OS · Operational mode (>)
request restart systemWarning: Stops all traffic until it's back up.
-
Check for app and threat updatesPAN-OS · Operational mode (>)
request content upgrade check -
Download the latest app and threat contentPAN-OS · Operational mode (>)
request content upgrade download latest -
Install the latest app and threat contentPAN-OS · Operational mode (>)
request content upgrade install version latest -
Download the latest antivirusPAN-OS · Operational mode (>)
request anti-virus upgrade download latest -
Fetch licences from Palo Alto NetworksPAN-OS · Operational mode (>)
request license fetch -
Show licencesPAN-OS · Operational mode (>)
request license info
Palo Alto: Troubleshooting
-
Ping from a dataplane interface addressPAN-OS · Operational mode (>)
ping source 192.168.20.25 host 198.51.100.10 -
Trace the route from a dataplane interface addressPAN-OS · Operational mode (>)
traceroute source 192.168.20.25 host 198.51.100.10 -
Test an authentication profilePAN-OS · Operational mode (>)
test authentication authentication-profile ldap-auth username netadmin password -
Check which URL category a site is inPAN-OS · Operational mode (>)
test url www.example.com -
Show an interface's error countersPAN-OS · Operational mode (>)
show counter interface ethernet1/1 -
Restart the management server processPAN-OS · Operational mode (>)
debug software restart process management-serverWarning: Drops admin sessions while it restarts. Traffic keeps flowing.
Fortinet: Getting around
-
Show the model, serial number, firmware and uptimeFortiOS
get system status -
Show CPU, memory, sessions and uptimeFortiOS
get system performance status -
Show part of the config (only settings changed from the default)FortiOS
show system interface -
Show part of the config with every default tooFortiOS
show full-configuration system interface -
Show config lines that match some textFortiOS
show | grep port1 -
Show matching config with the block around itFortiOS
show firewall policy | grep -f port1 -
Stop output pausing at the end of each screenFortiOS
config system console set output standard end -
Leave a config block without saving the changeFortiOS
abort -
Go into a VDOM (when VDOMs are on)FortiOS
config vdom edit root -
Go into global settings (when VDOMs are on)FortiOS
config global
Fortinet: Basic setup
-
Set the hostnameFortiOS
config system global set hostname fgt-hq end -
Set the admin idle timeout in minutesFortiOS
config system global set admintimeout 10 end -
Give an interface an IP address and allow management on itFortiOS
config system interface edit port2 set ip 192.168.10.1 255.255.255.0 set allowaccess ping https ssh next end -
Add a VLAN interfaceFortiOS
config system interface edit vlan10 set vdom root set interface port2 set vlanid 10 set ip 192.168.110.1 255.255.255.0 next end -
Add a default routeFortiOS
config router static edit 0 set gateway 203.0.113.1 set device wan1 next end -
Add a static routeFortiOS
config router static edit 0 set dst 10.20.0.0 255.255.255.0 set gateway 203.0.113.1 set device port2 next end -
Set the DNS serversFortiOS
config system dns set primary 192.168.10.53 set secondary 1.1.1.1 end -
Set a custom NTP serverFortiOS
config system ntp set ntpsync enable set type custom config ntpserver edit 1 set server pool.ntp.org next end end -
Add an admin userFortiOS
config system admin edit netadmin set accprofile super_admin set password ChangeMe-2026 next end -
Allow an admin to log in only from one networkFortiOS
config system admin edit netadmin set trusthost1 192.168.10.0 255.255.255.0 next endWarning: That admin can't log in from anywhere else. Set it on another admin first and test.
Fortinet: Interfaces and routing
-
Show interfaces with addresses and statusFortiOS
get system interface physical -
Show an interface's speed, duplex and errorsFortiOS
diagnose hardware deviceinfo nic port2 -
Show the routing tableFortiOS
get router info routing-table all -
Show the route to one addressFortiOS
get router info routing-table details 198.51.100.10 -
Add a link aggregation (LACP) interfaceFortiOS
config system interface edit agg1 set vdom root set type aggregate set member port3 port4 set lacp-mode active next end -
Group interfaces into a zoneFortiOS
config system zone edit inside set interface port2 vlan10 next end -
Renew an interface's DHCP addressFortiOS
execute interface dhcpclient-renew wan1 -
Show the ARP table (kernel view)FortiOS
diagnose ip arp list -
Clear the ARP tableFortiOS
execute clear system arp table -
Show the ARP tableFortiOS
get system arp -
Show BGP neighboursFortiOS
get router info bgp summary -
Show OSPF neighboursFortiOS
get router info ospf neighbor
Fortinet: Routing protocols
-
Set up OSPF in area 0FortiOS
config router ospf set router-id 10.255.255.1 config area edit 0.0.0.0 next end config network edit 1 set prefix 10.20.0.0 255.255.255.0 set area 0.0.0.0 next end end -
Set up a BGP neighbourFortiOS
config router bgp set as 65001 set router-id 10.255.255.1 config neighbor edit 10.0.12.2 set remote-as 65002 next end end -
Advertise a network in BGPFortiOS
config router bgp config network edit 1 set prefix 10.20.0.0 255.255.255.0 next end end -
Show BGP neighbour detailsFortiOS
get router info bgp neighbors -
Show BGP routesFortiOS
get router info bgp network -
Soft-reset all BGP sessions (keeps them up)FortiOS
execute router clear bgp all soft -
Reset all BGP sessionsFortiOS
execute router clear bgp allWarning: Drops every BGP session until they come back up.
-
Show OSPF interfacesFortiOS
get router info ospf interface -
Show policy routesFortiOS
diagnose firewall proute list
Fortinet: Objects and firewall policies
-
Add an address objectFortiOS
config firewall address edit web-server-1 set subnet 10.20.0.0 255.255.255.0 next end -
Add an address groupFortiOS
config firewall addrgrp edit web-servers set member web-server-1 next end -
Add a custom service (port)FortiOS
config firewall service custom edit tcp-8443 set tcp-portrange 443 next end -
Add a firewall policy with NAT to the internetFortiOS
config firewall policy edit 0 set name inside-to-internet set srcintf port2 set dstintf wan1 set srcaddr all set dstaddr all set action accept set schedule always set service ALL set nat enable set logtraffic all next end -
Move a policy above anotherFortiOS
config firewall policy move 5 before 2 end -
Turn a policy off without deleting itFortiOS
config firewall policy edit 5 set status disable next end -
Delete a policyFortiOS
config firewall policy delete 5 end -
Show one policyFortiOS
show firewall policy 5 -
Forward a port to an inside server (virtual IP)FortiOS
config firewall vip edit web-https set extintf wan1 set portforward enable set extip 203.0.113.10 set mappedip 192.168.10.80 set extport 443 set mappedport 443 next end -
Find which policy some traffic would matchFortiOS
diagnose firewall iprope lookup 192.168.10.25 0 198.51.100.10 443 6 port2
Fortinet: Security profiles and inspection
-
Turn on certificate inspection and the default profiles on a policyFortiOS
config firewall policy edit 5 set utm-status enable set ssl-ssh-profile certificate-inspection set av-profile default set webfilter-profile default set ips-sensor default set application-list default next end -
Show web filter rating statisticsFortiOS
diagnose webfilter fortiguard statistics -
Show the FortiGuard rating serversFortiOS
diagnose debug rating -
Show FortiGuard update statusFortiOS
diagnose autoupdate status -
Restart the IPS engineFortiOS
diagnose test application ipsmonitor 99Warning: Inspection pauses while it restarts.
-
Show the IP addresses behind FQDN objectsFortiOS
diagnose test application dnsproxy 6
Fortinet: Users and authentication
-
Add a local userFortiOS
config user local edit jsmith set type password set passwd ChangeMe-2026 next end -
Add a user groupFortiOS
config user group edit vpn-users set member jsmith next end -
Add an LDAP serverFortiOS
config user ldap edit corp-ldap set server 192.168.10.20 set cnid sAMAccountName set dn dc=example,dc=com set type regular set username svc-fortigate set password ChangeMe-2026 next end -
Add a RADIUS serverFortiOS
config user radius edit corp-radius set server 192.168.10.21 set secret RadiusSecret next end -
Test a login against a RADIUS serverFortiOS
diagnose test authserver radius corp-radius pap netadmin ChangeMe-2026 -
Debug authenticationFortiOS
diagnose debug application fnbamd -1 -
List authenticated firewall usersFortiOS
diagnose firewall auth list
Fortinet: SD-WAN
-
Turn on SD-WAN and add two internet linksFortiOS
config system sdwan set status enable config members edit 1 set interface wan1 set gateway 203.0.113.1 next edit 2 set interface wan2 set gateway 198.51.100.1 next end end -
Add a performance SLA (health check)FortiOS
config system sdwan config health-check edit internet set server 8.8.8.8 set members 1 2 next end end -
Show SD-WAN membersFortiOS
diagnose sys sdwan member -
Show health check results (loss, latency, jitter)FortiOS
diagnose sys sdwan health-check -
Show which links SD-WAN rules are usingFortiOS
diagnose sys sdwan service -
Show a link's SLA historyFortiOS
diagnose sys sdwan intf-sla-log wan1
Fortinet: DHCP and DNS
-
Run a DHCP server on an interfaceFortiOS
config system dhcp server edit 0 set interface port2 set default-gateway 192.168.10.1 set netmask 255.255.255.0 set dns-service default config ip-range edit 1 set start-ip 192.168.10.100 set end-ip 192.168.10.200 next end next end -
List DHCP leasesFortiOS
execute dhcp lease-list -
Clear one DHCP leaseFortiOS
execute dhcp lease-clear 192.168.10.25 -
Answer DNS queries on an interfaceFortiOS
config system dns-server edit port2 set mode recursive next end
Fortinet: VDOMs
-
Turn on multiple VDOMsFortiOS
config system global set vdom-mode multi-vdom endWarning: Logs you out, and moves the existing config into the root VDOM.
-
Add a VDOMFortiOS
config vdom edit root next end -
List VDOMsFortiOS
diagnose sys vd list
Fortinet: Sessions
-
Clear any old session filter firstFortiOS
diagnose sys session filter clear -
Filter sessions by source addressFortiOS
diagnose sys session filter src 192.168.10.25 -
Filter sessions by destination portFortiOS
diagnose sys session filter dport 443 -
Show the current session filterFortiOS
diagnose sys session filter -
List the sessions that match the filterFortiOS
diagnose sys session list -
Clear the sessions that match the filterFortiOS
diagnose sys session clearWarning: With no filter set, this clears every session on the FortiGate.
-
Show session countsFortiOS
diagnose sys session stat
Fortinet: Packet capture and debug flow
-
Capture traffic to and from an address on any interfaceFortiOS
diagnose sniffer packet any 'host 192.168.10.25' 4 0 l -
Capture one conversation on one interfaceFortiOS
diagnose sniffer packet port2 'host 192.168.10.25 and port 443' 4 100 a -
Reset debug settings firstFortiOS
diagnose debug reset -
Clear the old flow filterFortiOS
diagnose debug flow filter clear -
Debug the flow for one addressFortiOS
diagnose debug flow filter addr 192.168.10.25 -
Show function names in the flow debugFortiOS
diagnose debug flow show function-name enable -
Show which policies are checkedFortiOS
diagnose debug flow show iprope enable -
Add timestamps to debug outputFortiOS
diagnose debug console timestamp enable -
Trace the next 100 packetsFortiOS
diagnose debug flow trace start 100 -
Show debug output on the screenFortiOS
diagnose debug enable -
Stop debuggingFortiOS
diagnose debug disable -
Stop the flow traceFortiOS
diagnose debug flow trace stop
Fortinet: High availability
-
Show the cluster, which unit is primary and whyFortiOS
get system ha status -
Check the members' configs matchFortiOS
diagnose sys ha checksum cluster -
Log in to another cluster memberFortiOS
execute ha manage 1 netadmin -
Fail over by resetting this unit's HA uptimeFortiOS
diagnose sys ha reset-uptimeWarning: If override is off, the other unit becomes primary. Run it on the current primary.
-
Set up active-passive HAFortiOS
config system ha set group-name fgt-cluster set mode a-p set password ChangeMe-2026 set hbdev port5 50 set priority 200 end -
Show HA details per memberFortiOS
diagnose sys ha dump-by group -
Force a config sync to the other unitFortiOS
execute ha synchronize start -
Show failover historyFortiOS
diagnose sys ha history read
Fortinet: IPsec VPN
-
Show tunnels and whether they're upFortiOS
get vpn ipsec tunnel summary -
Show tunnel details, SAs and countersFortiOS
diagnose vpn tunnel list -
Show IKE gateways (phase 1)FortiOS
diagnose vpn ike gateway list -
Bring a tunnel's phase 2 upFortiOS
diagnose vpn tunnel up to-branch-p2 to-branch -
Reset a tunnel's phase 1FortiOS
diagnose vpn ike gateway clear name to-branchWarning: Drops the tunnel until it renegotiates.
-
Clear the old IKE debug filterFortiOS
diagnose vpn ike log filter clear -
Debug IKE for one remote peerFortiOS
diagnose vpn ike log filter rem-addr4 198.51.100.200 -
Turn on full IKE debuggingFortiOS
diagnose debug application ike -1
Fortinet: Logging
-
Send logs to a syslog serverFortiOS
config log syslogd setting set status enable set server 192.168.10.70 end -
Send logs to FortiAnalyzerFortiOS
config log fortianalyzer setting set status enable set server 192.168.10.75 end -
Test the FortiAnalyzer connectionFortiOS
execute log fortianalyzer test-connectivity -
Show FortiAnalyzer log statusFortiOS
diagnose test application fgtlogd 1 -
Show only event logsFortiOS
execute log filter category event -
Show the logs stored on the FortiGateFortiOS
execute log display -
Send test log messagesFortiOS
diagnose log test
Fortinet: Firmware, backups and FortiGuard
-
Back up the config to a TFTP serverFortiOS
execute backup config tftp fgt-hq.conf 192.168.10.60 -
Back up the config to an FTP serverFortiOS
execute backup config ftp fgt-hq.conf 192.168.10.60 backup BackupPass -
Restore the config from a TFTP serverFortiOS
execute restore config tftp fgt-hq.conf 192.168.10.60Warning: Replaces the whole config and reboots the FortiGate.
-
Upgrade firmware from a TFTP serverFortiOS
execute restore image tftp FGT_60F-v7.6.6.F-build3652-FORTINET.out 192.168.10.60Warning: Reboots the FortiGate. Check the upgrade path in the release notes and back up the config first.
-
Check FortiGuard licences and connectionFortiOS
get system fortiguard-service status -
Show the signature and engine versionsFortiOS
diagnose autoupdate versions -
Update signatures nowFortiOS
execute update-now -
Reboot the FortiGateFortiOS
execute rebootWarning: Stops all traffic until it's back up.
-
Shut down the FortiGateFortiOS
execute shutdown
Fortinet: Troubleshooting
-
Ping from the FortiGateFortiOS
execute ping 198.51.100.10 -
Ping from one of the FortiGate's addressesFortiOS
execute ping-options source 192.168.10.1 -
Trace the route to a hostFortiOS
execute traceroute 198.51.100.10 -
Show the busiest processes (press q to quit)FortiOS
diagnose sys top -
Show processes by CPU, with a summaryFortiOS
diagnose sys top-summary -
Check whether the FortiGate is in conserve modeFortiOS
diagnose hardware sysinfo conserve -
Show NTP sync statusFortiOS
diagnose sys ntp status -
SSH to another device from the FortiGateFortiOS
execute ssh [email protected] -
Read the crash logFortiOS
diagnose debug crashlog read -
Test a login against an LDAP serverFortiOS
diagnose test authserver ldap corp-ldap netadmin ChangeMe-2026
Cisco ASA and FTD: Modes and getting around
-
Go to privileged modeCisco ASA · User EXEC (>)
enable -
Go into configuration modeCisco ASA · Privileged EXEC (#)
configure terminal -
Leave configuration modeCisco ASA · Global config (config)#
end -
Show the model, ASA version, licence and uptimeCisco ASA · Privileged EXEC (#)
show version -
Stop output pausing at the end of each screenCisco ASA · Privileged EXEC (#)
terminal pager 0 -
Show the running configCisco ASA · Privileged EXEC (#)
show running-config -
Show config lines that match some textCisco ASA · Privileged EXEC (#)
show running-config | include access-list -
Show one part of the config, including defaultsCisco ASA · Privileged EXEC (#)
show running-config all ssh -
Show interfaces with names, addresses and statusCisco ASA · Privileged EXEC (#)
show interface ip brief -
Show interface names and security levelsCisco ASA · Privileged EXEC (#)
show nameif -
Save the configCisco ASA · Privileged EXEC (#)
write memory -
Show the date and timeCisco ASA · Privileged EXEC (#)
show clock
Cisco ASA and FTD: Basic setup
-
Set the hostnameCisco ASA · Global config (config)#
hostname asa-hq -
Set the domain nameCisco ASA · Global config (config)#
domain-name example.com -
Set the enable passwordCisco ASA · Global config (config)#
enable password ChangeMe-2026 -
Add an admin userCisco ASA · Global config (config)#
username netadmin password ChangeMe-2026 privilege 15 -
Use local users for SSH loginsCisco ASA · Global config (config)#
aaa authentication ssh console LOCAL -
Create an SSH keyCisco ASA · Global config (config)#
crypto key generate rsa modulus 2048 -
Allow SSH from a network on an interfaceCisco ASA · Global config (config)#
ssh 192.168.10.0 255.255.255.0 inside -
Turn on ASDM (the web manager)Cisco ASA · Global config (config)#
http server enable -
Allow ASDM from a network on an interfaceCisco ASA · Global config (config)#
http 192.168.10.0 255.255.255.0 inside -
Set the NTP serverCisco ASA · Global config (config)#
ntp server 192.168.10.123 -
Turn on DNS lookups through an interfaceCisco ASA · Global config (config)#
dns domain-lookup outside -
Send logs to a syslog serverCisco ASA · Global config (config)#
logging host inside 192.168.10.70 -
Turn logging onCisco ASA · Global config (config)#
logging enable -
Keep recent logs in memoryCisco ASA · Global config (config)#
logging buffered informational
Cisco ASA and FTD: Interfaces and routing
-
Name an interfaceCisco ASA · Global config (config)#
interface GigabitEthernet0/1 nameif inside -
Set its security level (100 trusted, 0 untrusted)Cisco ASA · Global config (config)#
interface GigabitEthernet0/1 security-level 100 -
Give it an IP addressCisco ASA · Global config (config)#
interface GigabitEthernet0/1 ip address 192.168.10.1 255.255.255.0 -
Bring it upCisco ASA · Global config (config)#
interface GigabitEthernet0/1 no shutdown -
Add a VLAN subinterfaceCisco ASA · Global config (config)#
interface GigabitEthernet0/1.10 vlan 10 nameif users ip address 192.168.110.1 255.255.255.0 -
Add a default routeCisco ASA · Global config (config)#
route outside 0.0.0.0 0.0.0.0 203.0.113.1 -
Add a static routeCisco ASA · Global config (config)#
route inside 10.20.0.0 255.255.255.0 192.168.10.254 -
Show the routing tableCisco ASA · Privileged EXEC (#)
show route -
Show one interface's counters and errorsCisco ASA · Privileged EXEC (#)
show interface GigabitEthernet0/1 -
Show the ARP tableCisco ASA · Privileged EXEC (#)
show arp
Cisco ASA and FTD: Objects, access lists and NAT
-
Add a host objectCisco ASA · Global config (config)#
object network web-server host 192.168.10.80 -
Add a network objectCisco ASA · Global config (config)#
object network inside-net subnet 10.20.0.0 255.255.255.0 -
Add an object groupCisco ASA · Global config (config)#
object-group network web-servers network-object object web-server -
Allow traffic in to a serverCisco ASA · Global config (config)#
access-list OUTSIDE_IN extended permit tcp any object web-server eq https -
Apply an access list to an interfaceCisco ASA · Global config (config)#
access-group OUTSIDE_IN in interface outside -
Hide inside users behind the outside address (PAT)Cisco ASA · Global config (config)#
object network inside-net subnet 10.20.0.0 255.255.255.0 nat (inside,outside) dynamic interface -
Forward a port on the outside address to a serverCisco ASA · Global config (config)#
object network web-server nat (inside,outside) static interface service tcp 443 443 -
Show access list hit countsCisco ASA · Privileged EXEC (#)
show access-list OUTSIDE_IN -
Reset access list hit countsCisco ASA · Privileged EXEC (#)
clear access-list OUTSIDE_IN counters -
Show NAT rules with hit countsCisco ASA · Privileged EXEC (#)
show nat detail -
Show current translationsCisco ASA · Privileged EXEC (#)
show xlate -
Clear translations after changing NATCisco ASA · Privileged EXEC (#)
clear xlateWarning: Drops every connection that uses NAT. Clear just the address you changed if you can.
Cisco ASA and FTD: Packet tracer and captures
-
Trace how a packet would be handled, rule by ruleCisco ASA · Privileged EXEC (#)
packet-tracer input inside tcp 192.168.10.25 12345 198.51.100.10 443 detailed -
Capture traffic between two hostsCisco ASA · Privileged EXEC (#)
capture CAP1 interface inside match ip host 192.168.10.25 host 198.51.100.10 -
Show a captureCisco ASA · Privileged EXEC (#)
show capture CAP1 -
Show a capture with full packet detailCisco ASA · Privileged EXEC (#)
show capture CAP1 detail -
Capture packets the firewall drops, with the reasonCisco ASA · Privileged EXEC (#)
capture ASPDROP type asp-drop all -
Show drop counters by reasonCisco ASA · Privileged EXEC (#)
show asp drop -
Copy a capture off as a pcap fileCisco ASA · Privileged EXEC (#)
copy /pcap capture:CAP1 tftp://192.168.10.60/CAP1.pcap -
Remove a captureCisco ASA · Privileged EXEC (#)
no capture CAP1
Cisco ASA and FTD: Connections and health
-
Show connections for an addressCisco ASA · Privileged EXEC (#)
show conn address 192.168.10.25 -
Count connectionsCisco ASA · Privileged EXEC (#)
show conn count -
Clear connections for an addressCisco ASA · Privileged EXEC (#)
clear conn address 192.168.10.25Warning: Cuts those connections straight away.
-
Show everything about one host (connections, translations)Cisco ASA · Privileged EXEC (#)
show local-host 192.168.10.25 -
Show CPU useCisco ASA · Privileged EXEC (#)
show cpu usage -
Show memoryCisco ASA · Privileged EXEC (#)
show memory -
Show traffic per interfaceCisco ASA · Privileged EXEC (#)
show traffic -
Show connection and translation ratesCisco ASA · Privileged EXEC (#)
show perfmon
Cisco ASA and FTD: Logging
-
Show the logs in memoryCisco ASA · Privileged EXEC (#)
show logging -
Show logs that match an addressCisco ASA · Privileged EXEC (#)
show logging | include 192.168.10.25 -
Clear the logs in memoryCisco ASA · Privileged EXEC (#)
clear logging buffer
Cisco ASA and FTD: Failover
-
Show failover state and which unit is activeCisco ASA · Privileged EXEC (#)
show failover -
Show a short failover stateCisco ASA · Privileged EXEC (#)
show failover state -
Make this unit activeCisco ASA · Privileged EXEC (#)
failover activeWarning: Moves traffic to this unit. Run it on the standby.
-
Make this unit standbyCisco ASA · Privileged EXEC (#)
no failover active -
Copy the config to the standby unitCisco ASA · Privileged EXEC (#)
write standby -
Run a command on the other unitCisco ASA · Privileged EXEC (#)
failover exec mate show version -
Reload the standby unitCisco ASA · Privileged EXEC (#)
failover reload-standby
Cisco ASA and FTD: VPN
-
Show IKEv2 tunnels (phase 1)Cisco ASA · Privileged EXEC (#)
show crypto ikev2 sa -
Show IKEv1 tunnels (phase 1)Cisco ASA · Privileged EXEC (#)
show crypto ikev1 sa -
Show IPsec SAs and counters for one peerCisco ASA · Privileged EXEC (#)
show crypto ipsec sa peer 198.51.100.200 -
Show VPN session totalsCisco ASA · Privileged EXEC (#)
show vpn-sessiondb summary -
List site-to-site sessionsCisco ASA · Privileged EXEC (#)
show vpn-sessiondb l2l -
List remote-access (AnyConnect) usersCisco ASA · Privileged EXEC (#)
show vpn-sessiondb anyconnect -
Disconnect a VPN session by addressCisco ASA · Privileged EXEC (#)
vpn-sessiondb logoff ipaddress 198.51.100.200 -
Debug IKEv2 negotiationCisco ASA · Privileged EXEC (#)
debug crypto ikev2 protocol 127 -
Turn off all debuggingCisco ASA · Privileged EXEC (#)
undebug all
Cisco ASA and FTD: Software, licences and backups
-
List files on flashCisco ASA · Privileged EXEC (#)
dir disk0: -
Copy an image to flash from a TFTP serverCisco ASA · Privileged EXEC (#)
copy tftp://192.168.10.60/cisco-asa-fp1k.9.24.1.SPA disk0:/cisco-asa-fp1k.9.24.1.SPA -
Boot from a new imageCisco ASA · Global config (config)#
boot system disk0:/cisco-asa-fp1k.9.24.1.SPA -
Show the boot settingsCisco ASA · Privileged EXEC (#)
show bootvar -
Reload the firewallCisco ASA · Privileged EXEC (#)
reloadWarning: Stops all traffic until it's back up.
-
Copy the running config to a TFTP serverCisco ASA · Privileged EXEC (#)
copy running-config tftp://192.168.10.60/asa-hq.cfg -
Show licencesCisco ASA · Privileged EXEC (#)
show license all
Cisco ASA and FTD: Troubleshooting
-
Ping from an interfaceCisco ASA · Privileged EXEC (#)
ping inside 198.51.100.10 -
Trace the route to a hostCisco ASA · Privileged EXEC (#)
traceroute 198.51.100.10 -
Test a login against a RADIUS or LDAP serverCisco ASA · Privileged EXEC (#)
test aaa-server authentication RADIUS-SERVERS host 192.168.10.90 username netadmin password ChangeMe-2026 -
Collect everything for Cisco TACCisco ASA · Privileged EXEC (#)
show tech-support
Cisco ASA and FTD: Firewall Threat Defense (FTD)
-
Show the version, model and UUIDCisco FTD · FTD CLI (>)
show version -
Show the management interface settingsCisco FTD · FTD CLI (>)
show network -
Set the management addressCisco FTD · FTD CLI (>)
configure network ipv4 manual 192.168.10.1 255.255.255.0 203.0.113.1Warning: Your SSH session drops if you're connected to the old address.
-
Register with a Firewall Management CenterCisco FTD · FTD CLI (>)
configure manager add 192.168.10.5 MyRegKey123 -
Show the manager and registration stateCisco FTD · FTD CLI (>)
show managers -
Remove the managerCisco FTD · FTD CLI (>)
configure manager deleteWarning: The FMC stops managing this device until you register it again.
-
Show the deployed configCisco FTD · FTD CLI (>)
show running-config -
Trace a packet through the firewall rulesCisco FTD · FTD CLI (>)
packet-tracer input inside tcp 192.168.10.25 12345 198.51.100.10 443 detailed -
Show connections for an addressCisco FTD · FTD CLI (>)
show conn address 192.168.10.25 -
Show failover stateCisco FTD · FTD CLI (>)
show failover -
Trace live traffic through Snort and the access policyCisco FTD · FTD CLI (>)
system support trace -
Debug which access rule Snort matchesCisco FTD · FTD CLI (>)
system support firewall-engine-debug -
Capture traffic as Snort sees itCisco FTD · FTD CLI (>)
capture-traffic -
Open the diagnostic CLI for ASA-style commands (then type enable and press Enter for the password)Cisco FTD · FTD CLI (>)
system support diagnostic-cli -
Add a local CLI userCisco FTD · FTD CLI (>)
configure user add netadmin config -
Open the FXOS chassis CLICisco FTD · FTD CLI (>)
connect fxos
pfSense: Console and shell basics
-
Open the console menu from an SSH shellpfSense shell
/etc/rc.initial -
Show the versionpfSense shell
cat /etc/version -
Show interfaces, addresses and link statepfSense shell
ifconfig -
Show one interfacepfSense shell
ifconfig igc1 -
Show uptime and loadpfSense shell
uptime -
Show the busiest processes and threadspfSense shell
top -aSH -
Show disk spacepfSense shell
df -h -
Show memory and swappfSense shell
swapinfo -h
pfSense: Firewall rules and states (pf)
-
Show the loaded firewall rulespfSense shell
pfctl -sr -
Show the rules with counterspfSense shell
pfctl -vvsr -
Show the NAT rulespfSense shell
pfctl -sn -
Show firewall status and counterspfSense shell
pfctl -si -
Show the state tablepfSense shell
pfctl -ss -
Show states for one addresspfSense shell
pfctl -ss | grep 192.168.1.25 -
Kill the states from one addresspfSense shell
pfctl -k 192.168.1.25Warning: Cuts that host's connections straight away.
-
Kill the states between two addressespfSense shell
pfctl -k 192.168.1.25 -k 198.51.100.10 -
List the tables (aliases, bogons, blocklists)pfSense shell
pfctl -s Tables -
Show the addresses in an alias or tablepfSense shell
pfctl -t bogons -T show -
Reload the firewall rules from the configpfSense shell
/etc/rc.filter_configure -
Turn the firewall off to get back inpfSense shell
pfctl -dWarning: Turns off all filtering and NAT, so the internet stops working too. Run pfctl -e or reload the rules as soon as you've fixed things.
-
Turn the firewall back onpfSense shell
pfctl -e -
Show how many states are in usepfSense shell
pfctl -si | grep -A1 'State Table' -
Watch states and traffic livepfSense shell
pftop -
List addresses locked out after failed loginspfSense shell
pfctl -t sshguard -T show -
Unblock an address locked out after failed loginspfSense shell
pfctl -t sshguard -T delete 192.168.1.25
pfSense: EasyRule from the shell
-
Block an address on WANpfSense shell
easyrule block wan 192.168.1.25 -
List addresses EasyRule has blockedpfSense shell
easyrule showblock wan -
Remove an EasyRule blockpfSense shell
easyrule unblock wan 192.168.1.25 -
Add a pass rule for one connectionpfSense shell
easyrule pass wan tcp 192.168.1.25 198.51.100.10 443
pfSense: Recovery and console fixes
-
Restore a recent config backup (console option 15)pfSense shell
/etc/rc.restore_config_backup -
Allow the web interface from WAN to get back inpfSense shell
pfSsh.php playback enableallowallwanWarning: Opens every port on WAN to everyone. Use it only to recover access, then remove the rule straight away.
-
Turn off the web interface's HTTP referer checkpfSense shell
pfSsh.php playback disablereferercheck -
Make a new self-signed certificate for the web interfacepfSense shell
pfSsh.php playback generateguicert -
Turn on SSHpfSense shell
pfSsh.php playback enablesshd -
Turn off the DHCP serverpfSense shell
pfSsh.php playback disabledhcpd -
List boot environments (ZFS)pfSense shell
bectl list -
Delete an old boot environment to free space (ZFS)pfSense shell
bectl destroy default_20260301Warning: Can't be undone. Don't delete the one marked active (N or R in bectl list).
pfSense: Logs
-
Watch the firewall log in plain textpfSense shell
tail -F /var/log/filter.log | filterparser.php -
Watch the system logpfSense shell
tail -F /var/log/system.log -
Show recent DHCP server log entriespfSense shell
tail -n 50 /var/log/dhcpd.log -
Watch the IPsec logpfSense shell
tail -F /var/log/ipsec.log -
Watch the OpenVPN logpfSense shell
tail -F /var/log/openvpn.log -
Watch the gateway monitoring logpfSense shell
tail -F /var/log/gateways.log -
Watch the DNS resolver logpfSense shell
tail -F /var/log/resolver.log -
Watch the Kea DHCP logpfSense shell
tail -F /var/log/dhcpd.log
pfSense: Packet capture and testing
-
Capture traffic to and from an addresspfSense shell
tcpdump -ni igc1 host 192.168.1.25 -
Capture one portpfSense shell
tcpdump -ni igc1 port 443 -
Save a capture to open in WiresharkpfSense shell
tcpdump -ni igc1 -w /tmp/capture.pcap host 192.168.1.25 -
See blocked packets as they're loggedpfSense shell
tcpdump -n -e -ttt -i pflog0 -
Ping from a specific source addresspfSense shell
ping -S 192.168.1.1 198.51.100.10 -
Trace the route to a hostpfSense shell
traceroute -n 198.51.100.10 -
Look up a name with the firewall's DNSpfSense shell
drill www.example.com -
Test a TCP port from the firewallpfSense shell
nc -vz 198.51.100.10 443
pfSense: Routing, ARP and listening services
-
Show the routing tablepfSense shell
netstat -rn -
Show the route to one addresspfSense shell
route -n get 198.51.100.10 -
Show the ARP tablepfSense shell
arp -an -
Show which services are listeningpfSense shell
sockstat -4l -
Show traffic per interface livepfSense shell
systat -ifstat 1 -
Show network buffer use (mbufs)pfSense shell
netstat -m -
Show per-interface packet and error counterspfSense shell
netstat -i
pfSense: DHCP, DNS and NTP
-
List DHCP leases (Kea)pfSense shell
cat /var/lib/kea/dhcp4.leases -
Find a lease by MAC or namepfSense shell
grep -i aa:bb:cc:00:01:00 /var/lib/kea/dhcp4.leases -
Restart the DHCP serverpfSense shell
pfSsh.php playback restartdhcpd -
Look up a name in the DNS resolver's cachepfSense shell
unbound-control -c /var/unbound/unbound.conf lookup www.example.com -
Flush one name from the DNS resolver's cachepfSense shell
unbound-control -c /var/unbound/unbound.conf flush www.example.com -
Flush the whole DNS resolver cachepfSense shell
unbound-control -c /var/unbound/unbound.conf reload -
Show DNS resolver statisticspfSense shell
unbound-control -c /var/unbound/unbound.conf stats_noreset -
Show NTP peers and sync statuspfSense shell
ntpq -pn
pfSense: High availability (CARP)
-
Show CARP status on each interfacepfSense shell
ifconfig | grep carp -
Put this firewall into CARP maintenance (hand over to the backup)pfSense shell
pfSsh.php playback disablecarpWarning: The backup firewall takes over. Run enablecarp to come back.
-
Turn CARP back onpfSense shell
pfSsh.php playback enablecarp -
Show pfsync state synchronisationpfSense shell
ifconfig pfsync0
pfSense: Traffic shaping and limiters
-
Show limiters and their queuespfSense shell
dnctl pipe show -
Show limiter schedulerspfSense shell
dnctl sched show -
Show ALTQ shaper queues with counterspfSense shell
pfctl -vvsq
pfSense: Services
-
Restart a service (unbound, dhcpd, ntpd, sshd)pfSense shell
pfSsh.php playback svc restart unbound -
Restart the web interfacepfSense shell
/etc/rc.restart_webgui -
Restart PHP-FPM when the web interface hangspfSense shell
/etc/rc.php-fpm_restart -
Restart an OpenVPN clientpfSense shell
pfSsh.php playback svc restart openvpn client 1 -
Restart an OpenVPN serverpfSense shell
pfSsh.php playback svc restart openvpn server 1 -
Change a user's password (it asks for it)pfSense shell
pfSsh.php playback changepassword admin -
Restart IPsecpfSense shell
pfSsh.php playback restartipsec
pfSense: VPN status
-
Show IPsec tunnels and SAspfSense shell
swanctl --list-sas -
Show IPsec connections that are configuredpfSense shell
swanctl --list-conns -
Show WireGuard tunnels and peerspfSense shell
wg show -
Show OpenVPN processespfSense shell
ps auxww | grep openvpn
pfSense: Configuration and backups
-
Back up the config to a filepfSense shell
cp /conf/config.xml /root/config-$(date +%Y%m%d).xml -
List the automatic config backupspfSense shell
ls -l /conf/backup/ -
Edit the config file directly (careful)pfSense shell
viconfigWarning: A mistake can stop pfSense booting cleanly. Back up config.xml first.
-
Clear the cached config after editing config.xmlpfSense shell
rm /tmp/config.cache -
Reload every setting from the configpfSense shell
/etc/rc.reload_all
pfSense: Packages and upgrades
-
Check for a new pfSense versionpfSense shell
pfSense-upgrade -c -
Upgrade pfSensepfSense shell
pfSense-upgradeWarning: Reboots the firewall. Back up the config and read the upgrade guide first.
-
List installed packagespfSense shell
pkg info -
Show pfSense packages availablepfSense shell
pkg search pfSense-pkg -
List installed pfSense packagespfSense shell
pfSsh.php playback listpkg -
Install a packagepfSense shell
pfSsh.php playback installpkg pfBlockerNG -
Remove a packagepfSense shell
pfSsh.php playback uninstallpkg pfBlockerNG -
RebootpfSense shell
shutdown -r nowWarning: Stops all traffic until it's back up.
-
Shut downpfSense shell
shutdown -p now
OPNsense: Console and shell basics
-
Open the console menu from an SSH shellOPNsense shell
opnsense-shell -
Show the OPNsense versionOPNsense shell
opnsense-version -
Show interfaces, addresses and link stateOPNsense shell
ifconfig -
Show one interfaceOPNsense shell
ifconfig igc1 -
Show uptime and loadOPNsense shell
uptime -
Show the busiest processes and threadsOPNsense shell
top -aSH -
Show disk spaceOPNsense shell
df -h -
RebootOPNsense shell
opnsense-shell rebootWarning: Stops all traffic until it's back up.
-
Shut downOPNsense shell
shutdown -p now
OPNsense: Services (configctl and pluginctl)
-
List the services OPNsense managesOPNsense shell
pluginctl -s -
Restart a service (unbound, dnsmasq, openssh, ntpd)OPNsense shell
pluginctl -s unbound restart -
Show a service's statusOPNsense shell
pluginctl -s unbound status -
List the enabled OpenVPN instances with their IDsOPNsense shell
pluginctl -S openvpn -
Restart one OpenVPN instanceOPNsense shell
pluginctl -s openvpn restart 1 -
Restart the DNS servicesOPNsense shell
pluginctl dns -
List every backend action configctl can runOPNsense shell
configctl configd actions -
Reload the firewall rulesOPNsense shell
configctl filter reload -
Reload all servicesOPNsense shell
configctl service reload all -
Restart SSHOPNsense shell
configctl sshd restart -
Reload the whole config without rebootingOPNsense shell
opnsense-shell reload -
Read a setting from the configOPNsense shell
pluginctl -g OPNsense.Gateways.gateway_item.0.name
OPNsense: Firewall rules and states (pf)
-
Show the loaded firewall rulesOPNsense shell
pfctl -sr -
Show the rules with countersOPNsense shell
pfctl -vvsr -
Show the NAT rulesOPNsense shell
pfctl -sn -
Show firewall status and countersOPNsense shell
pfctl -si -
Show the state tableOPNsense shell
pfctl -ss -
Show states for one addressOPNsense shell
pfctl -ss | grep 192.168.1.25 -
Kill the states from one addressOPNsense shell
pfctl -k 192.168.1.25Warning: Cuts that host's connections straight away.
-
Kill the states between two addressesOPNsense shell
pfctl -k 192.168.1.25 -k 198.51.100.10 -
List the tables (aliases, bogons)OPNsense shell
pfctl -s Tables -
Show the addresses in an aliasOPNsense shell
pfctl -t bogons -T show -
Watch states and traffic liveOPNsense shell
pftop -
Turn the firewall off to get back inOPNsense shell
pfctl -dWarning: Turns off all filtering and NAT, so the internet stops working too. Run configctl filter reload as soon as you've fixed things.
OPNsense: Logs
-
List the log foldersOPNsense shell
ls /var/log/ -
Watch today's firewall logOPNsense shell
tail -F /var/log/filter/filter_$(date +%Y%m%d).log -
Watch today's system logOPNsense shell
tail -F /var/log/system/system_$(date +%Y%m%d).log -
Search today's system log for errorsOPNsense shell
grep -i error /var/log/system/system_$(date +%Y%m%d).log -
Watch the backend (configd) logOPNsense shell
tail -F /var/log/configd/configd_$(date +%Y%m%d).log -
Watch the gateway monitoring logOPNsense shell
tail -F /var/log/gateways/gateways_$(date +%Y%m%d).log -
Watch the DNS resolver logOPNsense shell
tail -F /var/log/resolver/resolver_$(date +%Y%m%d).log -
Watch the IPsec logOPNsense shell
tail -F /var/log/ipsec/ipsec_$(date +%Y%m%d).log -
Watch the OpenVPN logOPNsense shell
tail -F /var/log/openvpn/openvpn_$(date +%Y%m%d).log -
See blocked and passed packets as pf logs themOPNsense shell
tcpdump -n -e -ttt -i pflog0
OPNsense: Packet capture and testing
-
Capture traffic to and from an addressOPNsense shell
tcpdump -ni igc1 host 192.168.1.25 -
Capture one portOPNsense shell
tcpdump -ni igc1 port 443 -
Save a capture to open in WiresharkOPNsense shell
tcpdump -ni igc1 -w /tmp/capture.pcap host 192.168.1.25 -
Ping from a specific source addressOPNsense shell
ping -S 192.168.1.1 198.51.100.10 -
Trace the route to a hostOPNsense shell
traceroute -n 198.51.100.10 -
Look up a name with the firewall's DNSOPNsense shell
drill www.example.com -
Test a TCP port from the firewallOPNsense shell
nc -vz 198.51.100.10 443
OPNsense: Routing, ARP and counters
-
Show the routing tableOPNsense shell
netstat -rn -
Show the route to one addressOPNsense shell
route -n get 198.51.100.10 -
Show the ARP tableOPNsense shell
arp -an -
Show which services are listeningOPNsense shell
sockstat -4l -
Show per-interface packet and error countersOPNsense shell
netstat -i -
Show network buffer use (mbufs)OPNsense shell
netstat -m -
Show traffic per interface liveOPNsense shell
systat -ifstat 1
OPNsense: DNS, DHCP and NTP
-
Look up a name in the Unbound cacheOPNsense shell
unbound-control -c /var/unbound/unbound.conf lookup www.example.com -
Flush one name from the Unbound cacheOPNsense shell
unbound-control -c /var/unbound/unbound.conf flush www.example.com -
Show Unbound statisticsOPNsense shell
unbound-control -c /var/unbound/unbound.conf stats_noreset -
Show the generated Dnsmasq configOPNsense shell
cat /usr/local/etc/dnsmasq.conf -
Restart Dnsmasq (DNS and DHCP)OPNsense shell
pluginctl -s dnsmasq restart -
Show NTP peers and sync statusOPNsense shell
ntpq -pn
OPNsense: VPN status
-
Show IPsec tunnels and SAsOPNsense shell
swanctl --list-sas -
Show IPsec connections that are configuredOPNsense shell
swanctl --list-conns -
Show WireGuard tunnels and peersOPNsense shell
wg show -
Stop WireGuardOPNsense shell
configctl wireguard stop -
Show OpenVPN processesOPNsense shell
ps auxww | grep openvpn
OPNsense: High availability (CARP)
-
Show CARP status on each interfaceOPNsense shell
ifconfig | grep carp -
Show pfsync state synchronisationOPNsense shell
ifconfig pfsync0
OPNsense: Recovery
-
Reset the root passwordOPNsense shell
opnsense-shell password -
List the automatic config backupsOPNsense shell
ls -la /conf/backup/ -
Restore an earlier config backupOPNsense shell
cp /conf/backup/config-1763985600.1234.xml /conf/config.xmlWarning: Replaces the whole running config. Copy the current config.xml somewhere first, then reboot.
-
Back up the config to a fileOPNsense shell
cp /conf/config.xml /root/config-$(date +%Y%m%d).xml -
Import a config from a USB stick or another diskOPNsense shell
opnsense-importer
OPNsense: Updates, packages and rollbacks
-
Check for updatesOPNsense shell
opnsense-update -c -
Download updates without installing themOPNsense shell
opnsense-update -f -
Update the base system, kernel and packagesOPNsense shell
opnsense-update -bkpWarning: Reboots may be needed. Back up config.xml first.
-
Upgrade to a new major releaseOPNsense shell
opnsense-update -ur 26.7Warning: Read the release notes and back up config.xml before a major upgrade.
-
Roll a package back to the version in an earlier releaseOPNsense shell
opnsense-revert -r 26.7 strongswan -
Go back to the kernel from an earlier releaseOPNsense shell
opnsense-update -kr 26.7Warning: Only on advice from the OPNsense team or for testing. Reboot afterwards.
-
Apply a fix from the OPNsense code repositoryOPNsense shell
opnsense-patch a1b2c3d -
List installed packagesOPNsense shell
pkg info -
List installed OPNsense pluginsOPNsense shell
pkg info | grep os-
FreeIPA: Install and setup
-
Give the server a fully qualified host name firstLinux
hostnamectl set-hostname ipa1.example.com -
Install the server packages with integrated DNS (RHEL, Rocky, Alma)Red Hat, Fedora
dnf install ipa-server ipa-server-dns -
Install the server packages with integrated DNS (Fedora)Red Hat, Fedora
dnf install freeipa-server freeipa-server-dns -
Open the firewall for FreeIPA and DNSRed Hat, Fedora
firewall-cmd --permanent --add-service={freeipa-4,dns} firewall-cmd --reload -
Install the first server, answering the questions as you goLinux
ipa-server-install -
Install the first server with integrated DNSLinux
ipa-server-install --setup-dns --auto-forwarders --auto-reverse -
Install the first server with no questions askedLinux
ipa-server-install -U --realm=EXAMPLE.COM --domain=example.com --setup-dns --auto-forwarders --auto-reverse --ds-password='ChangeMe-2026!' --admin-password='ChangeMe-2026!'Warning: The passwords end up in your shell history. Clear it afterwards, or leave them out and answer the prompts.
-
Install the client packages (RHEL, Rocky, Alma, Fedora)Red Hat, Fedora
dnf install ipa-client -
Install the client packages (Debian, Ubuntu)Debian, Ubuntu
apt install freeipa-client -
Join a machine to the domain, finding the server through DNSLinux
ipa-client-install --mkhomedir -
Join a machine to a named server and domainLinux
ipa-client-install --mkhomedir --domain=example.com --server=ipa1.example.com --principal=admin -
Join a machine with a one-time password, with no questions askedLinux
ipa-client-install --mkhomedir -U --password='Secret123' -
Remove a machine from the domainLinux
ipa-client-install --uninstall -
Remove FreeIPA from a serverLinux
ipa-server-install --uninstallWarning: On the last server this wipes the whole domain. On a replica, run ipa server-del from another server first.
-
Upgrade the data and config after updating the packagesLinux
ipa-server-upgrade -
Show the global settings (default shell, home folders, search limits)Linux
ipa config-show -
Change the default shell for new usersLinux
ipa config-mod --defaultshell=/bin/bash
FreeIPA: Kerberos and the ipa command
-
Get an admin ticket so ipa commands workLinux
kinit admin -
Get a ticket as yourselfLinux
kinit jsmith -
Show your tickets and when they expireLinux
klist -
Throw away your ticketsLinux
kdestroy -
Throw away every ticket cache you haveLinux
kdestroy -A -
Get a ticket as the machine itself using its keytabLinux
kinit -k -
List the keys in the machine's keytabLinux
klist -k /etc/krb5.keytab -
Check you can get a ticket for a serviceLinux
kvno host/web01.example.com -
Change your own passwordLinux
kpasswd -
Check the ipa command can reach the serverLinux
ipa ping -
List the help topicsLinux
ipa help topics -
List every ipa commandLinux
ipa help commands -
Show the options for one commandLinux
ipa user-add --help -
Show what the ipa command sends and receivesLinux
ipa -vv user-show admin
FreeIPA: Users
-
Add a userLinux
ipa user-add jsmith --first=Jane --last=Smith [email protected] -
Add a user and set a first password (they change it at first login)Linux
ipa user-add jsmith --first=Jane --last=Smith --password -
List all usersLinux
ipa user-find -
Search for users by surnameLinux
ipa user-find --last=Smith -
Show everything about a userLinux
ipa user-show jsmith --all -
Change a user's login shellLinux
ipa user-mod jsmith --shell=/bin/bash -
Add an SSH public key to a userLinux
ipa user-mod jsmith --sshpubkey="$(cat ~/.ssh/id_ed25519.pub)" -
Reset a user's password (they change it at next login)Linux
ipa passwd jsmith -
Push back when a user's password expiresLinux
ipa user-mod jsmith --password-expiration='20271231000000Z' -
Disable a userLinux
ipa user-disable jsmith -
Enable a user againLinux
ipa user-enable jsmith -
Unlock a user locked out by failed loginsLinux
ipa user-unlock jsmith -
Show failed logins and lockouts on each serverLinux
ipa user-status jsmith -
Delete a user but keep the account so you can restore itLinux
ipa user-del jsmith --preserve -
Restore a preserved userLinux
ipa user-undel jsmith -
Delete a user for goodLinux
ipa user-del jsmithWarning: Can't be undone. Use --preserve if you might need the account back.
-
Add a user who can't log in yet (a stage user)Linux
ipa stageuser-add jsmith --first=Jane --last=Smith -
Activate a stage userLinux
ipa stageuser-activate jsmith
FreeIPA: Groups
-
Add a groupLinux
ipa group-add linux-admins --desc="Linux administrators" -
Add a group without a GID (for access rules only)Linux
ipa group-add linux-admins --nonposix -
Add users to a groupLinux
ipa group-add-member linux-admins --users=jsmith -
Put a group inside another groupLinux
ipa group-add-member linux-admins --groups=admins -
Remove a user from a groupLinux
ipa group-remove-member linux-admins --users=jsmith -
Show a group and its membersLinux
ipa group-show linux-admins -
List all groupsLinux
ipa group-find -
List the groups a user is inLinux
ipa group-find --user=jsmith -
Let a user manage a group's members without being an adminLinux
ipa group-add-member-manager linux-admins --users=jsmith -
Delete a groupLinux
ipa group-del linux-admins
FreeIPA: Hosts and host groups
-
Add a host and its DNS recordLinux
ipa host-add web01.example.com --ip-address=192.168.10.21 -
Add a host and get a one-time password to enrol itLinux
ipa host-add web01.example.com --random -
List all hostsLinux
ipa host-find -
Show a hostLinux
ipa host-show web01.example.com -
Disable a host (removes its keys and certificates)Linux
ipa host-disable web01.example.com -
Delete a host and its DNS recordsLinux
ipa host-del web01.example.com --updatedns -
Add a host groupLinux
ipa hostgroup-add webservers --desc="Web servers" -
Add hosts to a host groupLinux
ipa hostgroup-add-member webservers --hosts=web01.example.com -
Show a host group and its membersLinux
ipa hostgroup-show webservers -
List all host groupsLinux
ipa hostgroup-find -
Put new hosts in a host group automaticallyLinux
ipa automember-add --type=hostgroup webservers -
Match new hosts whose name starts with webLinux
ipa automember-add-condition --type=hostgroup webservers --key=fqdn --inclusive-regex='^web' -
Apply the automatic membership rules to existing hostsLinux
ipa automember-rebuild --type=hostgroup
FreeIPA: Services and keytabs
-
Add a service, such as a web serverLinux
ipa service-add HTTP/web01.example.com -
List all servicesLinux
ipa service-find -
Show a serviceLinux
ipa service-show HTTP/web01.example.com -
Let a host manage a service's keytab and certificatesLinux
ipa service-add-host HTTP/web01.example.com --hosts=web01.example.com -
Create a keytab for a serviceLinux
ipa-getkeytab -s ipa1.example.com -p HTTP/web01.example.com -k /etc/httpd/conf/http.keytabWarning: Makes new keys, so any copy of the old keytab stops working. Use -r to get the existing keys instead.
-
Get the existing keys without changing themLinux
ipa-getkeytab -r -s ipa1.example.com -p HTTP/web01.example.com -k /etc/httpd/conf/http.keytab -
List the keys in a keytabLinux
klist -kt /etc/httpd/conf/http.keytab -
Disable a service (removes its keys)Linux
ipa service-disable HTTP/web01.example.com -
Delete a serviceLinux
ipa service-del HTTP/web01.example.com
FreeIPA: Access rules (HBAC)
-
List the access rulesLinux
ipa hbacrule-find -
Show the rule that lets everyone log in everywhereLinux
ipa hbacrule-show allow_all -
Add an access ruleLinux
ipa hbacrule-add ssh-webservers -
Let a group use the ruleLinux
ipa hbacrule-add-user ssh-webservers --groups=linux-admins -
Apply the rule to a host groupLinux
ipa hbacrule-add-host ssh-webservers --hostgroups=webservers -
Allow SSH logins onlyLinux
ipa hbacrule-add-service ssh-webservers --hbacsvcs=sshd -
Allow every login serviceLinux
ipa hbacrule-mod ssh-webservers --servicecat=all -
List the login services rules can useLinux
ipa hbacsvc-find -
Test whether a user can log in to a hostLinux
ipa hbactest --user=jsmith --host=web01.example.com --service=sshd -
Test one rule onlyLinux
ipa hbactest --user=jsmith --host=web01.example.com --service=sshd --rules=ssh-webservers -
Turn off the rule that lets everyone log in everywhereLinux
ipa hbacrule-disable allow_allWarning: Only users matched by another rule can log in afterwards, admins included. Test with ipa hbactest first.
-
Turn a rule back onLinux
ipa hbacrule-enable ssh-webservers -
Delete an access ruleLinux
ipa hbacrule-del ssh-webservers
FreeIPA: Sudo rules
-
Add a command sudo rules can allowLinux
ipa sudocmd-add /usr/bin/systemctl -
Add a group of commandsLinux
ipa sudocmdgroup-add service-control -
Add a command to a command groupLinux
ipa sudocmdgroup-add-member service-control --sudocmds=/usr/bin/systemctl -
Add a sudo ruleLinux
ipa sudorule-add web-admins-sudo -
Let a group use the sudo ruleLinux
ipa sudorule-add-user web-admins-sudo --groups=linux-admins -
Apply the sudo rule to a host groupLinux
ipa sudorule-add-host web-admins-sudo --hostgroups=webservers -
Allow one commandLinux
ipa sudorule-add-allow-command web-admins-sudo --sudocmds=/usr/bin/systemctl -
Allow a group of commandsLinux
ipa sudorule-add-allow-command web-admins-sudo --sudocmdgroups=service-control -
Allow every commandLinux
ipa sudorule-mod web-admins-sudo --cmdcat=all -
Apply the sudo rule to every hostLinux
ipa sudorule-mod web-admins-sudo --hostcat=all -
Let the rule run commands as any userLinux
ipa sudorule-mod web-admins-sudo --runasusercat=all -
Don't ask for a passwordLinux
ipa sudorule-add-option web-admins-sudo --sudooption='!authenticate' -
List the sudo rulesLinux
ipa sudorule-find -
Show a sudo ruleLinux
ipa sudorule-show web-admins-sudo -
Check what sudo lets you run on a clientLinux
sudo -l
FreeIPA: Passwords and two-factor
-
Show the global password policyLinux
ipa pwpolicy-show -
Set the maximum password age and minimum lengthLinux
ipa pwpolicy-mod --maxlife=180 --minlength=12 -
Lock accounts after 5 failed logins for 10 minutesLinux
ipa pwpolicy-mod --maxfail=5 --failinterval=60 --lockouttime=600 -
Add a stricter policy for one groupLinux
ipa pwpolicy-add linux-admins --priority=10 --minlength=16 -
Show which policy applies to a userLinux
ipa pwpolicy-show --user=jsmith -
Turn on password plus OTP for one userLinux
ipa user-mod jsmith --user-auth-type=otp -
Allow password or password plus OTP for everyoneLinux
ipa config-mod --user-auth-type=password --user-auth-type=otp -
Add an authenticator app token for a user (shows a QR code)Linux
ipa otptoken-add --owner=jsmith --type=totp -
List a user's tokensLinux
ipa otptoken-find --owner=jsmith -
Delete a tokenLinux
ipa otptoken-del a1b2c3d4-0000-4e5f-9a8b-123456789abc
FreeIPA: Certificates
-
List the certificates certmonger is tracking and renewingLinux
ipa-getcert list -
Request a certificate for a service and keep it renewedLinux
ipa-getcert request -f /etc/pki/tls/certs/web01.crt -k /etc/pki/tls/private/web01.key -K HTTP/web01.example.com -D web01.example.com -
Force a tracked certificate to renew nowLinux
ipa-getcert resubmit -i 20261125093000 -
Stop tracking a certificateLinux
ipa-getcert stop-tracking -i 20261125093000 -
Sign a certificate request you made yourselfLinux
ipa cert-request web01.csr --principal=HTTP/web01.example.com -
List certificates issued to a hostLinux
ipa cert-find --subject=web01.example.com -
Save a certificate to a fileLinux
ipa cert-show 12 --out=cert.pem -
Revoke a certificate (4 means superseded)Linux
ipa cert-revoke 12 --revocation-reason=4 -
List the certificate profilesLinux
ipa certprofile-find -
List the certificate authoritiesLinux
ipa ca-find -
Renew the CA certificateLinux
ipa-cacert-manage renewWarning: Run ipa-certupdate on every server and client afterwards so they trust the new CA certificate.
-
Update a server or client with the latest CA certificatesLinux
ipa-certupdate
FreeIPA: DNS
-
List the DNS zonesLinux
ipa dnszone-find -
Add a zoneLinux
ipa dnszone-add example.com -
Add a reverse zone for a subnetLinux
ipa dnszone-add --name-from-ip=192.168.10.0/24 -
Add an A record and its PTR recordLinux
ipa dnsrecord-add example.com app --a-rec=192.168.10.21 --a-create-reverse -
Add a CNAME recordLinux
ipa dnsrecord-add example.com app --cname-rec=web01 -
List the records in a zoneLinux
ipa dnsrecord-find example.com -
Show one recordLinux
ipa dnsrecord-show example.com app -
Delete an A recordLinux
ipa dnsrecord-del example.com app --a-rec=192.168.10.21 -
Set the global forwarder for outside namesLinux
ipa dnsconfig-mod --forwarder=1.1.1.1 -
Set the forwarder on one serverLinux
ipa dnsserver-mod ipa1.example.com --forwarder=1.1.1.1 -
Send another domain's lookups to its own DNS serversLinux
ipa dnsforwardzone-add ad.example.com --forwarder=192.168.10.5 --forward-policy=only -
Show the SRV records IPA needs, without changing anythingLinux
ipa dns-update-system-records --dry-run -
Fix missing or wrong IPA SRV recordsLinux
ipa dns-update-system-records -
Check clients can find the LDAP serversLinux
dig +short SRV _ldap._tcp.example.com
FreeIPA: Replicas and topology
-
Turn an enrolled client into a replica with a CA and DNSLinux
ipa-replica-install --setup-ca --setup-dns --auto-forwarders -
Add a CA to an existing replicaLinux
ipa-ca-install -
List the IPA serversLinux
ipa server-find -
Show which servers run the CALinux
ipa server-role-find --role='CA server' -
Show which server renews the CA certificateLinux
ipa config-show | grep -i renewal -
List the replication links for users and groupsLinux
ipa topologysegment-find domain -
List the replication links for the CALinux
ipa topologysegment-find ca -
Check the topology for missing linksLinux
ipa topologysuffix-verify domain -
Show replication status from this serverLinux
ipa-replica-manage list -v ipa1.example.com -
Rebuild a broken replica from another serverLinux
ipa-replica-manage re-initialize --from=ipa1.example.comWarning: Replaces this server's data with the other server's copy. Run it on the broken replica.
-
Remove a dead replica from the domainLinux
ipa server-del ipa2.example.comWarning: Check it's not the only CA or the CA renewal server first, with ipa server-role-find and ipa config-show.
FreeIPA: Active Directory trust
-
Install the trust packagesRed Hat, Fedora
dnf install ipa-server-trust-ad -
Open the firewall for the trustRed Hat, Fedora
firewall-cmd --permanent --add-service=freeipa-trust firewall-cmd --reload -
Set up this server to host trustsLinux
ipa-adtrust-install --add-sids -
Create the trust with an AD admin accountLinux
ipa trust-add --type=ad ad.example.com --admin Administrator --password -
List trustsLinux
ipa trust-find -
List the domains in the trusted forestLinux
ipa trustdomain-find ad.example.com -
Refresh the list of trusted domainsLinux
ipa trust-fetch-domains ad.example.com -
Check an AD user resolves on a Linux hostLinux
-
Make an external group to hold AD groupsLinux
ipa group-add ad_admins_external --external -
Put an AD group in the external groupLinux
ipa group-add-member ad_admins_external --external='Domain [email protected]' -
Give the AD group a normal IPA group to use in rulesLinux
ipa group-add ad_admins ipa group-add-member ad_admins --groups=ad_admins_external -
Let an AD user run ipa commands (step 1: add an ID override)Linux
ipa idoverrideuser-add 'Default Trust View' [email protected] -
Let an AD user run ipa commands (step 2: add them to admins)Linux
ipa group-add-member admins [email protected] -
Make an ID view to change AD users' attributes on some hostsLinux
ipa idview-add web-hosts-view -
Give an AD user a different GID in the viewLinux
ipa idoverrideuser-add web-hosts-view [email protected] --gidnumber=732001337 -
Apply the ID view to a hostLinux
ipa idview-apply web-hosts-view --hosts=web01.example.com
FreeIPA: Health and troubleshooting
-
Show the status of every IPA serviceLinux
ipactl status -
Restart every IPA serviceLinux
ipactl restart -
Run the health checks and show only problemsLinux
ipa-healthcheck --failures-only -
Run the health checks in readable formLinux
ipa-healthcheck --output-type=human -
Check only that the IPA services are runningLinux
ipa-healthcheck --source=ipahealthcheck.meta.services -
List the health check sourcesLinux
ipa-healthcheck --list-sources -
Run the health checks every dayLinux
systemctl enable --now ipa-healthcheck.timer -
Look up a user the way the system sees themLinux
id jsmith -
Look up a user in the passwd databaseLinux
getent passwd jsmith -
Check a user's lookup, login and access in one goLinux
sssctl user-checks jsmith -
Check SSSD is online and which server it's usingLinux
sssctl domain-status example.com -
Clear the SSSD cache so changes show up straight awayLinux
sss_cache -E -
Restart SSSDLinux
systemctl restart sssd -
Wipe the SSSD cache completelyLinux
systemctl stop sssd rm -rf /var/lib/sss/db/* systemctl start sssdWarning: Cached logins are lost, so users can't log in offline until the host reaches a server again.
-
Follow the SSSD logsLinux
journalctl -u sssd -f -
Follow the Kerberos server logLinux
tail -f /var/log/krb5kdc.log -
Follow the directory server error logLinux
tail -f /var/log/dirsrv/slapd-*/errors -
Follow the IPA web and API logLinux
tail -f /var/log/httpd/error_log -
Back up the whole server (stops IPA while it runs)Linux
ipa-backup -
Back up only the data, without stopping IPALinux
ipa-backup --data --online -
Restore a backupLinux
ipa-restore /var/lib/ipa/backup/ipa-full-2026-11-25-09-00-00Warning: Replaces everything on this server. Restoring one replica in a working domain can bring back old data, so read the docs first.
nmap: Install and basics
-
Install nmapDebian, Ubuntu
sudo apt install nmapRed Hat, Fedorasudo dnf install nmapAlpineapk add nmapmacOSbrew install nmapWindowswinget install Insecure.Nmap -
Show the nmap versionLinux, macOS, Windows
nmap --version -
Scan nmap's own test server, which you're allowed to scanLinux, macOS, Windows
nmap scanme.nmap.org -
Scan one host's 1,000 most common portsLinux, macOS, Windows
nmap 192.168.1.20 -
Scan a whole subnetLinux, macOS, Windows
nmap 192.168.1.0/24 -
Scan a range of addressesLinux, macOS, Windows
nmap 192.168.1.10-50 -
Scan the hosts listed in a fileLinux, macOS, Windows
nmap -iL targets.txt -
Leave some hosts out of a scanLinux, macOS, Windows
nmap 192.168.1.0/24 --exclude 192.168.1.1,192.168.1.254 -
Scan an IPv6 addressLinux, macOS, Windows
nmap -6 2001:db8::20
nmap: Host discovery
-
Find which hosts are up, without scanning portsLinux, macOS, Windows
nmap -sn 192.168.1.0/24 -
Find hosts on your local network using ARPLinux, macOS, Windows
sudo nmap -sn -PR 192.168.1.0/24 -
Find hosts that block ping by probing port 443Linux, macOS, Windows
nmap -sn -PS443 192.168.1.0/24 -
List the addresses a scan would cover, without scanningLinux, macOS, Windows
nmap -sL 192.168.1.0/24 -
Scan a host even if it doesn't answer pingLinux, macOS, Windows
nmap -Pn 192.168.1.20 -
Skip DNS lookups to speed up a scanLinux, macOS, Windows
nmap -n 192.168.1.0/24 -
Show why nmap thinks a host or port is upLinux, macOS, Windows
nmap --reason 192.168.1.20 -
Trace the route to each hostLinux, macOS, Windows
nmap --traceroute scanme.nmap.org -
Find hosts with ICMP echo (ping) requestsLinux, macOS, Windows
sudo nmap -sn -PE 192.168.1.0/24 -
Find hosts with ICMP timestamp requestsLinux, macOS, Windows
sudo nmap -sn -PP 192.168.1.0/24 -
Find hosts with ICMP address mask requestsLinux, macOS, Windows
sudo nmap -sn -PM 192.168.1.0/24 -
Find hosts with UDP probesLinux, macOS, Windows
sudo nmap -sn -PU53,161 192.168.1.0/24 -
Find hosts with TCP ACK probesLinux, macOS, Windows
nmap -sn -PA80,443 192.168.1.0/24 -
Combine several discovery probes to find more hostsLinux, macOS, Windows
sudo nmap -sn -PE -PS22,80,443 -PA80 -PU53 192.168.1.0/24 -
Look up names for every address, even hosts that are downLinux, macOS, Windows
nmap -sn -R 192.168.1.0/24 -
Use specific DNS servers for name lookupsLinux, macOS, Windows
nmap --dns-servers 1.1.1.1,8.8.8.8 192.168.1.0/24 -
Use your system's normal DNS resolverLinux, macOS, Windows
nmap --system-dns 192.168.1.0/24 -
List the interfaces and routes nmap can useLinux, macOS, Windows
nmap --iflist -
Scan through a specific network interfaceLinux, macOS, Windows
sudo nmap -e eth0 192.168.1.0/24 -
Scan hosts in a random orderLinux, macOS, Windows
nmap --randomize-hosts 192.168.1.0/24
nmap: Port scans
-
Scan specific portsLinux, macOS, Windows
nmap -p 22,80,443 192.168.1.20 -
Scan a range of portsLinux, macOS, Windows
nmap -p 1-1024 192.168.1.20 -
Scan all 65,535 portsLinux, macOS, Windows
nmap -p- 192.168.1.20 -
Scan ports by service nameLinux, macOS, Windows
nmap -p ssh,http,https 192.168.1.20 -
Scan the 100 most common ports (fast)Linux, macOS, Windows
nmap -F 192.168.1.20 -
Scan the 20 most common portsLinux, macOS, Windows
nmap --top-ports 20 192.168.1.20 -
Show only open portsLinux, macOS, Windows
nmap --open 192.168.1.0/24 -
Run a TCP SYN scanLinux, macOS, Windows
sudo nmap -sS 192.168.1.20 -
Run a full TCP connect scan, without rootLinux, macOS, Windows
nmap -sT 192.168.1.20 -
Scan the most common UDP portsLinux, macOS, Windows
sudo nmap -sU --top-ports 20 192.168.1.20 -
Scan TCP and UDP togetherLinux, macOS, Windows
sudo nmap -sS -sU -p T:22,80,443,U:53,161 192.168.1.20 -
Map which ports a firewall filters (ACK scan)Linux, macOS, Windows
sudo nmap -sA 192.168.1.20 -
Scan ports in order instead of randomlyLinux, macOS, Windows
nmap -r 192.168.1.20 -
Leave some ports out of a scanLinux, macOS, Windows
nmap -p 1-1024 --exclude-ports 25,110 192.168.1.20 -
Run a FIN scanLinux, macOS, Windows
sudo nmap -sF 192.168.1.20 -
Run a NULL scanLinux, macOS, Windows
sudo nmap -sN 192.168.1.20 -
Run an Xmas scanLinux, macOS, Windows
sudo nmap -sX 192.168.1.20 -
Run a TCP Window scanLinux, macOS, Windows
sudo nmap -sW 192.168.1.20 -
Run a Maimon scanLinux, macOS, Windows
sudo nmap -sM 192.168.1.20 -
Set your own TCP flagsLinux, macOS, Windows
sudo nmap --scanflags SYNFIN 192.168.1.20 -
Find which IP protocols a host supportsLinux, macOS, Windows
sudo nmap -sO 192.168.1.20 -
Scan SCTP portsLinux, macOS, Windows
sudo nmap -sY 192.168.1.20 -
Scan through an idle third host (zombie scan)Linux, macOS, Windows
sudo nmap -Pn -sI 192.168.1.30 192.168.1.20Warning: Uses another device to send the scan. Only use hosts you own as the idle host.
nmap: Services and operating systems
-
Find which software and version is on each open portLinux, macOS, Windows
nmap -sV 192.168.1.20 -
Try harder to identify servicesLinux, macOS, Windows
nmap -sV --version-intensity 9 192.168.1.20 -
Identify services quicklyLinux, macOS, Windows
nmap -sV --version-light 192.168.1.20 -
Guess the operating systemLinux, macOS, Windows
sudo nmap -O 192.168.1.20 -
Guess the operating system even when nmap isn't sureLinux, macOS, Windows
sudo nmap -O --osscan-guess 192.168.1.20 -
Run OS detection, versions, default scripts and traceroute togetherLinux, macOS, Windows
sudo nmap -A 192.168.1.20Warning: Easy for the target to notice and can trip intrusion alerts. Only run it on systems you're allowed to test.
nmap: Timing and performance
-
Scan faster on a reliable networkLinux, macOS, Windows
nmap -T4 192.168.1.0/24 -
Scan slowly and politelyLinux, macOS, Windows
nmap -T2 192.168.1.20 -
Send at least 1,000 packets a secondLinux, macOS, Windows
nmap --min-rate 1000 192.168.1.20 -
Retry each probe only onceLinux, macOS, Windows
nmap --max-retries 1 192.168.1.0/24 -
Give up on a host after 5 minutesLinux, macOS, Windows
nmap --host-timeout 5m 192.168.1.0/24 -
Wait a second between probesLinux, macOS, Windows
nmap --scan-delay 1s 192.168.1.20 -
Show progress every 30 secondsLinux, macOS, Windows
nmap --stats-every 30s 192.168.1.0/24
nmap: Firewall and IDS testing
-
Split probes into small fragmentsLinux, macOS, Windows
sudo nmap -f 192.168.1.20 -
Set the fragment sizeLinux, macOS, Windows
sudo nmap --mtu 16 192.168.1.20 -
Send probes from a set source portLinux, macOS, Windows
sudo nmap --source-port 53 192.168.1.20 -
Set the TTL on probesLinux, macOS, Windows
sudo nmap --ttl 64 192.168.1.20 -
Add random data to probesLinux, macOS, Windows
sudo nmap --data-length 25 192.168.1.20 -
Send probes with bad checksums to test the firewallLinux, macOS, Windows
sudo nmap --badsum 192.168.1.20 -
Scan slowly to test whether the IDS noticesLinux, macOS, Windows
nmap -T1 192.168.1.20 -
Hide your scan among random decoy addressesLinux, macOS, Windows
sudo nmap -D RND:5 192.168.1.20Warning: Makes the target see traffic from addresses that aren't yours. Only use it on networks you're allowed to test.
-
Hide your scan among decoy addresses you chooseLinux, macOS, Windows
sudo nmap -D 192.168.1.5,192.168.1.6,ME 192.168.1.20Warning: Makes the target see traffic from other addresses. Only use addresses and networks you're allowed to.
-
Use a random MAC address on your local networkLinux, macOS, Windows
sudo nmap --spoof-mac 0 192.168.1.20 -
Send probes from another source IP addressLinux, macOS, Windows
sudo nmap -S 192.168.1.99 -e eth0 -Pn 192.168.1.20Warning: Replies go to the address you set, not to you. Only use addresses you control.
-
Scan through a SOCKS proxyLinux, macOS, Windows
nmap -sT -Pn --proxies socks4://127.0.0.1:1080 192.168.1.20
nmap: Output
-
Show more detail as the scan runsLinux, macOS, Windows
nmap -v 192.168.1.20 -
Save results as textLinux, macOS, Windows
nmap -oN scan.txt 192.168.1.0/24 -
Save results as XMLLinux, macOS, Windows
nmap -oX scan.xml 192.168.1.0/24 -
Save results in a grep-friendly formatLinux, macOS, Windows
nmap -oG scan.gnmap 192.168.1.0/24 -
Save results in all formats at onceLinux, macOS, Windows
nmap -oA scan 192.168.1.0/24 -
Resume a scan that was stoppedLinux, macOS, Windows
nmap --resume scan.gnmap -
Compare two scans to see what changedLinux, macOS, Windows
ndiff old.xml new.xml -
Turn XML results into an HTML reportLinux, macOS
xsltproc scan.xml -o scan.html -
Show even more detail as the scan runsLinux, macOS, Windows
nmap -vv 192.168.1.20 -
Add to an existing results file instead of replacing itLinux, macOS, Windows
nmap -oN scan.txt --append-output 192.168.1.0/24 -
List the hosts that were up from grep-friendly resultsLinux, macOS
grep "Status: Up" scan.gnmap -
List open ports from grep-friendly resultsLinux, macOS
grep "/open/" scan.gnmap
nmap: Debugging
-
Show debugging detailLinux, macOS, Windows
nmap -d 192.168.1.20 -
Show every packet nmap sends and receivesLinux, macOS, Windows
sudo nmap --packet-trace -p 80 192.168.1.20
nmap: Scripts (NSE)
-
Run the default safe scriptsLinux, macOS, Windows
nmap -sC 192.168.1.20 -
Run scripts that are safe to useLinux, macOS, Windows
nmap --script safe 192.168.1.20 -
Run one scriptLinux, macOS, Windows
nmap --script http-title -p 80,443 192.168.1.0/24 -
Pass options to a scriptLinux, macOS, Windows
nmap --script http-title --script-args http.useragent="Mozilla/5.0" -p 80 192.168.1.20 -
Show help for a scriptLinux, macOS, Windows
nmap --script-help http-title -
Update the script databaseLinux, macOS, Windows
sudo nmap --script-updatedb -
Show a web server's page titleLinux, macOS, Windows
nmap --script http-title -p 80,443 192.168.1.20 -
Show a web server's response headersLinux, macOS, Windows
nmap --script http-headers -p 80,443 192.168.1.20 -
Show which HTTP methods a server allowsLinux, macOS, Windows
nmap --script http-methods -p 80,443 192.168.1.20 -
Show a server's TLS certificateLinux, macOS, Windows
nmap --script ssl-cert -p 443 192.168.1.20 -
List the TLS versions and ciphers a server supportsLinux, macOS, Windows
nmap --script ssl-enum-ciphers -p 443 192.168.1.20 -
List the algorithms an SSH server supportsLinux, macOS, Windows
nmap --script ssh2-enum-algos -p 22 192.168.1.20 -
Show what each service says when you connect (banners)Linux, macOS, Windows
nmap --script banner 192.168.1.20 -
Find a Windows machine's name and version over SMBLinux, macOS, Windows
nmap --script smb-os-discovery -p 445 192.168.1.20 -
Check whether SMB signing is requiredLinux, macOS, Windows
nmap --script smb2-security-mode -p 445 192.168.1.20 -
Check for known vulnerabilitiesLinux, macOS, Windows
nmap -sV --script vuln 192.168.1.20Warning: Easy for the target to notice and can trip intrusion alerts. Only run it on systems you're allowed to test.
-
Find subdomains by guessing common namesLinux, macOS, Windows
nmap --script dns-brute example.comWarning: Easy for the target to notice and can trip intrusion alerts. Only run it on systems you're allowed to test.
-
Run scripts that are both default and safeLinux, macOS, Windows
nmap --script "default and safe" 192.168.1.20 -
Run every HTTP scriptLinux, macOS, Windows
nmap --script "http-*" -p 80,443 192.168.1.20Warning: Easy for the target to notice and can trip intrusion alerts. Only run it on systems you're allowed to test.
-
Run all discovery scriptsLinux, macOS, Windows
nmap --script discovery 192.168.1.20Warning: Easy for the target to notice and can trip intrusion alerts. Only run it on systems you're allowed to test.
-
Run your own script fileLinux, macOS, Windows
nmap --script ./my-script.nse 192.168.1.20 -
Show what scripts send and receiveLinux, macOS, Windows
nmap --script http-title --script-trace -p 80 192.168.1.20 -
Check whether an FTP server allows anonymous loginLinux, macOS, Windows
nmap --script ftp-anon -p 21 192.168.1.20 -
List the commands an SMTP server supportsLinux, macOS, Windows
nmap --script smtp-commands -p 25 192.168.1.20 -
Check whether a mail server is an open relayLinux, macOS, Windows
nmap --script smtp-open-relay -p 25 192.168.1.20Warning: Easy for the target to notice and can trip intrusion alerts. Only run it on systems you're allowed to test.
-
Show SNMP system informationLinux, macOS, Windows
sudo nmap -sU --script snmp-info -p 161 192.168.1.20 -
Check whether a DNS server answers anyone (open resolver)Linux, macOS, Windows
sudo nmap -sU --script dns-recursion -p 53 192.168.1.20 -
Test whether a DNS server allows zone transfersLinux, macOS, Windows
nmap --script dns-zone-transfer --script-args dns-zone-transfer.domain=example.com -p 53 ns1.example.com -
Show NTP server informationLinux, macOS, Windows
sudo nmap -sU --script ntp-info -p 123 192.168.1.20 -
Show UPnP device informationLinux, macOS, Windows
sudo nmap -sU --script upnp-info -p 1900 192.168.1.20 -
Show an SSH server's host keysLinux, macOS, Windows
nmap --script ssh-hostkey -p 22 192.168.1.20 -
Show which login methods an SSH server allowsLinux, macOS, Windows
nmap --script ssh-auth-methods --script-args ssh.user=root -p 22 192.168.1.20 -
Show the encryption Remote Desktop usesLinux, macOS, Windows
nmap --script rdp-enum-encryption -p 3389 192.168.1.20 -
List the SMB versions a server supports, including SMBv1Linux, macOS, Windows
nmap --script smb-protocols -p 445 192.168.1.20 -
List SMB sharesLinux, macOS, Windows
nmap --script smb-enum-shares -p 445 192.168.1.20Warning: Easy for the target to notice and can trip intrusion alerts. Only run it on systems you're allowed to test.
-
Check for the EternalBlue (MS17-010) vulnerabilityLinux, macOS, Windows
nmap --script smb-vuln-ms17-010 -p 445 192.168.1.20 -
Check for the Heartbleed vulnerabilityLinux, macOS, Windows
nmap --script ssl-heartbleed -p 443 192.168.1.20 -
Show a web server's security headersLinux, macOS, Windows
nmap --script http-security-headers -p 443 192.168.1.20 -
Show a website's robots.txtLinux, macOS, Windows
nmap --script http-robots.txt -p 80,443 192.168.1.20 -
Look for common web pages and admin panelsLinux, macOS, Windows
nmap --script http-enum -p 80,443 192.168.1.20Warning: Easy for the target to notice and can trip intrusion alerts. Only run it on systems you're allowed to test.
-
Show MySQL server informationLinux, macOS, Windows
nmap --script mysql-info -p 3306 192.168.1.20 -
Show Microsoft SQL Server informationLinux, macOS, Windows
nmap --script ms-sql-info -p 1433 192.168.1.20 -
List known CVEs for the versions foundLinux, macOS, Windows
nmap -sV --script vulners 192.168.1.20Warning: Sends the software versions it finds to the vulners.com database.
-
Find DHCP servers on your networkLinux, macOS, Windows
sudo nmap --script broadcast-dhcp-discover -
Find hosts by broadcasting a pingLinux, macOS, Windows
sudo nmap --script broadcast-ping -
Find UPnP devices on your networkLinux, macOS, Windows
sudo nmap --script broadcast-upnp-info
nmap: Handy scans for your own network
-
Find web serversLinux, macOS, Windows
nmap -p 80,443,8080,8443 --open 192.168.1.0/24 -
Find devices with SSH openLinux, macOS, Windows
nmap -p 22 --open 192.168.1.0/24 -
Find devices with Remote Desktop openLinux, macOS, Windows
nmap -p 3389 --open 192.168.1.0/24 -
Find devices still using TelnetLinux, macOS, Windows
nmap -p 23 --open 192.168.1.0/24 -
Find printersLinux, macOS, Windows
nmap -p 515,631,9100 --open 192.168.1.0/24 -
Find DNS serversLinux, macOS, Windows
sudo nmap -sU -p 53 --open 192.168.1.0/24 -
Audit every port and service on one hostLinux, macOS, Windows
nmap -p- -sV -T4 192.168.1.20 -
Check what your server exposes to the internetLinux, macOS, Windows
nmap -Pn -p- 203.0.113.10 -
Find web admin pages on common portsLinux, macOS, Windows
nmap -p 80,443,8000,8080,8443,9443 --open 192.168.1.0/24 -
Find databasesLinux, macOS, Windows
nmap -p 1433,3306,5432,6379,27017 --open 192.168.1.0/24 -
Find file shares (SMB)Linux, macOS, Windows
nmap -p 139,445 --open 192.168.1.0/24 -
Find VNC serversLinux, macOS, Windows
nmap -p 5900-5910 --open 192.168.1.0/24 -
Find Proxmox serversLinux, macOS, Windows
nmap -p 8006 --open 192.168.1.0/24 -
Find devices that answer SNMPLinux, macOS, Windows
sudo nmap -sU -p 161 --open 192.168.1.0/24 -
Check the TLS setup of every web serverLinux, macOS, Windows
nmap --script ssl-enum-ciphers -p 443 --open 192.168.1.0/24 -
Save an inventory of every host and serviceLinux, macOS, Windows
nmap -sV -T4 -oX inventory.xml 192.168.1.0/24
Splunk: Search basics
-
Search an index for a wordSplunk search (SPL)
index=main error -
Search one sourcetypeSplunk search (SPL)
index=main sourcetype=syslog -
Search one hostSplunk search (SPL)
index=main host=WEB-01 -
Search every index you can seeSplunk search (SPL)
index=* 10.0.0.25Warning: Searching every index is slow on a big deployment. Name the index when you know it.
-
Match either wordSplunk search (SPL)
index=main (error OR fail*) -
Leave out events with a wordSplunk search (SPL)
index=main error NOT debug -
Match a field valueSplunk search (SPL)
index=main status=404 -
Match an exact phraseSplunk search (SPL)
index=main "connection refused" -
Find events where a field isn't a value, or is missingSplunk search (SPL)
index=main NOT status=200Warning: status!=200 only matches events that have a status field. NOT status=200 also returns events with no status at all.
-
Show only the newest 20 eventsSplunk search (SPL)
index=main | head 20 -
Show the oldest events firstSplunk search (SPL)
index=main | reverse -
Count events in each indexSplunk search (SPL)
| tstats count where index=* by index -
List the sourcetypes in an indexSplunk search (SPL)
| metadata type=sourcetypes index=main | table sourcetype totalCount -
Make a test event to try a search onSplunk search (SPL)
| makeresults | eval user="jsmith", src="10.0.0.25"
Splunk: Time ranges
-
Last 24 hoursSplunk search (SPL)
index=main earliest=-24h latest=now -
Last hour, snapped to the start of the hourSplunk search (SPL)
index=main earliest=-1h@h latest=@h -
YesterdaySplunk search (SPL)
index=main earliest=-1d@d latest=@d -
Last 7 full daysSplunk search (SPL)
index=main earliest=-7d@d latest=@d -
This week so far (from Monday)Splunk search (SPL)
index=main earliest=@w1 -
Between two exact timesSplunk search (SPL)
index=main earliest="11/23/2026:09:00:00" latest="11/23/2026:17:00:00"Warning: The format is month/day/year:hour:minute:second.
-
Show the time in a readable formatSplunk search (SPL)
index=main | eval time=strftime(_time, "%Y-%m-%d %H:%M:%S") | table time host _raw -
Group events into 5-minute bucketsSplunk search (SPL)
index=main | bin _time span=5m | stats count by _time
Splunk: Picking fields
-
Show only some fields in a tableSplunk search (SPL)
index=main | table _time host source _raw -
Keep only the fields you need (faster)Splunk search (SPL)
index=main | fields host, status, uri -
Drop a fieldSplunk search (SPL)
index=main | fields - _raw -
Rename a fieldSplunk search (SPL)
index=main | rename src_ip AS src -
Remove duplicatesSplunk search (SPL)
index=main | dedup host -
Sort, biggest firstSplunk search (SPL)
index=main | stats count by host | sort - count -
Filter on a calculationSplunk search (SPL)
index=main | where bytes > 1000000 -
Filter with wildcards in whereSplunk search (SPL)
index=main | where like(uri, "%admin%") -
Filter again after other commandsSplunk search (SPL)
index=main | stats count by user | search count>10 -
Fill empty fields with 0Splunk search (SPL)
index=main | fillnull value=0 -
See which fields exist and how full they areSplunk search (SPL)
index=main | fieldsummary | table field count distinct_count
Splunk: Counting and stats
-
Count events by a fieldSplunk search (SPL)
index=main | stats count by host -
Count by two fieldsSplunk search (SPL)
index=main | stats count by host, status -
Count unique valuesSplunk search (SPL)
index=main | stats dc(user) AS users by host -
Average, max and 95th percentileSplunk search (SPL)
index=main | stats avg(response_time) AS avg max(response_time) AS max p95(response_time) AS p95 by uri -
Sum a fieldSplunk search (SPL)
index=main | stats sum(bytes) AS bytes by src -
List the values seen for each groupSplunk search (SPL)
index=main | stats values(src) AS sources count by user -
First and last time something was seenSplunk search (SPL)
index=main | stats earliest(_time) AS first latest(_time) AS last by user | convert ctime(first) ctime(last) -
Top 10 values of a fieldSplunk search (SPL)
index=main | top limit=10 user -
Least common values of a fieldSplunk search (SPL)
index=main | rare limit=10 process_name -
Add a total to every row without groupingSplunk search (SPL)
index=main | eventstats count AS total by host -
Running count per userSplunk search (SPL)
index=main | streamstats count AS seen by user -
Add a totals row at the bottomSplunk search (SPL)
index=main | stats count by host | addcoltotals labelfield=host label=Total -
Add a sparkline to each rowSplunk search (SPL)
index=main | stats sparkline count by host
Splunk: Charts
-
Events over timeSplunk search (SPL)
index=main | timechart span=1h count -
Events over time, one line per hostSplunk search (SPL)
index=main | timechart span=1h count by host limit=10 -
Average over timeSplunk search (SPL)
index=main | timechart span=15m avg(response_time) -
A table with one row per host and a column per statusSplunk search (SPL)
index=main | chart count over host by status -
Compare today with last weekSplunk search (SPL)
index=main earliest=-7d@d | timechart span=1h count | timewrap 1d -
Forecast a trendSplunk search (SPL)
index=main | timechart span=1d count | predict count
Splunk: eval and functions
-
Make a new field from a sumSplunk search (SPL)
index=main | eval MB=round(bytes/1024/1024, 2) -
Set a value with ifSplunk search (SPL)
index=main | eval result=if(status>=400, "error", "ok") -
Set a value with several conditionsSplunk search (SPL)
index=main | eval severity=case(status>=500, "high", status>=400, "medium", true(), "low") -
Use the first field that has a valueSplunk search (SPL)
index=main | eval user=coalesce(user, Account_Name, username) -
Lower-case a fieldSplunk search (SPL)
index=main | eval user=lower(user) -
Length of a fieldSplunk search (SPL)
index=main | eval len=len(query) -
Part of a stringSplunk search (SPL)
index=main | eval prefix=substr(host, 1, 3) -
Split a string and take one partSplunk search (SPL)
index=main | eval domain=mvindex(split(user, "@"), 1) -
Turn a multivalue field into one row per valueSplunk search (SPL)
index=main | mvexpand recipient -
Replace text with a regexSplunk search (SPL)
index=main | eval uri=replace(uri, "\d+", "N") -
Check if an address is in a networkSplunk search (SPL)
index=main | where cidrmatch("10.0.0.0/8", src) -
Seconds as a readable durationSplunk search (SPL)
index=main | eval took=tostring(duration, "duration") -
Numbers with commasSplunk search (SPL)
index=main | stats count | eval count=tostring(count, "commas") -
Decode a URLSplunk search (SPL)
index=main | eval uri=urldecode(uri) -
Where an address is in the worldSplunk search (SPL)
index=main | iplocation src | stats count by Country
Splunk: Pulling fields out of text
-
Extract a field with a regexSplunk search (SPL)
index=main | rex "user=(?<user>\S+)" -
Extract from one field instead of _rawSplunk search (SPL)
index=main | rex field=uri "^/(?<section>[^/]+)" -
Extract every match, not just the firstSplunk search (SPL)
index=main | rex max_match=0 "(?<ip>\d{1,3}(?:\.\d{1,3}){3})" -
Mask card numbers in resultsSplunk search (SPL)
index=main | rex mode=sed "s/\d{4}-\d{4}-\d{4}-(\d{4})/XXXX-XXXX-XXXX-\1/g" -
Read fields from JSONSplunk search (SPL)
index=main | spath | table user.name, event.action -
Read one JSON pathSplunk search (SPL)
index=main | spath path=user.name output=user -
Read key=value pairs with other separatorsSplunk search (SPL)
index=main | extract pairdelim="," kvdelim=":"
Splunk: Lookups
-
Show what's in a lookupSplunk search (SPL)
| inputlookup bad_ips.csv -
Add fields from a lookupSplunk search (SPL)
index=main | lookup bad_ips.csv ip AS src OUTPUT owner, location -
Save results as a lookupSplunk search (SPL)
index=main | stats count by src | outputlookup bad_ips.csv -
Add to a lookup instead of replacing itSplunk search (SPL)
index=main | stats count by src | outputlookup append=true bad_ips.csv -
Search for anything in a lookup (a watchlist)Splunk search (SPL)
index=main [| inputlookup bad_ips.csv | fields src]Warning: The column name in the lookup must match the field name in the events. Rename it inside the brackets if it doesn't.
-
Find lookup rows that never showed upSplunk search (SPL)
| inputlookup bad_ips.csv | search NOT [search index=main earliest=-7d | stats count by src | fields src]
Splunk: Combining searches
-
Use one search's results to filter another (subsearch)Splunk search (SPL)
index=main [search index=main action=blocked | dedup src | fields src]Warning: Subsearches stop at 10,000 results and 60 seconds by default.
-
Add another search's results underneathSplunk search (SPL)
index=main sourcetype=a | append [search index=main sourcetype=b] -
Join two searches on a fieldSplunk search (SPL)
index=main sourcetype=a | join type=left user [search index=main sourcetype=b | fields user, department]Warning: join is slow and has subsearch limits. stats with by often does the same job faster.
-
Join two sourcetypes with stats insteadSplunk search (SPL)
index=main (sourcetype=a OR sourcetype=b) | stats values(department) AS department count by user -
Group related events into oneSplunk search (SPL)
index=main | transaction user maxspan=30m maxpause=5m
Splunk: Fast searches
-
Count by index and sourcetype instantlySplunk search (SPL)
| tstats count where index=* by index, sourcetype -
Events per hour from indexed dataSplunk search (SPL)
| tstats count where index=main by _time span=1h -
Count failed logins from a data modelSplunk search (SPL)
| tstats count from datamodel=Authentication where Authentication.action=failure by Authentication.src -
List hosts and when they last sent dataSplunk search (SPL)
| metadata type=hosts index=main | convert ctime(lastTime) | table host lastTime totalCount -
Find hosts that stopped sending dataSplunk search (SPL)
| metadata type=hosts index=main | where lastTime < relative_time(now(), "-24h") | convert ctime(lastTime) | table host lastTime -
List the indexes and their sizeSplunk search (SPL)
| rest /services/data/indexes | table title currentDBSizeMB totalEventCount -
List the saved searches and their schedulesSplunk search (SPL)
| rest /servicesNS/-/-/saved/searches | table title eai:acl.app cron_schedule
Splunk: Security: logins
-
Failed Windows logins by user and sourceSplunk search (SPL)
index=wineventlog EventCode=4625 | stats count by user, src | sort - count -
Possible brute force (many failures)Splunk search (SPL)
index=wineventlog EventCode=4625 | stats count by user, src | where count > 10 -
Failures followed by a successSplunk search (SPL)
index=wineventlog (EventCode=4625 OR EventCode=4624) | stats count(eval(EventCode=4625)) AS failures count(eval(EventCode=4624)) AS successes by user, src | where failures > 10 AND successes > 0 -
Password spraying (one source, many users)Splunk search (SPL)
index=wineventlog EventCode=4625 | stats dc(user) AS users by src | where users > 10 -
Accounts locked outSplunk search (SPL)
index=wineventlog EventCode=4740 | table _time user host -
RDP loginsSplunk search (SPL)
index=wineventlog EventCode=4624 Logon_Type=10 | stats count by user, src -
Logins outside working hoursSplunk search (SPL)
index=wineventlog EventCode=4624 | eval hour=tonumber(strftime(_time, "%H")) | where hour < 7 OR hour > 19 | stats count by user -
Failed SSH logins on LinuxSplunk search (SPL)
index=linux sourcetype=linux_secure "Failed password" | rex "for (invalid user )?(?<user>\S+) from (?<src>\S+)" | stats count by user, src | sort - count -
Successful SSH logins on LinuxSplunk search (SPL)
index=linux sourcetype=linux_secure "Accepted" | rex "Accepted \S+ for (?<user>\S+) from (?<src>\S+)" | stats count by user, src -
sudo use on LinuxSplunk search (SPL)
index=linux sourcetype=linux_secure sudo COMMAND | rex "sudo:\s+(?<user>\S+) :.*COMMAND=(?<command>.*)" | table _time host user command
Splunk: Security: Windows changes
-
New user accountsSplunk search (SPL)
index=wineventlog EventCode=4720 | table _time user src_user host -
Users added to a security groupSplunk search (SPL)
index=wineventlog (EventCode=4728 OR EventCode=4732 OR EventCode=4756) | table _time src_user user Group_Name host -
Accounts deletedSplunk search (SPL)
index=wineventlog EventCode=4726 | table _time user src_user host -
Security log clearedSplunk search (SPL)
index=wineventlog EventCode=1102 | table _time host user -
New services installedSplunk search (SPL)
index=wineventlog EventCode=7045 | table _time host Service_Name Service_File_Name -
Scheduled tasks createdSplunk search (SPL)
index=wineventlog EventCode=4698 | table _time host user Task_Name -
Processes started, with command linesSplunk search (SPL)
index=wineventlog EventCode=4688 | table _time host user New_Process_Name Process_Command_Line -
Rare processes across your hostsSplunk search (SPL)
index=wineventlog EventCode=4688 | rare limit=20 New_Process_Name -
Encoded PowerShell commandsSplunk search (SPL)
index=wineventlog EventCode=4688 New_Process_Name=*powershell.exe (Process_Command_Line="*-enc*" OR Process_Command_Line="*-EncodedCommand*") | table _time host user Process_Command_Line
Splunk: Security: network and web
-
Most-blocked sources on the firewallSplunk search (SPL)
index=firewall action=blocked | stats count by src | sort - count | head 20 -
Possible port scan (one source, many ports)Splunk search (SPL)
index=firewall | stats dc(dest_port) AS ports by src, dest | where ports > 50 -
Top talkers by bytesSplunk search (SPL)
index=firewall | stats sum(bytes) AS bytes by src | sort - bytes | head 10 | eval MB=round(bytes/1024/1024, 2) -
Traffic to an addressSplunk search (SPL)
index=firewall dest=10.0.0.25 | stats count by src, dest_port, action -
Connections from outside your countrySplunk search (SPL)
index=firewall action=allowed | iplocation src | where Country!="Ireland" | stats count by Country, src -
Web clients getting the most 404sSplunk search (SPL)
index=web sourcetype=access_combined status=404 | stats count by clientip | sort - count -
Web server errors over timeSplunk search (SPL)
index=web sourcetype=access_combined status>=500 | timechart span=1h count by status -
Unusual user agentsSplunk search (SPL)
index=web sourcetype=access_combined | rare limit=20 useragent -
Requests that look like SQL injectionSplunk search (SPL)
index=web sourcetype=access_combined | eval uri=urldecode(uri) | where match(uri, "(?i)union\s+select|or\s+1=1|sleep\(") -
Long DNS queries (possible tunnelling)Splunk search (SPL)
index=dns | eval len=len(query) | where len > 50 | stats count by src, query
Splunk: Splunk's own logs
-
Splunk errors by componentSplunk search (SPL)
index=_internal sourcetype=splunkd log_level=ERROR | stats count by component | sort - count -
Daily licence use by index (GB)Splunk search (SPL)
index=_internal source=*license_usage.log type=Usage | eval GB=b/1024/1024/1024 | timechart span=1d sum(GB) by idx -
Forwarders and when they last connectedSplunk search (SPL)
index=_internal sourcetype=splunkd group=tcpin_connections | stats latest(_time) AS last_seen by hostname | convert ctime(last_seen) -
Who ran which searchesSplunk search (SPL)
index=_audit action=search info=granted search=* | table _time user search -
Logins to SplunkSplunk search (SPL)
index=_audit action="login attempt" | stats count by user, info -
Slowest scheduled searchesSplunk search (SPL)
index=_internal sourcetype=scheduler status=success | stats avg(run_time) AS avg_seconds by savedsearch_name | sort - avg_seconds -
Skipped scheduled searchesSplunk search (SPL)
index=_internal sourcetype=scheduler status=skipped | stats count by savedsearch_name, reason
Splunk: CLI: start, stop and status
-
Start SplunkSplunk CLI
./splunk start -
Stop SplunkSplunk CLI
./splunk stop -
Restart SplunkSplunk CLI
./splunk restart -
Check whether Splunk is runningSplunk CLI
./splunk status -
Show the versionSplunk CLI
./splunk version -
Start Splunk when the server bootsSplunk CLI
sudo ./splunk enable boot-start -user splunk -
Stop starting at bootSplunk CLI
sudo ./splunk disable boot-start -
Show the management portSplunk CLI
./splunk show splunkd-port -
Show the web portSplunk CLI
./splunk show web-port
Splunk: CLI: getting data in
-
Let the indexer receive data from forwardersSplunk CLI
./splunk enable listen 9997 -
Send a forwarder's data to an indexerSplunk CLI
./splunk add forward-server idx1.example.com:9997 -
List where a forwarder sends dataSplunk CLI
./splunk list forward-server -
Stop sending to an indexerSplunk CLI
./splunk remove forward-server idx1.example.com:9997 -
Watch a log file or folderSplunk CLI
./splunk add monitor /var/log/secure -index main -sourcetype syslog -
List the files being watchedSplunk CLI
./splunk list monitor -
Index a file onceSplunk CLI
./splunk add oneshot /var/log/secure -index main -sourcetype syslog -
Point a forwarder at a deployment serverSplunk CLI
./splunk set deploy-poll ds1.example.com:8089 -
Push deployment server changes to clientsSplunk CLI
./splunk reload deploy-server -
List the deployment clientsSplunk CLI
./splunk list deploy-clients -
Create an indexSplunk CLI
./splunk add index main -
Delete all the data in an indexSplunk CLI
./splunk stop ./splunk clean eventdata -index main ./splunk startWarning: This permanently deletes every event in the index. There's no undo.
Splunk: CLI: config and troubleshooting
-
Show the merged inputs config and which file each line is fromSplunk CLI
./splunk btool inputs list --debug -
Show the merged outputs configSplunk CLI
./splunk btool outputs list --debug -
Show how a sourcetype is parsedSplunk CLI
./splunk btool props list syslog --debug -
Check config files for typosSplunk CLI
./splunk btool check -
Run a search from the command lineSplunk CLI
./splunk search "index=_internal | head 10" -
List the installed appsSplunk CLI
./splunk display app -
Install an app from a fileSplunk CLI
./splunk install app /tmp/my_app.tgz -
Collect a diag file for Splunk supportSplunk CLI
./splunk diag
Proxmox: Host and updates
-
Show the Proxmox VE versionProxmox VE
pveversion -
Show the version of every Proxmox packageProxmox VE
pveversion -v -
Show the node's CPU, memory and uptimeProxmox VE
pvesh get /nodes/$(hostname)/status -
Show every VM, container and storage in the clusterProxmox VE
pvesh get /cluster/resources -
Show the next free VM or container IDProxmox VE
pvesh get /cluster/nextid -
Show the subscription statusProxmox VE
pvesubscription get -
List the package repositories in useProxmox VE
cat /etc/apt/sources.list.d/* -
Update the hostProxmox VE
apt update && apt full-upgrade -
List recent tasks, such as backups and migrationsProxmox VE
pvenode task list -
Check the Proxmox services are runningProxmox VE
systemctl status pveproxy pvedaemon pvestatd pve-cluster -
Restart the web interfaceProxmox VE
systemctl restart pveproxy -
Restart the Proxmox servicesProxmox VE
systemctl restart pvedaemon pveproxy pvestatd -
Renew the node's web certificatesProxmox VE
pvecm updatecerts --force -
Collect a full system report for troubleshootingProxmox VE
pvereport -
Restart the hostProxmox VE
rebootWarning: VMs and containers without HA are shut down and only start again if they're set to start at boot.
Proxmox: VMs: everyday
-
List VMsProxmox VE
qm list -
Show a VM's statusProxmox VE
qm status 100 -
Show a VM's settingsProxmox VE
qm config 100 -
Start a VMProxmox VE
qm start 100 -
Shut a VM down cleanlyProxmox VE
qm shutdown 100 -
Shut a VM down, waiting up to 2 minutesProxmox VE
qm shutdown 100 --timeout 120 -
Restart a VM cleanlyProxmox VE
qm reboot 100 -
Stop a VM immediatelyProxmox VE
qm stop 100Warning: Like pulling the power, so unsaved data in the VM may be lost.
-
Stop a VM that's stuck with a lockProxmox VE
qm stop 100 --skiplockWarning: Like pulling the power, so unsaved data in the VM may be lost.
-
Reset a VMProxmox VE
qm reset 100Warning: Like pressing the reset button, so unsaved data in the VM may be lost.
-
Pause a VMProxmox VE
qm suspend 100 -
Resume a paused VMProxmox VE
qm resume 100 -
Remove a stuck lock from a VMProxmox VE
qm unlock 100 -
Start a VM when the host bootsProxmox VE
qm set 100 --onboot 1 -
Open a VM's serial consoleProxmox VE
qm terminal 100 -
Open a VM's QEMU monitorProxmox VE
qm monitor 100
Proxmox: VMs: create and change
-
Create a VM that boots from an ISOProxmox VE
qm create 100 --name web01 --memory 2048 --cores 2 --ostype l26 --net0 virtio,bridge=vmbr0 --scsihw virtio-scsi-pci --scsi0 local-lvm:32 --ide2 local:iso/ubuntu-24.04-live-server-amd64.iso,media=cdrom --boot order='scsi0;ide2' -
Change a VM's memoryProxmox VE
qm set 100 --memory 4096 -
Change a VM's CPU coresProxmox VE
qm set 100 --cores 4 -
Use the host's CPU type for best performanceProxmox VE
qm set 100 --cpu host -
Add a disk to a VMProxmox VE
qm set 100 --scsi1 local-lvm:50 -
Make a VM's disk biggerProxmox VE
qm disk resize 100 scsi0 +10GWarning: Disks can only grow. You'll also need to grow the partition inside the VM.
-
Move a VM's disk to other storage and remove the old copyProxmox VE
qm disk move 100 scsi0 local-zfs --delete 1 -
Import a disk image into a VMProxmox VE
qm disk import 100 debian.qcow2 local-lvm -
Insert an ISO into a VM's CD driveProxmox VE
qm set 100 --ide2 local:iso/virtio-win.iso,media=cdrom -
Eject a VM's ISOProxmox VE
qm set 100 --ide2 none,media=cdrom -
Change the boot orderProxmox VE
qm set 100 --boot order=scsi0 -
Add a second network card on another VLANProxmox VE
qm set 100 --net1 virtio,bridge=vmbr0,tag=20 -
Turn on the QEMU guest agent optionProxmox VE
qm set 100 --agent enabled=1 -
Run a command inside a VM through the guest agentProxmox VE
qm guest exec 100 -- uptime -
Show a VM's IP addresses through the guest agentProxmox VE
qm guest cmd 100 network-get-interfaces -
Add a serial console to a VMProxmox VE
qm set 100 --serial0 socket --vga serial0 -
Pass a USB device through to a VMProxmox VE
qm set 100 --usb0 host=1234:5678 -
Pass a PCI device, such as a GPU, through to a VMProxmox VE
qm set 100 --machine q35 --hostpci0 0000:01:00.0,pcie=1 -
Delete a VM and its disksProxmox VE
qm destroy 100 --purgeWarning: Deletes the VM and its disks, and can't be undone.
Proxmox: Templates, clones and cloud-init
-
Build an Ubuntu cloud-init templateProxmox VE
wget https://cloud-images.ubuntu.com/noble/current/noble-server-cloudimg-amd64.img qm create 9000 --name ubuntu-template --memory 2048 --cores 2 --net0 virtio,bridge=vmbr0 --scsihw virtio-scsi-pci qm set 9000 --scsi0 local-lvm:0,import-from=/root/noble-server-cloudimg-amd64.img qm set 9000 --ide2 local-lvm:cloudinit --boot order=scsi0 --serial0 socket --vga serial0 --agent enabled=1 qm template 9000 -
Set a VM's cloud-init user, SSH key and networkProxmox VE
qm set 9000 --ciuser gerard --sshkeys ~/.ssh/id_ed25519.pub --ipconfig0 ip=dhcp -
Give a cloud-init VM a static IP addressProxmox VE
qm set 101 --ipconfig0 ip=192.168.1.50/24,gw=192.168.1.1 -
Show the cloud-init settings a VM will getProxmox VE
qm cloudinit dump 9000 user -
Rebuild a VM's cloud-init drive after changesProxmox VE
qm cloudinit update 9000 -
Turn a VM into a templateProxmox VE
qm template 9000Warning: A template can't be started, and you can't turn it back into a normal VM.
-
Make a full clone of a templateProxmox VE
qm clone 9000 101 --name web02 --full -
Make a linked clone of a templateProxmox VE
qm clone 9000 102 --name web03
Proxmox: Snapshots and migration
-
Take a snapshot of a VMProxmox VE
qm snapshot 100 before-upgrade --description "Before upgrading" -
Take a snapshot of a VM including its memoryProxmox VE
qm snapshot 100 before-upgrade --vmstate 1 -
List a VM's snapshotsProxmox VE
qm listsnapshot 100 -
Roll a VM back to a snapshotProxmox VE
qm rollback 100 before-upgradeWarning: Loses everything that changed in the VM since the snapshot.
-
Delete a VM snapshotProxmox VE
qm delsnapshot 100 before-upgrade -
Move a running VM to another nodeProxmox VE
qm migrate 100 pve2 --online -
Move a running VM with local disks to another nodeProxmox VE
qm migrate 100 pve2 --online --with-local-disks
Proxmox: Containers (LXC)
-
List containersProxmox VE
pct list -
Show a container's statusProxmox VE
pct status 200 -
Show a container's settingsProxmox VE
pct config 200 -
Start a containerProxmox VE
pct start 200 -
Shut a container down cleanlyProxmox VE
pct shutdown 200 -
Restart a containerProxmox VE
pct reboot 200 -
Stop a container immediatelyProxmox VE
pct stop 200Warning: Processes in the container can't shut down cleanly.
-
Open a shell in a containerProxmox VE
pct enter 200 -
Run a command in a containerProxmox VE
pct exec 200 -- apt update -
Open a container's consoleProxmox VE
pct console 200 -
Create an unprivileged containerProxmox VE
pct create 200 local:vztmpl/debian-12-standard_12.7-1_amd64.tar.zst --hostname app01 --memory 1024 --cores 2 --rootfs local-lvm:8 --net0 name=eth0,bridge=vmbr0,ip=dhcp --unprivileged 1 --ssh-public-keys ~/.ssh/id_ed25519.pub -
Change a container's memoryProxmox VE
pct set 200 --memory 2048 -
Make a container's disk biggerProxmox VE
pct resize 200 rootfs +4GWarning: Disks can only grow.
-
Share a host folder with a containerProxmox VE
pct set 200 --mp0 /mnt/data,mp=/mnt/data -
Let a container run DockerProxmox VE
pct set 200 --features nesting=1,keyctl=1 -
Start a container when the host bootsProxmox VE
pct set 200 --onboot 1 -
Copy a file into a containerProxmox VE
pct push 200 ./config.yml /etc/app/config.yml -
Copy a file out of a containerProxmox VE
pct pull 200 /var/log/app.log ./app.log -
Take a snapshot of a containerProxmox VE
pct snapshot 200 before-upgrade -
List a container's snapshotsProxmox VE
pct listsnapshot 200 -
Roll a container back to a snapshotProxmox VE
pct rollback 200 before-upgradeWarning: Loses everything that changed in the container since the snapshot.
-
Clone a containerProxmox VE
pct clone 200 201 --hostname app02 --full -
Turn a container into a templateProxmox VE
pct template 200Warning: A template can't be started, and you can't turn it back into a normal container.
-
Move a container to another nodeProxmox VE
pct migrate 200 pve2 --restart -
Remove a stuck lock from a containerProxmox VE
pct unlock 200 -
Check a stopped container's filesystemProxmox VE
pct fsck 200 -
Delete a container and its disksProxmox VE
pct destroy 200 --purgeWarning: Deletes the container and its disks, and can't be undone.
Proxmox: Container templates
-
Update the list of container templatesProxmox VE
pveam update -
List the container templates you can downloadProxmox VE
pveam available --section system -
Download a container templateProxmox VE
pveam download local debian-12-standard_12.7-1_amd64.tar.zst -
List downloaded container templatesProxmox VE
pveam list local
Proxmox: Storage
-
Show each storage, its type and free spaceProxmox VE
pvesm status -
List what's on a storageProxmox VE
pvesm list local -
List the ISO images on a storageProxmox VE
pvesm list local --content iso -
List the NFS shares a server offersProxmox VE
pvesm scan nfs 192.168.1.5 -
Add an NFS share for backups and ISOsProxmox VE
pvesm add nfs nas-backup --server 192.168.1.5 --export /volume1/proxmox --content backup,iso -
Add a local folder as storageProxmox VE
pvesm add dir usb-backup --path /mnt/usb --content backup -
Turn off a storage without removing itProxmox VE
pvesm set nas-backup --disable 1 -
Remove a storage from Proxmox, leaving its filesProxmox VE
pvesm remove nas-backup -
Show thin-pool and volume usageProxmox VE
lvs -
List disks and partitionsProxmox VE
lsblk -
Show a disk's SMART healthProxmox VE
smartctl -a /dev/sda -
Wipe a disk so Proxmox can reuse itProxmox VE
wipefs -a /dev/sdbWarning: Erases the disk's partition table and data. Check the disk name with lsblk first.
Proxmox: ZFS
-
Show ZFS pool healthProxmox VE
zpool status -
Show ZFS pool size and free spaceProxmox VE
zpool list -
List ZFS datasets and volumesProxmox VE
zfs list -
Check a ZFS pool for errors (scrub)Proxmox VE
zpool scrub rpool -
Create a mirrored ZFS pool and add it as storageProxmox VE
zpool create -o ashift=12 tank mirror /dev/disk/by-id/ata-DISK1 /dev/disk/by-id/ata-DISK2 pvesm add zfspool tank --pool tank --content images,rootdirWarning: Erases both disks. Check the disk IDs with ls -l /dev/disk/by-id first.
-
Show how much memory the ZFS cache is usingProxmox VE
arc_summary | head -30
Proxmox: Backups and restores
-
Back up a VM nowProxmox VE
vzdump 100 --storage nas-backup --mode snapshot --compress zstd -
Back up several VMs and containersProxmox VE
vzdump 100 101 200 --storage nas-backup --mode snapshot --compress zstd -
Back up everything on this nodeProxmox VE
vzdump --all --storage nas-backup --mode snapshot --compress zstd -
Back up everything except some guestsProxmox VE
vzdump --all --exclude 999 --storage nas-backup --mode snapshot --compress zstd -
Back up a VM with it shut down, for a fully consistent copyProxmox VE
vzdump 100 --storage nas-backup --mode stop --compress zstd -
Add a note to a backupProxmox VE
vzdump 100 --storage nas-backup --mode snapshot --notes-template "{{guestname}} before upgrade" -
List backups on a storageProxmox VE
pvesm list nas-backup --content backup -
Show scheduled backup jobsProxmox VE
cat /etc/pve/jobs.cfg -
Restore a VM backup as a new VMProxmox VE
qmrestore /mnt/pve/nas-backup/dump/vzdump-qemu-100-2026_11_13-02_00_00.vma.zst 110 --storage local-lvm -
Restore a VM backup over the existing VMProxmox VE
qmrestore /mnt/pve/nas-backup/dump/vzdump-qemu-100-2026_11_13-02_00_00.vma.zst 100 --forceWarning: Replaces the VM and its disks with the backup.
-
Restore a container backup as a new containerProxmox VE
pct restore 210 /mnt/pve/nas-backup/dump/vzdump-lxc-200-2026_11_13-02_00_00.tar.zst --storage local-lvm
Proxmox: Clusters and HA
-
Create a clusterProxmox VE
pvecm create homelab -
Join this node to a clusterProxmox VE
pvecm add 192.168.1.10 -
Show the cluster and quorum statusProxmox VE
pvecm status -
List the nodes in the clusterProxmox VE
pvecm nodes -
Show corosync link statusProxmox VE
corosync-cfgtool -s -
Show cluster logsProxmox VE
journalctl -u corosync -u pve-cluster -
Let a node work alone when the others are downProxmox VE
pvecm expected 1Warning: Can cause the same VM to run twice if other nodes come back. Only use it when you're sure they're off.
-
Remove a node from the clusterProxmox VE
pvecm delnode pve3Warning: Shut the node down first and never bring it back with its old setup.
-
Show HA statusProxmox VE
ha-manager status -
Add a VM to HAProxmox VE
ha-manager add vm:100 -
Remove a VM from HAProxmox VE
ha-manager remove vm:100
Proxmox: Networking and firewall
-
Show the host's interfaces and bridgesProxmox VE
ip -br addr -
Show the host's network configProxmox VE
cat /etc/network/interfaces -
Apply network config changes without a rebootProxmox VE
ifreload -aWarning: A mistake can cut off your connection to the host, so have console access ready.
-
Show the Proxmox firewall statusProxmox VE
pve-firewall status -
Check firewall rules compile without errorsProxmox VE
pve-firewall compile -
Stop the Proxmox firewallProxmox VE
pve-firewall stopWarning: Removes all firewall rules until you start it again.
-
Start the Proxmox firewallProxmox VE
pve-firewall start
Proxmox: Users and API tokens
-
List usersProxmox VE
pveum user list -
Add a Proxmox userProxmox VE
pveum user add gerard@pve -
Set a user's passwordProxmox VE
pveum passwd gerard@pve -
Give a user admin rights on everythingProxmox VE
pveum acl modify / --users gerard@pve --roles PVEAdmin -
List rolesProxmox VE
pveum role list -
Create an API token for automationProxmox VE
pveum user token add gerard@pve automation --privsep 0Warning: The token's secret is shown once. Save it somewhere safe straight away.
-
Delete a userProxmox VE
pveum user delete gerard@pve
Proxmox: Hardware and passthrough
-
Check IOMMU is turned onProxmox VE
dmesg | grep -e DMAR -e IOMMU -
List IOMMU groupsProxmox VE
find /sys/kernel/iommu_groups/ -type l -
List PCI devices with their IDsProxmox VE
lspci -nn -
List USB devices with their IDsProxmox VE
lsusb -
Show CPU detailsProxmox VE
lscpu
Proxmox: Troubleshooting
-
Follow the system logProxmox VE
journalctl -f -
Show the web interface's log since bootProxmox VE
journalctl -u pveproxy -b -
Show the logs for a failed backup or taskProxmox VE
pvenode task list --errors -
Show the processes for a VMProxmox VE
ps aux | grep "qemu.*-id 100" -
Check the cluster filesystem is workingProxmox VE
systemctl status pve-cluster -
Show which VM disks use the most spaceProxmox VE
lvs --sort -data_percent
Git: Setup
-
Check which version of Git is installedLinux, macOS, Windows
git --version -
Set the name on your commitsLinux, macOS, Windows
git config --global user.name "Your Name" -
Set the email on your commitsLinux, macOS, Windows
git config --global user.email "[email protected]" -
Name the first branch main in new repositoriesLinux, macOS, Windows
git config --global init.defaultBranch main -
Use VS Code to write commit messagesLinux, macOS, Windows
git config --global core.editor "code --wait" -
Rebase instead of merge when you pullLinux, macOS, Windows
git config --global pull.rebase true -
Create a shortcut, so git st runs git statusLinux, macOS, Windows
git config --global alias.st status -
Show all your settings and where they come fromLinux, macOS, Windows
git config --list --show-origin
Git: Start a repository
-
Turn the current folder into a repositoryLinux, macOS, Windows
git init -
Copy a repository to your computerLinux, macOS, Windows
git clone https://github.com/user/repo.git -
Copy a repository into a folder with a different nameLinux, macOS, Windows
git clone https://github.com/user/repo.git my-folder -
Copy only the latest version of a repositoryLinux, macOS, Windows
git clone --depth 1 https://github.com/user/repo.git -
Copy a repository and switch to a specific branchLinux, macOS, Windows
git clone --branch develop https://github.com/user/repo.git
Git: See what has changed
-
See what has changedLinux, macOS, Windows
git status -
See what has changed, in short formLinux, macOS, Windows
git status -s -
Show changes you haven't staged yetLinux, macOS, Windows
git diff -
Show changes that are staged for the next commitLinux, macOS, Windows
git diff --staged -
List only the names of changed filesLinux, macOS, Windows
git diff --name-only -
Compare two branchesLinux, macOS, Windows
git diff main..my-branch -
Show what a commit changedLinux, macOS, Windows
git show abc1234 -
Show a file as it was in an earlier commitLinux, macOS, Windows
git show abc1234:path/to/file.txt
Git: Stage and commit
-
Stage a file for the next commitLinux, macOS, Windows
git add file.txt -
Stage every change, including new and deleted filesLinux, macOS, Windows
git add -A -
Choose which parts of a file to stageLinux, macOS, Windows
git add -p -
Save staged changes as a commitLinux, macOS, Windows
git commit -m "Describe the change" -
Stage changes to tracked files and commit in one stepLinux, macOS, Windows
git commit -am "Describe the change" -
Add staged changes to the last commitLinux, macOS, Windows
git commit --amend --no-editWarning: Rewrites history. Don't use it on commits you've already pushed and shared.
-
Change the last commit messageLinux, macOS, Windows
git commit --amend -m "New message"Warning: Rewrites history. Don't use it on commits you've already pushed and shared.
-
Make an empty commit, for example to rerun a workflowLinux, macOS, Windows
git commit --allow-empty -m "Rerun checks" -
Unstage a file but keep the editsLinux, macOS, Windows
git restore --staged file.txt -
Stop tracking a file but keep it on diskLinux, macOS, Windows
git rm --cached file.txt -
Delete a file and stage the deletionLinux, macOS, Windows
git rm file.txt -
Rename a file and stage the renameLinux, macOS, Windows
git mv old-name.txt new-name.txt
Git: Branches
-
List your branchesLinux, macOS, Windows
git branch -
List every branch, including ones on GitHubLinux, macOS, Windows
git branch -a -
Show the latest commit on each branchLinux, macOS, Windows
git branch -v -
Create a branch and switch to itLinux, macOS, Windows
git switch -c my-branch -
Switch to an existing branchLinux, macOS, Windows
git switch main -
Switch back to the previous branchLinux, macOS, Windows
git switch - -
Rename the current branchLinux, macOS, Windows
git branch -m new-name -
List branches already merged into mainLinux, macOS, Windows
git branch --merged main -
Delete a branch that has been mergedLinux, macOS, Windows
git branch -d my-branch -
Delete a branch even if it isn't mergedLinux, macOS, Windows
git branch -D my-branchWarning: Any commits only on that branch will be lost.
-
Delete a branch on GitHubLinux, macOS, Windows
git push origin --delete my-branch
Git: Merge and rebase
-
Merge a branch into the current branchLinux, macOS, Windows
git merge my-branch -
Merge and always create a merge commitLinux, macOS, Windows
git merge --no-ff my-branch -
Combine a branch's changes into one commitLinux, macOS, Windows
git merge --squash my-branch -
List files with merge conflictsLinux, macOS, Windows
git diff --name-only --diff-filter=U -
Mark a conflict as fixedLinux, macOS, Windows
git add file.txt -
Cancel a merge that has conflictsLinux, macOS, Windows
git merge --abort -
Move your branch on top of the latest mainLinux, macOS, Windows
git rebase mainWarning: Rewrites history. Don't use it on commits you've already pushed and shared.
-
Continue a rebase after fixing conflictsLinux, macOS, Windows
git rebase --continue -
Cancel a rebaseLinux, macOS, Windows
git rebase --abort -
Tidy up or combine the last 3 commitsLinux, macOS, Windows
git rebase -i HEAD~3Warning: Rewrites history. Don't use it on commits you've already pushed and shared.
-
Copy one commit onto the current branchLinux, macOS, Windows
git cherry-pick abc1234
Git: Work with GitHub
-
List the remote repositories you're connected toLinux, macOS, Windows
git remote -v -
Connect a repository to GitHubLinux, macOS, Windows
git remote add origin https://github.com/user/repo.git -
Change the GitHub address of a repositoryLinux, macOS, Windows
git remote set-url origin [email protected]:user/repo.git -
Download new changes without applying themLinux, macOS, Windows
git fetch -
Download changes and forget branches deleted on GitHubLinux, macOS, Windows
git fetch --prune -
Get the latest changes for your branchLinux, macOS, Windows
git pull -
Get the latest changes and put yours on topLinux, macOS, Windows
git pull --rebase -
Push your commits to GitHubLinux, macOS, Windows
git push -
Push a new branch to GitHubLinux, macOS, Windows
git push -u origin my-branch -
Check out a branch someone else pushedLinux, macOS, Windows
git switch their-branch -
List commits on your branch that aren't on main yetLinux, macOS, Windows
git log --oneline origin/main..HEAD -
Overwrite the branch on GitHub with yoursLinux, macOS, Windows
git push --force-with-leaseWarning: Replaces commits on GitHub. Only use it on your own branches.
Git: Undo changes
-
Throw away changes to a fileLinux, macOS, Windows
git restore file.txtWarning: Uncommitted changes to the file are lost.
-
Throw away all uncommitted changesLinux, macOS, Windows
git restore .Warning: Uncommitted changes are lost. New files you haven't staged are kept.
-
Undo the last commit but keep the changesLinux, macOS, Windows
git reset --soft HEAD~1 -
Undo the last commit and unstage its changesLinux, macOS, Windows
git reset HEAD~1 -
Delete the last commit and its changesLinux, macOS, Windows
git reset --hard HEAD~1Warning: The commit and any uncommitted changes are lost.
-
Make your branch match GitHub exactly (run git fetch first)Linux, macOS, Windows
git reset --hard origin/mainWarning: Local commits and uncommitted changes are lost.
-
Undo a commit you've already pushed, with a new commitLinux, macOS, Windows
git revert abc1234 -
Bring back a file from an earlier commitLinux, macOS, Windows
git restore --source abc1234 file.txt -
Find a lost commit, for example after a resetLinux, macOS, Windows
git reflog -
Preview which untracked files would be deletedLinux, macOS, Windows
git clean -n -
Delete untracked files and foldersLinux, macOS, Windows
git clean -fdWarning: Deletes files Git isn't tracking, and they can't be recovered. Run git clean -n first.
Git: Stash
-
Put uncommitted changes aside for laterLinux, macOS, Windows
git stash -
Put changes aside with a note, including new filesLinux, macOS, Windows
git stash push -u -m "Half-finished login form" -
List the changes you've put asideLinux, macOS, Windows
git stash list -
Show what the latest stash changesLinux, macOS, Windows
git stash show -p -
Bring back the latest stash and remove it from the listLinux, macOS, Windows
git stash pop -
Bring back the latest stash and keep it in the listLinux, macOS, Windows
git stash apply -
Delete the latest stashLinux, macOS, Windows
git stash dropWarning: The stashed changes are lost.
-
Create a branch from the latest stashLinux, macOS, Windows
git stash branch my-branch
Git: History
-
View history as a compact graphLinux, macOS, Windows
git log --oneline --graph -
View every branch as a graphLinux, macOS, Windows
git log --oneline --graph --all -
Show the last 5 commitsLinux, macOS, Windows
git log -5 --oneline -
Show every change to a file, including renamesLinux, macOS, Windows
git log --follow -p file.txt -
Find commits by words in their messageLinux, macOS, Windows
git log --grep="login" --oneline -
Find commits that added or removed some textLinux, macOS, Windows
git log -S "apiKey" --oneline -
Show commits by one personLinux, macOS, Windows
git log --author="Gerard" --oneline -
Show commits from the last two weeksLinux, macOS, Windows
git log --since="2 weeks ago" --oneline -
See who last changed each line of a fileLinux, macOS, Windows
git blame file.txt -
Count commits by each personLinux, macOS, Windows
git shortlog -sn
Git: Find a broken commit
-
Start searching for the commit that broke somethingLinux, macOS, Windows
git bisect start -
Mark the current commit as brokenLinux, macOS, Windows
git bisect bad -
Mark a commit as workingLinux, macOS, Windows
git bisect good abc1234 -
Finish searching and go back to where you wereLinux, macOS, Windows
git bisect reset
Git: Ignore files
-
Ignore a folder by adding it to .gitignoreLinux, macOS
echo "node_modules/" >> .gitignore -
Find out why a file is being ignoredLinux, macOS, Windows
git check-ignore -v file.txt -
List ignored filesLinux, macOS, Windows
git status --ignored
Git: Worktrees and submodules
-
Open another branch in a separate folderLinux, macOS, Windows
git worktree add ../hotfix hotfix -
List the folders open as worktreesLinux, macOS, Windows
git worktree list -
Remove a worktree folderLinux, macOS, Windows
git worktree remove ../hotfix -
Add another repository inside this oneLinux, macOS, Windows
git submodule add https://github.com/user/library.git libs/library -
Copy a repository and its submodulesLinux, macOS, Windows
git clone --recurse-submodules https://github.com/user/repo.git -
Download submodules after cloningLinux, macOS, Windows
git submodule update --init --recursive
Docker: Setup and help
-
Show the Docker client and server versionsLinux, macOS, Windows
docker version -
Show system-wide information, such as storage and container countsLinux, macOS, Windows
docker info -
Get help for any commandLinux, macOS, Windows
docker run --help -
Sign in to Docker HubLinux, macOS, Windows
docker login -
Sign in to another registry, such as GitHubLinux, macOS, Windows
docker login ghcr.io -
Sign in with a token without it showing in your historyLinux, macOS
echo "$TOKEN" | docker login ghcr.io -u myuser --password-stdin -
Sign out of a registryLinux, macOS, Windows
docker logout
Docker: Run containers
-
Run a container from an imageLinux, macOS, Windows
docker run nginx -
Run a container in the backgroundLinux, macOS, Windows
docker run -d nginx -
Run a container with a nameLinux, macOS, Windows
docker run -d --name my-container nginx -
Publish a container port on the hostLinux, macOS, Windows
docker run -d -p 8080:80 nginx -
Publish a port on localhost onlyLinux, macOS, Windows
docker run -d -p 127.0.0.1:8080:80 nginx -
Start an interactive shell in a new containerLinux, macOS, Windows
docker run -it ubuntu bash -
Run a container and remove it when it stopsLinux, macOS, Windows
docker run --rm -it alpine sh -
Set an environment variableLinux, macOS, Windows
docker run -d -e TZ=Europe/Dublin nginx -
Load environment variables from a fileLinux, macOS, Windows
docker run -d --env-file .env my-app -
Mount a folder from the host, read-onlyLinux, macOS
docker run -d -v "$(pwd)/site":/usr/share/nginx/html:ro nginx -
Mount a named volumeLinux, macOS, Windows
docker run -d -v app-data:/data my-app -
Restart the container automatically unless you stop itLinux, macOS, Windows
docker run -d --restart unless-stopped nginx -
Limit a container's memory and CPULinux, macOS, Windows
docker run -d --memory 512m --cpus 1.5 nginx -
Run a container on a specific networkLinux, macOS, Windows
docker run -d --network my-network nginx -
Run a container as a specific userLinux, macOS, Windows
docker run --rm -u 1000:1000 alpine id -
Override the image's entrypointLinux, macOS, Windows
docker run --rm -it --entrypoint sh my-app -
Run an image built for another platformLinux, macOS, Windows
docker run --rm --platform linux/amd64 alpine uname -m -
Give a container access to NVIDIA GPUsLinux, Windows
docker run --rm --gpus all ubuntu nvidia-smi -
Create a container without starting itLinux, macOS, Windows
docker create --name my-container nginx
Docker: Manage containers
-
List running containersLinux, macOS, Windows
docker ps -
List all containers, including stopped onesLinux, macOS, Windows
docker ps -a -
List only container IDsLinux, macOS, Windows
docker ps -q -
List containers whose name matchesLinux, macOS, Windows
docker ps --filter "name=web" -
List containers with their disk sizeLinux, macOS, Windows
docker ps -s -
Stop a containerLinux, macOS, Windows
docker stop my-container -
Start a stopped containerLinux, macOS, Windows
docker start my-container -
Restart a containerLinux, macOS, Windows
docker restart my-container -
Kill a container immediatelyLinux, macOS, Windows
docker kill my-containerWarning: The container can't shut down cleanly, so unsaved data may be lost.
-
Pause a containerLinux, macOS, Windows
docker pause my-container -
Resume a paused containerLinux, macOS, Windows
docker unpause my-container -
Rename a containerLinux, macOS, Windows
docker rename my-container my-container-old -
Change a running container's restart policyLinux, macOS, Windows
docker update --restart unless-stopped my-container -
Wait for a container to stop and print its exit codeLinux, macOS, Windows
docker wait my-container -
Remove a stopped containerLinux, macOS, Windows
docker rm my-container -
Remove a container even if it's runningLinux, macOS, Windows
docker rm -f my-containerWarning: Stops the container without a clean shutdown and deletes it.
-
Remove all stopped containersLinux, macOS, Windows
docker container pruneWarning: Deletes every stopped container and anything not saved to a volume.
-
Stop all running containersLinux, macOS
docker stop $(docker ps -q) -
Remove all containersLinux, macOS
docker rm -f $(docker ps -aq)Warning: Deletes every container, running or not. Data not in a volume is lost.
Docker: Logs and inspection
-
Show a container's logsLinux, macOS, Windows
docker logs my-container -
Follow a container's logsLinux, macOS, Windows
docker logs -f my-container -
Show the last 100 log linesLinux, macOS, Windows
docker logs --tail 100 my-container -
Show logs from the last hourLinux, macOS, Windows
docker logs --since 1h my-container -
Show logs with timestampsLinux, macOS, Windows
docker logs -t my-container -
Watch live CPU, memory and network useLinux, macOS, Windows
docker stats -
Show resource use once, without updatingLinux, macOS, Windows
docker stats --no-stream -
Show the processes running in a containerLinux, macOS, Windows
docker top my-container -
Show all of a container's settingsLinux, macOS, Windows
docker inspect my-container -
Get a container's IP addressLinux, macOS, Windows
docker inspect -f "{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}" my-container -
Show a container's health check statusLinux, macOS, Windows
docker inspect -f "{{.State.Health.Status}}" my-container -
Show a container's exit codeLinux, macOS, Windows
docker inspect -f "{{.State.ExitCode}}" my-container -
Show a container's published portsLinux, macOS, Windows
docker port my-container -
Show files changed inside a containerLinux, macOS, Windows
docker diff my-container -
Watch Docker events as they happenLinux, macOS, Windows
docker events
Docker: Shells and files
-
Open a shell inside a containerLinux, macOS, Windows
docker exec -it my-container sh -
Open a Bash shell inside a containerLinux, macOS, Windows
docker exec -it my-container bash -
Open a shell inside a container as rootLinux, macOS, Windows
docker exec -it -u root my-container sh -
Run a single command inside a containerLinux, macOS, Windows
docker exec my-container ls /app -
Run a command with an extra environment variableLinux, macOS, Windows
docker exec -e DEBUG=1 my-container env -
Copy a file out of a containerLinux, macOS, Windows
docker cp my-container:/app/config.yml ./config.yml -
Copy a file into a containerLinux, macOS, Windows
docker cp ./config.yml my-container:/app/config.yml -
Attach to a container's main process (detach with Ctrl+P, Ctrl+Q)Linux, macOS, Windows
docker attach my-container
Docker: Images
-
List imagesLinux, macOS, Windows
docker images -
Download an imageLinux, macOS, Windows
docker pull nginx -
Download a specific image versionLinux, macOS, Windows
docker pull nginx:1.27-alpine -
Download an image for another platformLinux, macOS, Windows
docker pull --platform linux/arm64 nginx -
Tag an image with a new nameLinux, macOS, Windows
docker tag my-app:latest myuser/my-app:1.0 -
Upload an image to a registryLinux, macOS, Windows
docker push myuser/my-app:1.0 -
Search Docker Hub for imagesLinux, macOS, Windows
docker search nginx -
Show an image's layers and how it was builtLinux, macOS, Windows
docker history nginx -
Show all of an image's settingsLinux, macOS, Windows
docker image inspect nginx -
Scan an image for known vulnerabilitiesLinux, macOS, Windows
docker scout cves nginx -
Save an image to a fileLinux, macOS, Windows
docker save -o my-app.tar my-app:latest -
Load an image from a fileLinux, macOS, Windows
docker load -i my-app.tar -
Save a container's changes as a new imageLinux, macOS, Windows
docker commit my-container my-app:snapshot -
Export a container's filesystem to a fileLinux, macOS, Windows
docker export -o my-container.tar my-container -
Create an image from an exported filesystemLinux, macOS, Windows
docker import my-container.tar my-app:imported -
Remove an imageLinux, macOS, Windows
docker rmi nginx -
Remove untagged (dangling) imagesLinux, macOS, Windows
docker image prune -
Remove all images no container is usingLinux, macOS, Windows
docker image prune -aWarning: Deletes every image not used by a container. You'll need to download or build them again.
Docker: Build images
-
Create a Dockerfile and Compose file for your projectLinux, macOS, Windows
docker init -
Build an image from the Dockerfile in this folderLinux, macOS, Windows
docker build -t my-app . -
Build with a different DockerfileLinux, macOS, Windows
docker build -f Dockerfile.prod -t my-app:prod . -
Build without using the cacheLinux, macOS, Windows
docker build --no-cache -t my-app . -
Build with the newest version of the base imageLinux, macOS, Windows
docker build --pull -t my-app . -
Pass a build argumentLinux, macOS, Windows
docker build --build-arg NODE_VERSION=22 -t my-app . -
Build only up to one stage of a multi-stage DockerfileLinux, macOS, Windows
docker build --target build -t my-app:build . -
Show the full build outputLinux, macOS, Windows
docker build --progress=plain -t my-app . -
Create a builder for multi-platform imagesLinux, macOS, Windows
docker buildx create --name multi --use -
List buildersLinux, macOS, Windows
docker buildx ls -
Build for Intel and ARM and push to a registryLinux, macOS, Windows
docker buildx build --platform linux/amd64,linux/arm64 -t myuser/my-app:1.0 --push . -
Clear the build cacheLinux, macOS, Windows
docker builder prune
Docker: Volumes
-
List volumesLinux, macOS, Windows
docker volume ls -
Create a volumeLinux, macOS, Windows
docker volume create app-data -
Show a volume's details, including where it's storedLinux, macOS, Windows
docker volume inspect app-data -
Back up a volume to a fileLinux, macOS
docker run --rm -v app-data:/data -v "$(pwd)":/backup alpine tar czf /backup/app-data.tar.gz -C /data . -
Restore a volume from a backupLinux, macOS
docker run --rm -v app-data:/data -v "$(pwd)":/backup alpine tar xzf /backup/app-data.tar.gz -C /dataWarning: Overwrites files in the volume with the ones in the backup.
-
Remove a volumeLinux, macOS, Windows
docker volume rm app-dataWarning: Deletes the data in the volume and can't be undone.
-
Remove unused anonymous volumesLinux, macOS, Windows
docker volume pruneWarning: Deletes the data in those volumes and can't be undone.
-
Remove all unused volumes, including named onesLinux, macOS, Windows
docker volume prune -aWarning: Deletes the data in every volume not used by a container, and can't be undone.
Docker: Networks
-
List networksLinux, macOS, Windows
docker network ls -
Create a networkLinux, macOS, Windows
docker network create my-network -
Show a network's details and connected containersLinux, macOS, Windows
docker network inspect my-network -
Connect a container to a networkLinux, macOS, Windows
docker network connect my-network my-container -
Disconnect a container from a networkLinux, macOS, Windows
docker network disconnect my-network my-container -
Use the host's network directlyLinux
docker run -d --network host nginx -
Give containers their own IP addresses on your LAN (macvlan)Linux
docker network create -d macvlan --subnet 192.168.1.0/24 --gateway 192.168.1.1 -o parent=eth0 lan -
Remove a networkLinux, macOS, Windows
docker network rm my-network -
Remove unused networksLinux, macOS, Windows
docker network prune
Docker: Docker Compose
-
Start a Compose stack in the backgroundLinux, macOS, Windows
docker compose up -d -
Start a Compose stack and show its outputLinux, macOS, Windows
docker compose up -
Rebuild images and start a Compose stackLinux, macOS, Windows
docker compose up -d --build -
Use a different Compose fileLinux, macOS, Windows
docker compose -f compose.prod.yaml up -d -
Run more copies of a serviceLinux, macOS, Windows
docker compose up -d --scale worker=3 -
Remove containers for services no longer in the fileLinux, macOS, Windows
docker compose up -d --remove-orphans -
Stop and remove a Compose stackLinux, macOS, Windows
docker compose down -
Stop and remove a Compose stack and its volumesLinux, macOS, Windows
docker compose down -vWarning: Deletes the stack's volumes and the data in them.
-
Stop a Compose stack without removing itLinux, macOS, Windows
docker compose stop -
Start a stopped Compose stackLinux, macOS, Windows
docker compose start -
Restart one serviceLinux, macOS, Windows
docker compose restart web -
List a stack's services and their statusLinux, macOS, Windows
docker compose ps -
List all running Compose projectsLinux, macOS, Windows
docker compose ls -
Follow logs for every serviceLinux, macOS, Windows
docker compose logs -f -
Follow logs for one serviceLinux, macOS, Windows
docker compose logs -f web -
Open a shell in a running serviceLinux, macOS, Windows
docker compose exec web sh -
Run a one-off command in a new service containerLinux, macOS, Windows
docker compose run --rm web npm test -
Show the processes in each serviceLinux, macOS, Windows
docker compose top -
Download the latest images for a stackLinux, macOS, Windows
docker compose pull -
Update a stack to its latest imagesLinux, macOS
docker compose pull && docker compose up -d -
Build a stack's imagesLinux, macOS, Windows
docker compose build -
Check the Compose file and show the final settingsLinux, macOS, Windows
docker compose config -
Rebuild and restart services when files changeLinux, macOS, Windows
docker compose watch
Docker: Disk space and clean-up
-
Show how much disk space Docker is usingLinux, macOS, Windows
docker system df -
Show disk use for each image, container and volumeLinux, macOS, Windows
docker system df -v -
Remove stopped containers, unused networks, dangling images and build cacheLinux, macOS, Windows
docker system pruneWarning: Deletes what it lists and can't be undone.
-
Remove everything Docker isn't using, including images and volumesLinux, macOS, Windows
docker system prune -a --volumesWarning: Deletes all unused images and volume data, and can't be undone.
Docker: Remote hosts and contexts
-
List Docker contextsLinux, macOS, Windows
docker context ls -
Add a remote Docker host over SSHLinux, macOS, Windows
docker context create homelab --docker "host=ssh://[email protected]" -
Switch to another Docker hostLinux, macOS, Windows
docker context use homelab -
Switch back to your local DockerLinux, macOS, Windows
docker context use default -
Run one command on a remote Docker hostLinux, macOS, Windows
docker -H ssh://[email protected] ps
Docker: Swarm
-
Turn this machine into a Swarm managerLinux, macOS, Windows
docker swarm init -
Show the command for joining a worker to the SwarmLinux, macOS, Windows
docker swarm join-token worker -
List the nodes in the SwarmLinux, macOS, Windows
docker node ls -
Create a service with 3 replicasLinux, macOS, Windows
docker service create --name web --replicas 3 -p 8080:80 nginx -
List servicesLinux, macOS, Windows
docker service ls -
Show where a service's tasks are runningLinux, macOS, Windows
docker service ps web -
Change how many replicas a service runsLinux, macOS, Windows
docker service scale web=5 -
Update a service to a new imageLinux, macOS, Windows
docker service update --image nginx:1.27 web -
Follow a service's logsLinux, macOS, Windows
docker service logs -f web -
Deploy a Compose file as a stackLinux, macOS, Windows
docker stack deploy -c compose.yaml my-stack -
Remove a stackLinux, macOS, Windows
docker stack rm my-stack -
Leave the SwarmLinux, macOS, Windows
docker swarm leave --forceWarning: On a manager, this can break the Swarm if it's the last one.
Terraform: Setup and help
-
Show the Terraform version and provider versionsLinux, macOS, Windows
terraform version -
Show the version as JSON for scriptsLinux, macOS, Windows
terraform version -json -
List the built-in functions this version has, as JSONLinux, macOS, Windows
terraform metadata functions -json -
List every commandLinux, macOS, Windows
terraform -help -
Get help for one commandLinux, macOS, Windows
terraform plan -help -
Turn on tab completion for commandsLinux, macOS
terraform -install-autocomplete -
Run a command against another folderLinux, macOS, Windows
terraform -chdir=environments/prod plan
Terraform: Start a project
-
Set up a folder: download providers and modules, and connect the backendLinux, macOS, Windows
terraform init -
Upgrade providers and modules to the newest versions your rules allowLinux, macOS, Windows
terraform init -upgrade -
Set up without changing the dependency lock file (fails if it's out of date)Linux, macOS, Windows
terraform init -lockfile=readonly -
Set up with backend settings kept in a separate fileLinux, macOS, Windows
terraform init -backend-config=backend.hcl -
Move existing state to a new backendLinux, macOS, Windows
terraform init -migrate-stateWarning: Copies your state to the new backend. Take a backup with terraform state pull first.
-
Switch backend without moving the stateLinux, macOS, Windows
terraform init -reconfigureWarning: Ignores the state in the old backend. Use -migrate-state if you want to keep it.
-
Set up without a backend, to validate code onlyLinux, macOS, Windows
terraform init -backend=false -
Download the modules your code usesLinux, macOS, Windows
terraform get -
Update modules to their newest allowed versionsLinux, macOS, Windows
terraform get -update -
Show which providers the code needsLinux, macOS, Windows
terraform providers -
Record provider checksums for every platform your team usesLinux, macOS, Windows
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64 -
Show every provider's schema as JSONLinux, macOS, Windows
terraform providers schema -json -
Download the providers into a local folder for offline or air-gapped useLinux, macOS, Windows
terraform providers mirror ./providers -
List every module the code declares (1.10+)Linux, macOS, Windows
terraform modules -
List every module the code declares as JSON (1.10+)Linux, macOS, Windows
terraform modules -json
Terraform: Format and validate
-
Format the files in this folderLinux, macOS, Windows
terraform fmt -
Format files in this folder and every folder below itLinux, macOS, Windows
terraform fmt -recursive -
Check formatting without changing files (for CI)Linux, macOS, Windows
terraform fmt -check -recursive -
Show what formatting would changeLinux, macOS, Windows
terraform fmt -diff -
Check the code is validLinux, macOS, Windows
terraform validate -
Get validation results as JSONLinux, macOS, Windows
terraform validate -json -
Try out expressions and functions interactivelyLinux, macOS, Windows
terraform console -
Work out one expression without opening the consoleLinux, macOS
echo 'cidrsubnet("10.0.0.0/16", 8, 2)' | terraform console
Terraform: Plan
-
Show what would changeLinux, macOS, Windows
terraform plan -
Save a plan to a file, to apply exactly that laterLinux, macOS, Windows
terraform plan -out=tfplanWarning: A saved plan can hold secrets in plain text. Don't commit it or leave it lying around.
-
Read a saved planLinux, macOS, Windows
terraform show tfplan -
Get a saved plan as JSONLinux, macOS, Windows
terraform show -json tfplan -
Set a variable for one runLinux, macOS, Windows
terraform plan -var="region=eu-west-1" -
Use a variables fileLinux, macOS, Windows
terraform plan -var-file=prod.tfvars -
Plan for one resource onlyLinux, macOS, Windows
terraform plan -target=aws_instance.webWarning: Targeting skips everything else, so the rest of your infrastructure can drift out of step. Use it to recover from problems, not as routine.
-
Show what a destroy would removeLinux, macOS, Windows
terraform plan -destroy -
Show how real infrastructure has drifted from the stateLinux, macOS, Windows
terraform plan -refresh-only -
Plan faster by skipping the refresh from the providerLinux, macOS, Windows
terraform plan -refresh=falseWarning: The plan uses what the state last recorded, so it can miss changes made outside Terraform.
-
Wait for a state lock instead of failing straight awayLinux, macOS, Windows
terraform plan -lock-timeout=60s -
Run more operations at once (the default is 10)Linux, macOS, Windows
terraform plan -parallelism=20 -
Plan without colour codes, for log filesLinux, macOS, Windows
terraform plan -no-color -
Show the plan as streaming JSON for tools to readLinux, macOS, Windows
terraform plan -json -
Group warnings into a short summaryLinux, macOS, Windows
terraform plan -compact-warnings -
Plan without taking a state lockLinux, macOS, Windows
terraform plan -lock=falseWarning: Another run could change the state at the same time. Only use this when you're sure nothing else is running.
Terraform: Apply and destroy
-
Make the changes, after showing the plan and asking yes or noLinux, macOS, Windows
terraform apply -
Apply a saved planLinux, macOS, Windows
terraform apply tfplan -
Apply without asking for confirmationLinux, macOS, Windows
terraform apply -auto-approveWarning: Makes the changes without showing you the plan first. Keep it for automation that has already reviewed a plan.
-
Apply with a variables fileLinux, macOS, Windows
terraform apply -var-file=prod.tfvars -
Apply one resource onlyLinux, macOS, Windows
terraform apply -target=aws_instance.webWarning: Targeting skips everything else, so the rest of your infrastructure can drift out of step. Use it to recover from problems, not as routine.
-
Destroy one resource and build it againLinux, macOS, Windows
terraform apply -replace=aws_instance.webWarning: Destroys the resource and creates a new one. Anything stored on it is lost and it may come back with a new address.
-
Apply and stream the progress as JSONLinux, macOS, Windows
terraform apply -json -auto-approve tfplan -
Run an action defined in the code (1.14+, Terraform only)Linux, macOS, Windows
terraform apply -invoke=action.aws_lambda_invoke.notify -
Preview running an action (1.14+, Terraform only)Linux, macOS, Windows
terraform plan -invoke=action.aws_lambda_invoke.notify -
Clear the tainted mark so a resource isn't rebuiltLinux, macOS, Windows
terraform untaint aws_instance.web -
Update the state to match real infrastructure, changing nothing elseLinux, macOS, Windows
terraform apply -refresh-only -
Destroy everything this configuration managesLinux, macOS, Windows
terraform destroyWarning: Deletes real infrastructure and its data. Read the plan it shows before typing yes.
-
Destroy one resourceLinux, macOS, Windows
terraform destroy -target=aws_instance.webWarning: Deletes the real resource, and anything that depends on it.
-
Destroy everything without askingLinux, macOS, Windows
terraform destroy -auto-approveWarning: Deletes real infrastructure and its data with no confirmation.
Terraform: Outputs and inspection
-
Show all outputsLinux, macOS, Windows
terraform output -
Show one output as plain text, for scriptsLinux, macOS, Windows
terraform output -raw db_endpointWarning: Prints sensitive outputs in plain text.
-
Show all outputs as JSONLinux, macOS, Windows
terraform output -jsonWarning: Prints sensitive outputs in plain text.
-
Show everything in the state in readable formLinux, macOS, Windows
terraform show -
Show the state as JSONLinux, macOS, Windows
terraform show -jsonWarning: State can hold passwords and keys in plain text, so treat this output as a secret.
-
Draw the dependency graph as an image (needs Graphviz)Linux, macOS
terraform graph | dot -Tsvg > graph.svg -
Draw the graph of a plan instead of the code (needs Graphviz)Linux, macOS, Windows
terraform graph -type=plan | dot -Tsvg > plan.svg
Terraform: State
-
List every resource in the stateLinux, macOS, Windows
terraform state list -
List the resources in one moduleLinux, macOS, Windows
terraform state list module.network -
Show everything recorded about one resourceLinux, macOS, Windows
terraform state show aws_instance.web -
Show a resource made with countLinux, macOS
terraform state show 'aws_instance.web[0]' -
Show a resource made with for_eachLinux, macOS
terraform state show 'aws_instance.web["blue"]'Windowsterraform state show 'aws_instance.web[\"blue\"]' -
Find a resource in the state by its provider ID (1.12+)Linux, macOS, Windows
terraform state list -id=i-0abc123def4567890 -
Show the identity of every resource as JSON (1.12+)Linux, macOS, Windows
terraform state identities -json -
Show the identity of one resource as JSON (1.12+)Linux, macOS, Windows
terraform state identities -json aws_instance.web -
Rename a resource in the state without rebuilding itLinux, macOS, Windows
terraform state mv aws_instance.web aws_instance.appWarning: Changes the state directly. Rename it in your code as well, or the next plan will want to destroy and recreate it.
-
Preview a state rename without changing anythingLinux, macOS, Windows
terraform state mv -dry-run aws_instance.web aws_instance.app -
Stop managing a resource without destroying itLinux, macOS, Windows
terraform state rm aws_instance.webWarning: Terraform forgets the resource, but the real thing keeps running. Remove it from your code too, or the next apply creates a second one.
-
Preview removing a resource from the stateLinux, macOS, Windows
terraform state rm -dry-run aws_instance.web -
Download the state to a file as a backupLinux, macOS, Windows
terraform state pull > backup.tfstateWarning: State can hold passwords and keys in plain text, so treat this output as a secret.
-
Upload a state file, replacing the one in the backendLinux, macOS, Windows
terraform state push backup.tfstateWarning: Replaces the state in the backend. Terraform refuses if your file is older than the state already there, unless you add -force. A wrong file here can make it lose track of everything.
-
Point the state at a provider that has movedLinux, macOS, Windows
terraform state replace-provider hashicorp/aws registry.example.com/acme/aws -
Remove a lock left behind by a crashed runLinux, macOS, Windows
terraform force-unlock 6f2c1d0e-1a2b-3c4d-5e6f-7a8b9c0d1e2fWarning: Only do this when you're sure nobody else is running Terraform. Unlocking during a real run can corrupt the state.
Terraform: Import and query
-
Bring an existing resource under Terraform's managementLinux, macOS, Windows
terraform import aws_instance.web i-0abc123def4567890 -
Write starter code for resources you're importing with import blocksLinux, macOS, Windows
terraform plan -generate-config-out=generated.tf -
Search your cloud account for resources using the list blocks in .tfquery.hcl files (1.14+, Terraform only)Linux, macOS, Windows
terraform query -
Search for resources and write import blocks and code for them (1.14+, Terraform only)Linux, macOS, Windows
terraform query -generate-config-out=generated.tf -
Get the search results as JSON (1.14+, Terraform only)Linux, macOS, Windows
terraform query -json -
Search with a variables file (1.14+, Terraform only)Linux, macOS, Windows
terraform query -var-file=prod.tfvars
Terraform: Workspaces
-
List workspacesLinux, macOS, Windows
terraform workspace list -
Show the current workspaceLinux, macOS, Windows
terraform workspace show -
Create a workspace and switch to itLinux, macOS, Windows
terraform workspace new staging -
Switch workspaceLinux, macOS, Windows
terraform workspace select staging -
Switch workspace, creating it if it doesn't existLinux, macOS, Windows
terraform workspace select -or-create staging -
Delete a workspaceLinux, macOS, Windows
terraform workspace delete stagingWarning: Deletes the workspace's state. Destroy its infrastructure first, or it's left running with nothing managing it.
-
Delete a workspace that still has resources in its stateLinux, macOS, Windows
terraform workspace delete -force stagingWarning: The resources keep running but Terraform forgets them. Destroy them first unless you mean to leave them.
Terraform: Tests
-
Run the tests in the tests folderLinux, macOS, Windows
terraform test -
Run one test fileLinux, macOS, Windows
terraform test -filter=tests/network.tftest.hcl -
Show the plan or state for each test as it runsLinux, macOS, Windows
terraform test -verbose -
Run the tests with a variables fileLinux, macOS, Windows
terraform test -var-file=prod.tfvars -
Run the tests in a different folderLinux, macOS, Windows
terraform test -test-directory=tests
Terraform: HCP Terraform
-
Log in to HCP Terraform and save a tokenLinux, macOS, Windows
terraform login -
Remove the saved tokenLinux, macOS, Windows
terraform logout -
Log in to Terraform Enterprise or another hostLinux, macOS, Windows
terraform login app.terraform.io -
Log out of another hostLinux, macOS, Windows
terraform logout app.terraform.io
Terraform: Automation and CI
-
Set up without stopping to ask questionsLinux, macOS, Windows
terraform init -input=false -
Plan in a pipeline and save the resultLinux, macOS, Windows
terraform plan -input=false -out=tfplan -
Apply the saved plan in a pipelineLinux, macOS, Windows
terraform apply -input=false tfplan -
Make the exit code say whether anything would change (0 no, 1 error, 2 yes)Linux, macOS, Windows
terraform plan -detailed-exitcode -
Tell Terraform it's running in automation, for quieter outputLinux, macOS
export TF_IN_AUTOMATION=1Windows$env:TF_IN_AUTOMATION = "1" -
Set a variable from the environmentLinux, macOS
export TF_VAR_region=eu-west-1Windows$env:TF_VAR_region = "eu-west-1" -
Add the same options to every planLinux, macOS
export TF_CLI_ARGS_plan="-parallelism=20" -
Choose the workspace from the environmentLinux, macOS
export TF_WORKSPACE=staging -
Never ask for input in this shellLinux, macOS
export TF_INPUT=0Windows$env:TF_INPUT = "0" -
Keep the .terraform working data in another folderLinux, macOS
export TF_DATA_DIR=.terraform-prod -
Share downloaded providers between projectsLinux, macOS
export TF_PLUGIN_CACHE_DIR="$HOME/.terraform.d/plugin-cache"
Terraform: Debugging
-
Turn on debug loggingLinux, macOS
export TF_LOG=DEBUGWindows$env:TF_LOG = "DEBUG" -
Turn on debug logging for one command onlyLinux, macOS
TF_LOG=DEBUG terraform plan -
Log Terraform itself without the provider noiseLinux, macOS
export TF_LOG_CORE=DEBUG -
Log only the providersLinux, macOS
export TF_LOG_PROVIDER=DEBUG -
Send the most detailed logs to a fileLinux, macOS
export TF_LOG=TRACE export TF_LOG_PATH=terraform.logWindows$env:TF_LOG = "TRACE" $env:TF_LOG_PATH = "terraform.log" -
Turn logging off againLinux, macOS
unset TF_LOG TF_LOG_PATHWindowsRemove-Item Env:TF_LOG, Env:TF_LOG_PATH
Ansible: Install and set up
-
Install Ansible with pipxLinux, macOS
pipx install --include-deps ansible -
Install Ansible with pipLinux, macOS
python3 -m pip install --user ansible -
Upgrade Ansible installed with pipxLinux, macOS
pipx upgrade --include-injected ansible -
Show the Ansible version, Python and config file in useLinux, macOS
ansible --version -
Make an ansible.cfg with every setting listed and commented outLinux, macOS
ansible-config init --disabled > ansible.cfg -
Show the settings you've changed from the defaultsLinux, macOS
ansible-config dump --only-changed -
Show the config file Ansible is readingLinux, macOS
ansible-config view -
List every setting with its environment variableLinux, macOS
ansible-config list -
List the built-in modulesLinux, macOS
ansible-doc --list ansible.builtin -
Show the docs and examples for a moduleLinux, macOS
ansible-doc ansible.builtin.copy -
Show a short task snippet for a moduleLinux, macOS
ansible-doc --snippet ansible.builtin.copy -
List the modules in a collectionLinux, macOS
ansible-doc --list community.general -
List plugins of one type, such as lookups or filtersLinux, macOS
ansible-doc --type lookup --list
Ansible: Inventory and host patterns
-
Show the inventory as JSON, with groups and variablesLinux, macOS
ansible-inventory -i inventory.ini --list -
Show the inventory as YAMLLinux, macOS
ansible-inventory -i inventory.ini --list --yaml -
Show the inventory as a tree of groupsLinux, macOS
ansible-inventory -i inventory.ini --graph -
Show a group's tree, with each host's variablesLinux, macOS
ansible-inventory -i inventory.ini --graph --vars webservers -
Show every variable for one hostLinux, macOS
ansible-inventory -i inventory.ini --host web1 -
Convert an INI inventory to YAMLLinux, macOS
ansible-inventory -i inventory.ini --list --yaml --output inventory.yml -
List the hosts a pattern matchesLinux, macOS
ansible webservers -i inventory.ini --list-hosts -
Target hosts in two groupsLinux, macOS
ansible 'webservers:dbservers' -i inventory.ini --list-hosts -
Target hosts in both groupsLinux, macOS
ansible 'webservers:&prod' -i inventory.ini --list-hosts -
Target a group but leave some hosts outLinux, macOS
ansible 'all:!dbservers' -i inventory.ini --list-hosts -
Target hosts whose names match a patternLinux, macOS
ansible 'web*' -i inventory.ini --list-hosts -
Run against hosts with no inventory file (note the trailing comma)Linux, macOS
ansible all -i web1, -m ansible.builtin.ping -
Use a folder of inventory filesLinux, macOS
ansible all -i inventory/ --list-hosts -
List the inventory plugins you have, such as aws_ec2 or proxmoxLinux, macOS
ansible-doc --type inventory --list -
Use a dynamic inventory from a cloudLinux, macOS
ansible-inventory -i aws_ec2.yml --graph
Ansible: Ad hoc commands
-
Check Ansible can reach and log in to every hostLinux, macOS
ansible all -i inventory.ini -m ansible.builtin.ping -
Run a command on a groupLinux, macOS
ansible webservers -i inventory.ini -a "uptime" -
Run a command with pipes or redirects (shell module)Linux, macOS
ansible webservers -i inventory.ini -m ansible.builtin.shell -a "ps aux | grep nginx" -
Run a command as root with sudoLinux, macOS
ansible webservers -i inventory.ini -a "whoami" --become -
Run as root and be asked for the sudo passwordLinux, macOS
ansible webservers -i inventory.ini -a "whoami" --become --ask-become-pass -
Log in as a particular userLinux, macOS
ansible webservers -i inventory.ini -m ansible.builtin.ping -u deploy -
Log in with a particular SSH keyLinux, macOS
ansible webservers -i inventory.ini -m ansible.builtin.ping --private-key ~/.ssh/id_ed25519 -
Log in with a password instead of a key (needs sshpass)Linux, macOS
ansible webservers -i inventory.ini -m ansible.builtin.ping --ask-pass -
Run on more hosts at onceLinux, macOS
ansible all -i inventory.ini -a "uptime" --forks 20 -
Show one line of output per hostLinux, macOS
ansible all -i inventory.ini -a "uptime" --one-line -
Run on just this machine, without SSHLinux, macOS
ansible localhost -m ansible.builtin.setup -a "filter=ansible_distribution*" -
Gather all facts about a hostLinux, macOS
ansible web1 -i inventory.ini -m ansible.builtin.setup -
Gather some facts with a filterLinux, macOS
ansible all -i inventory.ini -m ansible.builtin.setup -a "filter=ansible_distribution*" -
Save each host's facts to its own fileLinux, macOS
ansible all -i inventory.ini -m ansible.builtin.setup --tree facts -
Install a packageLinux, macOS
ansible webservers -i inventory.ini -m ansible.builtin.package -a "name=nginx state=present" --become -
Update every package on Debian or UbuntuLinux, macOS
ansible webservers -i inventory.ini -m ansible.builtin.apt -a "update_cache=true upgrade=dist" --becomeWarning: Upgrades every package at once. Try it on one host first, or add --check to see what would change.
-
Update every package on RHEL, Rocky or FedoraLinux, macOS
ansible webservers -i inventory.ini -m ansible.builtin.dnf -a "name=* state=latest" --becomeWarning: Upgrades every package at once. Try it on one host first.
-
Restart a serviceLinux, macOS
ansible webservers -i inventory.ini -m ansible.builtin.service -a "name=nginx state=restarted" --become -
Make sure a service is running and starts at bootLinux, macOS
ansible webservers -i inventory.ini -m ansible.builtin.service -a "name=nginx state=started enabled=true" --become -
Copy a file to hostsLinux, macOS
ansible webservers -i inventory.ini -m ansible.builtin.copy -a "src=files/motd dest=/etc/motd mode=0644" --become -
Fetch a file from hosts, into a folder per hostLinux, macOS
ansible webservers -i inventory.ini -m ansible.builtin.fetch -a "src=/var/log/syslog dest=fetched/" -
Make a folderLinux, macOS
ansible webservers -i inventory.ini -m ansible.builtin.file -a "path=/etc/motd state=directory mode=0755" --become -
Delete a file or folderLinux, macOS
ansible webservers -i inventory.ini -m ansible.builtin.file -a "path=/etc/motd state=absent" --becomeWarning: Deletes the path and everything in it on every matching host.
-
Add a userLinux, macOS
ansible webservers -i inventory.ini -m ansible.builtin.user -a "name=alice groups=sudo append=true" --become -
Add an SSH public key for a userLinux, macOS
ansible webservers -i inventory.ini -m ansible.posix.authorized_key -a "user=deploy key='$(cat ~/.ssh/id_ed25519.pub)'" --become -
Reboot hosts and wait for them to come backLinux, macOS
ansible webservers -i inventory.ini -m ansible.builtin.reboot --becomeWarning: Reboots every matching host. Add --forks 1 to do them one at a time.
-
Show disk space on every hostLinux, macOS
ansible all -i inventory.ini -a "df -h" -
Show a variable for each hostLinux, macOS
ansible all -i inventory.ini -m ansible.builtin.debug -a "var=ansible_host" -
See what an ad hoc command would change, without changing itLinux, macOS
ansible webservers -i inventory.ini -m ansible.builtin.package -a "name=nginx state=present" --become --check --diff
Ansible: Running playbooks
-
Run a playbookLinux, macOS
ansible-playbook -i inventory.ini site.yml -
Check a playbook's syntaxLinux, macOS
ansible-playbook -i inventory.ini site.yml --syntax-check -
Do a dry run that shows what would changeLinux, macOS
ansible-playbook -i inventory.ini site.yml --check --diff -
Show the changes in files as it runsLinux, macOS
ansible-playbook -i inventory.ini site.yml --diff -
Run on some hosts onlyLinux, macOS
ansible-playbook -i inventory.ini site.yml --limit web1 -
Run on a list of hosts from a fileLinux, macOS
ansible-playbook -i inventory.ini site.yml --limit @hosts.txt -
Rerun only the hosts that failed last timeLinux, macOS
ansible-playbook -i inventory.ini site.yml --limit @site.retry -
Run only tasks with a tagLinux, macOS
ansible-playbook -i inventory.ini site.yml --tags nginx -
Run everything except tasks with a tagLinux, macOS
ansible-playbook -i inventory.ini site.yml --skip-tags nginx -
List the tasks a playbook would runLinux, macOS
ansible-playbook -i inventory.ini site.yml --list-tasks -
List the tags in a playbookLinux, macOS
ansible-playbook -i inventory.ini site.yml --list-tags -
List the hosts a playbook would run onLinux, macOS
ansible-playbook -i inventory.ini site.yml --list-hosts -
Start part-way through, at a named taskLinux, macOS
ansible-playbook -i inventory.ini site.yml --start-at-task "Install nginx" -
Step through a playbook, confirming each taskLinux, macOS
ansible-playbook -i inventory.ini site.yml --step -
Set a variable from the command lineLinux, macOS
ansible-playbook -i inventory.ini site.yml --extra-vars "app_version=1.4.2" -
Load variables from a fileLinux, macOS
ansible-playbook -i inventory.ini site.yml --extra-vars @vars/prod.yml -
Set variables as JSONLinux, macOS
ansible-playbook -i inventory.ini site.yml --extra-vars '{"app_version": "1.4.2", "debug": false}' -
Run a playbook as root, asking for the sudo passwordLinux, macOS
ansible-playbook -i inventory.ini site.yml --become --ask-become-pass -
Run on at most 5 hosts at a timeLinux, macOS
ansible-playbook -i inventory.ini site.yml --forks 5 -
Run handlers even if a task failsLinux, macOS
ansible-playbook -i inventory.ini site.yml --force-handlers -
Clear cached facts before runningLinux, macOS
ansible-playbook -i inventory.ini site.yml --flush-cache -
Show more output, up to -vvvv for SSH detailLinux, macOS
ansible-playbook -i inventory.ini site.yml -vvv -
Show how long each task takesLinux, macOS
ANSIBLE_CALLBACKS_ENABLED=ansible.posix.profile_tasks ansible-playbook -i inventory.ini site.yml -
Show task results as readable YAMLLinux, macOS
ANSIBLE_CALLBACK_RESULT_FORMAT=yaml ansible-playbook -i inventory.ini site.yml -
Run several playbooks in orderLinux, macOS
ansible-playbook -i inventory.ini site.yml deploy.yml
Ansible: Vault and secrets
-
Make a new encrypted fileLinux, macOS
ansible-vault create group_vars/all/vault.yml -
Edit an encrypted fileLinux, macOS
ansible-vault edit group_vars/all/vault.yml -
Show an encrypted file's contentsLinux, macOS
ansible-vault view group_vars/all/vault.ymlWarning: Prints the secrets in plain text.
-
Encrypt an existing fileLinux, macOS
ansible-vault encrypt group_vars/all/vault.yml -
Decrypt a file back to plain textLinux, macOS
ansible-vault decrypt group_vars/all/vault.ymlWarning: Leaves the secrets in plain text on disk. Use view or edit instead if you only need to read or change them.
-
Change a vault file's passwordLinux, macOS
ansible-vault rekey group_vars/all/vault.yml -
Encrypt one value to paste into a variables fileLinux, macOS
ansible-vault encrypt_string --stdin-name app_version -
Run a playbook and be asked for the vault passwordLinux, macOS
ansible-playbook -i inventory.ini site.yml --ask-vault-pass -
Run a playbook with the vault password in a fileLinux, macOS
ansible-playbook -i inventory.ini site.yml --vault-password-file ~/.vault_passWarning: Keep the password file out of Git, and readable only by you (chmod 600).
-
Use a vault password file for every command in this terminalLinux, macOS
export ANSIBLE_VAULT_PASSWORD_FILE=~/.vault_pass -
Encrypt a file with a labelled vault ID, such as one per environmentLinux, macOS
ansible-vault encrypt --vault-id prod@prompt group_vars/all/vault.yml -
Run with more than one vault IDLinux, macOS
ansible-playbook -i inventory.ini site.yml --vault-id dev@prompt --vault-id prod@~/.vault_pass
Ansible: Collections and roles (Galaxy)
-
Install a collectionLinux, macOS
ansible-galaxy collection install community.general -
Install a collection at a versionLinux, macOS
ansible-galaxy collection install community.general:==10.0.0 -
Upgrade a collection to the newest versionLinux, macOS
ansible-galaxy collection install community.general --upgrade -
Install the collections and roles in a requirements fileLinux, macOS
ansible-galaxy install -r requirements.yml -
Install collections into the project folderLinux, macOS
ansible-galaxy collection install -r requirements.yml -p ./collections -
List installed collections and their versionsLinux, macOS
ansible-galaxy collection list -
Show where one collection is installedLinux, macOS
ansible-galaxy collection list community.general -
Check installed collections haven't been changedLinux, macOS
ansible-galaxy collection verify community.general -
Make a new role with the standard foldersLinux, macOS
ansible-galaxy role init webserver -
Make a new collection with the standard foldersLinux, macOS
ansible-galaxy collection init gerard.homelab -
Install a role from GalaxyLinux, macOS
ansible-galaxy role install geerlingguy.docker -
List installed rolesLinux, macOS
ansible-galaxy role list -
Remove a roleLinux, macOS
ansible-galaxy role remove geerlingguy.docker -
Build a collection into a tarball to shareLinux, macOS
ansible-galaxy collection build
Ansible: Linting and testing
-
Lint a projectLinux, macOS
ansible-lint -
Lint one playbookLinux, macOS
ansible-lint site.yml -
Fix the lint problems it can fix by itselfLinux, macOS
ansible-lint --fixWarning: Rewrites your YAML files. Commit first so you can see and undo the changes.
-
Lint against a stricter profileLinux, macOS
ansible-lint --profile production -
List the rules ansible-lint checksLinux, macOS
ansible-lint --list-rules -
Check YAML formattingLinux, macOS
yamllint . -
Make a Molecule test scenario in a role or collectionLinux, macOS
molecule init scenario default -
Run the full Molecule test: create, converge, verify, destroyLinux, macOS
molecule test -
Apply the role to the test instance and keep it runningLinux, macOS
molecule converge -
Run the role again to check nothing changes the second timeLinux, macOS
molecule idempotence -
Open a shell on the test instanceLinux, macOS
molecule login -
Delete the test instanceLinux, macOS
molecule destroy
Ansible: Windows hosts
-
Check Ansible can reach Windows hostsLinux, macOS
ansible windows -i inventory.ini -m ansible.windows.win_ping -
Run a PowerShell command on Windows hostsLinux, macOS
ansible windows -i inventory.ini -m ansible.windows.win_powershell -a "script='Get-Service | Where-Object Status -eq Running'" -
Restart a Windows serviceLinux, macOS
ansible windows -i inventory.ini -m ansible.windows.win_service -a "name=Spooler state=restarted" -
Install Windows updatesLinux, macOS
ansible windows -i inventory.ini -m ansible.windows.win_updates -a "category_names=SecurityUpdates reboot=true"Warning: Reboots the hosts if an update needs it.
-
Copy a file to Windows hostsLinux, macOS
ansible windows -i inventory.ini -m ansible.windows.win_copy -a "src=files/motd dest=C:\\Temp\\motd"
Ansible: Network devices
-
Run show commands on Cisco IOS devicesLinux, macOS
ansible switches -i inventory.ini -m cisco.ios.ios_command -a "commands='show version'" -
Gather facts from Cisco IOS devicesLinux, macOS
ansible switches -i inventory.ini -m cisco.ios.ios_facts -
Back up Cisco IOS running configsLinux, macOS
ansible switches -i inventory.ini -m cisco.ios.ios_config -a "backup=true" -
Run show commands on Cisco NX-OS devicesLinux, macOS
ansible switches -i inventory.ini -m cisco.nxos.nxos_command -a "commands='show version'" -
Run a command on any supported network OSLinux, macOS
ansible switches -i inventory.ini -m ansible.netcommon.cli_command -a "command='show version'" -
Connect to devices without setting the connection in the inventoryLinux, macOS
ansible switches -i inventory.ini -c ansible.netcommon.network_cli -e ansible_network_os=cisco.ios.ios -m cisco.ios.ios_command -a "commands='show clock'" -u deploy --ask-pass -
Install the Cisco and network collectionsLinux, macOS
ansible-galaxy collection install cisco.ios cisco.nxos ansible.netcommon
Ansible: Other tools
-
Pull a playbook from Git and run it on this machineLinux, macOS
ansible-pull -U https://github.com/example/ansible-config.git site.yml -
Open an interactive console for running tasks on hostsLinux, macOS
ansible-console -i inventory.ini webservers -
Run a playbook in an execution environment with ansible-navigatorLinux, macOS
ansible-navigator run site.yml -i inventory.ini --mode stdout -
Browse a playbook run's results with ansible-navigatorLinux, macOS
ansible-navigator replay site-artifact.json -
Build an execution environment image with ansible-builderLinux, macOS
ansible-builder build --tag my-ee:1.0
Ansible: Troubleshooting
-
Show every SSH connection detailLinux, macOS
ansible web1 -i inventory.ini -m ansible.builtin.ping -vvvv -
Print a variable's value for each hostLinux, macOS
ansible all -i inventory.ini -m ansible.builtin.debug -a "msg={{ ansible_host }}" -
Test a Jinja expression against a hostLinux, macOS
ansible web1 -i inventory.ini -m ansible.builtin.debug -a "msg={{ inventory_hostname | upper }}" -
Show which hosts are in a group, from inside AnsibleLinux, macOS
ansible localhost -i inventory.ini -m ansible.builtin.debug -a "msg={{ groups['webservers'] }}" -
Skip SSH host key checks, for brand-new lab machinesLinux, macOS
ANSIBLE_HOST_KEY_CHECKING=False ansible all -i inventory.ini -m ansible.builtin.pingWarning: Accepts any host key, so you can't tell if you're talking to the wrong machine. Use it only on a lab or test network.
-
Keep the files Ansible copies to hosts, to debug a moduleLinux, macOS
ANSIBLE_KEEP_REMOTE_FILES=1 ansible web1 -i inventory.ini -m ansible.builtin.ping -vvv -
Show the Python interpreter Ansible found on a hostLinux, macOS
ansible web1 -i inventory.ini -m ansible.builtin.setup -a "filter=ansible_python*" -
Use a particular Python on a hostLinux, macOS
ansible web1 -i inventory.ini -m ansible.builtin.ping -e ansible_python_interpreter=/usr/bin/python3 -
Use an ansible.cfg from another folderLinux, macOS
ANSIBLE_CONFIG=~/lab/ansible.cfg ansible-playbook -i inventory.ini site.yml -
Clear the fact cacheLinux, macOS
rm -rf ~/.ansible/fact_cache
kubectl: Setup and help
-
Show the kubectl versionLinux, macOS, Windows
kubectl version --client -
Show the kubectl and cluster versionsLinux, macOS, Windows
kubectl version -
Show the cluster's API addressLinux, macOS, Windows
kubectl cluster-info -
List every resource type, with short namesLinux, macOS, Windows
kubectl api-resources -
List the API versions the cluster supportsLinux, macOS, Windows
kubectl api-versions -
Explain a resource's fieldsLinux, macOS, Windows
kubectl explain pod.spec.containers -
Show every field of a resource as a treeLinux, macOS, Windows
kubectl explain deployment --recursive -
Turn on tab completionLinux, macOS
source <(kubectl completion bash)Windowskubectl completion powershell | Out-String | Invoke-Expression -
Turn on tab completion in zshLinux, macOS
source <(kubectl completion zsh) -
Use k as a short name for kubectlLinux, macOS
alias k=kubectlWindowsSet-Alias -Name k -Value kubectl -
List the kubectl plugins you haveLinux, macOS, Windows
kubectl plugin list -
List the flags every command takesLinux, macOS, Windows
kubectl options
kubectl: Contexts and kubeconfig
-
List contexts (clusters you can talk to)Linux, macOS, Windows
kubectl config get-contexts -
Show the current contextLinux, macOS, Windows
kubectl config current-context -
Switch to another contextLinux, macOS, Windows
kubectl config use-context prod-cluster -
Set the default namespace for the current contextLinux, macOS, Windows
kubectl config set-context --current --namespace=my-app -
Run one command against another contextLinux, macOS, Windows
kubectl get pods --context prod-cluster -
Show the current context's settingsLinux, macOS, Windows
kubectl config view --minify -
Show the kubeconfig with keys and tokensLinux, macOS, Windows
kubectl config view --minify --rawWarning: Prints a secret in plain text. Don't paste the output anywhere it could be saved or shared.
-
Rename a contextLinux, macOS, Windows
kubectl config rename-context prod-cluster prod -
Delete a contextLinux, macOS, Windows
kubectl config delete-context prod-cluster -
Use another kubeconfig file for one commandLinux, macOS, Windows
kubectl get nodes --kubeconfig ~/.kube/lab.yaml -
Use another kubeconfig file in this terminalLinux, macOS
export KUBECONFIG=~/.kube/lab.yamlWindows$env:KUBECONFIG = "~/.kube/lab.yaml" -
Merge a new kubeconfig into your main oneLinux, macOS
KUBECONFIG=~/.kube/config:~/.kube/lab.yaml kubectl config view --flatten > ~/.kube/config.new && mv ~/.kube/config.new ~/.kube/configWarning: Back up ~/.kube/config first.
-
Show who the cluster thinks you areLinux, macOS, Windows
kubectl auth whoami
kubectl: Viewing resources
-
List pods in the current namespaceLinux, macOS, Windows
kubectl get pods -
List pods in a namespaceLinux, macOS, Windows
kubectl get pods -n my-app -
List pods in every namespaceLinux, macOS, Windows
kubectl get pods --all-namespaces -
List pods with their node and IP addressLinux, macOS, Windows
kubectl get pods -o wide -
Watch pods change liveLinux, macOS, Windows
kubectl get pods --watch -
List pods with their labelsLinux, macOS, Windows
kubectl get pods --show-labels -
List pods with a labelLinux, macOS, Windows
kubectl get pods -l app=web -
List pods that are pendingLinux, macOS, Windows
kubectl get pods --field-selector=status.phase=Pending -
List pods on one nodeLinux, macOS, Windows
kubectl get pods --all-namespaces --field-selector=spec.nodeName=worker-1 -
List pods, newest lastLinux, macOS, Windows
kubectl get pods --sort-by=.metadata.creationTimestamp -
List pods by restart countLinux, macOS, Windows
kubectl get pods --sort-by=.status.containerStatuses[0].restartCount -
List the common resources in a namespaceLinux, macOS, Windows
kubectl get all -n my-app -
List several kinds of resource at onceLinux, macOS, Windows
kubectl get deployments,services,ingresses -n my-app -
Show a resource's details and recent eventsLinux, macOS, Windows
kubectl describe pod web-7d4b9c6f5-x2k8p -
Show a resource as YAMLLinux, macOS, Windows
kubectl get deployment web -o yaml -
Print just the namesLinux, macOS, Windows
kubectl get pods -o name -
Show your own columnsLinux, macOS, Windows
kubectl get pods -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,NODE:.spec.nodeName -
Print one field with JSONPathLinux, macOS, Windows
kubectl get pod web-7d4b9c6f5-x2k8p -o jsonpath="{.status.podIP}" -
List every container image in useLinux, macOS, Windows
kubectl get pods --all-namespaces -o jsonpath="{.items[*].spec.containers[*].image}" -
List the names of running pods with JSONPathLinux, macOS, Windows
kubectl get pods -o jsonpath="{.items[?(@.status.phase=='Running')].metadata.name}" -
List recent events, newest lastLinux, macOS, Windows
kubectl get events --sort-by=.lastTimestamp -
List warning events onlyLinux, macOS, Windows
kubectl events --types=Warning -
List the events for one resourceLinux, macOS, Windows
kubectl events --for pod/web-7d4b9c6f5-x2k8p -
Show CPU and memory for pods (needs metrics-server)Linux, macOS, Windows
kubectl top pods -
Show CPU and memory for nodes (needs metrics-server)Linux, macOS, Windows
kubectl top nodes
kubectl: Creating and applying
-
Create or update resources from a fileLinux, macOS, Windows
kubectl apply -f app.yaml -
Apply every file in a folderLinux, macOS, Windows
kubectl apply -f k8s/ -
Apply a Kustomize folderLinux, macOS, Windows
kubectl apply -k overlays/prod -
Show what kustomize would buildLinux, macOS, Windows
kubectl kustomize overlays/prod -
See what applying a file would changeLinux, macOS, Windows
kubectl diff -f app.yaml -
Check a file with the cluster without changing anythingLinux, macOS, Windows
kubectl apply -f app.yaml --dry-run=server -
Delete the resources in a fileLinux, macOS, Windows
kubectl delete -f app.yamlWarning: Deletes everything the file defines.
-
Make a deploymentLinux, macOS, Windows
kubectl create deployment web --image=nginx:1.29 --replicas=3 -
Write a deployment's YAML to a file, without creating itLinux, macOS, Windows
kubectl create deployment web --image=nginx:1.29 --dry-run=client -o yaml > app.yaml -
Run a single podLinux, macOS, Windows
kubectl run nginx --image=nginx:1.29 -
Expose a deployment as a serviceLinux, macOS, Windows
kubectl expose deployment web --port=443 --target-port=8080 -
Expose a deployment outside the cluster on a node portLinux, macOS, Windows
kubectl expose deployment web --type=NodePort --port=443 --target-port=8080 -
Make a namespaceLinux, macOS, Windows
kubectl create namespace my-app -
Run a one-off jobLinux, macOS, Windows
kubectl create job db-backup --image=nginx:1.29 -- date -
Make a cron job that runs every night at 2amLinux, macOS, Windows
kubectl create cronjob nightly-backup --image=nginx:1.29 --schedule="0 2 * * *" -- date -
Run a cron job nowLinux, macOS, Windows
kubectl create job db-backup --from=cronjob/nightly-backup -
Add or change a labelLinux, macOS, Windows
kubectl label pod web-7d4b9c6f5-x2k8p env=prod --overwrite -
Remove a labelLinux, macOS, Windows
kubectl label pod web-7d4b9c6f5-x2k8p env- -
Add a note (annotation)Linux, macOS, Windows
kubectl annotate deployment web owner=platform-team -
Edit a resource in your editorLinux, macOS, Windows
kubectl edit deployment web -
Change part of a resource from a patch fileLinux, macOS, Windows
kubectl patch deployment web --type=merge --patch-file=patch.yaml -
Delete a resourceLinux, macOS, Windows
kubectl delete deployment web -
Delete every resource with a labelLinux, macOS, Windows
kubectl delete deployment,service -l app=webWarning: Deletes every matching resource in the namespace.
-
Delete a namespace and everything in itLinux, macOS, Windows
kubectl delete namespace my-appWarning: Deletes every resource in the namespace, with no undo.
kubectl: Deployments and rollouts
-
Scale a deploymentLinux, macOS, Windows
kubectl scale deployment web --replicas=3 -
Change a deployment's imageLinux, macOS, Windows
kubectl set image deployment/web web=nginx:1.29.3 -
Watch a rollout until it finishesLinux, macOS, Windows
kubectl rollout status deployment/web -
Show a deployment's rollout historyLinux, macOS, Windows
kubectl rollout history deployment/web -
Show what changed in one revisionLinux, macOS, Windows
kubectl rollout history deployment/web --revision=2 -
Roll back to the previous versionLinux, macOS, Windows
kubectl rollout undo deployment/web -
Roll back to a particular revisionLinux, macOS, Windows
kubectl rollout undo deployment/web --to-revision=2 -
Restart every pod in a deployment, one at a timeLinux, macOS, Windows
kubectl rollout restart deployment/web -
Pause a rollout to make several changesLinux, macOS, Windows
kubectl rollout pause deployment/web -
Resume a paused rolloutLinux, macOS, Windows
kubectl rollout resume deployment/web -
Set an environment variable on a deploymentLinux, macOS, Windows
kubectl set env deployment/web LOG_LEVEL=debug -
List a deployment's environment variablesLinux, macOS, Windows
kubectl set env deployment/web --list -
Set CPU and memory requests and limitsLinux, macOS, Windows
kubectl set resources deployment web --requests=cpu=100m,memory=128Mi --limits=cpu=500m,memory=512Mi -
Scale a deployment on CPU useLinux, macOS, Windows
kubectl autoscale deployment web --min=2 --max=10 --cpu-percent=70 -
List autoscalersLinux, macOS, Windows
kubectl get hpa -
Wait until a deployment is availableLinux, macOS, Windows
kubectl wait --for=condition=Available deployment/web --timeout=120s -
Restart a stateful set or daemon setLinux, macOS, Windows
kubectl rollout restart statefulset/postgres
kubectl: Pods: logs, shells and files
-
Show a pod's logsLinux, macOS, Windows
kubectl logs web-7d4b9c6f5-x2k8p -
Follow a pod's logs liveLinux, macOS, Windows
kubectl logs -f web-7d4b9c6f5-x2k8p -
Show the logs from before a container crashed and restartedLinux, macOS, Windows
kubectl logs web-7d4b9c6f5-x2k8p --previous -
Show one container's logs in a pod with severalLinux, macOS, Windows
kubectl logs web-7d4b9c6f5-x2k8p -c web -
Show the last hour of logsLinux, macOS, Windows
kubectl logs web-7d4b9c6f5-x2k8p --since=1h -
Show the last 100 linesLinux, macOS, Windows
kubectl logs web-7d4b9c6f5-x2k8p --tail=100 -
Show logs from every pod with a labelLinux, macOS, Windows
kubectl logs -l app=web --all-containers --prefix -
Show logs from a deployment, without finding a pod nameLinux, macOS, Windows
kubectl logs deployment/web -
Open a shell in a podLinux, macOS, Windows
kubectl exec -it web-7d4b9c6f5-x2k8p -- sh -
Open a shell in one container of a podLinux, macOS, Windows
kubectl exec -it web-7d4b9c6f5-x2k8p -c web -- sh -
Run one command in a podLinux, macOS, Windows
kubectl exec web-7d4b9c6f5-x2k8p -- env -
Copy a file from a podLinux, macOS, Windows
kubectl cp web-7d4b9c6f5-x2k8p:/var/log/app.log app.log -
Copy a file into a podLinux, macOS, Windows
kubectl cp app.log web-7d4b9c6f5-x2k8p:/var/log/app.log -
Forward a local port to a podLinux, macOS, Windows
kubectl port-forward pod/web-7d4b9c6f5-x2k8p 8080:8080 -
Forward a local port to a serviceLinux, macOS, Windows
kubectl port-forward service/web 8080:443 -
Start a throwaway pod with a shell, deleted when you exitLinux, macOS, Windows
kubectl run tmp-shell --rm -it --image=busybox:1.37 --restart=Never -- sh -
Add a debug container to a running podLinux, macOS, Windows
kubectl debug -it web-7d4b9c6f5-x2k8p --image=busybox:1.37 --target=web -
Debug a pod with a copy you can changeLinux, macOS, Windows
kubectl debug web-7d4b9c6f5-x2k8p -it --copy-to=web-7d4b9c6f5-x2k8p-debug --container=web -- sh -
Open a shell on a nodeLinux, macOS, Windows
kubectl debug node/worker-1 -it --image=busybox:1.37Warning: The node's file system is mounted at /host, with full access.
-
Delete a pod (its deployment makes a new one)Linux, macOS, Windows
kubectl delete pod web-7d4b9c6f5-x2k8p -
Force delete a pod stuck in TerminatingLinux, macOS, Windows
kubectl delete pod web-7d4b9c6f5-x2k8p --grace-period=0 --forceWarning: The container may still be running on the node. Use it only when the node is gone or broken.
-
Show why a pod's containers restartedLinux, macOS, Windows
kubectl get pod web-7d4b9c6f5-x2k8p -o jsonpath="{.status.containerStatuses[*].lastState}"
kubectl: ConfigMaps and Secrets
-
Make a ConfigMap from valuesLinux, macOS, Windows
kubectl create configmap web-config --from-literal=LOG_LEVEL=info -
Make a ConfigMap from a fileLinux, macOS, Windows
kubectl create configmap web-config --from-file=nginx.conf -
Make a ConfigMap from a .env fileLinux, macOS, Windows
kubectl create configmap web-config --from-env-file=.env -
Show a ConfigMapLinux, macOS, Windows
kubectl describe configmap web-config -
Make a Secret from a fileLinux, macOS, Windows
kubectl create secret generic db-credentials --from-file=password.txt -
Make a Secret from a valueLinux, macOS, Windows
kubectl create secret generic db-credentials --from-literal=password=MyPasswordWarning: The value ends up in your shell history. Use --from-file to avoid that.
-
Make a Secret for pulling from a private registryLinux, macOS, Windows
kubectl create secret docker-registry db-credentials --docker-server=registry.example.com --docker-username=deploy --docker-password=MyRegistryTokenWarning: The password ends up in your shell history.
-
Make a TLS Secret from a certificate and keyLinux, macOS, Windows
kubectl create secret tls db-credentials --cert=tls.crt --key=tls.key -
List the keys in a Secret, without the valuesLinux, macOS, Windows
kubectl describe secret db-credentials -
Read one value from a SecretLinux, macOS
kubectl get secret db-credentials -o jsonpath="{.data['password']}" | base64 --decodeWindows[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String((kubectl get secret db-credentials -o jsonpath="{.data['password']}")))Warning: Prints a secret in plain text. Don't paste the output anywhere it could be saved or shared.
-
Write a Secret's YAML without creating it, for GitOps toolsLinux, macOS, Windows
kubectl create secret generic db-credentials --from-file=password.txt --dry-run=client -o yaml > app.yamlWarning: The YAML holds the secret, only base64-encoded. Encrypt it (for example with Sealed Secrets or SOPS) before committing it.
-
Load every key in a ConfigMap as environment variablesLinux, macOS, Windows
kubectl set env deployment/web --from=configmap/web-config -
Load every key in a Secret as environment variablesLinux, macOS, Windows
kubectl set env deployment/web --from=secret/db-credentials
kubectl: Services and networking
-
List servicesLinux, macOS, Windows
kubectl get services -
Show the pods behind a serviceLinux, macOS, Windows
kubectl get endpointslices -l kubernetes.io/service-name=web -
List ingressesLinux, macOS, Windows
kubectl get ingress --all-namespaces -
Show an ingress's rules and backendsLinux, macOS, Windows
kubectl describe ingress web -
Make an ingress for a hostLinux, macOS, Windows
kubectl create ingress web --class=nginx --rule="app.example.com/*=web:443" -
List network policiesLinux, macOS, Windows
kubectl get networkpolicies --all-namespaces -
Test a service from inside the clusterLinux, macOS, Windows
kubectl run tmp-curl --rm -it --image=curlimages/curl --restart=Never -- curl -s http://web.my-app.svc.cluster.local -
Test DNS from inside the clusterLinux, macOS, Windows
kubectl run tmp-dns --rm -it --image=busybox:1.37 --restart=Never -- nslookup kubernetes.default -
List Gateway API gateways and routes (needs the Gateway API CRDs)Linux, macOS, Windows
kubectl get gateways,httproutes --all-namespaces
kubectl: Nodes and cluster
-
List nodesLinux, macOS, Windows
kubectl get nodes -
List nodes with their IPs, OS and runtimeLinux, macOS, Windows
kubectl get nodes -o wide -
Show a node's capacity, conditions and podsLinux, macOS, Windows
kubectl describe node worker-1 -
Stop new pods being scheduled on a nodeLinux, macOS, Windows
kubectl cordon worker-1 -
Move every pod off a node, for maintenanceLinux, macOS, Windows
kubectl drain worker-1 --ignore-daemonsets --delete-emptydir-dataWarning: Evicts every pod on the node, and data in emptyDir volumes is lost.
-
Let pods be scheduled on a node againLinux, macOS, Windows
kubectl uncordon worker-1 -
Taint a node so only some pods run thereLinux, macOS, Windows
kubectl taint nodes worker-1 dedicated=gpu:NoSchedule -
Remove a taintLinux, macOS, Windows
kubectl taint nodes worker-1 dedicated=gpu:NoSchedule- -
Label a nodeLinux, macOS, Windows
kubectl label nodes worker-1 env=prod -
Check the API server is healthyLinux, macOS, Windows
kubectl get --raw=/readyz?verbose -
List certificate signing requestsLinux, macOS, Windows
kubectl get csr -
Approve a certificate signing requestLinux, macOS, Windows
kubectl certificate approve csr-8x2kq -
List custom resource types (CRDs)Linux, macOS, Windows
kubectl get crds
kubectl: Access control (RBAC)
-
Check whether you can do somethingLinux, macOS, Windows
kubectl auth can-i create deployments -n my-app -
List everything you can do in a namespaceLinux, macOS, Windows
kubectl auth can-i --list -n my-app -
Check what another user or service account can doLinux, macOS, Windows
kubectl auth can-i get secrets -n my-app --as=system:serviceaccount:my-app:deployer -
Make a service accountLinux, macOS, Windows
kubectl create serviceaccount deployer -n my-app -
Get a short-lived token for a service accountLinux, macOS, Windows
kubectl create token deployer -n my-app --duration=1hWarning: Prints a secret in plain text. Don't paste the output anywhere it could be saved or shared.
-
Make a role that can read podsLinux, macOS, Windows
kubectl create role pod-reader --verb=get,list,watch --resource=pods -n my-app -
Give a service account a roleLinux, macOS, Windows
kubectl create rolebinding deployer-pod-reader --role=pod-reader --serviceaccount=my-app:deployer -n my-app -
Give a user read-only access to a namespaceLinux, macOS, Windows
kubectl create rolebinding deployer-pod-reader --clusterrole=view [email protected] -n my-app -
Give a user admin over the whole clusterLinux, macOS, Windows
kubectl create clusterrolebinding deployer-pod-reader --clusterrole=cluster-admin [email protected]Warning: cluster-admin can do anything in every namespace.
-
List role bindings in every namespaceLinux, macOS, Windows
kubectl get rolebindings,clusterrolebindings --all-namespaces
kubectl: Storage
-
List persistent volume claimsLinux, macOS, Windows
kubectl get pvc -
List persistent volumesLinux, macOS, Windows
kubectl get pv -
List storage classesLinux, macOS, Windows
kubectl get storageclass -
Show why a volume claim is pendingLinux, macOS, Windows
kubectl describe pvc data-postgres-0 -
Delete a volume claimLinux, macOS, Windows
kubectl delete pvc data-postgres-0Warning: With the usual Delete reclaim policy, the volume and its data are deleted too.
kubectl: Troubleshooting
-
Find pods that aren't runningWindows
kubectl get pods --all-namespaces --field-selector=status.phase!=Running,status.phase!=SucceededLinux, macOSkubectl get pods --all-namespaces --field-selector='status.phase!=Running,status.phase!=Succeeded' -
Find pods in CrashLoopBackOffLinux, macOS
kubectl get pods --all-namespaces | grep CrashLoopBackOff -
Show the API calls kubectl makesLinux, macOS, Windows
kubectl get pods -v=6 -
Show the full API requests and responsesLinux, macOS, Windows
kubectl get pods -v=9Warning: The output can include your token. Check it before you share it.
-
Remove a stuck finalizer so a resource can deleteLinux, macOS, Windows
kubectl patch namespace/my-app --type=merge --patch-file=patch.yamlWarning: Skips the clean-up the finalizer was waiting for, which can leave things behind outside the cluster.
-
List the resources left in a namespace that won't deleteLinux, macOS
kubectl api-resources --verbs=list --namespaced -o name | xargs -n 1 kubectl get --show-kind --ignore-not-found -n my-app -
Check a manifest's fields against the clusterLinux, macOS, Windows
kubectl apply -f app.yaml --dry-run=server --validate=strict -
Convert a manifest to a newer API version (kubectl-convert plugin)Linux, macOS, Windows
kubectl convert -f app.yaml --output-version apps/v1
AWS CLI: Setup and help
-
Show the AWS CLI versionLinux, macOS, Windows
aws --version -
Get help for a serviceLinux, macOS, Windows
aws ec2 help -
Get help for one commandLinux, macOS, Windows
aws ec2 describe-instances help -
Get help on a topic, such as filters or quotingLinux, macOS, Windows
aws help topics -
Build a command step by step, with suggestions as you typeLinux, macOS, Windows
aws ec2 describe-instances --cli-auto-prompt -
Turn on tab completion in bashLinux, macOS
complete -C aws_completer aws -
Turn on tab completion in zshLinux, macOS
autoload bashcompinit && bashcompinit && complete -C aws_completer aws -
Show an example of every option a command takes, as JSONLinux, macOS, Windows
aws ec2 run-instances --generate-cli-skeleton -
Run a command with its options read from a JSON fileLinux, macOS, Windows
aws ec2 run-instances --cli-input-json file://input.json
AWS CLI: Sign in and profiles
-
Sign in with your AWS console username and password, in the browserLinux, macOS, Windows
aws login -
Sign in on a remote machine over SSH, by pasting a codeLinux, macOS, Windows
aws login --remote -
Sign in to a named profileLinux, macOS, Windows
aws login --profile dev -
Sign out and delete the saved sign-inLinux, macOS, Windows
aws logout -
Set up a profile for IAM Identity Center (SSO)Linux, macOS, Windows
aws configure sso -
Sign in with IAM Identity Center (SSO)Linux, macOS, Windows
aws sso login --profile dev -
Sign in with SSO on a machine with no browserLinux, macOS, Windows
aws sso login --profile dev --use-device-code -
Sign out of IAM Identity Center (SSO)Linux, macOS, Windows
aws sso logout -
Set up the default profile with an access keyLinux, macOS, Windows
aws configureWarning: This saves a long-term access key in plain text in ~/.aws/credentials. Prefer aws login or aws configure sso where you can.
-
Set up a named profile with an access keyLinux, macOS, Windows
aws configure --profile devWarning: This saves a long-term access key in plain text in ~/.aws/credentials. Prefer aws login or aws configure sso where you can.
-
List your profilesLinux, macOS, Windows
aws configure list-profiles -
Show where each setting comes from: profile, file or environmentLinux, macOS, Windows
aws configure list -
Show one setting from a profileLinux, macOS, Windows
aws configure get region --profile dev -
Change one setting in a profileLinux, macOS, Windows
aws configure set region eu-west-1 --profile dev -
Set a profile's default output formatLinux, macOS, Windows
aws configure set output table --profile dev -
Add a profile that assumes a role using another profileLinux, macOS, Windows
aws configure set role_arn arn:aws:iam::123456789012:role/Admin --profile admin aws configure set source_profile dev --profile admin -
Run one command as a profileLinux, macOS, Windows
aws s3 ls --profile dev -
Run one command in another regionLinux, macOS, Windows
aws ec2 describe-instances --region eu-west-1 -
Use a profile for every command in this terminalLinux, macOS
export AWS_PROFILE=devWindows$env:AWS_PROFILE = "dev" -
Use a region for every command in this terminalLinux, macOS
export AWS_REGION=eu-west-1Windows$env:AWS_REGION = "eu-west-1" -
Go back to the default profile in this terminalLinux, macOS
unset AWS_PROFILEWindowsRemove-Item Env:AWS_PROFILE -
Print your current sign-in as environment variables, for another toolLinux, macOS, Windows
aws configure export-credentials --profile dev --format envWarning: This prints secret keys to the screen. Don't paste the output anywhere it could be saved or shared.
-
Load your current sign-in into this terminal's environmentLinux, macOS
eval "$(aws configure export-credentials --profile dev --format env)"
AWS CLI: Identity and accounts
-
Show which account and user or role you're signed in asLinux, macOS, Windows
aws sts get-caller-identity -
Show just the account numberLinux, macOS, Windows
aws sts get-caller-identity --query Account --output text -
Get temporary keys for a roleLinux, macOS, Windows
aws sts assume-role --role-arn arn:aws:iam::123456789012:role/Admin --role-session-name my-sessionWarning: The output includes a secret key and session token in plain text.
-
Get temporary keys with an MFA codeLinux, macOS, Windows
aws sts get-session-token --serial-number arn:aws:iam::123456789012:mfa/my-phone --token-code 123456Warning: The output includes a secret key and session token in plain text.
-
Decode an "encoded authorization failure message"Linux, macOS, Windows
aws sts decode-authorization-message --encoded-message AbCdEf123... --query DecodedMessage --output text -
Show the account's aliasLinux, macOS, Windows
aws iam list-account-aliases -
List the accounts in your organizationLinux, macOS, Windows
aws organizations list-accounts --query "Accounts[].[Id,Name,Status]" --output table -
List the regions turned on for your accountLinux, macOS, Windows
aws ec2 describe-regions --query "Regions[].RegionName" --output text -
List the Availability Zones in a regionLinux, macOS, Windows
aws ec2 describe-availability-zones --region eu-west-1 --query "AvailabilityZones[].ZoneName" --output text
AWS CLI: Output, filtering and paging
-
Show output as a tableLinux, macOS, Windows
aws ec2 describe-instances --output table -
Show output as plain text, one row per line, for scriptsLinux, macOS, Windows
aws ec2 describe-instances --output text -
Show output as YAMLLinux, macOS, Windows
aws ec2 describe-instances --output yaml -
Pick fields out of the output with a queryLinux, macOS, Windows
aws ec2 describe-instances --query "Reservations[].Instances[].[InstanceId,InstanceType,State.Name]" --output table -
Name the columns in a tableLinux, macOS, Windows
aws ec2 describe-instances --query "Reservations[].Instances[].{ID:InstanceId,Type:InstanceType,State:State.Name}" --output table -
Keep only matching items with a queryLinux, macOS, Windows
aws ec2 describe-instances --query "Reservations[].Instances[?State.Name=='running'].InstanceId" --output text -
Filter on the AWS side, which is faster for big listsLinux, macOS, Windows
aws ec2 describe-instances --filters Name=instance-state-name,Values=running -
Filter by tagLinux, macOS, Windows
aws ec2 describe-instances --filters Name=tag:Environment,Values=prod -
Count the resultsLinux, macOS, Windows
aws ec2 describe-instances --query "length(Reservations[].Instances[])" -
Sort the results by a fieldLinux, macOS, Windows
aws ec2 describe-snapshots --owner-ids self --query "sort_by(Snapshots, &StartTime)[].[SnapshotId,StartTime]" --output text -
Show only the first few resultsLinux, macOS, Windows
aws ec2 describe-instances --max-items 10 -
Get the next page after --max-itemsLinux, macOS, Windows
aws ec2 describe-instances --max-items 10 --starting-token eyJOZXh0VG9rZW4iOi... -
Turn off the pager so output prints straight to the terminalLinux, macOS, Windows
aws ec2 describe-instances --no-cli-pager -
Turn off the pager for every command in this terminalLinux, macOS
export AWS_PAGER=""Windows$env:AWS_PAGER = "" -
Turn off the pager for goodLinux, macOS, Windows
aws configure set cli_pager "" -
Check you have permission without changing anythingLinux, macOS, Windows
aws ec2 run-instances --image-id ami-0abc123def4567890 --instance-type t3.micro --dry-run -
Wait until something is ready, such as an instance runningLinux, macOS, Windows
aws ec2 wait instance-running --instance-ids i-0abc123def4567890
AWS CLI: S3 storage
-
List your bucketsLinux, macOS, Windows
aws s3 ls -
List the files in a bucketLinux, macOS, Windows
aws s3 ls s3://my-bucket/ -
List every file in a bucket, with sizes and a totalLinux, macOS, Windows
aws s3 ls s3://my-bucket --recursive --human-readable --summarize -
Make a bucketLinux, macOS, Windows
aws s3 mb s3://my-bucket --region eu-west-1 -
Upload a fileLinux, macOS, Windows
aws s3 cp report.csv s3://my-bucket/reports/2026.csv -
Download a fileLinux, macOS, Windows
aws s3 cp s3://my-bucket/reports/2026.csv report.csv -
Upload a folderLinux, macOS, Windows
aws s3 cp ./site s3://my-bucket/site/ --recursive -
Copy a file between bucketsLinux, macOS, Windows
aws s3 cp s3://my-bucket/reports/2026.csv s3://my-backup-bucket/reports/2026.csv -
Print a file to the screenLinux, macOS, Windows
aws s3 cp s3://my-bucket/reports/2026.csv - -
Rename or move a fileLinux, macOS, Windows
aws s3 mv s3://my-bucket/reports/2026.csv s3://my-bucket/archive/2026.csv -
Sync a folder up to a bucket, copying only what changedLinux, macOS, Windows
aws s3 sync ./site s3://my-bucket/site/ -
Sync a bucket down to a folderLinux, macOS, Windows
aws s3 sync s3://my-bucket/site/ ./site -
Sync and delete files in the bucket that aren't in the folderLinux, macOS, Windows
aws s3 sync ./site s3://my-bucket/site/ --deleteWarning: Deletes files from the bucket. Run it with --dryrun first to see what it would remove.
-
Show what a sync would do without doing itLinux, macOS, Windows
aws s3 sync ./site s3://my-bucket/site/ --dryrun -
Sync only some filesLinux, macOS, Windows
aws s3 sync ./site s3://my-bucket/site/ --exclude "*" --include "*.html" -
Delete a fileLinux, macOS, Windows
aws s3 rm s3://my-bucket/reports/2026.csvWarning: Deleted files can't be got back unless versioning is on.
-
Delete everything under a folder in a bucketLinux, macOS, Windows
aws s3 rm s3://my-bucket/site/ --recursiveWarning: Deletes every file under that prefix. Run it with --dryrun first.
-
Delete an empty bucketLinux, macOS, Windows
aws s3 rb s3://my-bucket -
Delete a bucket and everything in itLinux, macOS, Windows
aws s3 rb s3://my-bucket --forceWarning: Deletes every file and then the bucket, with no undo. Old versions in a versioned bucket aren't removed, so the bucket delete fails until they're gone.
-
Make a link to download a file that expires in an hourLinux, macOS, Windows
aws s3 presign s3://my-bucket/reports/2026.csv --expires-in 3600Warning: Anyone with the link can download the file until it expires.
-
Show a file's size, type and metadataLinux, macOS, Windows
aws s3api head-object --bucket my-bucket --key reports/2026.csv -
Show which region a bucket is inLinux, macOS, Windows
aws s3api get-bucket-location --bucket my-bucket -
Turn on versioning for a bucketLinux, macOS, Windows
aws s3api put-bucket-versioning --bucket my-bucket --versioning-configuration Status=Enabled -
List every version of a fileLinux, macOS, Windows
aws s3api list-object-versions --bucket my-bucket --prefix reports/2026.csv -
Block all public access to a bucketLinux, macOS, Windows
aws s3api put-public-access-block --bucket my-bucket --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=true -
Show a bucket's policyLinux, macOS, Windows
aws s3api get-bucket-policy --bucket my-bucket --query Policy --output text -
Apply a bucket policy from a fileLinux, macOS, Windows
aws s3api put-bucket-policy --bucket my-bucket --policy file://input.json -
Show a bucket's default encryptionLinux, macOS, Windows
aws s3api get-bucket-encryption --bucket my-bucket -
Show a bucket's tagsLinux, macOS, Windows
aws s3api get-bucket-tagging --bucket my-bucket -
Upload with a storage class, such as Infrequent AccessLinux, macOS, Windows
aws s3 cp report.csv s3://my-bucket/reports/2026.csv --storage-class STANDARD_IA
AWS CLI: EC2 instances
-
List your instances with their ID, type, state and nameLinux, macOS, Windows
aws ec2 describe-instances --query "Reservations[].Instances[].[InstanceId,InstanceType,State.Name,Tags[?Key=='Name']|[0].Value]" --output table -
List running instancesLinux, macOS, Windows
aws ec2 describe-instances --filters Name=instance-state-name,Values=running --query "Reservations[].Instances[].InstanceId" --output text -
Show everything about one instanceLinux, macOS, Windows
aws ec2 describe-instances --instance-ids i-0abc123def4567890 -
Show an instance's public and private IP addressesLinux, macOS, Windows
aws ec2 describe-instances --instance-ids i-0abc123def4567890 --query "Reservations[].Instances[].[PublicIpAddress,PrivateIpAddress]" --output text -
Find an instance by its Name tagLinux, macOS, Windows
aws ec2 describe-instances --filters Name=tag:Name,Values=web-1 --query "Reservations[].Instances[].InstanceId" --output text -
Start an instanceLinux, macOS, Windows
aws ec2 start-instances --instance-ids i-0abc123def4567890 -
Stop an instanceLinux, macOS, Windows
aws ec2 stop-instances --instance-ids i-0abc123def4567890 -
Reboot an instanceLinux, macOS, Windows
aws ec2 reboot-instances --instance-ids i-0abc123def4567890 -
Terminate an instanceLinux, macOS, Windows
aws ec2 terminate-instances --instance-ids i-0abc123def4567890Warning: Terminating deletes the instance, and any volumes set to delete on termination, with no undo.
-
Stop people terminating an instance by mistakeLinux, macOS, Windows
aws ec2 modify-instance-attribute --instance-id i-0abc123def4567890 --disable-api-termination -
Launch an instanceLinux, macOS, Windows
aws ec2 run-instances --image-id ami-0abc123def4567890 --instance-type t3.micro --key-name my-key --subnet-id subnet-0abc123def4567890 --security-group-ids sg-0abc123def4567890 --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=web-1}]" -
Launch an instance with a start-up scriptLinux, macOS, Windows
aws ec2 run-instances --image-id ami-0abc123def4567890 --instance-type t3.micro --user-data file://setup.sh -
Change an instance's type (stop it first)Linux, macOS, Windows
aws ec2 modify-instance-attribute --instance-id i-0abc123def4567890 --instance-type Value=t3.large -
Check an instance's status checksLinux, macOS, Windows
aws ec2 describe-instance-status --instance-ids i-0abc123def4567890 -
Show an instance's console output, to debug a bootLinux, macOS, Windows
aws ec2 get-console-output --instance-id i-0abc123def4567890 --latest --output text -
Add or change a tagLinux, macOS, Windows
aws ec2 create-tags --resources i-0abc123def4567890 --tags Key=Environment,Value=prod -
Find the latest Amazon Linux 2023 imageLinux, macOS, Windows
aws ssm get-parameter --name /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64 --query Parameter.Value --output text -
Find the latest Ubuntu 24.04 imageLinux, macOS, Windows
aws ssm get-parameter --name /aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id --query Parameter.Value --output text -
List your own imagesLinux, macOS, Windows
aws ec2 describe-images --owners self --query "Images[].[ImageId,Name,CreationDate]" --output table -
Make an image from an instanceLinux, macOS, Windows
aws ec2 create-image --instance-id i-0abc123def4567890 --name web-1-backup -
List instance types with their CPUs and memoryLinux, macOS, Windows
aws ec2 describe-instance-types --filters Name=current-generation,Values=true --query "InstanceTypes[].[InstanceType,VCpuInfo.DefaultVCpus,MemoryInfo.SizeInMiB]" --output table -
Make a key pair and save the private keyLinux, macOS, Windows
aws ec2 create-key-pair --key-name my-key --query KeyMaterial --output text > my-key.pem -
List key pairsLinux, macOS, Windows
aws ec2 describe-key-pairs -
Delete a key pairLinux, macOS, Windows
aws ec2 delete-key-pair --key-name my-key
AWS CLI: VPCs and security groups
-
List VPCsLinux, macOS, Windows
aws ec2 describe-vpcs --query "Vpcs[].[VpcId,CidrBlock,IsDefault]" --output table -
List subnets in a VPCLinux, macOS, Windows
aws ec2 describe-subnets --filters Name=vpc-id,Values=vpc-0abc123def4567890 --query "Subnets[].[SubnetId,CidrBlock,AvailabilityZone]" --output table -
Make a VPCLinux, macOS, Windows
aws ec2 create-vpc --cidr-block 10.0.0.0/16 -
Make a subnetLinux, macOS, Windows
aws ec2 create-subnet --vpc-id vpc-0abc123def4567890 --cidr-block 10.0.1.0/24 --availability-zone eu-west-1a -
List route tables in a VPCLinux, macOS, Windows
aws ec2 describe-route-tables --filters Name=vpc-id,Values=vpc-0abc123def4567890 -
List internet gatewaysLinux, macOS, Windows
aws ec2 describe-internet-gateways -
List NAT gatewaysLinux, macOS, Windows
aws ec2 describe-nat-gateways -
List security groupsLinux, macOS, Windows
aws ec2 describe-security-groups --query "SecurityGroups[].[GroupId,GroupName,VpcId]" --output table -
Show a security group's rulesLinux, macOS, Windows
aws ec2 describe-security-group-rules --filters Name=group-id,Values=sg-0abc123def4567890 -
Make a security groupLinux, macOS, Windows
aws ec2 create-security-group --group-name web-sg --description "Web servers" --vpc-id vpc-0abc123def4567890 -
Allow a port in from one addressLinux, macOS, Windows
aws ec2 authorize-security-group-ingress --group-id sg-0abc123def4567890 --protocol tcp --port 443 --cidr 203.0.113.10/32 -
Allow HTTPS in from anywhereLinux, macOS, Windows
aws ec2 authorize-security-group-ingress --group-id sg-0abc123def4567890 --protocol tcp --port 443 --cidr 0.0.0.0/0 -
Remove a ruleLinux, macOS, Windows
aws ec2 revoke-security-group-ingress --group-id sg-0abc123def4567890 --protocol tcp --port 443 --cidr 203.0.113.10/32 -
Allow SSH from your own public IP addressLinux, macOS
aws ec2 authorize-security-group-ingress --group-id sg-0abc123def4567890 --protocol tcp --port 22 --cidr "$(curl -s https://checkip.amazonaws.com)/32" -
Find security groups open to the whole internetLinux, macOS, Windows
aws ec2 describe-security-groups --filters Name=ip-permission.cidr,Values=0.0.0.0/0 --query "SecurityGroups[].[GroupId,GroupName]" --output table -
Get a new Elastic IP addressLinux, macOS, Windows
aws ec2 allocate-address -
Attach an Elastic IP to an instanceLinux, macOS, Windows
aws ec2 associate-address --instance-id i-0abc123def4567890 --allocation-id eipalloc-0abc123def4567890 -
List Elastic IPs, including unattached ones you're paying forLinux, macOS, Windows
aws ec2 describe-addresses --query "Addresses[].[PublicIp,AllocationId,InstanceId]" --output table -
Release an Elastic IPLinux, macOS, Windows
aws ec2 release-address --allocation-id eipalloc-0abc123def4567890Warning: The address goes back to AWS and you can't get the same one back.
-
Turn on VPC flow logs to CloudWatchLinux, macOS, Windows
aws ec2 create-flow-logs --resource-type VPC --resource-ids vpc-0abc123def4567890 --traffic-type ALL --log-group-name vpc-flow-logs --deliver-logs-permission-arn arn:aws:iam::123456789012:role/Admin
AWS CLI: EBS volumes and snapshots
-
List volumesLinux, macOS, Windows
aws ec2 describe-volumes --query "Volumes[].[VolumeId,Size,VolumeType,State]" --output table -
List volumes that aren't attached to anythingLinux, macOS, Windows
aws ec2 describe-volumes --filters Name=status,Values=available --query "Volumes[].[VolumeId,Size,CreateTime]" --output table -
Make a volumeLinux, macOS, Windows
aws ec2 create-volume --availability-zone eu-west-1a --size 100 --volume-type gp3 -
Attach a volume to an instanceLinux, macOS, Windows
aws ec2 attach-volume --volume-id vol-0abc123def4567890 --instance-id i-0abc123def4567890 --device /dev/sdf -
Detach a volumeLinux, macOS, Windows
aws ec2 detach-volume --volume-id vol-0abc123def4567890 -
Make a volume biggerLinux, macOS, Windows
aws ec2 modify-volume --volume-id vol-0abc123def4567890 --size 100 -
Delete a volumeLinux, macOS, Windows
aws ec2 delete-volume --volume-id vol-0abc123def4567890Warning: The data on it is gone for good unless you have a snapshot.
-
Take a snapshot of a volumeLinux, macOS, Windows
aws ec2 create-snapshot --volume-id vol-0abc123def4567890 --description "Web servers" -
List your snapshotsLinux, macOS, Windows
aws ec2 describe-snapshots --owner-ids self --query "Snapshots[].[SnapshotId,VolumeId,StartTime,State]" --output table -
Make a volume from a snapshotLinux, macOS, Windows
aws ec2 create-volume --snapshot-id snap-0abc123def4567890 --availability-zone eu-west-1a -
Copy a snapshot to another regionLinux, macOS, Windows
aws ec2 copy-snapshot --source-region eu-west-1 --source-snapshot-id snap-0abc123def4567890 --region us-east-1 -
Delete a snapshotLinux, macOS, Windows
aws ec2 delete-snapshot --snapshot-id snap-0abc123def4567890Warning: Deleted snapshots can't be got back.
AWS CLI: IAM users, roles and policies
-
List usersLinux, macOS, Windows
aws iam list-users --query "Users[].[UserName,CreateDate]" --output table -
List rolesLinux, macOS, Windows
aws iam list-roles --query "Roles[].[RoleName,Arn]" --output table -
Show a role, including who can assume itLinux, macOS, Windows
aws iam get-role --role-name Admin -
Make a userLinux, macOS, Windows
aws iam create-user --user-name alice -
Add a user to a groupLinux, macOS, Windows
aws iam add-user-to-group --user-name alice --group-name Developers -
List a user's groupsLinux, macOS, Windows
aws iam list-groups-for-user --user-name alice -
Attach a managed policy to a userLinux, macOS, Windows
aws iam attach-user-policy --user-name alice --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess -
Attach a managed policy to a roleLinux, macOS, Windows
aws iam attach-role-policy --role-name Admin --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess -
Detach a policy from a roleLinux, macOS, Windows
aws iam detach-role-policy --role-name Admin --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess -
List the managed policies on a roleLinux, macOS, Windows
aws iam list-attached-role-policies --role-name Admin -
List the inline policies on a roleLinux, macOS, Windows
aws iam list-role-policies --role-name Admin -
Make a role from a trust policy fileLinux, macOS, Windows
aws iam create-role --role-name Admin --assume-role-policy-document file://input.json -
Make a policy from a JSON fileLinux, macOS, Windows
aws iam create-policy --policy-name ReadReports --policy-document file://input.json -
Show what a managed policy allowsLinux, macOS, Windows
aws iam get-policy-version --policy-arn arn:aws:iam::aws:policy/ReadOnlyAccess --version-id v1 -
Test whether a role is allowed to do somethingLinux, macOS, Windows
aws iam simulate-principal-policy --policy-source-arn arn:aws:iam::123456789012:role/Admin --action-names s3:GetObject --resource-arns "arn:aws:s3:::my-bucket/*" -
List a user's access keysLinux, macOS, Windows
aws iam list-access-keys --user-name alice -
Show when an access key was last usedLinux, macOS, Windows
aws iam get-access-key-last-used --access-key-id AKIAIOSFODNN7EXAMPLE -
Make an access key for a userLinux, macOS, Windows
aws iam create-access-key --user-name aliceWarning: The secret key is shown once, in plain text. Store it somewhere safe, and prefer short-term sign-in where you can.
-
Turn off an access keyLinux, macOS, Windows
aws iam update-access-key --user-name alice --access-key-id AKIAIOSFODNN7EXAMPLE --status Inactive -
Delete an access keyLinux, macOS, Windows
aws iam delete-access-key --user-name alice --access-key-id AKIAIOSFODNN7EXAMPLEWarning: Anything still using the key stops working straight away.
-
List a user's MFA devicesLinux, macOS, Windows
aws iam list-mfa-devices --user-name alice -
Download the credential report for every userLinux, macOS
aws iam generate-credential-report aws iam get-credential-report --query Content --output text | base64 --decode > credential-report.csv -
Show the account's password policyLinux, macOS, Windows
aws iam get-account-password-policy -
Show the account's IAM usage and limitsLinux, macOS, Windows
aws iam get-account-summary
AWS CLI: Lambda functions
-
List functionsLinux, macOS, Windows
aws lambda list-functions --query "Functions[].[FunctionName,Runtime,LastModified]" --output table -
Show a function's settingsLinux, macOS, Windows
aws lambda get-function-configuration --function-name my-function -
Run a function and save what it returnsLinux, macOS, Windows
aws lambda invoke --function-name my-function --cli-binary-format raw-in-base64-out --payload file://input.json response.json -
Run a function and show its last 4 KB of logsLinux, macOS
aws lambda invoke --function-name my-function --log-type Tail --query LogResult --output text response.json | base64 --decode -
Update a function's code from a zip fileLinux, macOS, Windows
aws lambda update-function-code --function-name my-function --zip-file fileb://function.zip -
Update a function's environment variablesLinux, macOS, Windows
aws lambda update-function-configuration --function-name my-function --environment "Variables={LOG_LEVEL=debug}" -
Change a function's memory and timeoutLinux, macOS, Windows
aws lambda update-function-configuration --function-name my-function --memory-size 512 --timeout 30 -
Publish a new versionLinux, macOS, Windows
aws lambda publish-version --function-name my-function -
Point an alias at a versionLinux, macOS, Windows
aws lambda update-alias --function-name my-function --name live --function-version 3 -
Make a function URL anyone can callLinux, macOS, Windows
aws lambda create-function-url-config --function-name my-function --auth-type NONEWarning: With NONE, anyone with the URL can run the function. You'll also need a resource policy that lets the public call it.
-
Delete a functionLinux, macOS, Windows
aws lambda delete-function --function-name my-functionWarning: Deletes the function and every version of it.
AWS CLI: CloudWatch logs and metrics
-
List log groupsLinux, macOS, Windows
aws logs describe-log-groups --query "logGroups[].[logGroupName,storedBytes]" --output table -
Follow a log group liveLinux, macOS, Windows
aws logs tail /aws/lambda/my-function --follow -
Show the last hour of a log groupLinux, macOS, Windows
aws logs tail /aws/lambda/my-function --since 1h -
Show log lines that match a wordLinux, macOS, Windows
aws logs tail /aws/lambda/my-function --since 1d --filter-pattern ERROR -
Search a log group across all its streamsLinux, macOS, Windows
aws logs filter-log-events --log-group-name /aws/lambda/my-function --filter-pattern ERROR -
Keep a log group's logs for 30 days onlyLinux, macOS, Windows
aws logs put-retention-policy --log-group-name /aws/lambda/my-function --retention-in-days 30 -
Find log groups that keep logs foreverLinux, macOS, Windows
aws logs describe-log-groups --query "logGroups[?retentionInDays==null].logGroupName" --output text -
Run a Logs Insights queryLinux, macOS, Windows
aws logs start-query --log-group-name /aws/lambda/my-function --start-time 1793836800 --end-time 1793923200 --query-string "fields @timestamp, @message | filter @message like /ERROR/ | limit 20" -
Get a Logs Insights query's resultsLinux, macOS, Windows
aws logs get-query-results --query-id 12ab3456-12ab-123a-789e-1234567890ab -
Delete a log groupLinux, macOS, Windows
aws logs delete-log-group --log-group-name /aws/lambda/my-functionWarning: Deletes every log in the group.
-
List alarms that are going offLinux, macOS, Windows
aws cloudwatch describe-alarms --state-value ALARM --query "MetricAlarms[].[AlarmName,StateReason]" --output table -
List the metrics for an instanceLinux, macOS, Windows
aws cloudwatch list-metrics --namespace AWS/EC2 --dimensions Name=InstanceId,Value=i-0abc123def4567890 -
Get an instance's average CPU over a dayLinux, macOS, Windows
aws cloudwatch get-metric-statistics --namespace AWS/EC2 --metric-name CPUUtilization --dimensions Name=InstanceId,Value=i-0abc123def4567890 --start-time 2026-11-17T00:00:00Z --end-time 2026-11-18T00:00:00Z --period 3600 --statistics Average -
Make an alarm for high CPULinux, macOS, Windows
aws cloudwatch put-metric-alarm --alarm-name web-1-high-cpu --namespace AWS/EC2 --metric-name CPUUtilization --dimensions Name=InstanceId,Value=i-0abc123def4567890 --statistic Average --period 300 --evaluation-periods 2 --threshold 80 --comparison-operator GreaterThanThreshold --alarm-actions arn:aws:sns:eu-west-1:123456789012:alerts -
Test an alarm by setting its stateLinux, macOS, Windows
aws cloudwatch set-alarm-state --alarm-name web-1-high-cpu --state-value ALARM --state-reason "Testing"
AWS CLI: Systems Manager
-
Open a shell on an instance without SSH (needs the Session Manager plugin)Linux, macOS, Windows
aws ssm start-session --target i-0abc123def4567890 -
Forward a port from an instance to your machine (needs the Session Manager plugin)Linux, macOS, Windows
aws ssm start-session --target i-0abc123def4567890 --document-name AWS-StartPortForwardingSession --parameters portNumber=3389,localPortNumber=13389 -
Forward a port through an instance to a database behind it (needs the Session Manager plugin)Linux, macOS, Windows
aws ssm start-session --target i-0abc123def4567890 --document-name AWS-StartPortForwardingSessionToRemoteHost --parameters host=my-db.abc123xyz.eu-west-1.rds.amazonaws.com,portNumber=5432,localPortNumber=5432 -
List instances Systems Manager can reachLinux, macOS, Windows
aws ssm describe-instance-information --query "InstanceInformationList[].[InstanceId,PingStatus,PlatformName]" --output table -
Run a shell command on instancesLinux, macOS, Windows
aws ssm send-command --instance-ids i-0abc123def4567890 --document-name AWS-RunShellScript --parameters "commands=['uptime']" -
Get the output of a command you sentLinux, macOS, Windows
aws ssm get-command-invocation --command-id a1b2c3d4-5678-90ab-cdef-EXAMPLE11111 --instance-id i-0abc123def4567890 -
Read a parameterLinux, macOS, Windows
aws ssm get-parameter --name /app/prod/db-host --query Parameter.Value --output text -
Read an encrypted parameterLinux, macOS, Windows
aws ssm get-parameter --name /app/prod/db-host --with-decryption --query Parameter.Value --output textWarning: Prints the secret in plain text.
-
List the parameters under a pathLinux, macOS, Windows
aws ssm get-parameters-by-path --path /app/prod --recursive --query "Parameters[].Name" -
Save a parameterLinux, macOS, Windows
aws ssm put-parameter --name /app/prod/db-host --value "db.internal" --type String --overwrite -
Save an encrypted parameterLinux, macOS, Windows
aws ssm put-parameter --name /app/prod/db-host --value "MyPassword" --type SecureString --overwriteWarning: The value ends up in your shell history. Read it from a file with file:// to avoid that.
-
Delete a parameterLinux, macOS, Windows
aws ssm delete-parameter --name /app/prod/db-host
AWS CLI: Secrets Manager and KMS
-
List secretsLinux, macOS, Windows
aws secretsmanager list-secrets --query "SecretList[].Name" -
Read a secretLinux, macOS, Windows
aws secretsmanager get-secret-value --secret-id prod/db/password --query SecretString --output textWarning: Prints the secret in plain text.
-
Store a new secret from a fileLinux, macOS, Windows
aws secretsmanager create-secret --name prod/db/password --secret-string file://input.json -
Change a secret's valueLinux, macOS, Windows
aws secretsmanager put-secret-value --secret-id prod/db/password --secret-string file://input.json -
Rotate a secret nowLinux, macOS, Windows
aws secretsmanager rotate-secret --secret-id prod/db/password -
Delete a secret after 7 daysLinux, macOS, Windows
aws secretsmanager delete-secret --secret-id prod/db/password --recovery-window-in-days 7 -
Cancel a secret's deletionLinux, macOS, Windows
aws secretsmanager restore-secret --secret-id prod/db/password -
List KMS keys and their aliasesLinux, macOS, Windows
aws kms list-aliases --query "Aliases[].[AliasName,TargetKeyId]" --output table -
Encrypt a small file with a KMS keyLinux, macOS, Windows
aws kms encrypt --key-id alias/my-key --plaintext fileb://report.csv --query CiphertextBlob --output text > encrypted.b64 -
Turn on yearly rotation for a KMS keyLinux, macOS, Windows
aws kms enable-key-rotation --key-id 1234abcd-12ab-34cd-56ef-1234567890ab
AWS CLI: Containers: ECR, ECS and EKS
-
Sign Docker in to your ECR registryLinux, macOS, Windows
aws ecr get-login-password --region eu-west-1 | docker login --username AWS --password-stdin 123456789012.dkr.ecr.eu-west-1.amazonaws.com -
Make an ECR repositoryLinux, macOS, Windows
aws ecr create-repository --repository-name my-app --image-scanning-configuration scanOnPush=true -
List ECR repositoriesLinux, macOS, Windows
aws ecr describe-repositories --query "repositories[].repositoryUri" --output text -
List the images in a repositoryLinux, macOS, Windows
aws ecr describe-images --repository-name my-app --query "imageDetails[].[imageTags[0],imagePushedAt]" --output table -
Show an image's scan findingsLinux, macOS, Windows
aws ecr describe-image-scan-findings --repository-name my-app --image-id imageTag=latest -
Delete an imageLinux, macOS, Windows
aws ecr batch-delete-image --repository-name my-app --image-ids imageTag=latest -
List ECS clustersLinux, macOS, Windows
aws ecs list-clusters -
List the services in a clusterLinux, macOS, Windows
aws ecs list-services --cluster my-cluster -
Show a service's deployments and eventsLinux, macOS, Windows
aws ecs describe-services --cluster my-cluster --services web -
Redeploy a service, pulling the image againLinux, macOS, Windows
aws ecs update-service --cluster my-cluster --service web --force-new-deployment -
Change how many tasks a service runsLinux, macOS, Windows
aws ecs update-service --cluster my-cluster --service web --desired-count 10 -
Wait until a service has finished deployingLinux, macOS, Windows
aws ecs wait services-stable --cluster my-cluster --services web -
List the running tasks in a serviceLinux, macOS, Windows
aws ecs list-tasks --cluster my-cluster --service-name web -
Open a shell in a running container (needs the Session Manager plugin)Linux, macOS, Windows
aws ecs execute-command --cluster my-cluster --task 0123456789abcdef0123456789abcdef --container app --interactive --command "/bin/sh" -
List EKS clustersLinux, macOS, Windows
aws eks list-clusters -
Set up kubectl for an EKS clusterLinux, macOS, Windows
aws eks update-kubeconfig --name my-cluster --region eu-west-1 -
Show an EKS cluster's version and endpointLinux, macOS, Windows
aws eks describe-cluster --name my-cluster --query "cluster.[version,endpoint,status]" -
List an EKS cluster's node groupsLinux, macOS, Windows
aws eks list-nodegroups --cluster-name my-cluster
AWS CLI: CloudFormation
-
List stacksLinux, macOS, Windows
aws cloudformation list-stacks --stack-status-filter CREATE_COMPLETE UPDATE_COMPLETE --query "StackSummaries[].[StackName,StackStatus]" --output table -
Check a template for mistakesLinux, macOS, Windows
aws cloudformation validate-template --template-body file://template.yaml -
Create or update a stack from a templateLinux, macOS, Windows
aws cloudformation deploy --stack-name my-stack --template-file template.yaml -
Deploy a stack that makes IAM rolesLinux, macOS, Windows
aws cloudformation deploy --stack-name my-stack --template-file template.yaml --capabilities CAPABILITY_NAMED_IAM -
Deploy a stack with parameter valuesLinux, macOS, Windows
aws cloudformation deploy --stack-name my-stack --template-file template.yaml --parameter-overrides InstanceType=t3.small -
See what a deploy would change without doing itLinux, macOS, Windows
aws cloudformation deploy --stack-name my-stack --template-file template.yaml --no-execute-changeset -
Show a stack's outputsLinux, macOS, Windows
aws cloudformation describe-stacks --stack-name my-stack --query "Stacks[0].Outputs" --output table -
Show what went wrong in a stackLinux, macOS, Windows
aws cloudformation describe-stack-events --stack-name my-stack --query "StackEvents[?contains(ResourceStatus, 'FAILED')].[LogicalResourceId,ResourceStatusReason]" --output table -
List the resources in a stackLinux, macOS, Windows
aws cloudformation list-stack-resources --stack-name my-stack -
Check whether a stack has drifted from its templateLinux, macOS, Windows
aws cloudformation detect-stack-drift --stack-name my-stack -
Delete a stackLinux, macOS, Windows
aws cloudformation delete-stack --stack-name my-stackWarning: Deletes every resource the stack made, unless it's set to be kept.
-
Wait until a stack is deletedLinux, macOS, Windows
aws cloudformation wait stack-delete-complete --stack-name my-stack
AWS CLI: Route 53 and CloudFront
-
List hosted zonesLinux, macOS, Windows
aws route53 list-hosted-zones --query "HostedZones[].[Id,Name]" --output table -
List the records in a zoneLinux, macOS, Windows
aws route53 list-resource-record-sets --hosted-zone-id Z0123456789ABCDEFGHIJ --query "ResourceRecordSets[].[Name,Type,TTL]" --output table -
Add or change records from a JSON fileLinux, macOS, Windows
aws route53 change-resource-record-sets --hosted-zone-id Z0123456789ABCDEFGHIJ --change-batch file://input.json -
Check whether a record change has gone liveLinux, macOS, Windows
aws route53 get-change --id C0123456789ABCDEFGHIJ -
Test what a zone answers for a nameLinux, macOS, Windows
aws route53 test-dns-answer --hosted-zone-id Z0123456789ABCDEFGHIJ --record-name www.example.com --record-type A -
List CloudFront distributionsLinux, macOS, Windows
aws cloudfront list-distributions --query "DistributionList.Items[].[Id,DomainName,Aliases.Items[0]]" --output table -
Clear the whole CloudFront cacheLinux, macOS, Windows
aws cloudfront create-invalidation --distribution-id E1ABCDEFGHIJKL --paths "/*" -
Clear the cache for some pathsLinux, macOS, Windows
aws cloudfront create-invalidation --distribution-id E1ABCDEFGHIJKL --paths /index.html "/css/*" -
List SSL certificates in Certificate ManagerLinux, macOS, Windows
aws acm list-certificates --region us-east-1 --query "CertificateSummaryList[].[DomainName,Status]" --output table
AWS CLI: RDS and DynamoDB
-
List RDS databasesLinux, macOS, Windows
aws rds describe-db-instances --query "DBInstances[].[DBInstanceIdentifier,Engine,DBInstanceStatus,Endpoint.Address]" --output table -
Take a snapshot of a databaseLinux, macOS, Windows
aws rds create-db-snapshot --db-instance-identifier my-db --db-snapshot-identifier my-db-before-upgrade -
List a database's snapshotsLinux, macOS, Windows
aws rds describe-db-snapshots --db-instance-identifier my-db -
Stop a databaseLinux, macOS, Windows
aws rds stop-db-instance --db-instance-identifier my-dbWarning: AWS starts a stopped database again by itself after 7 days.
-
Start a databaseLinux, macOS, Windows
aws rds start-db-instance --db-instance-identifier my-db -
Reboot a databaseLinux, macOS, Windows
aws rds reboot-db-instance --db-instance-identifier my-db -
Get a short-lived password for IAM database sign-inLinux, macOS, Windows
aws rds generate-db-auth-token --hostname my-db.abc123xyz.eu-west-1.rds.amazonaws.com --port 5432 --username app_user --region eu-west-1 -
List DynamoDB tablesLinux, macOS, Windows
aws dynamodb list-tables -
Show a table's keys, size and settingsLinux, macOS, Windows
aws dynamodb describe-table --table-name my-table -
Get one item by its keyLinux, macOS, Windows
aws dynamodb get-item --table-name my-table --key file://input.json -
Read every item in a tableLinux, macOS, Windows
aws dynamodb scan --table-name my-tableWarning: Reads the whole table, which is slow and costs read capacity on big tables.
-
Count the items in a tableLinux, macOS, Windows
aws dynamodb scan --table-name my-table --select COUNT -
Turn on point-in-time recovery for a tableLinux, macOS, Windows
aws dynamodb update-continuous-backups --table-name my-table --point-in-time-recovery-specification PointInTimeRecoveryEnabled=true
AWS CLI: SNS and SQS
-
List SNS topicsLinux, macOS, Windows
aws sns list-topics -
Send a message to a topicLinux, macOS, Windows
aws sns publish --topic-arn arn:aws:sns:eu-west-1:123456789012:alerts --message "Hello from the CLI" -
Subscribe an email address to a topicLinux, macOS, Windows
aws sns subscribe --topic-arn arn:aws:sns:eu-west-1:123456789012:alerts --protocol email --notification-endpoint [email protected] -
List SQS queuesLinux, macOS, Windows
aws sqs list-queues -
Send a message to a queueLinux, macOS, Windows
aws sqs send-message --queue-url https://sqs.eu-west-1.amazonaws.com/123456789012/my-queue --message-body "Hello from the CLI" -
Read messages from a queueLinux, macOS, Windows
aws sqs receive-message --queue-url https://sqs.eu-west-1.amazonaws.com/123456789012/my-queue --max-number-of-messages 10 -
Show how many messages are waiting in a queueLinux, macOS, Windows
aws sqs get-queue-attributes --queue-url https://sqs.eu-west-1.amazonaws.com/123456789012/my-queue --attribute-names ApproximateNumberOfMessages -
Empty a queueLinux, macOS, Windows
aws sqs purge-queue --queue-url https://sqs.eu-west-1.amazonaws.com/123456789012/my-queueWarning: Deletes every message in the queue, with no undo.
AWS CLI: Costs and audit
-
Show this month's spend by serviceLinux, macOS, Windows
aws ce get-cost-and-usage --time-period Start=2026-11-01,End=2026-12-01 --granularity MONTHLY --metrics UnblendedCost --group-by Type=DIMENSION,Key=SERVICEWarning: Each Cost Explorer request is charged, at about 1 US cent.
-
Forecast this month's billLinux, macOS, Windows
aws ce get-cost-forecast --time-period Start=2026-11-01,End=2026-12-01 --granularity MONTHLY --metric UNBLENDED_COSTWarning: Each Cost Explorer request is charged, at about 1 US cent.
-
List your budgetsLinux, macOS, Windows
aws budgets describe-budgets --account-id 123456789012 -
Show who did what in the last 90 days (CloudTrail)Linux, macOS, Windows
aws cloudtrail lookup-events --max-results 20 -
Find who deleted somethingLinux, macOS, Windows
aws cloudtrail lookup-events --lookup-attributes AttributeKey=EventName,AttributeValue=DeleteBucket -
Find everything a user didLinux, macOS, Windows
aws cloudtrail lookup-events --lookup-attributes AttributeKey=Username,AttributeValue=alice -
List your CloudTrail trailsLinux, macOS, Windows
aws cloudtrail describe-trails -
List resources with a tag, across servicesLinux, macOS, Windows
aws resourcegroupstaggingapi get-resources --tag-filters Key=Environment,Values=prod --query "ResourceTagMappingList[].ResourceARN" -
Show a service's quotasLinux, macOS, Windows
aws service-quotas list-service-quotas --service-code ec2 --query "Quotas[].[QuotaName,Value]" --output table
AWS CLI: Troubleshooting
-
Show every request and response, to debug a commandLinux, macOS, Windows
aws s3 ls --debugWarning: The debug output can include signed request headers. Check it before you share it.
-
Check which credentials the CLI foundLinux, macOS, Windows
aws configure list -
Run a command without signing it, for public bucketsLinux, macOS, Windows
aws s3 ls s3://noaa-ghcn-pds --no-sign-request -
Send a command to a different endpoint, such as LocalStackLinux, macOS, Windows
aws s3 ls --endpoint-url http://localhost:4566 -
Give a slow command longer before it times outLinux, macOS, Windows
aws s3 cp report.csv s3://my-bucket/reports/2026.csv --cli-read-timeout 300 -
Retry throttled requests more timesLinux, macOS, Windows
aws configure set max_attempts 10 -
Show errors as JSON, for scriptsLinux, macOS, Windows
aws s3 ls s3://my-bucket --cli-error-format json -
Clear cached role credentialsLinux, macOS
rm -rf ~/.aws/cli/cache -
Clear cached SSO tokensLinux, macOS
rm -rf ~/.aws/sso/cacheWarning: You'll need to run aws sso login again.
Azure CLI: Setup and help
-
Show the Azure CLI version, and its extensionsLinux, macOS, Windows
az version -
Update the Azure CLI and its extensionsLinux, macOS, Windows
az upgrade -
List every command groupLinux, macOS, Windows
az --help -
Get help for one command, with examplesLinux, macOS, Windows
az vm create --help -
Find commands and examples for a taskLinux, macOS, Windows
az find "create a storage account" -
List installed extensionsLinux, macOS, Windows
az extension list --output table -
Install an extensionLinux, macOS, Windows
az extension add --name ssh -
Update every installed extensionLinux, macOS
az extension list --query "[].name" --output tsv | xargs -n1 az extension update --name -
Let the CLI install extensions when a command needs oneLinux, macOS, Windows
az config set extension.use_dynamic_install=yes_without_prompt -
Show your CLI settingsLinux, macOS, Windows
az config get
Azure CLI: Sign in and subscriptions
-
Sign in in the browserLinux, macOS, Windows
az login -
Sign in on a machine with no browser, using a codeLinux, macOS, Windows
az login --use-device-code -
Sign in to a particular tenantLinux, macOS, Windows
az login --tenant contoso.onmicrosoft.com -
Sign in as a service principalLinux, macOS, Windows
az login --service-principal --username 00000000-0000-0000-0000-000000000000 --password MyClientSecret --tenant contoso.onmicrosoft.comWarning: The secret ends up in your shell history. Use a certificate, or read the secret from an environment variable.
-
Sign in with the managed identity of the VM or service you're onLinux, macOS, Windows
az login --identity -
Sign outLinux, macOS, Windows
az logout -
Show which subscription and account you're usingLinux, macOS, Windows
az account show --output table -
List your subscriptionsLinux, macOS, Windows
az account list --output table -
Switch to another subscriptionLinux, macOS, Windows
az account set --subscription "My Subscription" -
Run one command in another subscriptionLinux, macOS, Windows
az group list --subscription "My Subscription" -
Show which tenant each subscription is inLinux, macOS, Windows
az account list --all --query "[].{Subscription:name, Tenant:tenantId, State:state}" --output table -
List the regions available to your subscriptionLinux, macOS, Windows
az account list-locations --query "[].name" --output tsv -
Get an access token for the Azure APILinux, macOS, Windows
az account get-access-token --query accessToken --output tsvWarning: Prints a secret in plain text. Don't paste the output anywhere it could be saved or shared.
-
Get an access token for Microsoft GraphLinux, macOS, Windows
az account get-access-token --resource-type ms-graph --query accessToken --output tsvWarning: Prints a secret in plain text. Don't paste the output anywhere it could be saved or shared.
-
Forget every saved sign-in and subscriptionLinux, macOS, Windows
az account clear
Azure CLI: Output, queries and defaults
-
Show output as a tableLinux, macOS, Windows
az vm list --output table -
Show output as tab-separated text, for scriptsLinux, macOS, Windows
az vm list --output tsv -
Show output as YAMLLinux, macOS, Windows
az vm list --output yaml -
Show output as coloured JSONLinux, macOS, Windows
az vm list --output jsonc -
Show nothing on successLinux, macOS, Windows
az group create --name my-rg --location westeurope --output none -
Pick fields out of the output with a queryLinux, macOS, Windows
az vm list --query "[].{Name:name, Group:resourceGroup, Location:location}" --output table -
Keep only matching items with a queryLinux, macOS, Windows
az vm list --query "[?location=='westeurope'].name" --output tsv -
Keep items whose name contains some textLinux, macOS, Windows
az resource list --query "[?contains(name, 'web')].[name,type]" --output table -
Count the resultsLinux, macOS, Windows
az vm list --query "length(@)" -
Get one value for a scriptLinux, macOS, Windows
az account show --query id --output tsv -
Save one value in a variableLinux, macOS
subscription_id=$(az account show --query id --output tsv)Windows$subscriptionId = az account show --query id --output tsv -
Make table output the defaultLinux, macOS, Windows
az config set core.output=table -
Set a default resource groupLinux, macOS, Windows
az config set defaults.group=my-rg -
Set a default regionLinux, macOS, Windows
az config set defaults.location=westeurope -
Clear the default resource groupLinux, macOS, Windows
az config unset defaults.group -
Hide warnings and only show errorsLinux, macOS, Windows
az vm list --only-show-errors -
Start a long job and return straight awayLinux, macOS, Windows
az vm start --name web-1 --resource-group my-rg --no-wait
Azure CLI: Resource groups and resources
-
List resource groupsLinux, macOS, Windows
az group list --output table -
Make a resource groupLinux, macOS, Windows
az group create --name my-rg --location westeurope -
Check whether a resource group existsLinux, macOS, Windows
az group exists --name my-rg -
Show a resource groupLinux, macOS, Windows
az group show --name my-rg -
Delete a resource group and everything in itLinux, macOS, Windows
az group delete --name my-rg --yes --no-waitWarning: Deletes every resource in the group, with no undo, and --yes skips the prompt.
-
List the resources in a groupLinux, macOS, Windows
az resource list --resource-group my-rg --output table -
List every resource of one typeLinux, macOS, Windows
az resource list --resource-type Microsoft.Compute/virtualMachines --output table -
List resources with a tagLinux, macOS, Windows
az resource list --tag Environment=prod --output table -
Show a resource by its IDLinux, macOS, Windows
az resource show --ids /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/my-rg/providers/Microsoft.Compute/virtualMachines/web-1 -
Delete a resource by its IDLinux, macOS, Windows
az resource delete --ids /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/my-rg/providers/Microsoft.Compute/virtualMachines/web-1Warning: Deletes the resource with no undo.
-
Add a tag to a resource group, keeping its other tagsLinux, macOS, Windows
az group update --name my-rg --set tags.Environment=prod -
Add tags to a resource, keeping its other tagsLinux, macOS, Windows
az tag update --resource-id /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/my-rg/providers/Microsoft.Compute/virtualMachines/web-1 --operation Merge --tags Environment=prod -
Stop a resource group being deletedLinux, macOS, Windows
az lock create --name no-delete --resource-group my-rg --lock-type CanNotDelete -
List locksLinux, macOS, Windows
az lock list --output table -
Remove a lockLinux, macOS, Windows
az lock delete --name no-delete --resource-group my-rg -
Export a resource group as an ARM templateLinux, macOS, Windows
az group export --name my-rg > template.json -
Move resources to another resource groupLinux, macOS, Windows
az resource move --ids /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/my-rg/providers/Microsoft.Compute/virtualMachines/web-1 --destination-group my-other-rg -
List resource providers and whether they're registeredLinux, macOS, Windows
az provider list --query "[].{Provider:namespace, State:registrationState}" --output table -
Register a resource providerLinux, macOS, Windows
az provider register --namespace Microsoft.ContainerService
Azure CLI: Virtual machines
-
List VMs with their power state and IP addressesLinux, macOS, Windows
az vm list --show-details --query "[].{Name:name, Group:resourceGroup, State:powerState, PublicIP:publicIps, PrivateIP:privateIps}" --output table -
Show everything about one VMLinux, macOS, Windows
az vm show --name web-1 --resource-group my-rg --show-details -
Show a VM's public IP addressLinux, macOS, Windows
az vm show --name web-1 --resource-group my-rg --show-details --query publicIps --output tsv -
Make a Linux VM with an SSH keyLinux, macOS, Windows
az vm create --name web-1 --resource-group my-rg --image Ubuntu2404 --size Standard_B2s --admin-username azureuser --generate-ssh-keys -
Make a Linux VM with no public IP addressLinux, macOS, Windows
az vm create --name web-1 --resource-group my-rg --image Ubuntu2404 --admin-username azureuser --generate-ssh-keys --public-ip-address "" --nsg "" -
Make a Windows VMLinux, macOS, Windows
az vm create --name web-1 --resource-group my-rg --image Win2022Datacenter --size Standard_B2s --admin-username azureuser --admin-password MyPasswordWarning: The password ends up in your shell history. Leave out --admin-password to be asked for it.
-
Make a VM with a start-up script (cloud-init)Linux, macOS, Windows
az vm create --name web-1 --resource-group my-rg --image Ubuntu2404 --admin-username azureuser --generate-ssh-keys --custom-data cloud-init.yaml -
Start a VMLinux, macOS, Windows
az vm start --name web-1 --resource-group my-rg -
Stop a VM and stop paying for its computeLinux, macOS, Windows
az vm deallocate --name web-1 --resource-group my-rg -
Shut down a VM but keep it allocatedLinux, macOS, Windows
az vm stop --name web-1 --resource-group my-rgWarning: A stopped VM is still billed for compute. Use az vm deallocate to stop paying.
-
Restart a VMLinux, macOS, Windows
az vm restart --name web-1 --resource-group my-rg -
Delete a VMLinux, macOS, Windows
az vm delete --name web-1 --resource-group my-rg --yesWarning: Deletes the VM with no undo. Its disks, NIC and public IP are kept unless they were set to delete with it, and you keep paying for them.
-
List the sizes you can resize a VM toLinux, macOS, Windows
az vm list-vm-resize-options --name web-1 --resource-group my-rg --output table -
Resize a VMLinux, macOS, Windows
az vm resize --name web-1 --resource-group my-rg --size Standard_D2s_v5Warning: Restarts the VM.
-
List the VM sizes in a regionLinux, macOS, Windows
az vm list-sizes --location westeurope --output table -
List popular VM imagesLinux, macOS, Windows
az vm image list --output table -
Find images from a publisherLinux, macOS, Windows
az vm image list --publisher Canonical --offer ubuntu-24_04-lts --all --output table -
Open a port on a VMLinux, macOS, Windows
az vm open-port --name web-1 --resource-group my-rg --port 443 --priority 1010 -
Run a shell script on a Linux VM, without SSHLinux, macOS, Windows
az vm run-command invoke --name web-1 --resource-group my-rg --command-id RunShellScript --scripts "uptime" -
Run a PowerShell script on a Windows VM, without RDPLinux, macOS, Windows
az vm run-command invoke --name web-1 --resource-group my-rg --command-id RunPowerShellScript --scripts "Get-Service" -
Reset a Linux VM's SSH keyLinux, macOS, Windows
az vm user update --name web-1 --resource-group my-rg --username azureuser --ssh-key-value ~/.ssh/id_ed25519.pub -
Reset a VM's admin passwordLinux, macOS, Windows
az vm user update --name web-1 --resource-group my-rg --username azureuser --password MyPasswordWarning: The password ends up in your shell history.
-
SSH in with your Entra ID account (ssh extension)Linux, macOS, Windows
az ssh vm --name web-1 --resource-group my-rg -
Show a VM's boot log, to debug a bootLinux, macOS, Windows
az vm boot-diagnostics get-boot-log --name web-1 --resource-group my-rg -
Turn on boot diagnosticsLinux, macOS, Windows
az vm boot-diagnostics enable --name web-1 --resource-group my-rg -
Give a VM a managed identityLinux, macOS, Windows
az vm identity assign --name web-1 --resource-group my-rg -
List VM extensionsLinux, macOS, Windows
az vm extension list --vm-name web-1 --resource-group my-rg --output table -
Wait until a VM is runningLinux, macOS, Windows
az vm wait --name web-1 --resource-group my-rg --custom "instanceView.statuses[?code=='PowerState/running']" -
Schedule a VM to shut down every eveningLinux, macOS, Windows
az vm auto-shutdown --name web-1 --resource-group my-rg --time 1900
Azure CLI: Disks and snapshots
-
List the disks in a resource groupLinux, macOS, Windows
az disk list --resource-group my-rg --query "[].{Name:name, Group:resourceGroup, SizeGB:diskSizeGB, State:diskState}" --output table -
List disks that aren't attached to anythingLinux, macOS, Windows
az disk list --resource-group my-rg --query "[?diskState=='Unattached'].{Name:name, Group:resourceGroup, SizeGB:diskSizeGB}" --output table -
Make and attach a new data diskLinux, macOS, Windows
az vm disk attach --vm-name web-1 --resource-group my-rg --name web-1-data --new --size-gb 128 -
Attach an existing diskLinux, macOS, Windows
az vm disk attach --vm-name web-1 --resource-group my-rg --name web-1-data -
Detach a diskLinux, macOS, Windows
az vm disk detach --vm-name web-1 --resource-group my-rg --name web-1-data -
Make a disk bigger (deallocate the VM first)Linux, macOS, Windows
az disk update --name web-1-data --resource-group my-rg --size-gb 128 -
Take a snapshot of a diskLinux, macOS, Windows
az snapshot create --name web-1-data-snap --resource-group my-rg --source web-1-data -
List snapshotsLinux, macOS, Windows
az snapshot list --output table -
Make a disk from a snapshotLinux, macOS, Windows
az disk create --name web-1-data --resource-group my-rg --source web-1-data-snap -
Delete a diskLinux, macOS, Windows
az disk delete --name web-1-data --resource-group my-rg --yesWarning: The data is gone for good unless you have a snapshot.
-
Delete a snapshotLinux, macOS, Windows
az snapshot delete --name web-1-data-snap --resource-group my-rgWarning: Deleted snapshots can't be got back.
Azure CLI: Networking
-
List virtual networksLinux, macOS, Windows
az network vnet list --output table -
Make a virtual network with a subnetLinux, macOS, Windows
az network vnet create --name my-vnet --resource-group my-rg --address-prefixes 10.0.0.0/16 --subnet-name web --subnet-prefixes 10.0.1.0/24 -
List a virtual network's subnetsLinux, macOS, Windows
az network vnet subnet list --vnet-name my-vnet --resource-group my-rg --output table -
Add a subnetLinux, macOS, Windows
az network vnet subnet create --name web --vnet-name my-vnet --resource-group my-rg --address-prefixes 10.0.1.0/24 -
Peer two virtual networksLinux, macOS, Windows
az network vnet peering create --name my-vnet-to-hub --vnet-name my-vnet --resource-group my-rg --remote-vnet /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/hub-rg/providers/Microsoft.Network/virtualNetworks/hub-vnet --allow-vnet-access -
List network security groupsLinux, macOS, Windows
az network nsg list --output table -
Make a network security groupLinux, macOS, Windows
az network nsg create --name web-nsg --resource-group my-rg -
List a network security group's rulesLinux, macOS, Windows
az network nsg rule list --nsg-name web-nsg --resource-group my-rg --output table -
Allow a port in from one addressLinux, macOS, Windows
az network nsg rule create --nsg-name web-nsg --resource-group my-rg --name AllowHTTPS --priority 1010 --direction Inbound --access Allow --protocol Tcp --destination-port-ranges 443 --source-address-prefixes 203.0.113.10/32 -
Delete a ruleLinux, macOS, Windows
az network nsg rule delete --nsg-name web-nsg --resource-group my-rg --name AllowHTTPS -
Attach a network security group to a subnetLinux, macOS, Windows
az network vnet subnet update --name web --vnet-name my-vnet --resource-group my-rg --network-security-group web-nsg -
Allow SSH from your own public IP addressLinux, macOS
az network nsg rule create --nsg-name web-nsg --resource-group my-rg --name AllowMySSH --priority 100 --destination-port-ranges 22 --source-address-prefixes "$(curl -s https://api.ipify.org)/32" -
Show the rules that actually apply to a NICLinux, macOS, Windows
az network nic list-effective-nsg --name web-1VMNic --resource-group my-rg -
Show the routes that actually apply to a NICLinux, macOS, Windows
az network nic show-effective-route-table --name web-1VMNic --resource-group my-rg --output table -
List public IP addressesLinux, macOS, Windows
az network public-ip list --query "[].{Name:name, IP:ipAddress, AttachedTo:ipConfiguration.id}" --output table -
Make a static public IP addressLinux, macOS, Windows
az network public-ip create --name web-1-ip --resource-group my-rg --sku Standard --allocation-method Static -
Delete a public IP addressLinux, macOS, Windows
az network public-ip delete --name web-1-ip --resource-group my-rgWarning: The address goes back to Azure and you can't get the same one back.
-
List network interfacesLinux, macOS, Windows
az network nic list --output table -
Make a route table with a routeLinux, macOS, Windows
az network route-table create --name spoke-routes --resource-group my-rg az network route-table route create --route-table-name spoke-routes --resource-group my-rg --name to-firewall --address-prefix 203.0.113.10/32 --next-hop-type VirtualAppliance --next-hop-ip-address 10.0.0.4 -
Test whether traffic would be allowed to a VMLinux, macOS, Windows
az network watcher test-ip-flow --vm web-1 --resource-group my-rg --direction Inbound --protocol TCP --local 10.0.1.4:22 --remote 203.0.113.10:60000 -
List DNS zonesLinux, macOS, Windows
az network dns zone list --output table -
List the records in a DNS zoneLinux, macOS, Windows
az network dns record-set list --zone-name example.com --resource-group my-rg --output table -
Add an A recordLinux, macOS, Windows
az network dns record-set a add-record --zone-name example.com --resource-group my-rg --record-set-name www --ipv4-address 203.0.113.10 -
Add a CNAME recordLinux, macOS, Windows
az network dns record-set cname set-record --zone-name example.com --resource-group my-rg --record-set-name www --cname my-app.azurewebsites.net -
List private DNS zonesLinux, macOS, Windows
az network private-dns zone list --output table -
List private endpointsLinux, macOS, Windows
az network private-endpoint list --output table
Azure CLI: Storage
-
List storage accountsLinux, macOS, Windows
az storage account list --query "[].{Name:name, Group:resourceGroup, Kind:kind, Sku:sku.name}" --output table -
Make a storage accountLinux, macOS, Windows
az storage account create --name mystorageacct01 --resource-group my-rg --location westeurope --sku Standard_LRS --kind StorageV2 --min-tls-version TLS1_2 --allow-blob-public-access false -
Check whether a storage account name is freeLinux, macOS, Windows
az storage account check-name --name mystorageacct01 -
Turn off public blob access on an accountLinux, macOS, Windows
az storage account update --name mystorageacct01 --resource-group my-rg --allow-blob-public-access false -
Show a storage account's keysLinux, macOS, Windows
az storage account keys list --account-name mystorageacct01 --resource-group my-rg --output tableWarning: Prints a secret in plain text. Don't paste the output anywhere it could be saved or shared.
-
Show a storage account's connection stringLinux, macOS, Windows
az storage account show-connection-string --name mystorageacct01 --resource-group my-rg --output tsvWarning: Prints a secret in plain text. Don't paste the output anywhere it could be saved or shared.
-
Make a new key for a storage accountLinux, macOS, Windows
az storage account keys renew --account-name mystorageacct01 --resource-group my-rg --key primaryWarning: Anything still using the old key stops working straight away.
-
Make a blob container, signed in as yourselfLinux, macOS, Windows
az storage container create --name reports --account-name mystorageacct01 --auth-mode login -
List blob containersLinux, macOS, Windows
az storage container list --account-name mystorageacct01 --auth-mode login --output table -
List the files in a containerLinux, macOS, Windows
az storage blob list --container-name reports --account-name mystorageacct01 --auth-mode login --query "[].{Name:name, Size:properties.contentLength}" --output table -
Upload a fileLinux, macOS, Windows
az storage blob upload --container-name reports --account-name mystorageacct01 --auth-mode login --file report.csv --name 2026/report.csv -
Upload a file, replacing one that's thereLinux, macOS, Windows
az storage blob upload --container-name reports --account-name mystorageacct01 --auth-mode login --file report.csv --name 2026/report.csv --overwrite -
Download a fileLinux, macOS, Windows
az storage blob download --container-name reports --account-name mystorageacct01 --auth-mode login --name 2026/report.csv --file report.csv -
Upload a folderLinux, macOS, Windows
az storage blob upload-batch --destination reports --account-name mystorageacct01 --auth-mode login --source ./site -
Download a whole containerLinux, macOS, Windows
az storage blob download-batch --source reports --account-name mystorageacct01 --auth-mode login --destination ./site -
Delete a fileLinux, macOS, Windows
az storage blob delete --container-name reports --account-name mystorageacct01 --auth-mode login --name 2026/report.csvWarning: Deleted files can't be got back unless soft delete is on.
-
Delete every file that matches a patternLinux, macOS, Windows
az storage blob delete-batch --source reports --account-name mystorageacct01 --auth-mode login --pattern "logs/*.log"Warning: Deletes every match. Run it with --dryrun first.
-
Copy a file between accountsLinux, macOS, Windows
az storage blob copy start --destination-container reports --destination-blob 2026/report.csv --account-name mystorageacct01 --auth-mode login --source-uri https://otheracct.blob.core.windows.net/reports/2026/report.csv -
Make a read-only link to a file that expiresLinux, macOS, Windows
az storage blob generate-sas --container-name reports --account-name mystorageacct01 --name 2026/report.csv --permissions r --expiry 2026-12-31T23:59Z --auth-mode login --as-user --full-uriWarning: Anyone with the link can download the file until it expires.
-
Turn on soft delete for blobsLinux, macOS, Windows
az storage account blob-service-properties update --account-name mystorageacct01 --resource-group my-rg --enable-delete-retention true --delete-retention-days 14 -
Turn on static website hostingLinux, macOS, Windows
az storage blob service-properties update --account-name mystorageacct01 --auth-mode login --static-website --index-document index.html --404-document 404.html -
Make a file shareLinux, macOS, Windows
az storage share-rm create --name files --storage-account mystorageacct01 --resource-group my-rg --quota 128
Azure CLI: Entra ID and access control
-
Show who you're signed in asLinux, macOS, Windows
az ad signed-in-user show --query "{Name:displayName, UPN:userPrincipalName, Id:id}" -
Find a userLinux, macOS, Windows
az ad user list --filter "startswith(displayName, 'Alice')" --query "[].{Name:displayName, UPN:userPrincipalName}" --output table -
Show a userLinux, macOS, Windows
az ad user show --id [email protected] -
List a user's groupsLinux, macOS, Windows
az ad user get-member-groups --id [email protected] -
List groupsLinux, macOS, Windows
az ad group list --query "[].{Name:displayName, Id:id}" --output table -
List a group's membersLinux, macOS, Windows
az ad group member list --group "Cloud Admins" --query "[].userPrincipalName" --output tsv -
Add a user to a groupLinux, macOS, Windows
az ad group member add --group "Cloud Admins" --member-id 00000000-0000-0000-0000-000000000000 -
List app registrationsLinux, macOS, Windows
az ad app list --show-mine --query "[].{Name:displayName, AppId:appId}" --output table -
Find a service principalLinux, macOS, Windows
az ad sp list --display-name github-deploy --query "[].{Name:displayName, AppId:appId}" --output table -
Make a service principal with a role on a resource groupLinux, macOS, Windows
az ad sp create-for-rbac --name github-deploy --role Contributor --scopes /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/my-rgWarning: The output includes a client secret in plain text. Store it somewhere safe.
-
Give a service principal a new secretLinux, macOS, Windows
az ad sp credential reset --id 00000000-0000-0000-0000-000000000000Warning: Replaces the existing secret, so anything using it stops working. The new one is printed in plain text.
-
List role assignments in a resource groupLinux, macOS, Windows
az role assignment list --resource-group my-rg --output table -
List everything someone has access toLinux, macOS, Windows
az role assignment list --assignee [email protected] --all --output table -
Give someone a role on a resource groupLinux, macOS, Windows
az role assignment create --assignee [email protected] --role "Reader" --scope /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/my-rg -
Remove someone's roleLinux, macOS, Windows
az role assignment delete --assignee [email protected] --role "Reader" --resource-group my-rg -
List the built-in rolesLinux, macOS, Windows
az role definition list --query "[?roleType=='BuiltInRole'].roleName" --output tsv -
Show what a role allowsLinux, macOS, Windows
az role definition list --name "Reader" -
Show a managed identity's IDsLinux, macOS, Windows
az identity show --name my-identity --resource-group my-rg --query "{ClientId:clientId, PrincipalId:principalId}"
Azure CLI: Key Vault
-
List key vaultsLinux, macOS, Windows
az keyvault list --output table -
Make a key vault that uses Azure roles for accessLinux, macOS, Windows
az keyvault create --name my-vault --resource-group my-rg --location westeurope --enable-rbac-authorization true -
List the secrets in a vaultLinux, macOS, Windows
az keyvault secret list --vault-name my-vault --query "[].name" --output tsv -
Read a secretLinux, macOS, Windows
az keyvault secret show --vault-name my-vault --name db-password --query value --output tsvWarning: Prints a secret in plain text. Don't paste the output anywhere it could be saved or shared.
-
Save a secret from a fileLinux, macOS, Windows
az keyvault secret set --vault-name my-vault --name db-password --file report.csv -
Save a secretLinux, macOS, Windows
az keyvault secret set --vault-name my-vault --name db-password --value "MyPassword"Warning: The value ends up in your shell history. Use --file to avoid that.
-
Delete a secretLinux, macOS, Windows
az keyvault secret delete --vault-name my-vault --name db-password -
List deleted secrets you can still get backLinux, macOS, Windows
az keyvault secret list-deleted --vault-name my-vault --output table -
Get a deleted secret backLinux, macOS, Windows
az keyvault secret recover --vault-name my-vault --name db-password -
Make a keyLinux, macOS, Windows
az keyvault key create --vault-name my-vault --name my-key --kty RSA --size 3072 -
List certificates in a vaultLinux, macOS, Windows
az keyvault certificate list --vault-name my-vault --output table -
List deleted vaults you can still get backLinux, macOS, Windows
az keyvault list-deleted --output table -
Get a deleted vault backLinux, macOS, Windows
az keyvault recover --name my-vault
Azure CLI: App Service and Functions
-
List web appsLinux, macOS, Windows
az webapp list --query "[].{Name:name, Group:resourceGroup, State:state, Host:defaultHostName}" --output table -
List the runtimes you can useLinux, macOS, Windows
az webapp list-runtimes --os linux --output table -
Make an App Service planLinux, macOS, Windows
az appservice plan create --name my-plan --resource-group my-rg --sku B1 --is-linux -
Make a web app in a planLinux, macOS, Windows
az webapp create --name my-webapp --resource-group my-rg --plan my-plan --runtime "NODE:22-lts" -
Deploy a zip file to a web appLinux, macOS, Windows
az webapp deploy --name my-webapp --resource-group my-rg --src-path app.zip --type zip -
Follow a web app's logs liveLinux, macOS, Windows
az webapp log tail --name my-webapp --resource-group my-rg -
Turn on application loggingLinux, macOS, Windows
az webapp log config --name my-webapp --resource-group my-rg --application-logging filesystem --level information -
Restart a web appLinux, macOS, Windows
az webapp restart --name my-webapp --resource-group my-rg -
Stop a web appLinux, macOS, Windows
az webapp stop --name my-webapp --resource-group my-rg -
List a web app's settingsLinux, macOS, Windows
az webapp config appsettings list --name my-webapp --resource-group my-rg --output tableWarning: Settings often hold secrets, and they're shown in plain text.
-
Change a web app settingLinux, macOS, Windows
az webapp config appsettings set --name my-webapp --resource-group my-rg --settings LOG_LEVEL=debug -
Only allow HTTPS to a web appLinux, macOS, Windows
az webapp update --name my-webapp --resource-group my-rg --https-only true -
List deployment slotsLinux, macOS, Windows
az webapp deployment slot list --name my-webapp --resource-group my-rg --output table -
Swap a staging slot into productionLinux, macOS, Windows
az webapp deployment slot swap --name my-webapp --resource-group my-rg --slot staging --target-slot production -
Add a custom domain to a web appLinux, macOS, Windows
az webapp config hostname add --webapp-name my-webapp --resource-group my-rg --hostname SW1 -
List function appsLinux, macOS, Windows
az functionapp list --query "[].{Name:name, Group:resourceGroup, State:state}" --output table -
Make a function app on the Flex Consumption planLinux, macOS, Windows
az functionapp create --name my-func --resource-group my-rg --storage-account mystorageacct01 --flexconsumption-location westeurope --runtime python --runtime-version 3.12 -
Deploy a zip file to a function appLinux, macOS, Windows
az functionapp deployment source config-zip --name my-func --resource-group my-rg --src app.zip -
List the functions in an appLinux, macOS, Windows
az functionapp function list --name my-func --resource-group my-rg --output table -
Change a function app settingLinux, macOS, Windows
az functionapp config appsettings set --name my-func --resource-group my-rg --settings LOG_LEVEL=debug
Azure CLI: Containers: ACR, AKS, ACI and Container Apps
-
List container registriesLinux, macOS, Windows
az acr list --output table -
Make a container registryLinux, macOS, Windows
az acr create --name myregistry --resource-group my-rg --sku Basic -
Sign Docker in to a registryLinux, macOS, Windows
az acr login --name myregistry -
Build an image in Azure and push it, no Docker neededLinux, macOS, Windows
az acr build --registry myregistry --image my-app:v1 . -
List the repositories in a registryLinux, macOS, Windows
az acr repository list --name myregistry --output table -
List an image's tags, newest firstLinux, macOS, Windows
az acr repository show-tags --name myregistry --repository my-app --orderby time_desc --output table -
Delete an image tagLinux, macOS, Windows
az acr repository delete --name myregistry --image my-app:v1 --yesWarning: Deletes the image with no undo.
-
List AKS clustersLinux, macOS, Windows
az aks list --query "[].{Name:name, Group:resourceGroup, Version:kubernetesVersion, State:powerState.code}" --output table -
Set up kubectl for an AKS clusterLinux, macOS, Windows
az aks get-credentials --name my-aks --resource-group my-rg -
Install kubectl and kubeloginLinux, macOS, Windows
az aks install-cli -
Make an AKS clusterLinux, macOS, Windows
az aks create --name my-aks --resource-group my-rg --node-count 2 --generate-ssh-keys --enable-managed-identity -
Let an AKS cluster pull from a registryLinux, macOS, Windows
az aks update --name my-aks --resource-group my-rg --attach-acr myregistry -
Scale an AKS node poolLinux, macOS, Windows
az aks scale --name my-aks --resource-group my-rg --nodepool-name nodepool1 --node-count 3 -
List an AKS cluster's node poolsLinux, macOS, Windows
az aks nodepool list --cluster-name my-aks --resource-group my-rg --output table -
Show the versions an AKS cluster can upgrade toLinux, macOS, Windows
az aks get-upgrades --name my-aks --resource-group my-rg --output table -
Upgrade an AKS clusterLinux, macOS, Windows
az aks upgrade --name my-aks --resource-group my-rg --kubernetes-version 1.33.2Warning: Nodes are drained and replaced one by one. You can't go back to an older version.
-
Stop an AKS cluster to save moneyLinux, macOS, Windows
az aks stop --name my-aks --resource-group my-rg -
Start an AKS clusterLinux, macOS, Windows
az aks start --name my-aks --resource-group my-rg -
Run a kubectl command on a private AKS clusterLinux, macOS, Windows
az aks command invoke --name my-aks --resource-group my-rg --command "kubectl get pods -A" -
Run a container instanceLinux, macOS, Windows
az container create --name my-aci --resource-group my-rg --image nginx:latest --os-type Linux --cpu 1 --memory 1.5 --ports 80 --ip-address Public -
Show a container instance's logsLinux, macOS, Windows
az container logs --name my-aci --resource-group my-rg -
Open a shell in a container instanceLinux, macOS, Windows
az container exec --name my-aci --resource-group my-rg --exec-command "/bin/sh" -
List container appsLinux, macOS, Windows
az containerapp list --output table -
Update a container app to a new imageLinux, macOS, Windows
az containerapp update --name my-containerapp --resource-group my-rg --image myregistry.azurecr.io/my-app:v1 -
Follow a container app's logsLinux, macOS, Windows
az containerapp logs show --name my-containerapp --resource-group my-rg --follow -
Open a shell in a container appLinux, macOS, Windows
az containerapp exec --name my-containerapp --resource-group my-rg --command "/bin/sh"
Azure CLI: Databases
-
List Azure SQL serversLinux, macOS, Windows
az sql server list --output table -
List the databases on a SQL serverLinux, macOS, Windows
az sql db list --server my-sqlserver --resource-group my-rg --output table -
Let your IP address through a SQL server's firewallLinux, macOS, Windows
az sql server firewall-rule create --server my-sqlserver --resource-group my-rg --name AllowHTTPS --start-ip-address 203.0.113.10 --end-ip-address 203.0.113.10 -
Show a SQL database's connection stringLinux, macOS, Windows
az sql db show-connection-string --server my-sqlserver --name appdb --client ado.net -
List PostgreSQL flexible serversLinux, macOS, Windows
az postgres flexible-server list --output table -
Let your IP address through a PostgreSQL server's firewallLinux, macOS, Windows
az postgres flexible-server firewall-rule create --server-name my-postgres --resource-group my-rg --name AllowHTTPS --start-ip-address 203.0.113.10 -
Stop a PostgreSQL flexible serverLinux, macOS, Windows
az postgres flexible-server stop --name my-postgres --resource-group my-rgWarning: Azure starts a stopped server again by itself after 7 days.
-
Start a PostgreSQL flexible serverLinux, macOS, Windows
az postgres flexible-server start --name my-postgres --resource-group my-rg -
List MySQL flexible serversLinux, macOS, Windows
az mysql flexible-server list --output table -
List Cosmos DB accountsLinux, macOS, Windows
az cosmosdb list --query "[].{Name:name, Group:resourceGroup, Kind:kind}" --output table -
List Redis cachesLinux, macOS, Windows
az redis list --output table
Azure CLI: Monitoring and logs
-
Show the last day of changes in a resource groupLinux, macOS, Windows
az monitor activity-log list --resource-group my-rg --offset 1d --query "[].{Time:eventTimestamp, Who:caller, What:operationName.localizedValue, Status:status.value}" --output table -
Find who deleted somethingLinux, macOS, Windows
az monitor activity-log list --offset 7d --query "[?contains(operationName.value, 'delete')].{Time:eventTimestamp, Who:caller, Resource:resourceId}" --output table -
List the metrics a resource hasLinux, macOS, Windows
az monitor metrics list-definitions --resource /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/my-rg/providers/Microsoft.Compute/virtualMachines/web-1 --query "[].name.value" --output tsv -
Show a VM's CPU over the last hourLinux, macOS, Windows
az monitor metrics list --resource /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/my-rg/providers/Microsoft.Compute/virtualMachines/web-1 --metric "Percentage CPU" --interval PT5M --offset 1h --output table -
List metric alertsLinux, macOS, Windows
az monitor metrics alert list --output table -
Make an alert for high CPULinux, macOS, Windows
az monitor metrics alert create --name web-1-high-cpu --resource-group my-rg --scopes /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/my-rg/providers/Microsoft.Compute/virtualMachines/web-1 --condition "avg Percentage CPU > 80" --window-size 5m --evaluation-frequency 1m --action ops-team -
List action groupsLinux, macOS, Windows
az monitor action-group list --output table -
List Log Analytics workspacesLinux, macOS, Windows
az monitor log-analytics workspace list --output table -
Run a KQL query on a Log Analytics workspace (log-analytics extension)Linux, macOS, Windows
az monitor log-analytics query --workspace 00000000-0000-0000-0000-000000000000 --analytics-query "Heartbeat | summarize count() by Computer" --output table -
List a resource's diagnostic settingsLinux, macOS, Windows
az monitor diagnostic-settings list --resource /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/my-rg/providers/Microsoft.Compute/virtualMachines/web-1 -
Show Azure Advisor recommendationsLinux, macOS, Windows
az advisor recommendation list --query "[].{Category:category, Impact:impact, Problem:shortDescription.problem}" --output table
Azure CLI: Deployments: ARM and Bicep
-
Install or update BicepLinux, macOS, Windows
az bicep install -
Show the Bicep versionLinux, macOS, Windows
az bicep version -
Check a Bicep file for mistakes and build it to ARM JSONLinux, macOS, Windows
az bicep build --file main.bicep -
Turn an ARM template into BicepLinux, macOS, Windows
az bicep decompile --file template.json -
Check a deployment would work, without deployingLinux, macOS, Windows
az deployment group validate --resource-group my-rg --template-file main.bicep -
See what a deployment would changeLinux, macOS, Windows
az deployment group what-if --resource-group my-rg --template-file main.bicep -
Deploy a Bicep or ARM file to a resource groupLinux, macOS, Windows
az deployment group create --resource-group my-rg --template-file main.bicep -
Deploy with a parameters fileLinux, macOS, Windows
az deployment group create --resource-group my-rg --template-file main.bicep --parameters main.bicepparam -
Deploy and set one parameterLinux, macOS, Windows
az deployment group create --resource-group my-rg --template-file main.bicep --parameters environment=prod -
Deploy to a subscription, to make resource groups or policiesLinux, macOS, Windows
az deployment sub create --location westeurope --template-file main.bicep -
List deployments in a resource groupLinux, macOS, Windows
az deployment group list --resource-group my-rg --query "[].{Name:name, State:properties.provisioningState, Time:properties.timestamp}" --output table -
Show what went wrong in a deploymentLinux, macOS, Windows
az deployment operation group list --resource-group my-rg --name main --query "[?properties.provisioningState=='Failed'].properties.statusMessage" -
Show a deployment's outputsLinux, macOS, Windows
az deployment group show --resource-group my-rg --name main --query properties.outputs -
Deploy a deployment stack that deletes resources you remove from the fileLinux, macOS, Windows
az stack group create --name main --resource-group my-rg --template-file main.bicep --action-on-unmanage deleteResources --deny-settings-mode noneWarning: Resources you take out of the file are deleted on the next deploy.
Azure CLI: Policy, cost and Resource Graph
-
List policy assignmentsLinux, macOS, Windows
az policy assignment list --query "[].{Name:displayName, Scope:scope}" --output table -
Show how many resources break each policyLinux, macOS, Windows
az policy state summarize --query "policyAssignments[].{Policy:policyAssignmentId, NonCompliant:results.nonCompliantResources}" -
List resources that break policyLinux, macOS, Windows
az policy state list --filter "complianceState eq 'NonCompliant'" --query "[].{Resource:resourceId, Policy:policyDefinitionName}" --output table -
Assign a built-in policy to a resource groupLinux, macOS, Windows
az policy assignment create --name require-tags --policy 871b6d14-10aa-478d-b590-94f262ecfa99 --scope /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/my-rg -
Show your spend on each resource between two datesLinux, macOS, Windows
az consumption usage list --start-date 2026-11-01 --end-date 2026-11-30 --query "[].{Resource:instanceName, Cost:pretaxCost, Currency:currency}" --output table -
List your budgetsLinux, macOS, Windows
az consumption budget list --output table -
Make a monthly budgetLinux, macOS, Windows
az consumption budget create --budget-name monthly --amount 100 --category cost --time-grain monthly --start-date 2026-11-01 --end-date 2027-11-01 -
Search every resource you can see with KQL (resource-graph extension)Linux, macOS, Windows
az graph query --graph-query "Resources | summarize count() by type | order by count_ desc" --output table -
Find unattached disks across every subscription (resource-graph extension)Linux, macOS, Windows
az graph query --graph-query "Resources | where type =~ 'microsoft.compute/disks' and properties.diskState == 'Unattached' | project name, resourceGroup, sku.name" --output table -
Find VMs across every subscription (resource-graph extension)Linux, macOS, Windows
az graph query --graph-query "Resources | where type =~ 'microsoft.compute/virtualmachines' | project name, resourceGroup, location" --output table
Azure CLI: Troubleshooting
-
Show every request and response, to debug a commandLinux, macOS, Windows
az vm list --debugWarning: The debug output includes your access token. Check it before you share it.
-
Show more detail about what a command is doingLinux, macOS, Windows
az vm list --verbose -
Call any Azure REST API directlyLinux, macOS, Windows
az rest --method get --url "https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/resourcegroups?api-version=2021-04-01" -
Call Microsoft Graph directlyLinux, macOS, Windows
az rest --method get --url "https://graph.microsoft.com/v1.0/me" -
Clear the CLI's cache of resourcesLinux, macOS, Windows
az cache purge -
Fix sign-in problems by signing in again from scratchLinux, macOS, Windows
az account clear az login -
Turn off the CLI's usage dataLinux, macOS, Windows
az config set core.collect_telemetry=false -
Find the CLI's config and log folderLinux, macOS
echo ~/.azure -
Send a command through a proxyLinux, macOS
export HTTPS_PROXY=http://proxy.example.com:8080Windows$env:HTTPS_PROXY = "http://proxy.example.com:8080"
Google Cloud CLI: Setup and help
-
Show the gcloud version and installed componentsLinux, macOS, Windows
gcloud version -
Update gcloud and its componentsLinux, macOS, Windows
gcloud components update -
List components you can installLinux, macOS, Windows
gcloud components list -
Install kubectl and the GKE sign-in pluginLinux, macOS, Windows
gcloud components install kubectl gke-gcloud-auth-plugin -
Install the beta commandsLinux, macOS, Windows
gcloud components install beta -
Get help for a command, with examplesLinux, macOS, Windows
gcloud compute instances create --help -
Search the help for a wordLinux, macOS, Windows
gcloud help -- snapshot -
Show a cheat sheet of common commandsLinux, macOS, Windows
gcloud cheat-sheet -
Show where gcloud is installed and which settings it's usingLinux, macOS, Windows
gcloud info
Google Cloud CLI: Sign in and configurations
-
Sign in in the browserLinux, macOS, Windows
gcloud auth login -
Sign in on a machine with no browserLinux, macOS, Windows
gcloud auth login --no-browser -
Sign in for apps, SDKs and Terraform on this machineLinux, macOS, Windows
gcloud auth application-default login -
Sign in as a service account with a key fileLinux, macOS, Windows
gcloud auth activate-service-account --key-file=sa-key.jsonWarning: Key files are long-lived secrets. Prefer impersonation or workload identity where you can.
-
List the accounts you've signed in with, and which one is activeLinux, macOS, Windows
gcloud auth list -
Switch to another signed-in accountLinux, macOS, Windows
gcloud config set account [email protected] -
Sign out of an accountLinux, macOS, Windows
gcloud auth revoke [email protected] -
Print an access token for the Google Cloud APIsLinux, macOS, Windows
gcloud auth print-access-tokenWarning: Prints a secret in plain text. Don't paste the output anywhere it could be saved or shared.
-
Run one command as a service account, without a keyLinux, macOS, Windows
gcloud storage ls --impersonate-service-account=deployer@my-project.iam.gserviceaccount.com -
Show your current settings: account, project, region and zoneLinux, macOS, Windows
gcloud config list -
Set the default projectLinux, macOS, Windows
gcloud config set project my-project -
Set the default regionLinux, macOS, Windows
gcloud config set compute/region europe-west1 -
Set the default zoneLinux, macOS, Windows
gcloud config set compute/zone europe-west1-b -
Clear the default zoneLinux, macOS, Windows
gcloud config unset compute/zone -
Make a named configuration, such as one per client or projectLinux, macOS, Windows
gcloud config configurations create client-a -
List configurationsLinux, macOS, Windows
gcloud config configurations list -
Switch to another configurationLinux, macOS, Windows
gcloud config configurations activate client-a -
Run one command in another projectLinux, macOS, Windows
gcloud compute instances list --project=my-project -
Use a project for every command in this terminalLinux, macOS
export CLOUDSDK_CORE_PROJECT=my-projectWindows$env:CLOUDSDK_CORE_PROJECT = "my-project" -
Answer yes to every prompt, for scriptsLinux, macOS, Windows
gcloud compute instances delete web-1 --zone=europe-west1-b --quietWarning: --quiet skips the "are you sure" prompt, so this deletes the instance straight away.
Google Cloud CLI: Output, filters and formats
-
Show only some columns in a tableLinux, macOS, Windows
gcloud compute instances list --format="table(name, zone.basename(), status, networkInterfaces[0].networkIP)" -
Show output as JSONLinux, macOS, Windows
gcloud compute instances list --format=json -
Show output as YAMLLinux, macOS, Windows
gcloud compute instances describe web-1 --zone=europe-west1-b --format=yaml -
Get one value for a scriptLinux, macOS, Windows
gcloud config get-value project -
Print just the names, one per lineLinux, macOS, Windows
gcloud compute instances list --format="value(name)" -
Save a value in a variableLinux, macOS
ip=$(gcloud compute instances describe web-1 --zone=europe-west1-b --format="value(networkInterfaces[0].accessConfigs[0].natIP)")Windows$ip = gcloud compute instances describe web-1 --zone=europe-west1-b --format="value(networkInterfaces[0].accessConfigs[0].natIP)" -
Show output as CSVLinux, macOS, Windows
gcloud compute instances list --format="csv(name, zone.basename(), status)" -
Filter the resultsLinux, macOS, Windows
gcloud compute instances list --filter="status=RUNNING" -
Filter by a name that contains some textLinux, macOS, Windows
gcloud compute instances list --filter="name:web" -
Filter by labelLinux, macOS, Windows
gcloud compute instances list --filter="labels.env=prod" -
Combine filtersLinux, macOS, Windows
gcloud compute instances list --filter="status=RUNNING AND zone:europe-west1" -
Sort the resultsLinux, macOS, Windows
gcloud compute instances list --sort-by=~creationTimestamp -
Show only the first few resultsLinux, macOS, Windows
gcloud compute instances list --limit=10 -
Show every field as key and value, for finding a field's nameLinux, macOS, Windows
gcloud compute instances describe web-1 --zone=europe-west1-b --format=flattened
Google Cloud CLI: Projects, APIs and IAM
-
List your projectsLinux, macOS, Windows
gcloud projects list -
Show a projectLinux, macOS, Windows
gcloud projects describe my-project -
Make a projectLinux, macOS, Windows
gcloud projects create my-project --name="My Project" -
Delete a projectLinux, macOS, Windows
gcloud projects delete my-projectWarning: Shuts down everything in the project. You have 30 days to undelete it before it's gone for good.
-
Undelete a projectLinux, macOS, Windows
gcloud projects undelete my-project -
Link a project to a billing accountLinux, macOS, Windows
gcloud billing projects link my-project --billing-account=0X0X0X-0X0X0X-0X0X0X -
List the APIs turned on in a projectLinux, macOS, Windows
gcloud services list --enabled -
Turn on an APILinux, macOS, Windows
gcloud services enable compute.googleapis.com -
Turn off an APILinux, macOS, Windows
gcloud services disable compute.googleapis.comWarning: Anything using the API stops working.
-
List your organisationsLinux, macOS, Windows
gcloud organizations list -
List the folders in an organisationLinux, macOS, Windows
gcloud resource-manager folders list --organization=123456789012 -
Show who has which role in a projectLinux, macOS, Windows
gcloud projects get-iam-policy my-project --flatten="bindings[].members" --format="table(bindings.role, bindings.members)" -
Show the roles one person has in a projectLinux, macOS, Windows
gcloud projects get-iam-policy my-project --flatten="bindings[].members" --filter="bindings.members:[email protected]" --format="value(bindings.role)" -
Give someone a role in a projectLinux, macOS, Windows
gcloud projects add-iam-policy-binding my-project --member="user:[email protected]" --role=roles/viewer -
Remove someone's role in a projectLinux, macOS, Windows
gcloud projects remove-iam-policy-binding my-project --member="user:[email protected]" --role=roles/viewer -
List the predefined rolesLinux, macOS, Windows
gcloud iam roles list --format="table(name, title)" -
Show the permissions in a roleLinux, macOS, Windows
gcloud iam roles describe roles/viewer -
Find every resource in a projectLinux, macOS, Windows
gcloud asset search-all-resources --scope=projects/my-project --format="table(assetType, displayName, location)"
Google Cloud CLI: Compute Engine VMs
-
List VMsLinux, macOS, Windows
gcloud compute instances list -
Show everything about a VMLinux, macOS, Windows
gcloud compute instances describe web-1 --zone=europe-west1-b -
Show a VM's external IP addressLinux, macOS, Windows
gcloud compute instances describe web-1 --zone=europe-west1-b --format="value(networkInterfaces[0].accessConfigs[0].natIP)" -
Make a Debian VMLinux, macOS, Windows
gcloud compute instances create web-1 --zone=europe-west1-b --machine-type=e2-small --image-family=debian-12 --image-project=debian-cloud -
Make an Ubuntu VM with no external IP addressLinux, macOS, Windows
gcloud compute instances create web-1 --zone=europe-west1-b --machine-type=e2-small --image-family=ubuntu-2404-lts-amd64 --image-project=ubuntu-os-cloud --no-address -
Make a Spot VM, cheaper but can be stopped at any timeLinux, macOS, Windows
gcloud compute instances create web-1 --zone=europe-west1-b --machine-type=e2-small --provisioning-model=SPOT --instance-termination-action=STOP -
Make a VM with a start-up scriptLinux, macOS, Windows
gcloud compute instances create web-1 --zone=europe-west1-b --metadata-from-file=startup-script=startup.sh -
Start a VMLinux, macOS, Windows
gcloud compute instances start web-1 --zone=europe-west1-b -
Stop a VMLinux, macOS, Windows
gcloud compute instances stop web-1 --zone=europe-west1-b -
Restart a VM straight away, like pulling the plugLinux, macOS, Windows
gcloud compute instances reset web-1 --zone=europe-west1-b -
Delete a VMLinux, macOS, Windows
gcloud compute instances delete web-1 --zone=europe-west1-bWarning: Deletes the VM and its boot disk, with no undo. Other disks are kept unless they were set to auto-delete.
-
Delete a VM but keep its disksLinux, macOS, Windows
gcloud compute instances delete web-1 --zone=europe-west1-b --keep-disks=all -
Change a VM's machine type (stop it first)Linux, macOS, Windows
gcloud compute instances set-machine-type web-1 --zone=europe-west1-b --machine-type=e2-standard-2 -
SSH in to a VMLinux, macOS, Windows
gcloud compute ssh web-1 --zone=europe-west1-b -
SSH in to a VM with no external IP, through IAPLinux, macOS, Windows
gcloud compute ssh web-1 --zone=europe-west1-b --tunnel-through-iap -
Run one command on a VM over SSHLinux, macOS, Windows
gcloud compute ssh web-1 --zone=europe-west1-b --command="uptime" -
Copy a file to a VMLinux, macOS, Windows
gcloud compute scp report.csv web-1:~/ --zone=europe-west1-b -
Copy a file from a VMLinux, macOS, Windows
gcloud compute scp web-1:~/report.csv . --zone=europe-west1-b -
Forward a port from a VM to your machine, through IAPLinux, macOS, Windows
gcloud compute start-iap-tunnel web-1 3389 --local-host-port=localhost:13389 --zone=europe-west1-b -
Show a VM's serial console output, to debug a bootLinux, macOS, Windows
gcloud compute instances get-serial-port-output web-1 --zone=europe-west1-b -
Add or change a labelLinux, macOS, Windows
gcloud compute instances add-labels web-1 --zone=europe-west1-b --labels=env=prod -
Change a VM's start-up scriptLinux, macOS, Windows
gcloud compute instances add-metadata web-1 --zone=europe-west1-b --metadata-from-file=startup-script=startup.sh -
Turn on OS Login for a projectLinux, macOS, Windows
gcloud compute project-info add-metadata --metadata=enable-oslogin=TRUE -
List the machine types in a zoneLinux, macOS, Windows
gcloud compute machine-types list --filter="zone:europe-west1-b" -
List public images from a familyLinux, macOS, Windows
gcloud compute images list --filter="family:debian" -
List your own imagesLinux, macOS, Windows
gcloud compute images list --no-standard-images -
Make an image from a VM's diskLinux, macOS, Windows
gcloud compute images create web-1-image --source-disk=web-1-data --source-disk-zone=europe-west1-b -
List zones and regionsLinux, macOS, Windows
gcloud compute zones list
Google Cloud CLI: Disks and snapshots
-
List disksLinux, macOS, Windows
gcloud compute disks list -
List disks that aren't attached to anythingLinux, macOS, Windows
gcloud compute disks list --filter="-users:*" -
Make a diskLinux, macOS, Windows
gcloud compute disks create web-1-data --zone=europe-west1-b --size=200GB --type=pd-balanced -
Attach a disk to a VMLinux, macOS, Windows
gcloud compute instances attach-disk web-1 --zone=europe-west1-b --disk=web-1-data -
Detach a diskLinux, macOS, Windows
gcloud compute instances detach-disk web-1 --zone=europe-west1-b --disk=web-1-data -
Make a disk biggerLinux, macOS, Windows
gcloud compute disks resize web-1-data --zone=europe-west1-b --size=200GBWarning: Disks can only grow. You'll also need to grow the file system inside the VM.
-
Take a snapshot of a diskLinux, macOS, Windows
gcloud compute snapshots create web-1-data-snap --source-disk=web-1-data --source-disk-zone=europe-west1-b -
List snapshotsLinux, macOS, Windows
gcloud compute snapshots list -
Make a disk from a snapshotLinux, macOS, Windows
gcloud compute disks create web-1-data --zone=europe-west1-b --source-snapshot=web-1-data-snap -
Delete a diskLinux, macOS, Windows
gcloud compute disks delete web-1-data --zone=europe-west1-bWarning: The data is gone for good unless you have a snapshot.
-
Delete a snapshotLinux, macOS, Windows
gcloud compute snapshots delete web-1-data-snapWarning: Deleted snapshots can't be got back.
Google Cloud CLI: VPC networking
-
List VPC networksLinux, macOS, Windows
gcloud compute networks list -
Make a VPC network with custom subnetsLinux, macOS, Windows
gcloud compute networks create my-vpc --subnet-mode=custom -
List subnetsLinux, macOS, Windows
gcloud compute networks subnets list -
Make a subnetLinux, macOS, Windows
gcloud compute networks subnets create web --network=my-vpc --region=europe-west1 --range=10.10.0.0/24 -
Let VMs with no external IP reach Google APIsLinux, macOS, Windows
gcloud compute networks subnets update web --region=europe-west1 --enable-private-ip-google-access -
List firewall rulesLinux, macOS, Windows
gcloud compute firewall-rules list -
Allow a port in from one addressLinux, macOS, Windows
gcloud compute firewall-rules create allow-https --network=my-vpc --allow=tcp:443 --source-ranges=203.0.113.10/32 -
Allow a port in to VMs with a network tagLinux, macOS, Windows
gcloud compute firewall-rules create allow-https --network=my-vpc --allow=tcp:443 --source-ranges=0.0.0.0/0 --target-tags=web -
Allow SSH through IAP onlyLinux, macOS, Windows
gcloud compute firewall-rules create allow-iap-ssh --network=my-vpc --allow=tcp:22 --source-ranges=35.235.240.0/20 -
Allow SSH from your own public IP addressLinux, macOS
gcloud compute firewall-rules create allow-my-ssh --network=my-vpc --allow=tcp:22 --source-ranges="$(curl -s https://ifconfig.me)/32" -
Delete a firewall ruleLinux, macOS, Windows
gcloud compute firewall-rules delete allow-https -
Add a network tag to a VMLinux, macOS, Windows
gcloud compute instances add-tags web-1 --zone=europe-west1-b --tags=web -
Reserve a static external IP addressLinux, macOS, Windows
gcloud compute addresses create web-ip --region=europe-west1 -
List reserved IP addresses, including unused ones you're paying forLinux, macOS, Windows
gcloud compute addresses list -
Release a static IP addressLinux, macOS, Windows
gcloud compute addresses delete web-ip --region=europe-west1Warning: The address goes back to Google and you can't get the same one back.
-
Give private VMs internet access with Cloud NATLinux, macOS, Windows
gcloud compute routers create my-router --network=my-vpc --region=europe-west1 gcloud compute routers nats create my-nat --router=my-router --region=europe-west1 --auto-allocate-nat-external-ips --nat-all-subnet-ip-ranges -
List routesLinux, macOS, Windows
gcloud compute routes list -
List Cloud DNS zonesLinux, macOS, Windows
gcloud dns managed-zones list -
List the records in a DNS zoneLinux, macOS, Windows
gcloud dns record-sets list --zone=example-com -
Add an A recordLinux, macOS, Windows
gcloud dns record-sets create www.example.com. --zone=example-com --type=A --ttl=300 --rrdatas=203.0.113.10
Google Cloud CLI: Cloud Storage
-
List your bucketsLinux, macOS, Windows
gcloud storage ls -
List the files in a bucketLinux, macOS, Windows
gcloud storage ls gs://my-bucket -
List every file in a bucket, with sizesLinux, macOS, Windows
gcloud storage ls --long --recursive gs://my-bucket -
Show how much space a bucket usesLinux, macOS, Windows
gcloud storage du --summarize --readable-sizes gs://my-bucket -
Make a bucketLinux, macOS, Windows
gcloud storage buckets create gs://my-bucket --location=europe-west1 --uniform-bucket-level-access --public-access-prevention -
Upload a fileLinux, macOS, Windows
gcloud storage cp report.csv gs://my-bucket/reports/2026.csv -
Download a fileLinux, macOS, Windows
gcloud storage cp gs://my-bucket/reports/2026.csv report.csv -
Upload a folderLinux, macOS, Windows
gcloud storage cp --recursive ./site gs://my-bucket/ -
Print a file to the screenLinux, macOS, Windows
gcloud storage cat gs://my-bucket/reports/2026.csv -
Rename or move a fileLinux, macOS, Windows
gcloud storage mv gs://my-bucket/reports/2026.csv gs://my-bucket/archive/2026.csv -
Sync a folder up to a bucket, copying only what changedLinux, macOS, Windows
gcloud storage rsync --recursive ./site gs://my-bucket/site/ -
Sync and delete files in the bucket that aren't in the folderLinux, macOS, Windows
gcloud storage rsync --recursive --delete-unmatched-destination-objects ./site gs://my-bucket/site/Warning: Deletes files from the bucket. Run it with --dry-run first to see what it would remove.
-
Delete a fileLinux, macOS, Windows
gcloud storage rm gs://my-bucket/reports/2026.csvWarning: Deleted files can't be got back unless versioning or soft delete is on.
-
Delete everything under a folder in a bucketLinux, macOS, Windows
gcloud storage rm --recursive gs://my-bucket/site/Warning: Deletes every file under that prefix, with no prompt.
-
Delete a bucket and everything in itLinux, macOS, Windows
gcloud storage rm --recursive gs://my-bucketWarning: Deletes every file and then the bucket, with no undo.
-
Show a bucket's settingsLinux, macOS, Windows
gcloud storage buckets describe gs://my-bucket -
Turn on versioning for a bucketLinux, macOS, Windows
gcloud storage buckets update gs://my-bucket --versioning -
List every version of a fileLinux, macOS, Windows
gcloud storage ls --all-versions gs://my-bucket/reports/2026.csv -
Make a download link that expires in an hourLinux, macOS, Windows
gcloud storage sign-url gs://my-bucket/reports/2026.csv --duration=1h --impersonate-service-account=deployer@my-project.iam.gserviceaccount.comWarning: Anyone with the link can download the file until it expires.
-
Give someone read access to a bucketLinux, macOS, Windows
gcloud storage buckets add-iam-policy-binding gs://my-bucket --member="user:[email protected]" --role=roles/storage.objectViewer -
Delete files after 30 daysLinux, macOS, Windows
gcloud storage buckets update gs://my-bucket --lifecycle-file=lifecycle.json
Google Cloud CLI: Service accounts
-
List service accountsLinux, macOS, Windows
gcloud iam service-accounts list -
Make a service accountLinux, macOS, Windows
gcloud iam service-accounts create deployer --display-name="GitHub deployer" -
Give a service account a role in the projectLinux, macOS, Windows
gcloud projects add-iam-policy-binding my-project --member="serviceAccount:[email protected]" --role=roles/viewer -
Let someone act as a service accountLinux, macOS, Windows
gcloud iam service-accounts add-iam-policy-binding [email protected] --member="user:[email protected]" --role=roles/iam.serviceAccountTokenCreator -
List a service account's keysLinux, macOS, Windows
gcloud iam service-accounts keys list [email protected] -
Make a key file for a service accountLinux, macOS, Windows
gcloud iam service-accounts keys create sa-key.json [email protected]Warning: The key file is a long-lived secret. Prefer impersonation or workload identity where you can.
-
Delete a service account keyLinux, macOS, Windows
gcloud iam service-accounts keys delete 1234567890abcdef1234567890abcdef12345678 [email protected]Warning: Anything still using the key stops working straight away.
-
Turn off a service accountLinux, macOS, Windows
gcloud iam service-accounts disable [email protected] -
Delete a service accountLinux, macOS, Windows
gcloud iam service-accounts delete [email protected]Warning: Anything running as it loses access. You have 30 days to undelete it.
Google Cloud CLI: Secret Manager and KMS
-
List secretsLinux, macOS, Windows
gcloud secrets list -
Make a secret from a fileLinux, macOS, Windows
gcloud secrets create db-password --data-file=report.csv -
Read the latest version of a secretLinux, macOS, Windows
gcloud secrets versions access latest --secret=db-passwordWarning: Prints a secret in plain text. Don't paste the output anywhere it could be saved or shared.
-
Add a new version of a secret from a fileLinux, macOS, Windows
gcloud secrets versions add db-password --data-file=report.csv -
List a secret's versionsLinux, macOS, Windows
gcloud secrets versions list db-password -
Turn off an old secret versionLinux, macOS, Windows
gcloud secrets versions disable 1 --secret=db-password -
Let a service account read a secretLinux, macOS, Windows
gcloud secrets add-iam-policy-binding db-password --member="serviceAccount:[email protected]" --role=roles/secretmanager.secretAccessor -
Delete a secretLinux, macOS, Windows
gcloud secrets delete db-passwordWarning: Deletes every version of the secret, with no undo.
-
Make a KMS key ringLinux, macOS, Windows
gcloud kms keyrings create my-keyring --location=europe-west1 -
Make a KMS key that rotates every 90 daysLinux, macOS, Windows
gcloud kms keys create my-key --keyring=my-keyring --location=europe-west1 --purpose=encryption --rotation-period=90d --next-rotation-time=2027-01-01T00:00:00Z -
Encrypt a file with a KMS keyLinux, macOS, Windows
gcloud kms encrypt --key=my-key --keyring=my-keyring --location=europe-west1 --plaintext-file=report.csv --ciphertext-file=report.csv.enc -
Decrypt a file with a KMS keyLinux, macOS, Windows
gcloud kms decrypt --key=my-key --keyring=my-keyring --location=europe-west1 --ciphertext-file=report.csv.enc --plaintext-file=report.csv
Google Cloud CLI: Cloud Run and Cloud Functions
-
Deploy the current folder to Cloud Run, building it for youLinux, macOS, Windows
gcloud run deploy my-service --source=. --region=europe-west1 -
Deploy a container image to Cloud RunLinux, macOS, Windows
gcloud run deploy my-service --image=europe-west1-docker.pkg.dev/my-project/my-repo/my-app:v1 --region=europe-west1 -
Deploy a public Cloud Run service anyone can callLinux, macOS, Windows
gcloud run deploy my-service --image=europe-west1-docker.pkg.dev/my-project/my-repo/my-app:v1 --region=europe-west1 --allow-unauthenticatedWarning: Anyone on the internet can call the service.
-
List Cloud Run servicesLinux, macOS, Windows
gcloud run services list -
Show a Cloud Run service's URLLinux, macOS, Windows
gcloud run services describe my-service --region=europe-west1 --format="value(status.url)" -
Set environment variables on a Cloud Run serviceLinux, macOS, Windows
gcloud run services update my-service --region=europe-west1 --update-env-vars=LOG_LEVEL=debug -
Use a secret as an environment variableLinux, macOS, Windows
gcloud run services update my-service --region=europe-west1 --update-secrets=LOG_LEVEL=db-password:latest -
Change a service's memory and CPULinux, macOS, Windows
gcloud run services update my-service --region=europe-west1 --memory=1Gi --cpu=1 -
List a service's revisionsLinux, macOS, Windows
gcloud run revisions list --service=my-service --region=europe-west1 -
Send all traffic to the latest revisionLinux, macOS, Windows
gcloud run services update-traffic my-service --region=europe-west1 --to-latest -
Roll back to an earlier revisionLinux, macOS, Windows
gcloud run services update-traffic my-service --region=europe-west1 --to-revisions=my-service-00042-abc=100 -
Read a Cloud Run service's logsLinux, macOS, Windows
gcloud run services logs read my-service --region=europe-west1 --limit=50 -
Follow a Cloud Run service's logs (beta component)Linux, macOS, Windows
gcloud beta run services logs tail my-service --region=europe-west1 -
Run a Cloud Run jobLinux, macOS, Windows
gcloud run jobs execute nightly-report --region=europe-west1 --wait -
Delete a Cloud Run serviceLinux, macOS, Windows
gcloud run services delete my-service --region=europe-west1 -
List Cloud FunctionsLinux, macOS, Windows
gcloud functions list -
Deploy an HTTP function from the current folderLinux, macOS, Windows
gcloud functions deploy my-function --gen2 --runtime=python312 --region=europe-west1 --source=. --entry-point=handler --trigger-http -
Read a function's logsLinux, macOS, Windows
gcloud functions logs read my-function --region=europe-west1 --limit=50 -
Call a functionLinux, macOS, Windows
gcloud functions call my-function --region=europe-west1 --data="{}" -
Delete a functionLinux, macOS, Windows
gcloud functions delete my-function --region=europe-west1
Google Cloud CLI: GKE, Artifact Registry and Cloud Build
-
List GKE clustersLinux, macOS, Windows
gcloud container clusters list -
Make an Autopilot clusterLinux, macOS, Windows
gcloud container clusters create-auto my-cluster --region=europe-west1 -
Set up kubectl for a clusterLinux, macOS, Windows
gcloud container clusters get-credentials my-cluster --region=europe-west1 -
Show a cluster's version and statusLinux, macOS, Windows
gcloud container clusters describe my-cluster --region=europe-west1 --format="table(name, currentMasterVersion, status)" -
List the versions you can upgrade toLinux, macOS, Windows
gcloud container get-server-config --region=europe-west1 -
Upgrade a cluster's control planeLinux, macOS, Windows
gcloud container clusters upgrade my-cluster --region=europe-west1 --master --cluster-version=1.33Warning: You can't downgrade afterwards.
-
List a Standard cluster's node poolsLinux, macOS, Windows
gcloud container node-pools list --cluster=my-cluster --region=europe-west1 -
Resize a Standard cluster's node poolLinux, macOS, Windows
gcloud container clusters resize my-cluster --region=europe-west1 --node-pool=default-pool --num-nodes=10 -
Delete a clusterLinux, macOS, Windows
gcloud container clusters delete my-cluster --region=europe-west1Warning: Deletes the cluster and everything running in it.
-
Make a Docker repository in Artifact RegistryLinux, macOS, Windows
gcloud artifacts repositories create my-repo --repository-format=docker --location=europe-west1 -
List Artifact Registry repositoriesLinux, macOS, Windows
gcloud artifacts repositories list -
Sign Docker in to Artifact RegistryLinux, macOS, Windows
gcloud auth configure-docker europe-west1-docker.pkg.dev -
List the images in a repositoryLinux, macOS, Windows
gcloud artifacts docker images list europe-west1-docker.pkg.dev/my-project/my-repo -
Build the Dockerfile in this folder with Cloud Build and push the image, no Docker neededLinux, macOS, Windows
gcloud builds submit --tag=europe-west1-docker.pkg.dev/my-project/my-repo/my-app:v1 -
List recent buildsLinux, macOS, Windows
gcloud builds list --limit=10 -
Follow a build's logsLinux, macOS, Windows
gcloud builds log 0a1b2c3d-1234-5678-9abc-def012345678 --stream
Google Cloud CLI: Cloud SQL
-
List Cloud SQL instancesLinux, macOS, Windows
gcloud sql instances list -
Show a Cloud SQL instanceLinux, macOS, Windows
gcloud sql instances describe my-db -
Connect to a database with its client (needs psql or mysql)Linux, macOS, Windows
gcloud sql connect my-db --user=postgres -
List the databases on an instanceLinux, macOS, Windows
gcloud sql databases list --instance=my-db -
Set a database user's passwordLinux, macOS, Windows
gcloud sql users set-password postgres --instance=my-db --prompt-for-password -
Take a backup nowLinux, macOS, Windows
gcloud sql backups create --instance=my-db -
List backupsLinux, macOS, Windows
gcloud sql backups list --instance=my-db -
Export a database to a bucketLinux, macOS, Windows
gcloud sql export sql my-db gs://my-bucket/appdb.sql.gz --database=appdb -
Restart a Cloud SQL instanceLinux, macOS, Windows
gcloud sql instances restart my-db -
Stop a Cloud SQL instance to save moneyLinux, macOS, Windows
gcloud sql instances patch my-db --activation-policy=NEVER -
Start a stopped Cloud SQL instanceLinux, macOS, Windows
gcloud sql instances patch my-db --activation-policy=ALWAYS -
Delete a Cloud SQL instanceLinux, macOS, Windows
gcloud sql instances delete my-dbWarning: Deletes the instance and its automatic backups. Export the data first if you need it.
Google Cloud CLI: Logging, monitoring and Pub/Sub
-
Read the last hour of errors in a projectLinux, macOS, Windows
gcloud logging read "severity >= ERROR" --freshness=1h --limit=50 -
Read a VM's logsLinux, macOS, Windows
gcloud logging read "resource.type = gce_instance AND resource.labels.instance_id = 1234567890123456789" --limit=50 -
Read who changed what (audit logs)Linux, macOS, Windows
gcloud logging read "logName : cloudaudit.googleapis.com%2Factivity" --freshness=1d --format="table(timestamp, protoPayload.authenticationInfo.principalEmail, protoPayload.methodName)" -
List log names in a projectLinux, macOS, Windows
gcloud logging logs list -
List log sinksLinux, macOS, Windows
gcloud logging sinks list -
Send logs to a bucketLinux, macOS, Windows
gcloud logging sinks create warnings-to-bucket storage.googleapis.com/my-bucket --log-filter="severity >= WARNING" -
List alerting policiesLinux, macOS, Windows
gcloud monitoring policies list --format="table(displayName, enabled)" -
List Pub/Sub topicsLinux, macOS, Windows
gcloud pubsub topics list -
Make a Pub/Sub topicLinux, macOS, Windows
gcloud pubsub topics create orders -
Send a message to a topicLinux, macOS, Windows
gcloud pubsub topics publish orders --message="Hello from gcloud" -
Make a subscription to a topicLinux, macOS, Windows
gcloud pubsub subscriptions create orders-worker --topic=orders -
Read messages from a subscriptionLinux, macOS, Windows
gcloud pubsub subscriptions pull orders-worker --auto-ack --limit=10
Google Cloud CLI: Billing and quotas
-
List your billing accountsLinux, macOS, Windows
gcloud billing accounts list -
Show which billing account a project usesLinux, macOS, Windows
gcloud billing projects describe my-project -
List the projects on a billing accountLinux, macOS, Windows
gcloud billing projects list --billing-account=0X0X0X-0X0X0X-0X0X0X -
List budgetsLinux, macOS, Windows
gcloud billing budgets list --billing-account=0X0X0X-0X0X0X-0X0X0X -
Make a monthly budgetLinux, macOS, Windows
gcloud billing budgets create --billing-account=0X0X0X-0X0X0X-0X0X0X --display-name="Monthly budget" --budget-amount=100EUR --threshold-rule=percent=0.9 -
Show a region's Compute Engine quotasLinux, macOS, Windows
gcloud compute regions describe europe-west1 --flatten="quotas[]" --format="table(quotas.metric, quotas.usage, quotas.limit)" -
Show the recommendations for idle VMsLinux, macOS, Windows
gcloud recommender recommendations list --project=my-project --recommender=google.compute.instance.IdleResourceRecommender --location=europe-west1-b
Google Cloud CLI: BigQuery (bq)
-
List datasetsLinux, macOS, Windows
bq ls -
List the tables in a datasetLinux, macOS, Windows
bq ls analytics -
Show a table's schema and sizeLinux, macOS, Windows
bq show analytics.events -
Run a SQL queryLinux, macOS, Windows
bq query --nouse_legacy_sql "SELECT * FROM analytics.events LIMIT 10" -
See how much data a query would read, without running itLinux, macOS, Windows
bq query --nouse_legacy_sql --dry_run "SELECT * FROM analytics.events" -
Make a datasetLinux, macOS, Windows
bq mk --dataset --location=europe-west1 my-project:analytics -
Load a CSV file into a tableLinux, macOS, Windows
bq load --source_format=CSV --autodetect analytics.events report.csv
Google Cloud CLI: Troubleshooting
-
Show more detail about what a command is doingLinux, macOS, Windows
gcloud compute instances list --verbosity=debug -
Show every request and responseLinux, macOS, Windows
gcloud compute instances list --log-httpWarning: The output includes your access token. Check it before you share it.
-
Check gcloud's network and settingsLinux, macOS, Windows
gcloud info --run-diagnostics -
Show the log of your recent gcloud commandsLinux, macOS, Windows
gcloud info --show-log -
Clear the sign-in used by apps and SDKsLinux, macOS, Windows
gcloud auth application-default revoke -
Set the quota project for apps and SDKs, to fix quota errorsLinux, macOS, Windows
gcloud auth application-default set-quota-project my-project -
Send gcloud through a proxyLinux, macOS, Windows
gcloud config set proxy/type http gcloud config set proxy/address proxy.example.com gcloud config set proxy/port 8080 -
Turn off usage reportingLinux, macOS, Windows
gcloud config set disable_usage_reporting true