summaryrefslogtreecommitdiffstats
path: root/bashrc/common
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--bashrc/common/ssh-agent-forwarding.sh55
1 files changed, 55 insertions, 0 deletions
diff --git a/bashrc/common/ssh-agent-forwarding.sh b/bashrc/common/ssh-agent-forwarding.sh
new file mode 100644
index 0000000..fc43ee1
--- /dev/null
+++ b/bashrc/common/ssh-agent-forwarding.sh
@@ -0,0 +1,55 @@
+TMPFILE=$(mktemp)
+
+# cleanup old agent-sockets
+if [ -r "${HOME}/.ssh-agent-forwardin" ]; then
+ cut -d" " -f2 "${HOME}/.ssh-agent-forwarding" | \
+ xargs ls -a 2>/dev/null | \
+ grep -f - "${HOME}/.ssh-agent-forwarding" | \
+ sort -n > "${TMPFILE}"
+
+ mv "${TMPFILE}" "${HOME}/.ssh-agent-forwarding"
+fi
+
+# if this login is via ssh and ssh-agent is forwarded
+if [ -n "$SSH_AUTH_SOCK" -a -n "$SSH_CLIENT" ]; then
+
+ # add current socket
+ echo "$(date +%s) $SSH_AUTH_SOCK $SSH_CLIENT" >> "${TMPFILE}"
+fi
+
+if [ -z "$SSH_AUTH_SOCK" -a -r "${HOME}/.ssh-agent-forwarding" ]; then
+ SSH_AUTH_SOCK=$(tail -n 1 "${HOME}/.ssh-agent-forwarding" | cut -d" " -f2)
+ export SSH_AUTH_SOCK
+fi
+
+fixssh() {
+ if [ ! -r "${HOME}/.ssh-agent-forwarding" ]; then
+ echo "No ssh-agent forwardings found."
+ return 1
+ fi
+
+ if [ -z "$1" -o "$1" == "latest" ]; then
+ SSH_AUTH_SOCK=$(tail -n 1 "${HOME}/.ssh-agent-forwarding" | cut -d" " -f2)
+ else
+ REMOTE=$(echo $1 | grep -o "[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}")
+
+ if [[ "$REMOTE" == "$1" ]]; then
+ SSH_AUTH_SOCK=$(grep " $REMOTE " "${HOME}/.ssh-agent-forwarding" | head -n 1 | cut -d" " -f2)
+ else
+ REMOTE=$(dig +short "$1" | tr '\n' ' ')
+
+ if [ -n "${REMOTE}" ]; then
+ SSH_AUTH_SOCK=$(grep " ${REMOTE##*: } " "${HOME}/.ssh-agent-forwarding" | head -n 1 | cut -d" " -f2)
+ else
+ SSH_AUTH_SOCK=$(grep "$1" "${HOME}/.ssh-agent-forwarding" | head -n 1 | cut -d" " -f2)
+ fi
+ fi
+ fi
+
+ if [ -z "$SSH_AUTH_SOCK" ]; then
+ echo "Nothing found!"
+ return 1
+ fi
+
+ export SSH_AUTH_SOCK
+}