The scripts I posted to open SSH connections through port knocking are very useful to me. But when it comes to transferring files with SCP, port knocking is a nightmare. So I’ve done a similar bash function that automatically deals with the knocks before starting the scp command.
I’ve introduced a delay of 0.5 seconds between the knocks, because I noticed that sometimes the server was not responding to the knocks. The gist code available at GitHub for the pssh() bash function has also been updated with the delay.
#!/bin/bash
# SCP Connection Port Knocker## 1 - Append this code to your .bashrc or .bash_profile file# 2 - Create a .portknocks file in your home directory with a list like# host1 port1# host1 port2# ...# host1 portN# host2 port1# ...# 3 - You must open a new terminal session to use the new function# 4 - Use it as you would use the ssh command# scp user@server:~/hello ~/hello => psscp user@server:~/hello ~/hello## It accepts the usual options of the SCP program
psscp() { while getopts "dfl:prtvBCc:i:P:q1246S:o:F:" FLAG dotruedone
j=$OPTIND while [ ${@:$j:1} ] doHOST=${@:$j:1} HOST=${HOST#*@} HOST=${HOST%:*} if [ "$HOST" != "." ] && [ "$HOST" != ".." ] thenHOSTS="${HOSTS}${HOST}\n" fi ((j++)) done
echo -e $HOSTS | sort -u | \ while read HOST doif [ $HOST ] thenCNT=1 cat ~/.portknocks | grep ^$HOST | awk '{ for(i=2; i <= NF; i++) printf "%s\n", $i}' | \ while read PORT doecho "Knocking $HOST ($CNT)" nc -w 1 $HOST $PORT & sleep 0.5 && ((CNT++)) donefidone
scp $*}
