Skip to content

Instantly share code, notes, and snippets.

@daniellowtw
Last active January 17, 2020 17:51
Show Gist options
  • Save daniellowtw/35e34571d3938786d254084d618ff0b8 to your computer and use it in GitHub Desktop.
Save daniellowtw/35e34571d3938786d254084d618ff0b8 to your computer and use it in GitHub Desktop.
sshrc
#!/usr/bin/env bash
# Source: https://liam.sh/post/importing-bash-functions-over-ssh
sshrc() {
local SSHHOME=${SSHHOME:=~}
if [ ! -f $SSHHOME/.sshrc ]; then
echo "No such file: $SSHHOME/.sshrc"
exit 1
fi
local sshrcfile=.sshrc
SIZE=$(tar cz -h -C $SSHHOME .sshrc | wc -c)
if [ $SIZE -gt 65536 ]; then
echo >&2 $'.sshrc must be less than 64kb\ncurrent size: '$SIZE' bytes'
exit 1
fi
ssh -t "$@" "
command -v xxd > /dev/null 2>&1 || { echo >&2 \"sshrc requires xxd to be installed on the server, but it's not. Aborting.\"; exit 1; }
export SSHHOME=/tmp;echo $'"$(cat "$0" | xxd -p)"' | xxd -p -r > \$SSHHOME/sshrc;chmod +x \$SSHHOME/sshrc
echo $'"$(
cat <<'EOF' | xxd -p
if [ -e /etc/etc/profile ];then source /etc/profile;fi
if [ -e /etc/bashrc ];then source /etc/bashrc;fi
if [ -e /etc/bash.bashrc ];then source /etc/bash.bashrc;fi
if [ -e ~/.bashrc ];then source ~/.bashrc;fi
export PATH=$PATH:$SSHHOME;source $SSHHOME/.sshrc;
cat $SSHHOME/.sshrc | sed -rn "s:function ([a-zA-Z]+) .*:\1:p" | while read fnc;do export -f $fnc;done > /dev/null 2>&1
rm -f $SSHHOME/.post-sshrc $SSHHOME/.sshrc $SSHHOME/sshrc > /dev/null 2>&1 || echo "Unable to cleanup sshrc"
EOF
)"' | xxd -p -r > \$SSHHOME/.post-sshrc
echo $'"$(tar cz -h -C $SSHHOME .sshrc | xxd -p)"' | xxd -p -r | tar mxz -C \$SSHHOME
export SSHHOME=\$SSHHOME;bash --rcfile \$SSHHOME/.post-sshrc
"
}
if [ $1 ]; then
command -v xxd >/dev/null 2>&1 || {
echo >&2 "sshrc requires xxd to be installed locally, but it's not. Aborting."
exit 1
}
sshrc $@
else ssh; fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment