🖥️ssh

➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the ssh command with important options and switches using examples.

▁ ▂ ▃ ▄ ꧁ 🔴☠ COMMANDLINE-KUNGFU WITH CHEATSHEETS ☠🔴꧂▅ ▃ ▂ ▁

#                ███████╗███████╗██╗  ██╗
#                ██╔════╝██╔════╝██║  ██║
#                ███████╗███████╗███████║
#                ╚════██║╚════██║██╔══██║
#                ███████║███████║██║  ██║
#                ╚══════╝╚══════╝╚═╝  ╚═╝

# ssh
# access a remote host via SSH

# explicitly specify a key for connection
# (if you have Too many authentication failures for *username*)
ssh -i some_id_rsa -o IdentitiesOnly=yes them@there:/path/

# switch off pubkey authentication
ssh -o PubkeyAuthentication=no [email protected]

# Get help on SSH escape sequences
# Useful for terminating unresponsive sessions
# The default escape character is ~ (tilde), escapes are only recognized immediately after newline
$ [Enter]~?

                                        
# To ssh via pem file (which normally needs 0600 permissions):
ssh -i /path/to/file.pem [email protected]

# To connect on an non-standard port:
ssh -p 2222 [email protected]

# To connect and forward the authentication agent
ssh -A [email protected]

# To execute a command on a remote server:
ssh -t [email protected] 'the-remote-command'

# To tunnel an x session over SSH:
ssh -X [email protected]

# Redirect traffic with a tunnel between local host (port 8080) and a remote
# host (remote.example.com:5000) through a proxy (personal.server.com):
ssh -f -L 8080:remote.example.com:5000 [email protected] -N

# To launch a specific x application over SSH:
ssh -X -t [email protected] 'chromium-browser'

# To create a SOCKS proxy on localhost and port 9999
ssh -D 9999 [email protected]

# -X use an xsession, -C compress data, "-c blowfish" use the encryption blowfish
ssh [email protected] -C -c blowfish -X

# For more information, see:
# http://unix.stackexchange.com/q/12755/44856

# Copy files and folders through ssh from remote host to pwd with tar.gz compression
# when there is no rsync command available
ssh [email protected] "cd /var/www/Shared/; tar zcf - asset1 asset2" | tar zxf -

# Mount folder/filesystem through SSH
# Install SSHFS from https://github.com/libfuse/sshfs
# Will allow you to mount a folder securely over a network.
sshfs name@server:/path/to/folder /path/to/mount/point

# Emacs can read file through SSH
# Doc: http://www.gnu.org/software/emacs/manual/html_node/emacs/Remote-Files.html
emacs /ssh:name@server:/path/to/file

[RETURN][RETURN]~C 
# Open openssh's client prompt so you can add another tunnel without having to logout. Example: -L 8080:192.168.1.1:80

#==============================#
# CMD SSH
#==============================##==============================#
ssh -D 9999 you@remotehost
# Use -D to create a SOCKS5 tunnel inside your SSH connection. Some programs (like a web browser) can use these.

ssh -L 9909:192.168.1.1:80 home
# Connections to tcp localhost:9909 will be made to 192.168.1.1:80 via SSH tunnel to home. 

ssh laptop eject -t
#

ssh --like -u fb::Bob_Reach http://alicebates.dyndns.com 
# Use Facebook authentication for SSH and auto "Like" the host too. New ssh options.

ssh -t user1@server1 'ssh -t user2@server2 "ssh -t user3@server3"'
# After all the host keys and auth, you'll be on server3.

ssh -N -L2001:localhost:80 somemachine
# start a tunnel from some machines port 80 to your local post 2001 now you can acces the website by going to http://localhost:2001/ s far as i know. i use this to access a customers intraweb application. this way the customer only needs to open up port 22 (ssh) in the firewall for just one ip address of some machine in your local lan (your hub machine). this way you can hop for your laptop to that local machine to the customers machine. as secure as it get its while still being relatively easy to use. no tokenstuff needed (i hate tokens and the 'supposed better' security).
# The params explaination:
#	-f tells ssh to go into the background (daemonize).
#	-N tells ssh that you don''t want to run a remote command. That is, you only want to forward ports.
#	-q tells ssh to be quiet
#	-L specifies the port forwarding

# If you want use one of the reserved ports (i.e., under 1023), you will have to run as root (using sudo). Also if you want to connect to server behind the DMZ, you can use a intermediate. This is useful where your have your local machine outside a firewall; a visible machine on the DMZ; and a third machine invisible to the outside.

ssh -f -N -q -L 80:192.168.1.69:80 [email protected]
#

ssh -D 9000 somemachine
# Sets up local port 9000 as a SOCKS 5 proxy via somemachine

ssh -f -N -L 8025:smtp.comcast.net:25 my_home_machine -L 8110:mail.comcast.net:110 my_home_machine
# a little more details, for example, in the case of an email client on a laptop, pointing to localhost:8025 for SMTP services, and localhost:8110 for POP3 services associated with a Comcast account, w/out traversing ?foreign? networks with clear text credentials, looks like. then, when changing locations:

ssh -f -N -L 0.0.0.0:8080:google.com:80 me@remote
# You can also allow access to the tunnel from incoming connections besides 127.0.0.1 which is the default when not stipulated. This allows on any net interface
    # or
ssh -f -N -L 10.1.1.120:8080:google.com:80 me@remote
# This allows any machine that can access your 10.1.1.120 interface access to the tunnel. This is not considering firewalls.

ssh -t user1@server1 'ssh -t user2@server2 "ssh -t user3@server3"'
# After all the host keys and auth, you'll be on server3.

ssh -D 8989 you@remotehost
# Create a dynamic SOCKS5 proxy on port 8989 using an SSH connection. Some apps can be configured to use this.

ssh -R *:8080:localhost:80 remoteserver
# Make local webserver available via remoteserver:8080. Req. GatewayPorts yes on sshd

ssh -L 9909:192.168.1.1:80 home
# Connections to tcp localhost:9909 will be made to 192.168.1.1:80 via SSH tunnel to home. 

# You've already ssh'd (openssh) somewhere but forgot to specify socks5 proxy. Just hit 
<Enter> then ~C and then -D 8888

ssh -D 9999 you@remotehost
# Use -D to create a SOCKS5 tunnel inside your SSH connection. Some programs (like a web browser) can use these.

# network copy with ssh and tar - You can use ssh in conjunction with tar to pull an entire directory tree from a remote machine into your current directory:
ssh <username@sourcehost> tar cf - -C <sourcedir> . | tar xvf -

# For example, let's say you have a "bsmith" account on a host called "apple". You want to copy those files into your "bobsmith" account on a host called "pear". You'd log into your "bobsmith@pear" account and type the following:
ssh bsmith@apple tar cf - -C /home/bsmith . | tar xvf -
# This technique is useful when you have insufficient disk space on the source machine to make an intermediate tarball.

while :; do ssh [email protected] -L8081:localhost:80 -N -v -g ; sleep 100; done
# nice; this line is also very lazy/handy; default ssh tunnel plus recovers automatically after failure. do not forget the sleep!

sshfs user@remotehost:/remotedir mydir
# sshfs is a nice util that uses FUSE and SSH to mount a remote directory as a local one.

RCMD_CMD_ARGS='-o VerifyHostKeyDNS=yes -o StrictHostKeyChecking=no' dsh -g all -e true
# Import ssh host keys without verification - Automatically import host keys for cluster of machines named 'all' -> Using the 'dsh' command from the clusterit tools - http://sourceforge.net/projects/clusterit

cat ~/.ssh/id_dsa.pub | ssh me@remotebox "cat >> ~/.ssh/authorized_keys"
# Just an example, concatenating your SSH key on another host.

ssh me@remotebox "ps auxf" | cat > ~/ProccessesForRemoteBox
    or
ssh <.ssh/id_rsa.pub user@server "cat >>.ssh/authorized_keys"
# Or maybe you would rather dump all the processes running on another computer into a local file

cat /dev/dsp | ssh me@remotebox "cat > /dev/dsp"
# What about playing local audio... Remotely (So both computers play the same thing)

ssh $WEBSERVER tail -f $LOGFILE | logstalgia
# See http://logstalgia.io/

ssh backup@<host> "sudo mysqldump $MYSQLOPTS | pbzip2 -c" | tee >($SSH_CMD "cat > $RPATH/<filename>-`date +%Y-%m-%d-%H-%M`.bz2") > $LPATH/<filename>-`date +%H-%M-%S`.bz2
# I use it to copy the output of a backup job to both a local host and a remote location by piping tee's output to ssh

bro-cut -Cd ts host host_p unparsed_version <software.log|awk -F\\t '$2=="10.2.3.4" && $3=="22"{if(l!=$4){print;l=$4}}' 
# SSH version change -  bro-cut is part of the Bro NSM package. The command will search the software.log and print when it detects the version of ssh changing.

# Use -D to create a SOCKS5 tunnel inside your SSH connection. Some programs (like a web browser) can use these.
ssh -D 1917 [email protected] 

ssh machine "while read -r; do DISPLAY=:0 xdotool getactivewindow key space; done" 
# Forgot your pres. remote ? use your phone

ssh-keygen -t rsa -b 4096
#

ssh-copy-id -i /root/.ssh/id_rsa [email protected]
#

openssl pkcs8 -topk8 -v2 des3 -in id_rsa.old -out id_rsa
# Private-Key Sicherer & abwärtskompatible machen: Umwandeln in anderes Format (PCKS#8)

ssh-keygen -R User@Host
# Eintrag aus /root/.ssh/known_hosts Datei löschen

ssh -C
# aktiviert Komprimierung bei schlechter internetleitung - erhöht latenz

ssh -p 2222 [email protected]
# Auf Port 2222 verbinden

ssh -D 3128 [email protected]
# Dynamische Port Weiterleitung um z.B. mit FritzBox zu verbinden ohne Remote-Administration freigeschaltet zu haben. Dazu brauchen Sie zu Hause einen Rechner, der per SSH erreichbar ist. Nun starten Sie den Browser auf Ihrem lokalen Rechner. In der Netzwerkkonfiguration tragen Sie als Proxy die Adresse 127.0.0.1 als Port 3128 und als Protokoll SOCKS5 ein. Auch andere Programme können sie so VPN tunneln, indem Sie ihnen diesen Proxy vorgeben, durch den SSH-Tunnel hindurchsurfen. 

# Setup a SOCKS5 proxy on port 8222 over an SSH connection. You can use this with for instance Mozilla Thunderbird to keep your home IP out of email headers. It will look like it came from the remote host you connect to.
ssh -D 8222 [email protected] 

ssh 192.168.2.155 pwd
# Führt pwd aus und meldet sich wieder ab

&& Und Verknüpfung ->  Zweites Kommando wird nur dann ausgeführt wenn erstes erfolgreich

|| Oder Verknüpfung > Zweite Befehl läuft nur dann wenn erster NICHT erfolgreich war

Um auf diese Weise ein Konsolenprogramm zu starten, das interaktiv arbeitet und Tastatureingaben entgegennimmt müssen Sie SSH zusätzlich den Parameter -t mitgeben

ssh -t
ssh -t huhnix.org 'tail -f /var/log/daemon.log'
# Startet Pseudo Terminal und sorgt dafür das sie so lange eingeloggt bleiben bis Programm beendet ist.
# z.b. tail -f oder top in ssh-pipe

ssh -vvv
# Bringt mehr infos

ssh-copy-id --i ~/.ssh/id_rsa.pub [email protected]
# ssh schlüssel kopieren

ssh -t -X rechner2 ssh -t -X rechner3 xterm &
# Von Rechner1 aus über rechner2 mit rechner3 verbinden und das grafikprogramm xterm starten

scp -r ~/Dokumente/ct [email protected]:
# Ganze verzeichnisbäume rekursive kopieren -> kopiert ordner ct und gesamten inhalt

scp -C 
# Komprimierung

scp -P
# scp auf port - achtung anderst als bei ssh mit -p

scp -l
# Bandbreite beschränken

sftp kann cd, ls, get oder put help, quit pwd exit

sftp -r 
sftp -r [email protected]:Dokumente/ct
# ganze Verzeichnisbäume übertragen

sftp -l
# Bandbreite beschränken

ssh -o ControlMaster=yes -o ControlPath=~/.ssh/control-%h_%p_%r huhnix.org
2. ssh-o ControlPath=~/.ssh/control-%h_%p_%r huhnix.org
# ssh Mulitplexing - d.h mehrere ssh sessions über einzige tcp verbindung schicken. der ssh-client nutzt ab der zweiten verbindung dann eine bereits existierede und verzichtet auf handshake. geschwindigkeitsvorteil -o ControlMaster=yes eine Masterverbindung -o ControlPath= definieren sie den Socket. Beim nächsten ssh aufruf zu diesem Rechner ist lediglich die Option -o ControlPath= erforderlich. Geht auch mit scp und sftp und rsync oder git

~/.ssh/config
ssh wertet diese datei aus
Host Name		#Speziell
Host * 			#Global
CheckHostIP No		# Für dynip adressen

remode ssh dd -> run from remote computer

$ dd if=/dev/sda | gzip -1 - | ssh user@local dd of=image.gz
run from local computer

$ ssh user@remote "dd if=/dev/sda | gzip -1 -" | dd of=image.gz

 
ssh -D 8222 [email protected] 
# Setup a SOCKS5 proxy on port 8222 over an SSH connection. You can use this with for instance Mozilla Thunderbird to keep your home IP out of email headers. It will look like it came from the remote host you connect to.

ssh -R *:8080:localhost:80 remoteserver 
# Make local webserver available via remoteserver:8080. Req. GatewayPorts yes on sshd

ssh -g -L 8025:smtp.other\.net:25 [email protected]\.net 
# Setup SMTP tunnel (listening on yourhost:8025) and allow others to use it (-g)

ssh -D 8989 you@remotehost 
# Create a dynamic SOCKS5 proxy on port 8989 using an SSH connection. Some apps can be configured to use this.

# Test your bash skills.
ssh [email protected] -p 2220

# Run remote X11 applications with ssh
ssh -X servername
# Explanation: You could follow this command with any other call to an X app: xeyes &
# Limitations: If ssh forwarding is permitted on the ssh server

# Put an ssh session in the background
~^z
# Explanation: 
    # Normally, ^z (read: ctrl-z) pauses the execution of the current foreground task. That does not work in an ssh session, because it is intercepted by the remote shell. ~^z is a special escape character for this case, to pause the ssh session and drop you back to the local shell.
    # For all escape characters see ~?
    # The ~ escape character must always follow a newline to be interpreted as special.
    # See man ssh for more details, search for ESCAPE CHARACTERS

# Copy a directory with a large number of files to another server -> 
tar cp -C /path/to/dir . | ssh server2 'tar x -C /path/to/target'
# Explanation: With a large number of files, scp or rsync can take very very long. It's much faster to tar up on one side and extract on the other. Without the -f flag tar writes output to standard output and expects input from standard input, so piping to ssh can work this way, without creating any intermediary files.
# You may (or may not) gain an extra speed boost by compression, either with the z flag for tar, or with the -C flag for ssh, or with gzip pipes in the middle, like this:
    # tar cp -C /path/to/dir . | gzip | ssh server2 'gzip -cd | tar x -C /path/to/target'
# Limitations: Depending on your system and version of tar, you may need to hyphenate the flags, for example tar -cp, and tar -x. The -C flag might also not work, but that shouldn't be too difficult to work around.

# Run a local shell script on a remote server without copying it there
ssh user@server bash < /path/to/local/script.sh

# Explanation: Yes this is almost trivial: a simple input redirection, from a local shell script to be executed by bash on the remote server.
# The important point being, if you have a complex and very long chain of commands to run on a remote server, it is better to put the commands in a shell script, break the long one-liner to multiple lines for readability and easier debugging.
# Replace bash accordingly depending on the language of the script, for example for python:
ssh user@server python < /path/to/local/script.py

http://www.youtube.com/watch?v=8QlNUzWB-iI … 
# Then this one time, in the terminal, I stuck an SSH tunnel inside an SSH tunnel inside an SSH tunnel inside an SSH tunnel inside an SSH tunnel inside an SSH tunnel inside an SSH tunnel inside an SSH tunnel inside an SSH tunnel.... I was using SSH on my smart phone once and I looked up for a moment and thought.. TRUCK!!!!!!!

ssh user@host script && ssh user@host script && ssh user@host script && ssh user@host script && ssh user@host script && ssh user@host script && ssh user@host script 

# Remote Linux Desktop via Linux
# Open a remote linux desktop from an linux client
# the easy way for gnome or kde you need the right skript, f.e. startx could work or startkde
ssh -X  user@servername startxfce4

# this is the difficult way:
# create an window which is bound to display :1
Xnest -geometry 1024x768 :1
# Opens an Terminal via SSH tunnel which starts an remote applikation in an lokal display
xterm -display :1 -e ssh -X user@servername startxfce4   

# bash-ssh-tunnelling
# Useful Bash/Linux SSH tunnelling commands
## Start SSH agent
eval "$(ssh-agent -s)"

## Open SSH tunnel on port 3307
ssh -fN -L 3307:127.0.0.1:3306 [email protected]

## Check the tunnel is active
netstat -lnp | grep ssh | grep :3307

## Close the tunnel
ps aux | grep ssh | grep 3307 # get the pid
kill <pid> # kill process

#SSH connection through host in the middle
ssh -J user@reachable_host user@unreacheable_host

# SSH connection through host in the middle
ssh -J user@reachable_host user@unreacheable_host

# 
cat ~/.ssh/id_rsa.pub | ssh <user>@<hostname> 'cat >> .ssh/authorized_keys && echo "Key copied"'

# port forwarding - pem file used by AWS servers for additional security
ssh -L8888:localhost:80 -i nov15a.pem [email protected]

# SFTP upload through HTTPS proxy - Overwrites remote file without asking! Uses HTTPS proxy that supports CONNECT. Actually uses SSH and not SFTP to upload the file.
cat myFile.json | ssh root@remoteSftpServer -o "ProxyCommand=nc.openbsd -X connect -x proxyhost:proxyport %h %p" 'cat > myFile.json'

# Block all brute force attacks in realtime (IPv4/SSH) -> Was to long with a loop, use a while loop for have it running 24/7
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

# Block all IPv4 addresses that has brute forcing our ssh server -> For ipv6 use: grep -oE "\b([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4}\b"
for idiots in "$(cat /var/log/auth.log|grep invalid| grep -oE '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b')"; do iptables -A INPUT -s "$idiots" -j DROP; done

#==============================##==============================#
# CMD SSH
#==============================##==============================#
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

  █║▌│║█║▌★ KALI ★ PARROT ★ DEBIAN 🔴 PENTESTING ★ HACKING ★ █║▌│║█║▌

              ██╗ ██╗ ██████╗  ██████╗ ██╗  ██╗███████╗██████╗
             ████████╗██╔══██╗██╔═══██╗╚██╗██╔╝██╔════╝██╔══██╗
             ╚██╔═██╔╝██║  ██║██║   ██║ ╚███╔╝ █████╗  ██║  ██║
             ████████╗██║  ██║██║   ██║ ██╔██╗ ██╔══╝  ██║  ██║
             ╚██╔═██╔╝██████╔╝╚██████╔╝██╔╝ ██╗███████╗██████╔╝
              ╚═╝ ╚═╝ ╚═════╝  ╚═════╝ ╚═╝  ╚═╝╚══════╝╚═════╝

               █║▌│║█║▌ WITH COMMANDLINE-KUNGFU POWER █║▌│║█║▌

░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░