How to safely start the ssh-agent from .bashrc
Here is a quick script addition to our .bashrc file which will start a ssh-agent once and load the proper environment variables for the other terminal you will sub-sequentially open.
------ cut here ------->
test=`/bin/ps -ef | /bin/grep ssh-agent | /bin/grep ${USER} | /usr/bin/awk '{print $2}' | xargs`
if [ ! -e "$HOME/agent.sh" -o "$test" = "" ]; then
if [ ! -e "$HOME/agent.sh" -a "$test" != "" ]; then
kill -9 ${test}
else
/usr/bin/test -e $HOME/agent.sh && /bin/rm -f $HOME/agent.sh
fi;
/usr/bin/ssh-agent >&$HOME/agent.sh.tmp && \
/bin/sed "s/echo/#echo/" $HOME/agent.sh.tmp >$HOME/agent.sh && \
/bin/rm -f $HOME/agent.sh.tmp
fi;
/usr/bin/test -e $HOME/agent.sh && source $HOME/agent.sh
alias kagent="kill -9 $SSH_AGENT_PID"
<------ cut here -------
Tips
- Most trivial remark: the above is a SH script and it sources the agent.sh - please verify that ssh-agent output sh commands (and not csh commands). If your system global default shell is bash or sh, this will be true.
- If you use this script, please use
% ssh-add -L
to check if keys are already upload or load them using the same command. ssh-add cannot be automated in .bashrc since it will prompt for your passphrase.
- Note that the file agent.sh resides in your home directory. If on any terminal, ssh-add tells you
Could not open a connection to your authenticated agentthen source agent.sh and try again
- Starting an agent automatically in this manner implies that ANYONE having access to your machine, laptop could access your remote accounts without having to type a password. You MUST understand this includes automated command executed on your behalf. To minimize this risk, consider the following:
- Be careful of the use of an agent on a node which is not a personal laptop or computer. If multiple people have access to the machine, consider it a NO start.
- If you do start an agent, upload your keys when needed. You may destroy your keys by using the
% ssh-add -D
command. You may also destroy the agent (which will have the same effect).
- The command kagent has been defined above to kill the first agent detached via this method.
- To make sure -A option is implicit while using ssh (and/or -X) consult Caveats, issues, special cases and possible problems for further information on tweaking your client side $HOME/.ssh/config .
PLease, le me know if this script causes problems and your suggestion to improve.
- jeromel's blog
- Login or register to post comments
