0

Good day, I have read through the similar topics all day long but unfortunately could not find the answer suitable to my situation. So here is what I'm trying to do. I have the shell script with quite a few functions and one of the function supposes to call ssh-agent:

sh_agent_run () {
 case "$(pidof ssh-agent | wc -w)" in
  0)  echo "SSH agent is not running. Startting SSH agent."
      eval `ssh-agent -s`
      ssh-add ${ssh_key}
      ;;
  1)  echo "SSH agent is running. Nothing to do."
      ;;
  *)  echo "Too much instances of SSH agent is running. Stopping SSH agent instances and running just one"
    while pidof ssh-agent; do
      echo "Stopping ssh-agent..."
      killall -9 ssh-agent
      sleep 1
    done
    echo "Starting valid SSH agent instance"
    eval `ssh-agent -s`
    ssh-add ${ssh_key}
  ;;
 esac
}

The output says:

[root@centos versions]# ./ssh_tunnels.sh -sr SSH agent is not running. Startting SSH agent. Identity added: (path to ssh key)

But when I'm trying to connect to the ssh-agent and check the key with ssh-add -L command it says:

[root@centos versions]# ssh-add -l Could not open a connection to your authentication agent.

Could somebody please help me to adjust my function so I can build it into my script and use? This is critical not to run ssh-agent via .bashrc, I need to bale to manage ssh-agent via this script (start, stop, status, etc.)

Thank you in advance

4

In order to make your script work, you're going to have to run it with .:

. ./ssh_tunnels.sh

The . or source command tells bash (YMMV with other shells) to execute the script using the current shell rather than starting a new copy of bash to run the script.

This is needed because the command

eval `ssh-agent -s`

sets environment variables that let all of the other ssh programs know how to communicate with the agent. Environment variables are only valid in the shell they are set in (and any programs run from that shell). They are not passed back up into the parent shell, so unless you run the commands in the current shell with . the SSH_AUTH_SOCK and SSH_AGENT_PID variables will be lost when the script exits.

  • Thanks for your answer, appreciated. It works perfectly fine now, however now I should not use "exit" in my "case" statement to keep the shell opened :) Thanks a lot, you are my life saver! – Alex Miroshnyk Dec 30 '16 at 7:02
2

I recommend keychain from gentoo.

https://wiki.gentoo.org/wiki/Keychain

Also exists as an RPM:

https://www.rpmfind.net/linux/rpm2html/search.php?query=keychain

It gives a cli tool and examples for how to tie into your shell environment.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.