CLI Cheatsheet

Posted on Wed 01 April 2020 • Last modified on Wed 01 April 2020

While this cheatsheet may contain short flags (e.g. -s), I urge you to always use long flags (e.g. --long) when you write a script to allow easier maintenance.

Archives

Store a file into an AES encrypted ZIP file (superuser.com)

7za a OUTPUT.zip INPUT.txt -tzip -mem=AES256 -mx9 -p'PASSWORD'

Check encryption method for a ZIP file (superuser.com)
- Attribute Encrypted must contain a “+”

7z l -slt INPUT.zip | grep -e "AES" -e "Encrypted"

Certificates

Connect directly to a host using openssl

openssl s_client -connect YOUR.EXAMPLE.HOST:PORT

Connect directly with gnu-tls without SNI

gnutls-cli --disable-sni YOUR.EXAMPLE.HOST

Specify your own certificates when connecting via curl

curl --cafile /PATH/TO/FILE https://YOUR.EXAMPLE.HOST

Checksums / Hashes

Calculate the MD5 checksum for a string (askubuntu.com)

# on linux
echo -n "STRING" | md5sum

# on macOS
md5 -s "STRING"

Configuration management

Ansible

Start a playbook at a specific task (docs.ansible.com)

ansible-playbook PLAYBOOK.yml --start-at-task="NAME"

Limit execution to multiple specific hosts (ansible-tips-and-tricks.readthedocs.io)

ansible-playbook PLAYBOOK.yml --limit "HOST1,HOST2,HOST3"

Limit execution to a group of hosts (ansible-tips-and-tricks.readthedocs.io)

ansible-playbook PLAYBOOK.yml --limit "GROUP"

List hosts affected by a playbook (stackoverflow.com)

ansible-playbook PLAYBOOK.yml --list-hosts

List groups a host belongs to (stackoverflow.com)

ansible HOST --module-name debug --args var=group_names

Diffs / Patches

Create a patch file from the diff of two files (gitlab.com: omnibus-gitlab)

diff --new-file --text --unified --recursive ORIGINAL.rb INPUT.rb > OUTPUT.patch

Encoding / Decoding

Decode a base64+gzip encoded file (commandroll.com)

cat INPUTFILE | base64 --decode | zcat OUTPUTFILE

File systems

List inode usage

df -i

Firewalls

iptables

Remove a specific rule

# Find the rule
iptables --list-rules

# Remove the rule
iptables --delete FULL_RULE_SPEC  # without the starting -A

Hardware

Find information about the mainboard (provided by mgIT)

dmidecode --type 2

Images

Remove EXIF data using imagemagick

mogrify -strip INPUT.jpg

Languages / Locales

View currently set locales

locale

View installed and useable locales

locale --all-locales

Logfiles

Empty out (truncate) an existing file

truncate --size 0 FILE

Package Managers

Apt (Debian)

Fix a missing apt key

apt-key adv --keyserver ha.pool.sks-keyservers.net --recv-keys KEY_ID

Gem (Ruby)

Install a gem locally

gem install --user-install GEM

Homebrew (macOS)

Install a previous version of a package (stackoverflow.com)

brew tap-new YOUR_CUSTOM/TAP_NAME
# e.g. brew tap-new ghostlyrics/local

brew extract --version "SEM_VERSION" PACKAGE YOUR_CUSTOM/TAP_NAME
# e.g. brew extract --version 2.9.2 ansible ghostlyrics/local

brew install PACKAGE@VERSION
# e.g. brew install ansible@2.9.2

brew unlink PACKAGE
# e.g. brew unlink ansible

brew link PACKAGE@VERSION
# e.g. brew link ansible@2.9.2

Poetry (Python)

Start with a new project without skeleton

poetry init

Install or activate a virtual environment

poetry shell

Install project dependencies - will install from poetry.lock if available, from pyproject.toml if not.

poetry shell
poetry install

Password Generation

Create a memorable, easily typeable password using xkcdpass

xkcdpass --delimiter "-" --numwords 4

Find patterns in a file, explicitly not using RegEx (stackexchange.com)

grep --fixed-strings --regexp "STRING" FILE

Stream Redirection

Redirect stdout, stderr and send to background

COMMAND > OUTPUT 2>&1 &

Stylesheets

Convert LESS to CSS using less

lessc LESS.less CSS.css

Systemd

Find out whether the system has finished startup procedures

systemctl is-system-running

Find failed units

systemctl list-units --state=failed

Show dependencies of a unit

systemctl show -p "Wants" TARGET.target

Show DNS resolvers

systemd-resolve --status

Reset failed state for a unit

systemctl reset-failed SERVICE.service

Reload configuration files

systemctl daemon-reload 

Version Control

Git

Cherry-pick a series of commits, including the first commit (stackoverflow.com)

git cherry-pick "HASH_A^..HASH_B"

Create a patch from the last commit

git format-patch HEAD~1

Remove merged local branches (hacksparrow.com)

git branch --merged \
  | grep --extended-regexp --invert-match "(^\*|master|dev)" \
  | xargs git branch --delete

Webservers

Start a minimal Python server for debugging

# using Python3
python3 -m http.server

# using Python2 (EOL!)
python -m SimpleHTTPServer

extra: macOS

Find 32 bit applications (provided by @maclemon)

mdfind "kMDItemExecutableArchitectures == '*i386*' && kMDItemExecutableArchitectures != '*x86*'"

Open tmux with iTerm2 native tabs

# initial session creation
tmux -CC

# attach to running session
tmux -CC a

extra: Windows

Redirect command output to a file (docs.microsoft.com)

PROGRAM.exe | Out-File -FilePath OUTPUT.txt

extra: Snippets

This section might be split off into its own file eventually.

MySQL

Skip one statement during replication

STOP SLAVE;
SET GLOBAL SQL_SLAVE_SKIP_COUNTER=1;
START SLAVE;

Python

Convert a byte array to a string

example.decode('utf-8')

Flush print() immediately

print('example', flush=True)

Suppress output of subprocess.run()

import subprocess
subprocess.run(['example'], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

SQLite

Export data from the SQLite database to a CSV file

sqlite3 PATH_TO_DATABASE

# in SQLite prompt (sqlite> )
.headers on
.mode csv
.output OUTPUT_FILE.csv
QUERY;
.quit

systemd

Create a systemd unit that always succeeds (askubuntu.com, manpages.ubuntu.com) - Commands are wrapped in a call to a shell because shell operators are not implemented in systemd.

[Unit]
Description=Example service
After=network.target

[Service]
Type=oneshot
ExecStart=/bin/bash -c "/usr/bin/example || /bin/true"