简体   繁体   中英

How to run ssh-agent and ssh-add through an SH script?

I have two following commands which I manually run when I connect on my VPS:

eval ssh-agent $SHELL
ssh-add /home/duvdevan/.ssh/id_rsa

I tried adding them into a ssh.sh and run it within that directory using:

./ssh.sh

But nothing happends.

I'm not that bash -savvy so any help is appreciated.

Instead of running, you need to source the script:

. ./ssh.sh

Otherwise, the environment variables set by the eval command will not be visible in your current shell, and so it cannot know where to find the running ssh agent.

To give a bit more background, here's how this works:

  • the ssh-agent command starts an ssh agent, and prints to stdout the environment variables you need to set to connect to the agent. The output is formatted as commands to execute. For a test, you can just run this command and see what it prints
  • the eval command executes the commands printed by ssh-agent . As mentioned earlier, these are commands to set environment variables. After these are executed, the ssh commands you will run in this shell will know where to find the agent
  • the ssh-add command is able to find the agent, thanks to the environment variables set earlier
  • these variables are set until the script exits. When you run ./ssh.sh , the variables are set inside the process of that script, and longer available after the script is finished
  • by sourcing the ssh.sh script using . , the commands inside will be executed in the current shell, and therefore the environment variables are still set, and so your ssh related command can find the agent

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM