Last active
September 21, 2022 05:24
-
-
Save lesca/995f56cb88f529736a5b3d80883f8961 to your computer and use it in GitHub Desktop.
easily re-use ssh-agent session
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# agent file | |
agentFile="$HOME/ssh-agent.txt" | |
function getCurrentKey { | |
# current key | |
currentKey=$(ssh-add -l) | |
errorCode=$? | |
echo Status=$errorCode | |
echo $currentKey | |
return $errorCode | |
} | |
function addKey { | |
# if no key then exit | |
[[ ! -f "$HOME/.ssh/id_rsa" ]] && echo "Error: id_rsa not exists." && exit | |
# new agent | |
ssh-agent -s > $agentFile | |
# load agent to current context | |
source $agentFile | |
# add the key to current agent | |
ssh-add | |
} | |
function connect { | |
# if pre-defined | |
[[ "$1" == "" ]] && con="-p 2222 lesca@localhost" | |
# else use $1 | |
[[ "$con" == "" ]] && con=$1 | |
# connect | |
echo "Connecting to host - $con" | |
ssh $con | |
exit | |
} | |
function clean { | |
echo "Cleaning cached keys ..." | |
killall ssh-agent 2> /dev/null | |
rm -f $agentFile | |
exit | |
} | |
# clean | |
[[ "$1" == "clean" ]] && clean | |
# get current key | |
echo "Looking for key from memory ..." | |
getCurrentKey | |
errorCode=$? | |
[[ "$errorCode" == "0" ]] && connect $1 | |
[[ "$errorCode" != "0" ]] && ssh-agent -k 2> /dev/null | |
[[ "$errorCode" != "0" ]] && [[ -f "$agentFile" ]] && echo "Reusing agent file ..." && source $agentFile | |
# check key again | |
echo "Looking for key from agent file ..." | |
getCurrentKey | |
errorCode=$? | |
[[ "$errorCode" == "0" ]] && connect $1 | |
[[ "$errorCode" != "0" ]] && ssh-agent -k 2> /dev/null | |
[[ "$errorCode" != "0" ]] && echo "Addding key ..." && addKey | |
# check key again | |
echo "Looking for just added key ..." | |
getCurrentKey | |
errorCode=$? | |
[[ "$errorCode" == "0" ]] && connect $1 | |
[[ "$errorCode" != "0" ]] && ssh-agent -k 2> /dev/null | |
[[ "$errorCode" != "0" ]] && echo "Failed adding key ..." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment