Bash Cheatsheet

I've gotten tired of googling the same things over and over again.

While loops

Note to self: If you find yourself doing this, you should probably stop and reevaluate why you're not using python.

Infinite loop

while [ $item = true ]; do echo 'bla'; done

While value is an empty string

while [[ -z "$value" ]]; do
    echo "value is empty"
    # here's where we break out
    if [[ "$value" ]]; then
        echo "exiting loop because value has been set to $value"

For loops

This will compute the md5sums for every item in the current directory:

for i in $(ls); do md5sum $i; done | sort

This will print out 1 through 10:

for COUNT in $(seq 1 10); do
  echo $COUNT
  sleep 1

SCP file to a remote host with a specific port

scp -P <port>


SCP file between two remote hosts from your computer

This is useful if you have two aws instances, and want to transfer a file between them from your laptop.
scp -3 -i <pem file> user1@system_with_file:/file/to/xfer user2@system_that_needs_file:/file/to/xfer


Create sudo user non-interactively

Skip the prompts that come with creating a user typically, and give them sudoers privileges. Replace <username> with the user you want to create.

# The man page explanation for --gecos isn't that intuitive IMO
# Basically specifying --gecos "" states you don't want to ask
# for real name, phone, etc.
adduser --disabled-password --gecos "" <username>
touch /etc/sudoers.d/10_*username*
echo '*username* ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/10_*username*


Run function as another user

export -f <function_name>
su <user to run function as> -c "bash -c <function_name>"

Exit-on-error mode

Put this at the top of your bash script: set -e.
If a command returns a nonzero status, the shell will exit.

Resources: - man page

See files that would be unzipped without unzipping

unzip -v <file>.zip>

Unzip to a directory

unzip -d /opt


Color output in less

Use less -r <file>

Code Style

Function declarations:



Variable declaration:


Source filenames should be lowercase with underscores to separate words, i.e.


Global variables in functions

If you want to set something as a global variable and use it in a function, do the following:

export SOMETHING="variable"

    echo $SOMETHING

Parse an env file

export $(egrep -v '^#' .env | xargs)

The env file you want to parse should look something like this:



Send message to all users

echo "hi" | wall

Move file with rsync

rsync --partial --progress filename.txt user@ipaddress_or_hostname:~

Use SSH and rsync together

rsync -avzhe ssh <folder to copy> user@


Break up VM into multiple 1 GB files

Need to transfer a VM? Try this.
split -b 1000m vm.ova vm.ova.split

Bring it back together

cat vm.ova.splita* > vm.ova

Kill netcat after 3 seconds

Great if netcat doesn't want to die
timeout 3 nc 80; echo exit=$?


Find if string exists in a file

if grep -q SomeString "$File"; then
  Some Actions # SomeString was found


Delete files if they match a wildcard

If you have two files, someFile and someFile2, this will delete both of them:

if ls someFile* 1> /dev/null 2>&1; then
  rm someFile*


Check if multiple binaries are installed

if hash cowsay 2>/dev/null && hash gshuf 2>/dev/null; then
  # do things if both are installed

Check if file does not exist

if [ ! -f "some/file.txt" ]; then
  # do things if the file is not there

One-liner to check if file exists

if [ ! -f /tmp/foo.txt ]; then echo "File not found!"; else echo "file found"; fi


Create directory if it doesn't exist

[[ -d dir ]] || mkdir dir


View output of a running process in another bash session

strace -p <pid> -e write


Number of duplicate lines in a file

sort <file> | uniq -c


Run command in another directory as another user

This particular example is used to run a command as root in another directory

sudo -u root /bin/bash -c 'pushd "$HOME/.some_directory/"; ls -lart; popd'


Bypass post-install configurations

If you have to install things via apt and run into blue screens that require human interaction, do this to avoid it:

sudo DEBIAN_FRONTEND=noninteractive apt install -yq [packagename]


Get count of and list of most frequently used bash commands

history | awk '{a[$2]++;next}END{for (i in a){print i " --> " a[i]}}' | sort -nr -k3

Reinstall a package in a debian-based system

sudo apt install --reinstall <package> -y

Unable to fetch some archives, maybe run apt-get update or try with --fix-missing

Run this if apt update --fix-missing isn't working for you:

rm -rf /var/lib/apt/lists/*; apt update

Alternatively, you can also try:

apt clean; apt update


View images on a remote system

ssh -Y user@server
apt install -y eog
eog pictures/foo.png


Save off auth logs for review

Useful to see who has logged into your system and when

last -F > /tmp/last

"Incognito mode" for bash

Turn off history for a session.

export HISTFILE=

If you do want a record of your activity in another file, run this command instead:

export HISTFILE=0

This will create a file, 0, with your history for that session.


List NFS mounts

mount |grep nfs

When all users last logged in


All previously logged in users

lastlog |grep -v "Never"	


Find if host is sharing file systems

If there are local mounts, you will be able to see who you're sharing with.

showmount -e localhost

Hosts with active connections to the system

netstat -pan |grep ESTABLISHED

Check if file has a certain number of lines

If file has 3 lines, tell us about it:

if [[ $(wc -l file) == *3* ]]; then
  echo "There are three lines in file"


If wc provides an inaccurate count

Add a newline to the end of the file with:

printf "\n" >> file.txt



strace /bin/ls

Filter on write functions:

strace -e write /bin/ls


Used to get the assembly output of a given binary

objdump -d <binary> | tee binary_output.txt


There's a whole page I've dedicated to this:
GDB Notes

List largest directories and files

du -hsx * | sort -rh | head -10


Semicolon vs + in find


Check if you can ssh to several hosts


for SERVER in $(cat hosts.txt); do
  ssh -i id_rsa -o StrictHostKeyChecking=no -o BatchMode=yes user@$SERVER exit && echo OK $SERVER || echo ERR $SERVER



List tickets in a keytab

ktutil -kt file.keytab list


Create kerberos ticket

kinit <username> -k -t /where/to/store/keytab/nameofkeytab.keytab

Not matching with grep

This example will find all jobs that don't contain com:

launchctl list | grep -v com

Regexing with grep

This will get the version of ruby from rvm:
rvm list | head -n 1 |grep -Po '\-(.*?)\s' | tail -c +2
The output from that command that it is parsing will look something like this: ruby-2.5.1 [ x86_64 ]

It will return 2.5.1.


Egrep Regex and return capture group

This will read a file with a bunch of gmail addresses in it (among other things), and then print the unique email addresses found.

cat file.txt| grep | egrep -o '\' | uniq -u


Create self-signed cert

openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365


Create SSH key script

if [ ! -e ~/.ssh/ ]; then
  echo 'Creating your public and private ssh keys'
  echo '----------------------------------------'

  # Create public and private 2048 bit ssh key pair without pw prompt
  ssh-keygen -t rsa -b 2048 -f ~/.ssh/id_rsa -N ''

  # Copy new key to make it possible to autologin
  cat ~/.ssh/ >> ~/.ssh/authorized_keys
  chmod 0600 ~/.ssh/authorized_keys

  # Add the ssh key
  eval "$(ssh-agent)"
  ssh-add ~/.ssh/id_rsa
  echo "Public ssh key file already exists"
  echo "----------------------------------------"


Generate public key from private key

ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/



Extract command

This will extract several popular formats for you without needing to worry about the syntax for each:

extract() {
  if [ -f $1 ] ; then
      case $1 in
          *.tar.bz2)   tar xvjf $1    ;;
          *.tar.gz)    tar xvzf $1    ;;
          *.bz2)       bunzip2 $1     ;;
          *.rar)       rar x $1       ;;
          *.gz)        gunzip $1      ;;
          *.tar)       tar xvf $1     ;;
          *.tbz2)      tar xvjf $1    ;;
          *.tgz)       tar xvzf $1    ;;
          *.zip)       unzip $1       ;;
          *.Z)         uncompress $1  ;;
          *.7z)        7z x $1        ;;
          *)           echo "don't know how to extract '$1'..." ;;
      echo "'$1' is not a valid file!"


Untar to specific directory

tar -xf archive.tar -C /target/directory


Create tar.gz with var

tar -czvf "$name".tar.gz $name

Show successful ssh logins

grep sshd.\*Accepted /var/log/auth.log

Show failed ssh logins

grep sshd.\*Failed /var/log/auth.log

Create encrypted zip

zip -r original_file
openssl enc -in -aes-256-cbc -e >
# enter password when prompted

Depending on the situation, you may consider destroying the original unencrypted file:


Decrypt and unzip encrypted zip

openssl enc -in -aes-256-cbc -d >
# enter password when prompted

Remove duplicates from a file

sort inputFile | uniq -u > outputfile


Get status code

curl -I


Upload a file

To upload a file to an endpoint at /upload with a form field, fileUpload, you can do the following:

curl -F "fileUpload=@test.txt" -vvv

Send a POST request with params

curl -d "param1=value1&param2=value2" -X POST http://localhost:4999/target

Download a file

This will also ensure that if a proxy is in place, it will not be used to connect to

curl --output puppet-linux -vvvv --noproxy


Download a file to a certain folder

curl${TER_VER}/terraform_${TER_VER} -L -o /home/$USER/Downloads/terraform_${TER_VER}

-L - in case a redirect is found
o - create your own file name (alternatively you can use --output)


Use proxy

Useful to proxy requests through something like Burp Suite.

curl -X GET --proxy http://localhost:8080


3000 millisecond timeout

curl -m 3


Check if a string is a timestamp

date -r <string>

For example:

date -r 1530279830


Kill all python processes in Ubuntu

pkill python


Useful alternative to man pages

Display Web Content in Terminal

lynx -dump
wget -O -


Open file, grep it, send output to command

This particular example will search for instances of the ENC string and send them to eyaml decrypt -s:

cat file.txt |grep ENC | xargs --null eyaml decrypt -s

Delete to end of line in terminal


Delete to beginning of line in terminal


Generate a self-signed cert

openssl req -new -newkey rsa:4096 -x509 -sha256 -days 365 -nodes -out key.crt -keyout key.key

Find secrets on git server

This can be useful if you land on a git server and want some juicy secrets

for i in $(git ls-tree -r master | cut -d " " -f 3 | cut -f 1); do echo -e "${i}"; git cat-file -p ${i} | grep -i password; done


Grep through several tar.gz files

find . -name \*.tar.gz -print0 | xargs -0 zgrep "STRING"


SSHD with custom file

sshd -f <path/to/sshd_config/file>
For example:
sshd -f /tmp/sshd_config

The sshd_config file can look roughly like this:

Port 6022
HostKey /tmp/sshd_config/host_rsa
PasswordAuthentication yes
PermitRootLogin no

Run command repeatedly

My default tends to be while true; do <command>; sleep 2; done. However, a cleaner alternative can be done with watch:

watch <command>

For example:

watch date


Sleep with timer

Set MIN to the desired number of minutes you want to sleep for:

MIN=1 && for i in $(seq $(($MIN*60)) -1 1); do echo -n "$i, "; sleep 1; done; echo -e


Base64 encode with no word wrap

Useful for long strings that you want to base64 encode.

echo "thing" | base64 -w 0


Base64 decode string

echo 'stringtodecode' | base64 -d


Test if variable is set

if [ -z $1 ]; then
  echo "no input provided";
else echo "input is '$1'";


Add ssh fingerprint to known_hosts

Useful if you need this functionality in a script (sometimes this arises with ansible, for instance)

ssh-keyscan -H <ip address> >> ~/.ssh/known_hosts


Check if input is an ip address

if [ -z $1 ]; then
  echo "Usage: $0 <ip address>"
  if [[ $1 =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    echo "Valid IP input, doing things with $1"
    echo "Invalid IP input"


Making this into a function

check_input() {
  if [ -z $1 ]; then
    echo "Usage: $0 <ip address>"
    if [[ $1 =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
      echo "Valid IP input, doing things with $1"
      echo "Invalid IP input"

# Pass input from $1 to function
check_input $1


Check if input is != to a string

if [[ "$1" != "puppet" ]] && [[ $1 != "chef" ]] || [[ -z $1 ]]; then
  echo "Usage: $0 <CM target>"


Output only found files w/ grep

grep -rnlw "stringtofind" .



Show open ports

ufw status

Allow port

Open the firewall for port 46666:

ufw allow 46666/tcp

Allow service

This will work for OpenSSH:

ufw allow 'OpenSSH'

This is for Apache:

ufw allow 'Apache Full'

Disable UFW

ufw disable

Enable UFW

ufw enable


Keep NC listener open

This will ensure that netcat doesn't hang when an incoming connection is established.

nc -lvk <port to listen on>


Create random string

head /dev/urandom | tr -dc A-Za-z0-9 | head -c 13 ; echo ''

Example usage:

wget -O "/var/www/html/$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 13 ; echo '').php"


Remove newline from end of string

tr -d '\n'


Create three directories in tmp:

mkdir /tmp/{d1,d2,d3}

Crontabs for another user

You need to be root to do this.

List crontabs for <user>:

crontab -u <user> -l

You can also edit a crontab by using -e in place of -l.

Copy file to location with random name

# This will remove dashes, newlines and spaces
name=$(date | md5sum | tr -d '-' | tr -d '\n' | tr -d ' ')
if cp -R orig "$name"; then
  echo "Created $name"



SCP files using wildcard

Be sure to escape the wildcard, i.e. file-\*

Full example:

scp ubuntu@target:~/.config/cred\*


Show routes

netstat -nrl

Create route

This is useful if you're having issues with VPN and something like Burp Suite.

sudo route add <target system> <local IP>

Netstat (without actually running it)

awk 'function hextodec(str,ret,n,i,k,c){
    ret = 0
    n = length(str)
    for (i = 1; i <= n; i++) {
        c = tolower(substr(str, i, 1))
        k = index("123456789abcdef", c)
        ret = ret * 16 + k
    return ret
function getIP(str,ret){
    for (i=5; i>0; i-=2) {
        ret = ret"."hextodec(substr(str,i,2))
    ret = ret":"hextodec(substr(str,index(str,":")+1,4))
    return ret
NR > 1 {{if(NR==2)print "Local - Remote";local=getIP($2);remote=getIP($3)}{print local" - "remote}}' /proc/net/tcp 


Show routing rules to reach a destination

ip route get <target>

For example, this will show the route that your system will take to get to (Google's DNS Server):

ip route get

Note that you can also run this command on a mac after you install the iproute2mac package via: brew install iproute2mac



Remove leading and trailing whitespace

awk '{$1=$1;print}'


Print everything but first column

This assumes you have text coming from before the |.

| awk '{$1=""; print $0}'


Split on /, print first column after split

awk -F '/' '{print $0}'

Use as an alias

This particular example will get the IPv6 address for eth0. The trick is remembering to escape the $2:

alias getIP="ifconfig eth0 |grep inet6 |grep global | head -n1 | awk '{print \$2}'"



Echo output

@echo Things I want to say!


Get size of current directory

du -hsx


Grep output of find and save to file

find . -iname "thing to find" -exec grep -rnw "term to search" {} \; | tee filename

As an example, we can search for all python files recursively from the current directory and then grep for the word "git" in those files:

find . -iname "*.py" -exec grep -rnw "git" {} \; | tee git


Find and replace all instances of a string

This will find all go files recursively from the current directory and replace all instances of "toreplace" with "replaced".


find . -iname "*.go" | xargs sed -i 's/toreplace/replaced/g'

OS X with gnu-sed (installed via brew install gnu-sed):

find . -iname "*.go" | xargs gsed -i 's/toreplace/replaced/g'


Find all bin files and create single file with strings output

find . -iname "*.bin" -exec strings "{}" \; | tee combined_strings_output.txt


Find directories with a certain name

find . -type d -name "thingtosearchfor*" -print 2>/dev/null


Find a specific file

find /etc -name "passwd"

Find all bash_histories and send their contents to a file

find . -iname ".bash_history" -exec cat {} \; | tee ~/bash_histories.txt


List all directories the current user has access to

find . -maxdepth 1 -type d -perm -u=rx

Run ls -lart on all dirs current user can access

This will also display the folder at the top of the output because we've used +.

find . -maxdepth 1 -type d -perm -u=rx -exec ls -lart {} + 2>/dev/null

Find all bash_history files the current user can read

find . -maxdepth 1 -type d -perm -u=rx -print0 | xargs -0 -I{} find '{}' -readable -iname '.bash_history' 2>/dev/null

Find all .ssh directories that the current user has access to


find . -maxdepth 1 -type d -perm -u=rx -print0  | xargs -0 -I{} find '{}' -readable -type d -iname '.ssh' 2>/dev/null

Not quite as clean:

find . -maxdepth 1 -type d -perm -u=rx | xargs ls -lart 2>/dev/null |grep .ssh | grep "^.r..r..r"

Breaking this down:

find . -maxdepth 1 -type d -perm -u=rx - find all directories the current user has access to

| xargs ls -lart 2>/dev/null - send the output of the find command to

ls -lart and suppress the Permission denied messages

|grep .ssh | grep "^.r..r..r" - output all files with ssh in the name with read permissions for all users

Show all occurences of users running ssh

find . -name .bash_history -print -exec grep ssh {} \;

Find all .go files recursively

find . -name "*.go"

Find bins with SUIC or SGID set

Added output to /tmp/out.txt and backgrounded in the event you're on a crappy shell.

for i in `locate -r "bin$"`; do find $i \( -perm -4000 -o -perm -2000 \) -type f 2>/dev/null; done | tee /tmp/out.txt &

Search for secrets in config.xml files recursively

In this example, we are searching for patterns in config.xml files matching <secret, <password, or <credential:

find . -name "config.xml" -exec grep -iE "<secret|<password|<credential" {} + | uniq -u

Find all csv files and delete them

find . -name "*.csv" -exec rm {} +

Delete all json files recursively

find . -name "*.json" -exec rm {} \;


Show all executable files

find . -maxdepth 1 -perm -111 -type f


Find world writeable directories

find /\(-perm -o w -perm -o x\) -type d 2>/dev/null


Remove any files in a directory

find "/path/to/dir" -type f -exec rm /path/to/dir/* {} \;


Find files not matching a pattern name

This will list all files in the current directory that do NOT have .template., .settings. in their name.

find . -type f -not -name "*.template.*" -not -name "*.settings.*"


Look for unique ip addresses with find output

find . -type f -not -name "*.template.*" -not -name "*.settings.*" | xargs grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" | sort -u

Resources: - find ip addresses with grep - getting unique ip addresses

Great find tutorial

TomNomNom breaks down the find command and makes it very approachable with this tweet:

Open command for editing

This is very useful if you have a long command that you want to modify quickly.

Type the following to open a file:
CTRL + x CTRL + e


Get second column of file

cat output.csv | awk '{print $2}'

Make offline copy of a site

wget --mirror            \
     --convert-links     \
     --html-extension    \
     --wait=2            \
     -o log              \


Download entirety of a site

wget --random-wait -r -p -e robots=off -U mozilla



Insert text after matched string

This will add retries=2 after [ssh_connection] in ansible.cfg:

sed -i '/\[ssh_connection\]/a retries=2' ansible.cfg


Remove last line of a file

sed -i '$ d' foo.txt


Find and replace line in file

This will work with both osx and linux. It's important to note that you should not change anything except for <orig pattern>, <modified>, and file.txt.

sed -i".orig" 's/<orig pattern>/<modified>/' file.txt


Find and replace line assigned to variable in file

OSX (this will create a file.original, which is necessary for native OSX sed):

new_str="so new"
sed -i'.original' -e "s/staticlineinfile/$new_str/g" "file/to/change.conf"

Remove the .original file:

rm "file/to/change.conf.original"

Linux (you can also use gsed in OSX if you install gnu sed):

sed -i "s/dahclamps/$name/g" "$name/default/app.conf"

This will avoid having to create and remove the .original file.


Add prefix to command output

yourcommand1 | sed  's/^/[prefix1]/'

For example, this will get all ip addresses associated with running containers, and add http:// to the front of each of them:

docker ps | awk '{ print $13 }' | grep -o -P "(.*:\d+)" | sed  's/^/http:\/\//'


Remove nth line of a file

Remove the nth line of a file:

sed 'Nd' file

You have to use -i to modify the file.

For example, to remove the second line from somefile.txt and overwrite it:

sed -i '2d' somefile.txt


Change shell with sed

This will change the shell from /usr/sbin/nologin to /bin/bash for the www-data user:

sed -i '/www-data/s/\/usr\/sbin\/nologin/\/bin\/bash/g' /etc/passwd


Get nth line of a file

sed 'NUMq;d' file

For example, to get the second line from somefile.txt:

sed '2q;d' somefile.txt


Merge two folders

rsync -avh --progress /path/to/source/ /path/to/destination

For example, if you have a recipes folder in /Volumes/stuff/recipes that you want to sync with your local recipes folder:

rsync -avh --progress ~/recipes /Volumes/stuff

Resources: you want to move,are on the same filesystem.

Conditional based on output of a command

if echo $(command_to_run) | grep -q "thing to find in output of command"
    then echo "Yay, we found things!"
    else "We didn't find the thing we wanted to find!"; exit 1



chmod u+s <filename>


Remove files without an extension

In this case, we'll rm every file that doesn't end with the apk file extension:

find . -type f ! -name "*.apk" -exec rm {} \;


Assign output to variable

pid=`adb shell ps -A | grep processname | awk -F' ' '{print $2}'`


Get first two characters of a string

Use head -c 2

Example that will get the first two characters of the apk found in /tmp:

find /tmp -name "*.apk*" | head -c 2


Break long command down

This is useful if you have a long command and want to be able to lay it out to analyze. Assign the parameter to a variable and add \ through out the content of that parameter.

For example:

curl $command



Get today's date

today=`date '+DATE:%m%d%y' | cut -d: -f2`

Get the time

time=`date '+TIME:%H%M%S' | cut -d: -f2`

Get the year

year=`date | cut -d' ' -f 6`

Get the month and day

month_day=`date '+DATE:%m%d' | cut -d: -f 2`

Kill process by name

pkill "name of app"

For example, /Applications/ can be killed with:

pkill "Rectangle"


Run script on startup via systemd

Create service

  1. Create systemd service file called <service name>.service and set the path to where you plan to have the script on disk:

ExecStart=/usr/local/bin/<name of script>.sh

  1. Create the script to run on startup (call it whatever you want).

  2. Move the files into place and set the permissions:

sudo mv <name of script>.sh /usr/local/bin/<name of script>.sh
sudo mv <service name>.service /etc/systemd/system/<service name>.service
sudo chmod 744 /usr/local/bin/<name of script>.sh
sudo chmod 664 /etc/systemd/system/<service name>.service
  1. Enable the service:
sudo systemctl daemon-reload
sudo systemctl enable <service name>.service


Check service is running

service <name of service> status

Show what's listening on a port

sudo lsof -i -P -n | grep LISTEN


Exclude file from zip

This will exclude the .git folder, the file and the Makefile:

zip -r . -x '*.git*' -x -x Makefile

Resources: - excluding files - make a zip of everything in the current directory

Trim whitespace from a bash var

echo "   lol  " | xargs


Show open ports

This is one option that has some nice and concise output:

sudo lsof -i -P -n |grep LISTEN

Here's another for newer versions of linux with a bit more info:

sudo ss -tulwn


Handy Shortcuts


This will get the last run command:


So for example, if you run this command:

ls -lart

and then run this command:

!! |grep bash_history

You will be running the equivalent of:

ls -lart |grep bash_history


This will get the second command run in a line of commands:


For example, if you run this command:

file $(ldd /bin/ls | grep | cut -d' ' -f3) -L

and then type this in:


you will get the following command:

$(ldd /bin/ls | grep | cut -d' ' -f3)

Resource: - this will not be available for you unless you purchase the course, sorry.


Variable declaration:

var = foo
@echo $(var)

This will output foo.

Run several actions in a row

all: build test

	go build

	go test -v

To run everything, simply run:


Resources: - echo - running several actions in a row

Get public IP

wget -O - 2>/dev/null

Tree view of processes

Run this to get a sense of processes and their parents

ps axjf

Run command over SSH

ssh ubuntu@yoursystem 'sudo apt-get update'


Download file to specific dir with wget

mkdir $install_dir
wget <file to download> -P $install_dir


Get newest file matching a string

This will find all files that start with vncpass in /home/ubuntu/vnc and get the most recent one:

ls -t /home/ubuntu/vnc/vncpass* | head -1


Get certificate portion of pem file

openssl x509 -in cert.pem -outform der | base64 -w 64

For a full example, run this to generate a self-signed cert:

openssl req \
    -x509 \
    -nodes \
    -newkey rsa:2048 \
    -keyout server.key \
    -out server.crt \
    -days 3650 \
    -subj "/C=GB/ST=London/L=London/O=Global Security/OU=IT Department/"

and then run:

openssl x509 -in server.crt -outform der | base64 -w 64


Curl with client certificate

This will help you to avoid using the -k option if you're using a self signed certificate (which you probably shouldn't unless you're doing some testing or have another good reason).

Get the client certificate (client.pem):

echo quit | openssl s_client -showcerts -servername -connect > cacert.pem

Use it in your curl command:

curl --cacert cacert.pem -X POST -d 'data=hi'

Resources: - get the cacert and use it - cert generation

Forward local service to remote host

This will forward a service running on localhost:3000 to a remote host on port 3000, and will allow other systems on the network to access that service.

On the remote host, run this command to add a line to the sshd_config:

echo 'GatewayPorts clientspecified' | sudo tee -a /etc/ssh/sshd_config

Next, restart the ssh service:

service ssh restart

Finally, run this command from the system running the service:

ssh -R :3000:localhost:3000 user@$target_server


Diff output of two commands

This will diff the output of a find command with a bunch of not statements against a find command that pipes it output to grep, which in turn uses a perl regex to try an find files that match a bunch of numbers.json.

diff <(find . -type f -not -name "*.template.*" -not -name "*.settings.*") <(find . -type f -name "*.json*" | grep -P '.*?\d+.json')

Resources: - diff - using grep with find

Get PID's without ps

find /proc -mindepth 2 -maxdepth 2 -name exe -exec ls -lh {} \; 2>/dev/null


Netstat without netstat

Copy pasta ftw:

awk 'function hextodec(str,ret,n,i,k,c){
    ret = 0
    n = length(str)
    for (i = 1; i <= n; i++) {
        c = tolower(substr(str, i, 1))
        k = index("123456789abcdef", c)
        ret = ret * 16 + k
    return ret
function getIP(str,ret){
    for (i=5; i>0; i-=2) {
        ret = ret"."hextodec(substr(str,i,2))
    ret = ret":"hextodec(substr(str,index(str,":")+1,4))
    return ret
NR > 1 {{if(NR==2)print "Local - Remote";local=getIP($2);remote=getIP($3)}{print local" - "remote}}' /proc/net/tcp 


Show lines that match in two files

grep -Ff file1.txt file2.txt