summaryrefslogtreecommitdiffstats
path: root/bashrc/common/ssh-agent-forwarding.sh
blob: fc43ee13852ff5800533581ae707094740ca91c6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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
}