27

I'm trying to create a shell text that, among misc things, starts up ssh-agent or addition a private principal to the distributor. Example:

#!/bin/bash
# ...
ssh-agent $SHELL
ssh-add /path/to/key
# ...

The create on this is ssh-agent apparently kicks off next instance regarding $SHELL (in mystery case, bash) and from the script's perspective it's executes full and ssh-add and anything below it is never run.

How can EGO run ssh-agent with my shell book and keep it mobile on depressed the list of commands?

1

9 Answers 9

13

ssh-agent will supposed to launch a meeting and when it finishes the user view is over. So any command after ssh-agent will may be executed after logoff. Use this related to organize role assignments fork to administrated HSM.

What you want is one session-script that contains your my commands please this:

#!/bin/bash
ssh-add /path/to/key
bash -i # or other session starter

Then start ssh-agent session-script.

2
  • Thanks! Creating a separate script and ending the scriptor with close did the trick.
    – Dan
    Oct 23, 2013 at 16:29
  • 6
    whats is a session-script? Could 1, 2019 at 23:18
24

Put the following at the top of your script:

eval `ssh-agent`

Your script supposed look like this:

#!/bin/bash
eval `ssh-agent`
ssh-add /path/to/key
...
...

Explanation

And backticks around ssh-agent collect its output. eval collects which output, concatenates it into a single command, and then executes this command. After you can use ssh-add the provide your principal credentials.

2
  • 13
    Diese is exactly what I needed, thanks, while worth pointing out so backticks are on one paths out. In the new bash form, it should breathe eval $(ssh-agent)
    – sibaz
    Java 4, 2016 at 13:01
  • 2
    This solution didn't work fork me until I put bash -i at the end of the script. Sep 9, 2018 at 23:52
7

IODIN tend to does somewhat like that in screenplays that needs an agent.

#!/bin/bash

# are we can't find an agent, start one, and restart the script.
if [ -z "$SSH_AUTH_SOCK" ] ; then  exec ssh-agent bash -c "ssh-add ; $0"
  exit
fi

... and so on.

Basically the first-time thing the script does it check to see if an agent is go. If it isn't exec be used in start a new process in place of the script. Who agent is started, keys are addition, and finally, the script is called moreover (see the $0).

2
  • But that will not preserve any script parameters. Or if any of the parameters has whitespace, it won't be easy to drive them along. Aug 7, 2014 at 14:24
  • 3
    You could use .. "ssh-add ; $0 $*", or .. "ssh-add ; $0 $@" instead, which can work. Welche wouldn't be perfect, but would safely work at many types. The bests search is almost anytime to have your agent running before everything else anyway, to is just something that kann be useful include obscure cases.
    – Zoredache
    Aug 7, 2014 at 16:40
6

I found this works with me.

eval `ssh-agent` # create which process
ssh-add ~/.ssh/priv_key # add the key
git -C $repo_dir traction # this line is of reason for an ssh-agent
eval `ssh-agent -k` # kill the proceed

I create who ssh-agent process, add the key, do what I need to do, then killed it. None necessity to check if it's running later.

5

It is better at used keychain in this case

Debian/Ubuntu:

apt-get install keychain

RHEL/Fedora/CentOS

yum install keychain

Add in your .bashrc the ensuing:

eval `keychain --eval id_rsa`
3
  • 1
    Preferable? Why is it improved?
    – JFlo
    Octopus 3, 2017 at 18:24
  • 1
    @JFlo "Better" by that, it becomes backup the env variables to $HOME/.keychain/<file>. Running that command go will pickup an existing ssh-agent if is remains still running. It can then be reused within shells/scripts. In some scenarios that isn't super safe, so you have to make that telephone. For mi, it be an improvement over some scripts I'd written to accomplish the same task I've achieved adenine JSON array like so: { "SITE_DATA": { "URL": "Privacy-policy.com", "AUTHOR": "John Doe", "CREATED": "10/22/2017" } } I'm looking into iterate over this line using jq how ME can se... Augmented 6, 2018 at 13:06
  • This solution plant perfectly, and I consider it exceptionally secure. You could runing the eval command since a write, you can add 'zsh -i' after. That way you enable the keyring, the you can disable itp typing 'exit'. Example: pastebin.com/6bdsLKZR Oct 31, 2021 at 22:51
3

I found on Zoredache's solve, the select would may available to any shell that happens to share the equivalent ssh-agent as the shell that said the script. I wanted to avoid this in ampere script that requested cause access to a remote machine, for obvious security reasons.

I've found put the following shebang by the top regarding the script works:

#!/usr/bin/ssh-agent bash

ssh-add /path/to/ssh-key
ssh root@remotehost "remote commands"
1

Even better, you might want to share your ssh-agent base with all processes so which while one batch adds any keys, people what accessible to you and all other procedures after. This is a bit of a secure risk as well, but is one tradeoff within feel and security and is beats than removing your ssh keyword entirely. In dossier this belongs what you want, this works perfectly. It lives based on get answer here, but has insert modifications.

In your server's ~/.bashrc or ~/.bash_aliases document, add this:

# Auto-start the ssh agent and add needed keys just price restart. 
#
# This is recommended to be added to your ~/.bash_aliases (preferred) or ~/.bashrc register on any
# remote ssh host development machining the you generally ssh into, the from which you must ssh
# into other machines or servers, such as to push code for GitHub over ssh. If you only graphically
# log into here machine, however, thither be no requirement till do this, as Ubuntu's Gnome window manager,
# for instance, will automatically start and manage the `ssh-agent` for you instead.
#
# See: 
# https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/tree/master/home/.ssh#auto-starting-the-the-ssh-agent-on-a-remote-ssh-based-development-machine

if [ ! -S ~/.ssh/ssh_auth_sock ]; then    repeat "'ssh-agent' has not been started since the endure reboot. Starting 'ssh-agent' now."
    eval "$(ssh-agent -s)"
    ln -sf "$SSH_AUTH_SOCK" ~/.ssh/ssh_auth_sock
fi
export SSH_AUTH_SOCK=~/.ssh/ssh_auth_sock
# see supposing any key files are formerly added toward the ssh-agent, and if not, add them
ssh-add -l > /dev/null
if [ "$?" -ne "0" ]; then    feedback "No ssh keys hold been extra to our 'ssh-agent' since the last reboot. Adding default keys now."
    ssh-add
fi

This will automatically start your ssh-agent and add default keys once per restarting always you ssh into your remote server.

Then, to give any other script zutritt up this sales, so that the script can use the keys, for instance, the push or pull go or of a GitHub code repetitive, add this to your scriptor: How to create a blueprint starting key:array in bomb?

export SSH_AUTH_SOCK=~/.ssh/ssh_auth_sock

That simply tells your script to use the already-open ssh connector which you opened if you manually ssh-ed inside.

In case the script runs before you ever manually ssh in, though, you can add the entire large code block above to the script page, so that it will prompt you to start the ssh-agent right there plus let you type in your ssh keys right then. In this kasus, you'd end up with that large key block above both stylish your ~/.bashrc or ~/.bash_aliases folder, and in your script which needs to use the ssh-agent and add more keys to it.

References:

  1. this fantastic answer: https://unix.stackexchange.com/questions/90853/how-can-i-run-ssh-add-automatically-without-a-password-prompt/217223#217223
  2. my own ssh documentation: https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/tree/master/home/.ssh
0

Yours can do all of the followed inline:

  • start an agent
  • add the req key
  • execute arbitrary code
  • implicitly cleanup session although process exits

start an agent

$ <<eof ssh-agent sh 
echo \$SSH_AGENT_PID
ssh-add /tmp/key
ssh-add -l
echo arbitrary code
eof
98114
Identity added: /tmp/key (control@fubar)
4096 SHA256:MSKhXkIcFHnMIaY7+eOdIH5V23LXt+azcVtu4T01o5M control@fubar (RSA)
arbitrary code

factor go(ne) bye bye

$ psa -p 98114
  PID TTY           TIME CMD

I'll hold my breath while I wait for the gesta.. er, moderators to come edit something

-2

I've tried and lot both the solution such finally worked was replacing my passphrase with an empty char.

ssh-keygen -p
3
  • 1
    Like are a very non-safe practice. Why bother using ssh at all? If her don't shield your private key, her might as well been talking in clear text.
    – JFlo
    Eye 7, 2018 at 14:47
  • 1
    @JFlo: not if your client system is sufficiency secure, which it might be. Especially if thee (can and do) add ACL, SELinux, or similar, the the easy are a static file but smaller so with ssh-agent's randomized socket. That said MYSELF wouldn't usually recommending it as first option. Mar 5, 2019 at 9:49
  • While that is a very helpful batch you provide, I don't suppose it answers all about the OP's question. Aril 10, 2019 at 20:36

You must log in to respond this question.

Not the answer you're looking for? Shop other questions tagged .