How can I run ssh-add automatically, without a password prompt?












216














I want to communicate between several computers on my network (static Ethernet), through SSH. In order to do that I need to run ssh-add every time I log in on a specific machine, how can I do it so that it's set up once and it doesn't ask me for the passphrase every time I log in or reboot my machine?



I know that there is a way that you should add some lines to the bash_profile file, but I still need to type the password every time I reboot/log in to a specific machine.



if [ -z "$SSH_AUTH_SOCK" ] ; then
eval `ssh-agent -s`
ssh-add
fi









share|improve this question
























  • similar to this question stackoverflow.com/questions/18880024/start-ssh-agent-on-login
    – steampowered
    May 9 '16 at 16:33
















216














I want to communicate between several computers on my network (static Ethernet), through SSH. In order to do that I need to run ssh-add every time I log in on a specific machine, how can I do it so that it's set up once and it doesn't ask me for the passphrase every time I log in or reboot my machine?



I know that there is a way that you should add some lines to the bash_profile file, but I still need to type the password every time I reboot/log in to a specific machine.



if [ -z "$SSH_AUTH_SOCK" ] ; then
eval `ssh-agent -s`
ssh-add
fi









share|improve this question
























  • similar to this question stackoverflow.com/questions/18880024/start-ssh-agent-on-login
    – steampowered
    May 9 '16 at 16:33














216












216








216


175





I want to communicate between several computers on my network (static Ethernet), through SSH. In order to do that I need to run ssh-add every time I log in on a specific machine, how can I do it so that it's set up once and it doesn't ask me for the passphrase every time I log in or reboot my machine?



I know that there is a way that you should add some lines to the bash_profile file, but I still need to type the password every time I reboot/log in to a specific machine.



if [ -z "$SSH_AUTH_SOCK" ] ; then
eval `ssh-agent -s`
ssh-add
fi









share|improve this question















I want to communicate between several computers on my network (static Ethernet), through SSH. In order to do that I need to run ssh-add every time I log in on a specific machine, how can I do it so that it's set up once and it doesn't ask me for the passphrase every time I log in or reboot my machine?



I know that there is a way that you should add some lines to the bash_profile file, but I still need to type the password every time I reboot/log in to a specific machine.



if [ -z "$SSH_AUTH_SOCK" ] ; then
eval `ssh-agent -s`
ssh-add
fi






ssh ssh-agent






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 22 mins ago









Peter Mortensen

88758




88758










asked Sep 16 '13 at 10:31









zdun8zdun8

1,212497




1,212497












  • similar to this question stackoverflow.com/questions/18880024/start-ssh-agent-on-login
    – steampowered
    May 9 '16 at 16:33


















  • similar to this question stackoverflow.com/questions/18880024/start-ssh-agent-on-login
    – steampowered
    May 9 '16 at 16:33
















similar to this question stackoverflow.com/questions/18880024/start-ssh-agent-on-login
– steampowered
May 9 '16 at 16:33




similar to this question stackoverflow.com/questions/18880024/start-ssh-agent-on-login
– steampowered
May 9 '16 at 16:33










14 Answers
14






active

oldest

votes


















304














This is a typical example of a trade-off between security and convenience. Luckily there are a number of options. The most appropriate solution depends on the usage scenario and desired level of security.



ssh-key with passphrase, no ssh-agent



Now the passphrase has to be entered every time the key is used for authentication. While this is the best option from a security standpoint, it offers the worst usability. This may also lead to a weak passphrase being chosen in-order-to lessen the burden of entering it repeatedly.



ssh-key with passphrase, with ssh-agent



Adding the following to ~/.bash_profile will automatically start ssh-agent and load the ssh-key(s) on login:



if [ -z "$SSH_AUTH_SOCK" ] ; then
eval `ssh-agent -s`
ssh-add
fi


Now the passphrase must be entered upon every login. While slightly better from a usability perspective, this has the drawback that ssh-agent prompts for the passphrase regardless of if the key is to be used or not during the login session. Each new login also spawns a distinct ssh-agent instance which remains running with the added keys in memory even after logout, unless explicitly killed.



To kill ssh_agent on logout, add the following to ~/.bash_logout



if [ -n "$SSH_AUTH_SOCK" ] ; then
eval `/usr/bin/ssh-agent -k`
fi


or the following to ~/.bash_profile



trap 'test -n "$SSH_AUTH_SOCK" && eval `/usr/bin/ssh-agent -k`' 0


Creating multiple ssh-agent instances can be avoided by creating a persistent communication socket to the agent at a fixed location in the file system, such as in Collin Anderson's answer. This is an improvement over spawning multiple agents instances, however, unless explicitly killed the decrypted key still remains in memory after logout.



On desktops, ssh-agents included with the desktop environment, such as the Gnome Keyring SSH Agent, can be a better approach as they typically can be made to prompt for the passphrase the first time the ssh-key is used during a login session and store the decrypted private key in memory until the end of the session.



ssh-key with passphrase, with ssh-ident



ssh-ident is a utility that can manage ssh-agent on your behalf and load identities as necessary. It adds keys only once as they are needed, regardless of how many terminals, ssh or login sessions that require access to an ssh-agent. It can also add and use a different agent and different set of keys depending on the host being connected to, or the directory ssh is invoked from. This allows for isolating keys when using agent forwarding with different hosts. It also allows to use multiple accounts on sites like GitHub.



To enable ssh-ident, install it and add the following alias to your ~/bash_profile:



alias ssh='/path/to/ssh-ident'


ssh-key with passphrase, with keychain



keychain is a small utility which manages ssh-agent on your behalf and
allows the ssh-agent to remain running when the login session ends. On subsequent logins, keychain will connect to the existing ssh-agent instance. In practice, this means that the passphrase must be be entered only during the first login after a reboot. On subsequent logins, the unencrypted key from the existing ssh-agent instance is used. This can also be useful for allowing passwordless RSA/DSA authentication in cron jobs without passwordless ssh-keys.



To enable keychain, install it and add something like the following to ~/.bash_profile:



eval `keychain --agents ssh --eval id_rsa`


From a security point of view, ssh-ident and keychain are worse than ssh-agent instances limited to the lifetime of a particular session, but they offer a high level of convenience. To improve the security of keychain, some people add the --clear option to their ~/.bash_profile keychain invocation. By doing this passphrases must be re-entered on login as above, but cron jobs will still have access to the unencrypted keys after the user logs out. The keychain wiki page has more information and examples.



ssh-key without passphrase



From a security standpoint, this is the worst option since the private key is entirely unprotected in case it is exposed. This is, however, the only way to make sure that the passphrase need not be re-entered after a reboot.



ssh-key with passphrase, with ssh-agent, passing passphrase to ssh-add from script



While it might seem like a straightforward idea to pass the passphrase to ssh-add from a script, e.g. echo "passphrasen" | ssh-add, this is not as straighforward as it seems as ssh-add does not read the passphrase from stdin, but opens /dev/tty directly for reading.



This can be worked around with expect, a tool for automating interactive applications. Below is an example of a script which adds a ssh-key using a passphrase stored in the script:



#!/usr/bin/expect -f
spawn ssh-add /home/user/.ssh/id_rsa
expect "Enter passphrase for /home/user/.ssh/id_rsa:"
send "passphrasen";
expect "Identity added: /home/user/.ssh/id_rsa (/home/user/.ssh/id_rsa)"
interact


Note that as the passphrase is stored in plaintext in the script, from a security perspective, this is hardly better than having a passwordless ssh-key. If this approach is to be used, it is important to make sure that the expect script containing the passphrase has proper permissions set to it, making it readable, writable and runnable only by the key owner.






share|improve this answer



















  • 1




    Okay, but when I put your code to ~/.bash_profile I have to type in password every time I login, I don't want that either. I am not concerned about security at all. echo "passn" | ssh-add doesn't work
    – zdun8
    Sep 17 '13 at 12:59






  • 3




    @user1607072 Yeah, that is how the ssh-agent snippet in ~/.bash_profile behaves as explained in the answer. You might want to look at the keychain utility. With keychain you need to enter the password on first login after reboot, but on subsequent logins keychain will connect to an existing ssh-agent instance with the decrypted key in memory. Apart from that there's the option of generating a ssh-key without a passphrase, but this is of course not recommended.
    – Thomas Nyman
    Sep 17 '13 at 13:35






  • 2




    @user1607072 While I would strongly suggest one of the more secure approaches, there is a way to pass the passphrase to ssh-add from a script. The reason echo "passn" | ssh-add does not work is that ssh-add does not read the password from stdin, but opens /dev/tty directly for reading. Updated the answer to include a workaround for this, using an utility called expect.
    – Thomas Nyman
    Sep 17 '13 at 18:03








  • 1




    @user1607072 It might be a bit overkill for your use case, but Kerberos in combination with ssh GSSAPI support can also be used for passwordless ssh logins. The corresponding authentication method in ssh is called gssapi-with-mic. This is usually used in larger networks, but of course if you have interest in this it might be worth looking into.
    – Thomas Nyman
    Sep 18 '13 at 11:54








  • 1




    @ErickBrown: Already answered here. The SSH Agent unit should be stopped on logout if you have user lingering disabled in the systemd login manager. If user lingering is enabled, the systemd user instance and the SSH Agent unit are kept running even after the last login session is closed.
    – Thomas Nyman
    Jul 25 '18 at 8:00



















79














Add this to your ~/.bashrc:



if [ ! -S ~/.ssh/ssh_auth_sock ]; then
eval `ssh-agent`
ln -sf "$SSH_AUTH_SOCK" ~/.ssh/ssh_auth_sock
fi
export SSH_AUTH_SOCK=~/.ssh/ssh_auth_sock
ssh-add -l > /dev/null || ssh-add


This should only prompt for a password the first time you login after each reboot. It will keep reusing the same ssh-agent as long as it stays running.






share|improve this answer



















  • 1




    very neat, this way you only have one ssh-agent running (: Multiple agents as in @thomasNyman's second solution seems a security risk to me...
    – drevicko
    Feb 10 '16 at 11:54






  • 1




    After researching in various sites and reading various solutions, this one here seems to be the clearest, straight to the point. Very nice. +1
    – Dr Beco
    Jul 18 '16 at 0:40






  • 1




    better to do this: `alias ssh=ssh-check-agent", and have the check-agent version do the above. that way: a) you only get one agent and b) you only get the agent if you need it
    – Erik Aronesty
    Jul 26 '16 at 20:31








  • 2




    I think -s is the default, so we're already doing that.
    – Collin Anderson
    Nov 22 '16 at 16:25






  • 1




    ssh-add -l returns an exit code of 0 when the agent has identities and 1 when it does not so you can cut grep out of the last command and use ssh-add -l > '/dev/null' || ssh-add
    – Grant Humphries
    Dec 20 '16 at 2:21





















11














Not closely related to the OP's question, but it might be useful to others: since 7.2.0 ssh(1) has an option that allows adding a key to ssh-agent upon first authentication; the option is AddKeysToAgent and can be set to yes, no, ask, or confirm, systemwide or on your personal .ssh/config file.



Reference: https://www.openssh.com/txt/release-7.2






share|improve this answer



















  • 2




    Applicable to those who are new to the .ssh/config file: this applies to ssh and anything that uses ssh behind it, for example scp, and can be done on a per-host basis.
    – SEoF
    Sep 25 '17 at 14:32



















5














ssh-agent caches various unlocked ssh-keys, so you can have ssh-keys protected by passwords, but without having to type them every single time.



In order to cache unlocked keys, it obviously needs to unlock those keys. For unlocking keys that are locked with a passphrase, it obviously needs to know these passphrases.



Any method that does not require authorization from a human being (e.g. "typing in a password") will not only make your system insecure; it will also render the entire purpose of the ssh-agent meaningless.



Having said all this, you can simply use ssh-keys that are not password protected (hit Enter when asked for a password during key-generation).
Since there isn't any password, ssh-agent doesn't need to ask you for one in order to (not) cache it.






share|improve this answer























  • I agree, as long as your keys are properly user-only-permissioned, there is little advantage to ssh-agent over permissionless keys. i like to ssh into a login server, and then, that server has a bunch of permssionless keys, each of which can only be used to unlock one other server. the login server does nothing else, so it's much harder to hack/spoof, etc... the other servers have no password access, are key-only.
    – Erik Aronesty
    Jul 26 '16 at 20:34





















4














I won't recommend you ssh-add (which need to open a ssh-agent) at login. This is because you can't control when the ssh-agent section ends, and can create security risk when you need not use the keyfiles at one login section.



Rather, I recommend to write a script which opens a ssh-agent's section sub-shell, with all keyfiles auto added, and be called when needed to use ssh. If you could adopt so, read on.



You would have two choices:




  1. Remove all passphrases for your keys, which have weak security if your key files are stolen. (thus not recommended)


  2. Use the same passphrase for your keys. Then when you ssh-add keyfile1 keyfile2 ..., you will only need to type the passphrase once, per section.



In both cases, you could write such script file "ssh_keys_section.sh" as below:



#!/bin/bash
# This script run a ssh-agent on a sub-shell and automatically ssh-add all keyfiles at once.
# This agent ends when you type `exit` to close the sub-shell.
exec ssh-agent bash -c "ssh-add /path/to/keyfile1 /path/to/keyfile2 ...; exec bash"


Remarks:




  • Command to change or delete passphrase: ssh-keygen -p -f keyfile

  • Within the sub-shell, you might even fork more terminals which share the same unlocked keys, by using maybe a command like /path/to/yourterminal & (depends on OS)






share|improve this answer































    3














    Here is a workaround to automate your SSH passphrase.





    1. Create a one-liner script which prints your passphrase to standard output, e.g.:



       echo 'echo MY_SSH_PASSWORD' > ~/.print_ssh_password && chmod 700 ~/.print_ssh_password


      Important: Ensure you copy the leading space to prevent storing your password to your history.




    And use one of the below methods.





    • using a standard input approach:



      cat ~/.ssh/id_rsa | SSH_ASKPASS=~/.print_ssh_password ssh-add -



    • or named pipe approach:





      1. Create a named pipe (you could also try a process substitution):



        mkfifo --mode 0600 ~/.ssh_fifo



      2. Run ssh-add by specifying the program used for the authentication:



        cat ~/.ssh/id_rsa >~/.ssh_fifo | SSH_ASKPASS=~/.print_ssh_password ssh-add ~/.ssh_fifo



      See: man ssh-add to read more about SSH_ASKPASS.








    share|improve this answer



















    • 1




      The echo my_passphrase is a big security hole. First after you have typed it, the password is in clear text in the history file of what ever shell you use. And second command line arguments are world readable on Unix (ps -ef). Never put passwords in command line arguments!
      – ceving
      Aug 24 '16 at 9:03






    • 1




      @ceving Adding extra leading space solves the problem with the history file. Added extra info.
      – kenorb
      Aug 24 '16 at 9:25










    • @kenorb: That doesn't solve the bigger problem of the password visible in ps output. The history file is typically only readable by the owning user anyway, but the command lines are readable by all users on a system.
      – Thomas Nyman
      Nov 23 '16 at 14:37



















    2














    if [ ! -S ${HOME}/.ssh/ssh_auth_sock ]; then
    eval $(ssh-agent)
    ln -sf "${SSH_AUTH_SOCK}" ${HOME}/.ssh/ssh_auth_sock
    fi
    export SSH_AUTH_SOCK=${HOME}/.ssh/ssh_auth_sock

    ssh_keys=$(find -E ~/.ssh -type f -regex '.*(rsa$|pem)')
    ssh_agent_keys=$(ssh-add -l | awk '{key=NF-1; print $key}')

    for k in "${ssh_keys}"; do
    for l in "${ssh_agent_keys}"; do
    if [[ ! "${k}" = "${l}" ]]; then
    ssh-add "${k}" > /dev/null 2>&1
    fi
    done
    done





    share|improve this answer































      1














      SSH_ENV="$HOME/.ssh/environment"

      function start_agent {
      echo "Initialising new SSH agent..."
      /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
      echo succeeded
      chmod 600 "${SSH_ENV}"
      . "${SSH_ENV}" > /dev/null
      /usr/bin/ssh-add;
      }

      # Source SSH settings, if applicable

      if [ -f "${SSH_ENV}" ]; then
      . "${SSH_ENV}" > /dev/null
      #ps ${SSH_AGENT_PID} doesn't work under cywgin
      ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
      start_agent;
      }
      else
      start_agent;
      fi


      Giving credit here: https://www.cygwin.com/ml/cygwin/2001-06/msg00537.html



      This solution is also endorsed here: http://mah.everybody.org/docs/ssh






      share|improve this answer





























        1














        Single sign on solution for SSH could lead me to pam_ssh.



        According to this article, the concept is:




        If you work with multiple *nix-based machines via ssh, you are probably tired of constantly having to enter your password every time you want to access another box. There is a secure way to allow you to access every machine, that you have ssh access to, without having to enter another password (other than the one you signed on with originally.)







        This is actually quite simple to do, you basically just create a public/private key pair to authenticate yourself to your other machines, then have PAM spawn an agent to load your keys after you logon, providing a single signon solution to accessing all your remote machines. This guide will walk you through setting this up.




        I have not verified this would actually work.






        share|improve this answer































          1














          I used to use the script mentioned by steampowered, I've made the below one now, because it doesn't leave files lying around.



          Working on zsh shell only.



          #!/bin/sh

          AGENT_BIN=`which ssh-agent`
          AGENT_ADD_BIN=`which ssh-add`
          AGENT_PID=`ps -fe | grep ${AGENT_BIN} | awk -vuser=$USER -vcmd="$AGENT_BIN" '$1==user && $8==cmd{print $2;exit;}'`
          if [ -z "$AGENT_BIN" ]; then
          echo "no ssh agent found!";
          return
          fi
          if [ "" -eq "$AGENT_PID" ]; then
          if read -sq "YN?Do you want to unlock your ssh keys?"; then
          echo ""
          output=`$AGENT_BIN | sed 's/echo/#echo/g'`
          eval $output
          $AGENT_ADD_BIN
          fi
          else
          for f in "/proc/"*
          do
          cmdline=`cat "$f/cmdline"`
          if [ "${AGENT_BIN}" -ef "${cmdline}" ]; then
          export SSH_AUTH_SOCK=`cat $f/net/unix | grep --binary-file=text -oP '((/[^/]*?)+/ssh-[^/]+/agent.d+$)'`
          export SSH_AGENT_PID=${f##*/}
          break;
          fi
          done
          fi





          share|improve this answer































            0














            Add this to your ~/.bashrc file:



            ssh-add -L|grep identities > /dev/null && ssh-add /path/to/ssh/private/key





            share|improve this answer























            • I don't see how this relates to the question, which is about not being prompted for the password on subsequent logins.
              – Chris Down
              Jan 6 '14 at 13:23





















            0














            In order to add a (possibly passwordless) key and ensure that ssh-add will not prompt for a password, no matter what, even when running under X:



            DISPLAY= ssh-add -k /path/to/key </dev/null &>/dev/null


            Exit status indicates success or failure.






            share|improve this answer





























              0














              If you are running seahorse as your password manager
              ... Which you probably are ;D



              Another solution that achieves the goal you are looking for is simply adding the ssh keys to seahorse for automatic unlock upon login. The major benefit to this is that you never have to enter a password for the keys after you login through gdm, or whatever your loging in with even if the keys have a password. This REQUIRES both the private key and the public key. They also MUST follow a naming convention for seahorse. The default is acceptable (id_rsa for private key and id_rsa.pub for public key... Really anything that is privatekeyname and privatekeyname.pub)



              To add you ssh key to seahorse for automatic unlock upon login;
              (on fedora25, I'm not sure where the path is on other distros though its most likely very similar)



              /lib64/seahorse/seahorse-ssh-askpass /path/to/keys/here


              For me, it was



              /lib64/seahorse/seahorse-ssh-askpass ~/.ssh/id_rsa


              (seahorse will automatically assume that the public key in my case was id_rsa.pub)



              After executing the command, seahorse will pop open a cute little gtk password field to enter the password for the private key into. or just leave it blank if you generated the key without a password.



              Seahorse won't prompt you if everything went okay. You will need to attempt to ssh into the target machine. Then seahorse will prompt you to unlock the key with a password graphically (THIS WILL ONLY HAPPEN ONCE) again but it should look a little different this time ;P (this is also the part where seahorse does some seahorse to ssh-add magic I believe), and offer the OPTION to unlock the key upon login, you must check this option to achieve your goal.



              Just because I didn't read all the answers, I would recommend undoing what everyone told you to do with ssh-add before attempting this answer. Doing so otherwise might result in something bad happening to your keys, idk.






              share|improve this answer





























                0














                Here is the definitive script.



                Update $PASSW, then copy-paste it in your Terminal



                # <sshpass> via typinator
                # Updated: 2017-01-18_21h36
                #
                # apt-get update -y; apt-get install expect -qy

                # Pass this value to ssh-add
                PASSW="myfancypass123"

                # Define a name for this script
                THIS_SCRIPT="$(date +%Y-%m-%d_%H-%M-%S-%N)".sh

                # Create a fresh directory to work from / Clean up
                rm -rf ~/temp; mkdir -p ~/temp; cd ~/temp; ls -la


                # Output our bash script file - BEGIN
                cat <<< '
                #!/bin/bash

                set -u # Stop if an unbound variable is referenced
                set -e # Stop on first error
                export HISTIGNORE="expect*";

                # Normal CMDs
                echo && echo "The process should take about 10 seconds:" && echo
                eval "$(ssh-agent -s)"; sleep 0.5;

                # Define VAR passed when this bash-script was launched
                password="$@"

                # Launch the expect magic
                expect -c "
                spawn ssh-add /root/.ssh/id_rsa
                expect "?assword:"
                send "$passwordr"
                expect "?password:"
                send "$passwordr"
                expect eof"

                export HISTIGNORE="";
                export password="";
                ' > $THIS_SCRIPT
                # Output our bash script file - END


                # Ensure we are in the right path
                cd ~/temp; ls -la; sleep 1;

                # Run the bash script
                chmod +x ./$THIS_SCRIPT; ./$THIS_SCRIPT "$PASSW"; unset password;

                # Clean up
                rm -rf ~/temp; mkdir -p ~/temp; cd ~/temp; ls -la





                share|improve this answer























                  Your Answer








                  StackExchange.ready(function() {
                  var channelOptions = {
                  tags: "".split(" "),
                  id: "106"
                  };
                  initTagRenderer("".split(" "), "".split(" "), channelOptions);

                  StackExchange.using("externalEditor", function() {
                  // Have to fire editor after snippets, if snippets enabled
                  if (StackExchange.settings.snippets.snippetsEnabled) {
                  StackExchange.using("snippets", function() {
                  createEditor();
                  });
                  }
                  else {
                  createEditor();
                  }
                  });

                  function createEditor() {
                  StackExchange.prepareEditor({
                  heartbeatType: 'answer',
                  autoActivateHeartbeat: false,
                  convertImagesToLinks: false,
                  noModals: true,
                  showLowRepImageUploadWarning: true,
                  reputationToPostImages: null,
                  bindNavPrevention: true,
                  postfix: "",
                  imageUploader: {
                  brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                  contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                  allowUrls: true
                  },
                  onDemand: true,
                  discardSelector: ".discard-answer"
                  ,immediatelyShowMarkdownHelp:true
                  });


                  }
                  });














                  draft saved

                  draft discarded


















                  StackExchange.ready(
                  function () {
                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f90853%2fhow-can-i-run-ssh-add-automatically-without-a-password-prompt%23new-answer', 'question_page');
                  }
                  );

                  Post as a guest















                  Required, but never shown

























                  14 Answers
                  14






                  active

                  oldest

                  votes








                  14 Answers
                  14






                  active

                  oldest

                  votes









                  active

                  oldest

                  votes






                  active

                  oldest

                  votes









                  304














                  This is a typical example of a trade-off between security and convenience. Luckily there are a number of options. The most appropriate solution depends on the usage scenario and desired level of security.



                  ssh-key with passphrase, no ssh-agent



                  Now the passphrase has to be entered every time the key is used for authentication. While this is the best option from a security standpoint, it offers the worst usability. This may also lead to a weak passphrase being chosen in-order-to lessen the burden of entering it repeatedly.



                  ssh-key with passphrase, with ssh-agent



                  Adding the following to ~/.bash_profile will automatically start ssh-agent and load the ssh-key(s) on login:



                  if [ -z "$SSH_AUTH_SOCK" ] ; then
                  eval `ssh-agent -s`
                  ssh-add
                  fi


                  Now the passphrase must be entered upon every login. While slightly better from a usability perspective, this has the drawback that ssh-agent prompts for the passphrase regardless of if the key is to be used or not during the login session. Each new login also spawns a distinct ssh-agent instance which remains running with the added keys in memory even after logout, unless explicitly killed.



                  To kill ssh_agent on logout, add the following to ~/.bash_logout



                  if [ -n "$SSH_AUTH_SOCK" ] ; then
                  eval `/usr/bin/ssh-agent -k`
                  fi


                  or the following to ~/.bash_profile



                  trap 'test -n "$SSH_AUTH_SOCK" && eval `/usr/bin/ssh-agent -k`' 0


                  Creating multiple ssh-agent instances can be avoided by creating a persistent communication socket to the agent at a fixed location in the file system, such as in Collin Anderson's answer. This is an improvement over spawning multiple agents instances, however, unless explicitly killed the decrypted key still remains in memory after logout.



                  On desktops, ssh-agents included with the desktop environment, such as the Gnome Keyring SSH Agent, can be a better approach as they typically can be made to prompt for the passphrase the first time the ssh-key is used during a login session and store the decrypted private key in memory until the end of the session.



                  ssh-key with passphrase, with ssh-ident



                  ssh-ident is a utility that can manage ssh-agent on your behalf and load identities as necessary. It adds keys only once as they are needed, regardless of how many terminals, ssh or login sessions that require access to an ssh-agent. It can also add and use a different agent and different set of keys depending on the host being connected to, or the directory ssh is invoked from. This allows for isolating keys when using agent forwarding with different hosts. It also allows to use multiple accounts on sites like GitHub.



                  To enable ssh-ident, install it and add the following alias to your ~/bash_profile:



                  alias ssh='/path/to/ssh-ident'


                  ssh-key with passphrase, with keychain



                  keychain is a small utility which manages ssh-agent on your behalf and
                  allows the ssh-agent to remain running when the login session ends. On subsequent logins, keychain will connect to the existing ssh-agent instance. In practice, this means that the passphrase must be be entered only during the first login after a reboot. On subsequent logins, the unencrypted key from the existing ssh-agent instance is used. This can also be useful for allowing passwordless RSA/DSA authentication in cron jobs without passwordless ssh-keys.



                  To enable keychain, install it and add something like the following to ~/.bash_profile:



                  eval `keychain --agents ssh --eval id_rsa`


                  From a security point of view, ssh-ident and keychain are worse than ssh-agent instances limited to the lifetime of a particular session, but they offer a high level of convenience. To improve the security of keychain, some people add the --clear option to their ~/.bash_profile keychain invocation. By doing this passphrases must be re-entered on login as above, but cron jobs will still have access to the unencrypted keys after the user logs out. The keychain wiki page has more information and examples.



                  ssh-key without passphrase



                  From a security standpoint, this is the worst option since the private key is entirely unprotected in case it is exposed. This is, however, the only way to make sure that the passphrase need not be re-entered after a reboot.



                  ssh-key with passphrase, with ssh-agent, passing passphrase to ssh-add from script



                  While it might seem like a straightforward idea to pass the passphrase to ssh-add from a script, e.g. echo "passphrasen" | ssh-add, this is not as straighforward as it seems as ssh-add does not read the passphrase from stdin, but opens /dev/tty directly for reading.



                  This can be worked around with expect, a tool for automating interactive applications. Below is an example of a script which adds a ssh-key using a passphrase stored in the script:



                  #!/usr/bin/expect -f
                  spawn ssh-add /home/user/.ssh/id_rsa
                  expect "Enter passphrase for /home/user/.ssh/id_rsa:"
                  send "passphrasen";
                  expect "Identity added: /home/user/.ssh/id_rsa (/home/user/.ssh/id_rsa)"
                  interact


                  Note that as the passphrase is stored in plaintext in the script, from a security perspective, this is hardly better than having a passwordless ssh-key. If this approach is to be used, it is important to make sure that the expect script containing the passphrase has proper permissions set to it, making it readable, writable and runnable only by the key owner.






                  share|improve this answer



















                  • 1




                    Okay, but when I put your code to ~/.bash_profile I have to type in password every time I login, I don't want that either. I am not concerned about security at all. echo "passn" | ssh-add doesn't work
                    – zdun8
                    Sep 17 '13 at 12:59






                  • 3




                    @user1607072 Yeah, that is how the ssh-agent snippet in ~/.bash_profile behaves as explained in the answer. You might want to look at the keychain utility. With keychain you need to enter the password on first login after reboot, but on subsequent logins keychain will connect to an existing ssh-agent instance with the decrypted key in memory. Apart from that there's the option of generating a ssh-key without a passphrase, but this is of course not recommended.
                    – Thomas Nyman
                    Sep 17 '13 at 13:35






                  • 2




                    @user1607072 While I would strongly suggest one of the more secure approaches, there is a way to pass the passphrase to ssh-add from a script. The reason echo "passn" | ssh-add does not work is that ssh-add does not read the password from stdin, but opens /dev/tty directly for reading. Updated the answer to include a workaround for this, using an utility called expect.
                    – Thomas Nyman
                    Sep 17 '13 at 18:03








                  • 1




                    @user1607072 It might be a bit overkill for your use case, but Kerberos in combination with ssh GSSAPI support can also be used for passwordless ssh logins. The corresponding authentication method in ssh is called gssapi-with-mic. This is usually used in larger networks, but of course if you have interest in this it might be worth looking into.
                    – Thomas Nyman
                    Sep 18 '13 at 11:54








                  • 1




                    @ErickBrown: Already answered here. The SSH Agent unit should be stopped on logout if you have user lingering disabled in the systemd login manager. If user lingering is enabled, the systemd user instance and the SSH Agent unit are kept running even after the last login session is closed.
                    – Thomas Nyman
                    Jul 25 '18 at 8:00
















                  304














                  This is a typical example of a trade-off between security and convenience. Luckily there are a number of options. The most appropriate solution depends on the usage scenario and desired level of security.



                  ssh-key with passphrase, no ssh-agent



                  Now the passphrase has to be entered every time the key is used for authentication. While this is the best option from a security standpoint, it offers the worst usability. This may also lead to a weak passphrase being chosen in-order-to lessen the burden of entering it repeatedly.



                  ssh-key with passphrase, with ssh-agent



                  Adding the following to ~/.bash_profile will automatically start ssh-agent and load the ssh-key(s) on login:



                  if [ -z "$SSH_AUTH_SOCK" ] ; then
                  eval `ssh-agent -s`
                  ssh-add
                  fi


                  Now the passphrase must be entered upon every login. While slightly better from a usability perspective, this has the drawback that ssh-agent prompts for the passphrase regardless of if the key is to be used or not during the login session. Each new login also spawns a distinct ssh-agent instance which remains running with the added keys in memory even after logout, unless explicitly killed.



                  To kill ssh_agent on logout, add the following to ~/.bash_logout



                  if [ -n "$SSH_AUTH_SOCK" ] ; then
                  eval `/usr/bin/ssh-agent -k`
                  fi


                  or the following to ~/.bash_profile



                  trap 'test -n "$SSH_AUTH_SOCK" && eval `/usr/bin/ssh-agent -k`' 0


                  Creating multiple ssh-agent instances can be avoided by creating a persistent communication socket to the agent at a fixed location in the file system, such as in Collin Anderson's answer. This is an improvement over spawning multiple agents instances, however, unless explicitly killed the decrypted key still remains in memory after logout.



                  On desktops, ssh-agents included with the desktop environment, such as the Gnome Keyring SSH Agent, can be a better approach as they typically can be made to prompt for the passphrase the first time the ssh-key is used during a login session and store the decrypted private key in memory until the end of the session.



                  ssh-key with passphrase, with ssh-ident



                  ssh-ident is a utility that can manage ssh-agent on your behalf and load identities as necessary. It adds keys only once as they are needed, regardless of how many terminals, ssh or login sessions that require access to an ssh-agent. It can also add and use a different agent and different set of keys depending on the host being connected to, or the directory ssh is invoked from. This allows for isolating keys when using agent forwarding with different hosts. It also allows to use multiple accounts on sites like GitHub.



                  To enable ssh-ident, install it and add the following alias to your ~/bash_profile:



                  alias ssh='/path/to/ssh-ident'


                  ssh-key with passphrase, with keychain



                  keychain is a small utility which manages ssh-agent on your behalf and
                  allows the ssh-agent to remain running when the login session ends. On subsequent logins, keychain will connect to the existing ssh-agent instance. In practice, this means that the passphrase must be be entered only during the first login after a reboot. On subsequent logins, the unencrypted key from the existing ssh-agent instance is used. This can also be useful for allowing passwordless RSA/DSA authentication in cron jobs without passwordless ssh-keys.



                  To enable keychain, install it and add something like the following to ~/.bash_profile:



                  eval `keychain --agents ssh --eval id_rsa`


                  From a security point of view, ssh-ident and keychain are worse than ssh-agent instances limited to the lifetime of a particular session, but they offer a high level of convenience. To improve the security of keychain, some people add the --clear option to their ~/.bash_profile keychain invocation. By doing this passphrases must be re-entered on login as above, but cron jobs will still have access to the unencrypted keys after the user logs out. The keychain wiki page has more information and examples.



                  ssh-key without passphrase



                  From a security standpoint, this is the worst option since the private key is entirely unprotected in case it is exposed. This is, however, the only way to make sure that the passphrase need not be re-entered after a reboot.



                  ssh-key with passphrase, with ssh-agent, passing passphrase to ssh-add from script



                  While it might seem like a straightforward idea to pass the passphrase to ssh-add from a script, e.g. echo "passphrasen" | ssh-add, this is not as straighforward as it seems as ssh-add does not read the passphrase from stdin, but opens /dev/tty directly for reading.



                  This can be worked around with expect, a tool for automating interactive applications. Below is an example of a script which adds a ssh-key using a passphrase stored in the script:



                  #!/usr/bin/expect -f
                  spawn ssh-add /home/user/.ssh/id_rsa
                  expect "Enter passphrase for /home/user/.ssh/id_rsa:"
                  send "passphrasen";
                  expect "Identity added: /home/user/.ssh/id_rsa (/home/user/.ssh/id_rsa)"
                  interact


                  Note that as the passphrase is stored in plaintext in the script, from a security perspective, this is hardly better than having a passwordless ssh-key. If this approach is to be used, it is important to make sure that the expect script containing the passphrase has proper permissions set to it, making it readable, writable and runnable only by the key owner.






                  share|improve this answer



















                  • 1




                    Okay, but when I put your code to ~/.bash_profile I have to type in password every time I login, I don't want that either. I am not concerned about security at all. echo "passn" | ssh-add doesn't work
                    – zdun8
                    Sep 17 '13 at 12:59






                  • 3




                    @user1607072 Yeah, that is how the ssh-agent snippet in ~/.bash_profile behaves as explained in the answer. You might want to look at the keychain utility. With keychain you need to enter the password on first login after reboot, but on subsequent logins keychain will connect to an existing ssh-agent instance with the decrypted key in memory. Apart from that there's the option of generating a ssh-key without a passphrase, but this is of course not recommended.
                    – Thomas Nyman
                    Sep 17 '13 at 13:35






                  • 2




                    @user1607072 While I would strongly suggest one of the more secure approaches, there is a way to pass the passphrase to ssh-add from a script. The reason echo "passn" | ssh-add does not work is that ssh-add does not read the password from stdin, but opens /dev/tty directly for reading. Updated the answer to include a workaround for this, using an utility called expect.
                    – Thomas Nyman
                    Sep 17 '13 at 18:03








                  • 1




                    @user1607072 It might be a bit overkill for your use case, but Kerberos in combination with ssh GSSAPI support can also be used for passwordless ssh logins. The corresponding authentication method in ssh is called gssapi-with-mic. This is usually used in larger networks, but of course if you have interest in this it might be worth looking into.
                    – Thomas Nyman
                    Sep 18 '13 at 11:54








                  • 1




                    @ErickBrown: Already answered here. The SSH Agent unit should be stopped on logout if you have user lingering disabled in the systemd login manager. If user lingering is enabled, the systemd user instance and the SSH Agent unit are kept running even after the last login session is closed.
                    – Thomas Nyman
                    Jul 25 '18 at 8:00














                  304












                  304








                  304






                  This is a typical example of a trade-off between security and convenience. Luckily there are a number of options. The most appropriate solution depends on the usage scenario and desired level of security.



                  ssh-key with passphrase, no ssh-agent



                  Now the passphrase has to be entered every time the key is used for authentication. While this is the best option from a security standpoint, it offers the worst usability. This may also lead to a weak passphrase being chosen in-order-to lessen the burden of entering it repeatedly.



                  ssh-key with passphrase, with ssh-agent



                  Adding the following to ~/.bash_profile will automatically start ssh-agent and load the ssh-key(s) on login:



                  if [ -z "$SSH_AUTH_SOCK" ] ; then
                  eval `ssh-agent -s`
                  ssh-add
                  fi


                  Now the passphrase must be entered upon every login. While slightly better from a usability perspective, this has the drawback that ssh-agent prompts for the passphrase regardless of if the key is to be used or not during the login session. Each new login also spawns a distinct ssh-agent instance which remains running with the added keys in memory even after logout, unless explicitly killed.



                  To kill ssh_agent on logout, add the following to ~/.bash_logout



                  if [ -n "$SSH_AUTH_SOCK" ] ; then
                  eval `/usr/bin/ssh-agent -k`
                  fi


                  or the following to ~/.bash_profile



                  trap 'test -n "$SSH_AUTH_SOCK" && eval `/usr/bin/ssh-agent -k`' 0


                  Creating multiple ssh-agent instances can be avoided by creating a persistent communication socket to the agent at a fixed location in the file system, such as in Collin Anderson's answer. This is an improvement over spawning multiple agents instances, however, unless explicitly killed the decrypted key still remains in memory after logout.



                  On desktops, ssh-agents included with the desktop environment, such as the Gnome Keyring SSH Agent, can be a better approach as they typically can be made to prompt for the passphrase the first time the ssh-key is used during a login session and store the decrypted private key in memory until the end of the session.



                  ssh-key with passphrase, with ssh-ident



                  ssh-ident is a utility that can manage ssh-agent on your behalf and load identities as necessary. It adds keys only once as they are needed, regardless of how many terminals, ssh or login sessions that require access to an ssh-agent. It can also add and use a different agent and different set of keys depending on the host being connected to, or the directory ssh is invoked from. This allows for isolating keys when using agent forwarding with different hosts. It also allows to use multiple accounts on sites like GitHub.



                  To enable ssh-ident, install it and add the following alias to your ~/bash_profile:



                  alias ssh='/path/to/ssh-ident'


                  ssh-key with passphrase, with keychain



                  keychain is a small utility which manages ssh-agent on your behalf and
                  allows the ssh-agent to remain running when the login session ends. On subsequent logins, keychain will connect to the existing ssh-agent instance. In practice, this means that the passphrase must be be entered only during the first login after a reboot. On subsequent logins, the unencrypted key from the existing ssh-agent instance is used. This can also be useful for allowing passwordless RSA/DSA authentication in cron jobs without passwordless ssh-keys.



                  To enable keychain, install it and add something like the following to ~/.bash_profile:



                  eval `keychain --agents ssh --eval id_rsa`


                  From a security point of view, ssh-ident and keychain are worse than ssh-agent instances limited to the lifetime of a particular session, but they offer a high level of convenience. To improve the security of keychain, some people add the --clear option to their ~/.bash_profile keychain invocation. By doing this passphrases must be re-entered on login as above, but cron jobs will still have access to the unencrypted keys after the user logs out. The keychain wiki page has more information and examples.



                  ssh-key without passphrase



                  From a security standpoint, this is the worst option since the private key is entirely unprotected in case it is exposed. This is, however, the only way to make sure that the passphrase need not be re-entered after a reboot.



                  ssh-key with passphrase, with ssh-agent, passing passphrase to ssh-add from script



                  While it might seem like a straightforward idea to pass the passphrase to ssh-add from a script, e.g. echo "passphrasen" | ssh-add, this is not as straighforward as it seems as ssh-add does not read the passphrase from stdin, but opens /dev/tty directly for reading.



                  This can be worked around with expect, a tool for automating interactive applications. Below is an example of a script which adds a ssh-key using a passphrase stored in the script:



                  #!/usr/bin/expect -f
                  spawn ssh-add /home/user/.ssh/id_rsa
                  expect "Enter passphrase for /home/user/.ssh/id_rsa:"
                  send "passphrasen";
                  expect "Identity added: /home/user/.ssh/id_rsa (/home/user/.ssh/id_rsa)"
                  interact


                  Note that as the passphrase is stored in plaintext in the script, from a security perspective, this is hardly better than having a passwordless ssh-key. If this approach is to be used, it is important to make sure that the expect script containing the passphrase has proper permissions set to it, making it readable, writable and runnable only by the key owner.






                  share|improve this answer














                  This is a typical example of a trade-off between security and convenience. Luckily there are a number of options. The most appropriate solution depends on the usage scenario and desired level of security.



                  ssh-key with passphrase, no ssh-agent



                  Now the passphrase has to be entered every time the key is used for authentication. While this is the best option from a security standpoint, it offers the worst usability. This may also lead to a weak passphrase being chosen in-order-to lessen the burden of entering it repeatedly.



                  ssh-key with passphrase, with ssh-agent



                  Adding the following to ~/.bash_profile will automatically start ssh-agent and load the ssh-key(s) on login:



                  if [ -z "$SSH_AUTH_SOCK" ] ; then
                  eval `ssh-agent -s`
                  ssh-add
                  fi


                  Now the passphrase must be entered upon every login. While slightly better from a usability perspective, this has the drawback that ssh-agent prompts for the passphrase regardless of if the key is to be used or not during the login session. Each new login also spawns a distinct ssh-agent instance which remains running with the added keys in memory even after logout, unless explicitly killed.



                  To kill ssh_agent on logout, add the following to ~/.bash_logout



                  if [ -n "$SSH_AUTH_SOCK" ] ; then
                  eval `/usr/bin/ssh-agent -k`
                  fi


                  or the following to ~/.bash_profile



                  trap 'test -n "$SSH_AUTH_SOCK" && eval `/usr/bin/ssh-agent -k`' 0


                  Creating multiple ssh-agent instances can be avoided by creating a persistent communication socket to the agent at a fixed location in the file system, such as in Collin Anderson's answer. This is an improvement over spawning multiple agents instances, however, unless explicitly killed the decrypted key still remains in memory after logout.



                  On desktops, ssh-agents included with the desktop environment, such as the Gnome Keyring SSH Agent, can be a better approach as they typically can be made to prompt for the passphrase the first time the ssh-key is used during a login session and store the decrypted private key in memory until the end of the session.



                  ssh-key with passphrase, with ssh-ident



                  ssh-ident is a utility that can manage ssh-agent on your behalf and load identities as necessary. It adds keys only once as they are needed, regardless of how many terminals, ssh or login sessions that require access to an ssh-agent. It can also add and use a different agent and different set of keys depending on the host being connected to, or the directory ssh is invoked from. This allows for isolating keys when using agent forwarding with different hosts. It also allows to use multiple accounts on sites like GitHub.



                  To enable ssh-ident, install it and add the following alias to your ~/bash_profile:



                  alias ssh='/path/to/ssh-ident'


                  ssh-key with passphrase, with keychain



                  keychain is a small utility which manages ssh-agent on your behalf and
                  allows the ssh-agent to remain running when the login session ends. On subsequent logins, keychain will connect to the existing ssh-agent instance. In practice, this means that the passphrase must be be entered only during the first login after a reboot. On subsequent logins, the unencrypted key from the existing ssh-agent instance is used. This can also be useful for allowing passwordless RSA/DSA authentication in cron jobs without passwordless ssh-keys.



                  To enable keychain, install it and add something like the following to ~/.bash_profile:



                  eval `keychain --agents ssh --eval id_rsa`


                  From a security point of view, ssh-ident and keychain are worse than ssh-agent instances limited to the lifetime of a particular session, but they offer a high level of convenience. To improve the security of keychain, some people add the --clear option to their ~/.bash_profile keychain invocation. By doing this passphrases must be re-entered on login as above, but cron jobs will still have access to the unencrypted keys after the user logs out. The keychain wiki page has more information and examples.



                  ssh-key without passphrase



                  From a security standpoint, this is the worst option since the private key is entirely unprotected in case it is exposed. This is, however, the only way to make sure that the passphrase need not be re-entered after a reboot.



                  ssh-key with passphrase, with ssh-agent, passing passphrase to ssh-add from script



                  While it might seem like a straightforward idea to pass the passphrase to ssh-add from a script, e.g. echo "passphrasen" | ssh-add, this is not as straighforward as it seems as ssh-add does not read the passphrase from stdin, but opens /dev/tty directly for reading.



                  This can be worked around with expect, a tool for automating interactive applications. Below is an example of a script which adds a ssh-key using a passphrase stored in the script:



                  #!/usr/bin/expect -f
                  spawn ssh-add /home/user/.ssh/id_rsa
                  expect "Enter passphrase for /home/user/.ssh/id_rsa:"
                  send "passphrasen";
                  expect "Identity added: /home/user/.ssh/id_rsa (/home/user/.ssh/id_rsa)"
                  interact


                  Note that as the passphrase is stored in plaintext in the script, from a security perspective, this is hardly better than having a passwordless ssh-key. If this approach is to be used, it is important to make sure that the expect script containing the passphrase has proper permissions set to it, making it readable, writable and runnable only by the key owner.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Oct 30 '17 at 23:40









                  foxyblue

                  1033




                  1033










                  answered Sep 16 '13 at 12:21









                  Thomas NymanThomas Nyman

                  20.1k74969




                  20.1k74969








                  • 1




                    Okay, but when I put your code to ~/.bash_profile I have to type in password every time I login, I don't want that either. I am not concerned about security at all. echo "passn" | ssh-add doesn't work
                    – zdun8
                    Sep 17 '13 at 12:59






                  • 3




                    @user1607072 Yeah, that is how the ssh-agent snippet in ~/.bash_profile behaves as explained in the answer. You might want to look at the keychain utility. With keychain you need to enter the password on first login after reboot, but on subsequent logins keychain will connect to an existing ssh-agent instance with the decrypted key in memory. Apart from that there's the option of generating a ssh-key without a passphrase, but this is of course not recommended.
                    – Thomas Nyman
                    Sep 17 '13 at 13:35






                  • 2




                    @user1607072 While I would strongly suggest one of the more secure approaches, there is a way to pass the passphrase to ssh-add from a script. The reason echo "passn" | ssh-add does not work is that ssh-add does not read the password from stdin, but opens /dev/tty directly for reading. Updated the answer to include a workaround for this, using an utility called expect.
                    – Thomas Nyman
                    Sep 17 '13 at 18:03








                  • 1




                    @user1607072 It might be a bit overkill for your use case, but Kerberos in combination with ssh GSSAPI support can also be used for passwordless ssh logins. The corresponding authentication method in ssh is called gssapi-with-mic. This is usually used in larger networks, but of course if you have interest in this it might be worth looking into.
                    – Thomas Nyman
                    Sep 18 '13 at 11:54








                  • 1




                    @ErickBrown: Already answered here. The SSH Agent unit should be stopped on logout if you have user lingering disabled in the systemd login manager. If user lingering is enabled, the systemd user instance and the SSH Agent unit are kept running even after the last login session is closed.
                    – Thomas Nyman
                    Jul 25 '18 at 8:00














                  • 1




                    Okay, but when I put your code to ~/.bash_profile I have to type in password every time I login, I don't want that either. I am not concerned about security at all. echo "passn" | ssh-add doesn't work
                    – zdun8
                    Sep 17 '13 at 12:59






                  • 3




                    @user1607072 Yeah, that is how the ssh-agent snippet in ~/.bash_profile behaves as explained in the answer. You might want to look at the keychain utility. With keychain you need to enter the password on first login after reboot, but on subsequent logins keychain will connect to an existing ssh-agent instance with the decrypted key in memory. Apart from that there's the option of generating a ssh-key without a passphrase, but this is of course not recommended.
                    – Thomas Nyman
                    Sep 17 '13 at 13:35






                  • 2




                    @user1607072 While I would strongly suggest one of the more secure approaches, there is a way to pass the passphrase to ssh-add from a script. The reason echo "passn" | ssh-add does not work is that ssh-add does not read the password from stdin, but opens /dev/tty directly for reading. Updated the answer to include a workaround for this, using an utility called expect.
                    – Thomas Nyman
                    Sep 17 '13 at 18:03








                  • 1




                    @user1607072 It might be a bit overkill for your use case, but Kerberos in combination with ssh GSSAPI support can also be used for passwordless ssh logins. The corresponding authentication method in ssh is called gssapi-with-mic. This is usually used in larger networks, but of course if you have interest in this it might be worth looking into.
                    – Thomas Nyman
                    Sep 18 '13 at 11:54








                  • 1




                    @ErickBrown: Already answered here. The SSH Agent unit should be stopped on logout if you have user lingering disabled in the systemd login manager. If user lingering is enabled, the systemd user instance and the SSH Agent unit are kept running even after the last login session is closed.
                    – Thomas Nyman
                    Jul 25 '18 at 8:00








                  1




                  1




                  Okay, but when I put your code to ~/.bash_profile I have to type in password every time I login, I don't want that either. I am not concerned about security at all. echo "passn" | ssh-add doesn't work
                  – zdun8
                  Sep 17 '13 at 12:59




                  Okay, but when I put your code to ~/.bash_profile I have to type in password every time I login, I don't want that either. I am not concerned about security at all. echo "passn" | ssh-add doesn't work
                  – zdun8
                  Sep 17 '13 at 12:59




                  3




                  3




                  @user1607072 Yeah, that is how the ssh-agent snippet in ~/.bash_profile behaves as explained in the answer. You might want to look at the keychain utility. With keychain you need to enter the password on first login after reboot, but on subsequent logins keychain will connect to an existing ssh-agent instance with the decrypted key in memory. Apart from that there's the option of generating a ssh-key without a passphrase, but this is of course not recommended.
                  – Thomas Nyman
                  Sep 17 '13 at 13:35




                  @user1607072 Yeah, that is how the ssh-agent snippet in ~/.bash_profile behaves as explained in the answer. You might want to look at the keychain utility. With keychain you need to enter the password on first login after reboot, but on subsequent logins keychain will connect to an existing ssh-agent instance with the decrypted key in memory. Apart from that there's the option of generating a ssh-key without a passphrase, but this is of course not recommended.
                  – Thomas Nyman
                  Sep 17 '13 at 13:35




                  2




                  2




                  @user1607072 While I would strongly suggest one of the more secure approaches, there is a way to pass the passphrase to ssh-add from a script. The reason echo "passn" | ssh-add does not work is that ssh-add does not read the password from stdin, but opens /dev/tty directly for reading. Updated the answer to include a workaround for this, using an utility called expect.
                  – Thomas Nyman
                  Sep 17 '13 at 18:03






                  @user1607072 While I would strongly suggest one of the more secure approaches, there is a way to pass the passphrase to ssh-add from a script. The reason echo "passn" | ssh-add does not work is that ssh-add does not read the password from stdin, but opens /dev/tty directly for reading. Updated the answer to include a workaround for this, using an utility called expect.
                  – Thomas Nyman
                  Sep 17 '13 at 18:03






                  1




                  1




                  @user1607072 It might be a bit overkill for your use case, but Kerberos in combination with ssh GSSAPI support can also be used for passwordless ssh logins. The corresponding authentication method in ssh is called gssapi-with-mic. This is usually used in larger networks, but of course if you have interest in this it might be worth looking into.
                  – Thomas Nyman
                  Sep 18 '13 at 11:54






                  @user1607072 It might be a bit overkill for your use case, but Kerberos in combination with ssh GSSAPI support can also be used for passwordless ssh logins. The corresponding authentication method in ssh is called gssapi-with-mic. This is usually used in larger networks, but of course if you have interest in this it might be worth looking into.
                  – Thomas Nyman
                  Sep 18 '13 at 11:54






                  1




                  1




                  @ErickBrown: Already answered here. The SSH Agent unit should be stopped on logout if you have user lingering disabled in the systemd login manager. If user lingering is enabled, the systemd user instance and the SSH Agent unit are kept running even after the last login session is closed.
                  – Thomas Nyman
                  Jul 25 '18 at 8:00




                  @ErickBrown: Already answered here. The SSH Agent unit should be stopped on logout if you have user lingering disabled in the systemd login manager. If user lingering is enabled, the systemd user instance and the SSH Agent unit are kept running even after the last login session is closed.
                  – Thomas Nyman
                  Jul 25 '18 at 8:00













                  79














                  Add this to your ~/.bashrc:



                  if [ ! -S ~/.ssh/ssh_auth_sock ]; then
                  eval `ssh-agent`
                  ln -sf "$SSH_AUTH_SOCK" ~/.ssh/ssh_auth_sock
                  fi
                  export SSH_AUTH_SOCK=~/.ssh/ssh_auth_sock
                  ssh-add -l > /dev/null || ssh-add


                  This should only prompt for a password the first time you login after each reboot. It will keep reusing the same ssh-agent as long as it stays running.






                  share|improve this answer



















                  • 1




                    very neat, this way you only have one ssh-agent running (: Multiple agents as in @thomasNyman's second solution seems a security risk to me...
                    – drevicko
                    Feb 10 '16 at 11:54






                  • 1




                    After researching in various sites and reading various solutions, this one here seems to be the clearest, straight to the point. Very nice. +1
                    – Dr Beco
                    Jul 18 '16 at 0:40






                  • 1




                    better to do this: `alias ssh=ssh-check-agent", and have the check-agent version do the above. that way: a) you only get one agent and b) you only get the agent if you need it
                    – Erik Aronesty
                    Jul 26 '16 at 20:31








                  • 2




                    I think -s is the default, so we're already doing that.
                    – Collin Anderson
                    Nov 22 '16 at 16:25






                  • 1




                    ssh-add -l returns an exit code of 0 when the agent has identities and 1 when it does not so you can cut grep out of the last command and use ssh-add -l > '/dev/null' || ssh-add
                    – Grant Humphries
                    Dec 20 '16 at 2:21


















                  79














                  Add this to your ~/.bashrc:



                  if [ ! -S ~/.ssh/ssh_auth_sock ]; then
                  eval `ssh-agent`
                  ln -sf "$SSH_AUTH_SOCK" ~/.ssh/ssh_auth_sock
                  fi
                  export SSH_AUTH_SOCK=~/.ssh/ssh_auth_sock
                  ssh-add -l > /dev/null || ssh-add


                  This should only prompt for a password the first time you login after each reboot. It will keep reusing the same ssh-agent as long as it stays running.






                  share|improve this answer



















                  • 1




                    very neat, this way you only have one ssh-agent running (: Multiple agents as in @thomasNyman's second solution seems a security risk to me...
                    – drevicko
                    Feb 10 '16 at 11:54






                  • 1




                    After researching in various sites and reading various solutions, this one here seems to be the clearest, straight to the point. Very nice. +1
                    – Dr Beco
                    Jul 18 '16 at 0:40






                  • 1




                    better to do this: `alias ssh=ssh-check-agent", and have the check-agent version do the above. that way: a) you only get one agent and b) you only get the agent if you need it
                    – Erik Aronesty
                    Jul 26 '16 at 20:31








                  • 2




                    I think -s is the default, so we're already doing that.
                    – Collin Anderson
                    Nov 22 '16 at 16:25






                  • 1




                    ssh-add -l returns an exit code of 0 when the agent has identities and 1 when it does not so you can cut grep out of the last command and use ssh-add -l > '/dev/null' || ssh-add
                    – Grant Humphries
                    Dec 20 '16 at 2:21
















                  79












                  79








                  79






                  Add this to your ~/.bashrc:



                  if [ ! -S ~/.ssh/ssh_auth_sock ]; then
                  eval `ssh-agent`
                  ln -sf "$SSH_AUTH_SOCK" ~/.ssh/ssh_auth_sock
                  fi
                  export SSH_AUTH_SOCK=~/.ssh/ssh_auth_sock
                  ssh-add -l > /dev/null || ssh-add


                  This should only prompt for a password the first time you login after each reboot. It will keep reusing the same ssh-agent as long as it stays running.






                  share|improve this answer














                  Add this to your ~/.bashrc:



                  if [ ! -S ~/.ssh/ssh_auth_sock ]; then
                  eval `ssh-agent`
                  ln -sf "$SSH_AUTH_SOCK" ~/.ssh/ssh_auth_sock
                  fi
                  export SSH_AUTH_SOCK=~/.ssh/ssh_auth_sock
                  ssh-add -l > /dev/null || ssh-add


                  This should only prompt for a password the first time you login after each reboot. It will keep reusing the same ssh-agent as long as it stays running.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Dec 24 '16 at 16:43

























                  answered Jul 20 '15 at 16:48









                  Collin AndersonCollin Anderson

                  951178




                  951178








                  • 1




                    very neat, this way you only have one ssh-agent running (: Multiple agents as in @thomasNyman's second solution seems a security risk to me...
                    – drevicko
                    Feb 10 '16 at 11:54






                  • 1




                    After researching in various sites and reading various solutions, this one here seems to be the clearest, straight to the point. Very nice. +1
                    – Dr Beco
                    Jul 18 '16 at 0:40






                  • 1




                    better to do this: `alias ssh=ssh-check-agent", and have the check-agent version do the above. that way: a) you only get one agent and b) you only get the agent if you need it
                    – Erik Aronesty
                    Jul 26 '16 at 20:31








                  • 2




                    I think -s is the default, so we're already doing that.
                    – Collin Anderson
                    Nov 22 '16 at 16:25






                  • 1




                    ssh-add -l returns an exit code of 0 when the agent has identities and 1 when it does not so you can cut grep out of the last command and use ssh-add -l > '/dev/null' || ssh-add
                    – Grant Humphries
                    Dec 20 '16 at 2:21
















                  • 1




                    very neat, this way you only have one ssh-agent running (: Multiple agents as in @thomasNyman's second solution seems a security risk to me...
                    – drevicko
                    Feb 10 '16 at 11:54






                  • 1




                    After researching in various sites and reading various solutions, this one here seems to be the clearest, straight to the point. Very nice. +1
                    – Dr Beco
                    Jul 18 '16 at 0:40






                  • 1




                    better to do this: `alias ssh=ssh-check-agent", and have the check-agent version do the above. that way: a) you only get one agent and b) you only get the agent if you need it
                    – Erik Aronesty
                    Jul 26 '16 at 20:31








                  • 2




                    I think -s is the default, so we're already doing that.
                    – Collin Anderson
                    Nov 22 '16 at 16:25






                  • 1




                    ssh-add -l returns an exit code of 0 when the agent has identities and 1 when it does not so you can cut grep out of the last command and use ssh-add -l > '/dev/null' || ssh-add
                    – Grant Humphries
                    Dec 20 '16 at 2:21










                  1




                  1




                  very neat, this way you only have one ssh-agent running (: Multiple agents as in @thomasNyman's second solution seems a security risk to me...
                  – drevicko
                  Feb 10 '16 at 11:54




                  very neat, this way you only have one ssh-agent running (: Multiple agents as in @thomasNyman's second solution seems a security risk to me...
                  – drevicko
                  Feb 10 '16 at 11:54




                  1




                  1




                  After researching in various sites and reading various solutions, this one here seems to be the clearest, straight to the point. Very nice. +1
                  – Dr Beco
                  Jul 18 '16 at 0:40




                  After researching in various sites and reading various solutions, this one here seems to be the clearest, straight to the point. Very nice. +1
                  – Dr Beco
                  Jul 18 '16 at 0:40




                  1




                  1




                  better to do this: `alias ssh=ssh-check-agent", and have the check-agent version do the above. that way: a) you only get one agent and b) you only get the agent if you need it
                  – Erik Aronesty
                  Jul 26 '16 at 20:31






                  better to do this: `alias ssh=ssh-check-agent", and have the check-agent version do the above. that way: a) you only get one agent and b) you only get the agent if you need it
                  – Erik Aronesty
                  Jul 26 '16 at 20:31






                  2




                  2




                  I think -s is the default, so we're already doing that.
                  – Collin Anderson
                  Nov 22 '16 at 16:25




                  I think -s is the default, so we're already doing that.
                  – Collin Anderson
                  Nov 22 '16 at 16:25




                  1




                  1




                  ssh-add -l returns an exit code of 0 when the agent has identities and 1 when it does not so you can cut grep out of the last command and use ssh-add -l > '/dev/null' || ssh-add
                  – Grant Humphries
                  Dec 20 '16 at 2:21






                  ssh-add -l returns an exit code of 0 when the agent has identities and 1 when it does not so you can cut grep out of the last command and use ssh-add -l > '/dev/null' || ssh-add
                  – Grant Humphries
                  Dec 20 '16 at 2:21













                  11














                  Not closely related to the OP's question, but it might be useful to others: since 7.2.0 ssh(1) has an option that allows adding a key to ssh-agent upon first authentication; the option is AddKeysToAgent and can be set to yes, no, ask, or confirm, systemwide or on your personal .ssh/config file.



                  Reference: https://www.openssh.com/txt/release-7.2






                  share|improve this answer



















                  • 2




                    Applicable to those who are new to the .ssh/config file: this applies to ssh and anything that uses ssh behind it, for example scp, and can be done on a per-host basis.
                    – SEoF
                    Sep 25 '17 at 14:32
















                  11














                  Not closely related to the OP's question, but it might be useful to others: since 7.2.0 ssh(1) has an option that allows adding a key to ssh-agent upon first authentication; the option is AddKeysToAgent and can be set to yes, no, ask, or confirm, systemwide or on your personal .ssh/config file.



                  Reference: https://www.openssh.com/txt/release-7.2






                  share|improve this answer



















                  • 2




                    Applicable to those who are new to the .ssh/config file: this applies to ssh and anything that uses ssh behind it, for example scp, and can be done on a per-host basis.
                    – SEoF
                    Sep 25 '17 at 14:32














                  11












                  11








                  11






                  Not closely related to the OP's question, but it might be useful to others: since 7.2.0 ssh(1) has an option that allows adding a key to ssh-agent upon first authentication; the option is AddKeysToAgent and can be set to yes, no, ask, or confirm, systemwide or on your personal .ssh/config file.



                  Reference: https://www.openssh.com/txt/release-7.2






                  share|improve this answer














                  Not closely related to the OP's question, but it might be useful to others: since 7.2.0 ssh(1) has an option that allows adding a key to ssh-agent upon first authentication; the option is AddKeysToAgent and can be set to yes, no, ask, or confirm, systemwide or on your personal .ssh/config file.



                  Reference: https://www.openssh.com/txt/release-7.2







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Oct 17 '16 at 7:58

























                  answered Oct 15 '16 at 6:26









                  Guilherme SalazarGuilherme Salazar

                  21123




                  21123








                  • 2




                    Applicable to those who are new to the .ssh/config file: this applies to ssh and anything that uses ssh behind it, for example scp, and can be done on a per-host basis.
                    – SEoF
                    Sep 25 '17 at 14:32














                  • 2




                    Applicable to those who are new to the .ssh/config file: this applies to ssh and anything that uses ssh behind it, for example scp, and can be done on a per-host basis.
                    – SEoF
                    Sep 25 '17 at 14:32








                  2




                  2




                  Applicable to those who are new to the .ssh/config file: this applies to ssh and anything that uses ssh behind it, for example scp, and can be done on a per-host basis.
                  – SEoF
                  Sep 25 '17 at 14:32




                  Applicable to those who are new to the .ssh/config file: this applies to ssh and anything that uses ssh behind it, for example scp, and can be done on a per-host basis.
                  – SEoF
                  Sep 25 '17 at 14:32











                  5














                  ssh-agent caches various unlocked ssh-keys, so you can have ssh-keys protected by passwords, but without having to type them every single time.



                  In order to cache unlocked keys, it obviously needs to unlock those keys. For unlocking keys that are locked with a passphrase, it obviously needs to know these passphrases.



                  Any method that does not require authorization from a human being (e.g. "typing in a password") will not only make your system insecure; it will also render the entire purpose of the ssh-agent meaningless.



                  Having said all this, you can simply use ssh-keys that are not password protected (hit Enter when asked for a password during key-generation).
                  Since there isn't any password, ssh-agent doesn't need to ask you for one in order to (not) cache it.






                  share|improve this answer























                  • I agree, as long as your keys are properly user-only-permissioned, there is little advantage to ssh-agent over permissionless keys. i like to ssh into a login server, and then, that server has a bunch of permssionless keys, each of which can only be used to unlock one other server. the login server does nothing else, so it's much harder to hack/spoof, etc... the other servers have no password access, are key-only.
                    – Erik Aronesty
                    Jul 26 '16 at 20:34


















                  5














                  ssh-agent caches various unlocked ssh-keys, so you can have ssh-keys protected by passwords, but without having to type them every single time.



                  In order to cache unlocked keys, it obviously needs to unlock those keys. For unlocking keys that are locked with a passphrase, it obviously needs to know these passphrases.



                  Any method that does not require authorization from a human being (e.g. "typing in a password") will not only make your system insecure; it will also render the entire purpose of the ssh-agent meaningless.



                  Having said all this, you can simply use ssh-keys that are not password protected (hit Enter when asked for a password during key-generation).
                  Since there isn't any password, ssh-agent doesn't need to ask you for one in order to (not) cache it.






                  share|improve this answer























                  • I agree, as long as your keys are properly user-only-permissioned, there is little advantage to ssh-agent over permissionless keys. i like to ssh into a login server, and then, that server has a bunch of permssionless keys, each of which can only be used to unlock one other server. the login server does nothing else, so it's much harder to hack/spoof, etc... the other servers have no password access, are key-only.
                    – Erik Aronesty
                    Jul 26 '16 at 20:34
















                  5












                  5








                  5






                  ssh-agent caches various unlocked ssh-keys, so you can have ssh-keys protected by passwords, but without having to type them every single time.



                  In order to cache unlocked keys, it obviously needs to unlock those keys. For unlocking keys that are locked with a passphrase, it obviously needs to know these passphrases.



                  Any method that does not require authorization from a human being (e.g. "typing in a password") will not only make your system insecure; it will also render the entire purpose of the ssh-agent meaningless.



                  Having said all this, you can simply use ssh-keys that are not password protected (hit Enter when asked for a password during key-generation).
                  Since there isn't any password, ssh-agent doesn't need to ask you for one in order to (not) cache it.






                  share|improve this answer














                  ssh-agent caches various unlocked ssh-keys, so you can have ssh-keys protected by passwords, but without having to type them every single time.



                  In order to cache unlocked keys, it obviously needs to unlock those keys. For unlocking keys that are locked with a passphrase, it obviously needs to know these passphrases.



                  Any method that does not require authorization from a human being (e.g. "typing in a password") will not only make your system insecure; it will also render the entire purpose of the ssh-agent meaningless.



                  Having said all this, you can simply use ssh-keys that are not password protected (hit Enter when asked for a password during key-generation).
                  Since there isn't any password, ssh-agent doesn't need to ask you for one in order to (not) cache it.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 24 mins ago









                  Peter Mortensen

                  88758




                  88758










                  answered Sep 16 '13 at 11:08









                  umläuteumläute

                  4,5781434




                  4,5781434












                  • I agree, as long as your keys are properly user-only-permissioned, there is little advantage to ssh-agent over permissionless keys. i like to ssh into a login server, and then, that server has a bunch of permssionless keys, each of which can only be used to unlock one other server. the login server does nothing else, so it's much harder to hack/spoof, etc... the other servers have no password access, are key-only.
                    – Erik Aronesty
                    Jul 26 '16 at 20:34




















                  • I agree, as long as your keys are properly user-only-permissioned, there is little advantage to ssh-agent over permissionless keys. i like to ssh into a login server, and then, that server has a bunch of permssionless keys, each of which can only be used to unlock one other server. the login server does nothing else, so it's much harder to hack/spoof, etc... the other servers have no password access, are key-only.
                    – Erik Aronesty
                    Jul 26 '16 at 20:34


















                  I agree, as long as your keys are properly user-only-permissioned, there is little advantage to ssh-agent over permissionless keys. i like to ssh into a login server, and then, that server has a bunch of permssionless keys, each of which can only be used to unlock one other server. the login server does nothing else, so it's much harder to hack/spoof, etc... the other servers have no password access, are key-only.
                  – Erik Aronesty
                  Jul 26 '16 at 20:34






                  I agree, as long as your keys are properly user-only-permissioned, there is little advantage to ssh-agent over permissionless keys. i like to ssh into a login server, and then, that server has a bunch of permssionless keys, each of which can only be used to unlock one other server. the login server does nothing else, so it's much harder to hack/spoof, etc... the other servers have no password access, are key-only.
                  – Erik Aronesty
                  Jul 26 '16 at 20:34













                  4














                  I won't recommend you ssh-add (which need to open a ssh-agent) at login. This is because you can't control when the ssh-agent section ends, and can create security risk when you need not use the keyfiles at one login section.



                  Rather, I recommend to write a script which opens a ssh-agent's section sub-shell, with all keyfiles auto added, and be called when needed to use ssh. If you could adopt so, read on.



                  You would have two choices:




                  1. Remove all passphrases for your keys, which have weak security if your key files are stolen. (thus not recommended)


                  2. Use the same passphrase for your keys. Then when you ssh-add keyfile1 keyfile2 ..., you will only need to type the passphrase once, per section.



                  In both cases, you could write such script file "ssh_keys_section.sh" as below:



                  #!/bin/bash
                  # This script run a ssh-agent on a sub-shell and automatically ssh-add all keyfiles at once.
                  # This agent ends when you type `exit` to close the sub-shell.
                  exec ssh-agent bash -c "ssh-add /path/to/keyfile1 /path/to/keyfile2 ...; exec bash"


                  Remarks:




                  • Command to change or delete passphrase: ssh-keygen -p -f keyfile

                  • Within the sub-shell, you might even fork more terminals which share the same unlocked keys, by using maybe a command like /path/to/yourterminal & (depends on OS)






                  share|improve this answer




























                    4














                    I won't recommend you ssh-add (which need to open a ssh-agent) at login. This is because you can't control when the ssh-agent section ends, and can create security risk when you need not use the keyfiles at one login section.



                    Rather, I recommend to write a script which opens a ssh-agent's section sub-shell, with all keyfiles auto added, and be called when needed to use ssh. If you could adopt so, read on.



                    You would have two choices:




                    1. Remove all passphrases for your keys, which have weak security if your key files are stolen. (thus not recommended)


                    2. Use the same passphrase for your keys. Then when you ssh-add keyfile1 keyfile2 ..., you will only need to type the passphrase once, per section.



                    In both cases, you could write such script file "ssh_keys_section.sh" as below:



                    #!/bin/bash
                    # This script run a ssh-agent on a sub-shell and automatically ssh-add all keyfiles at once.
                    # This agent ends when you type `exit` to close the sub-shell.
                    exec ssh-agent bash -c "ssh-add /path/to/keyfile1 /path/to/keyfile2 ...; exec bash"


                    Remarks:




                    • Command to change or delete passphrase: ssh-keygen -p -f keyfile

                    • Within the sub-shell, you might even fork more terminals which share the same unlocked keys, by using maybe a command like /path/to/yourterminal & (depends on OS)






                    share|improve this answer


























                      4












                      4








                      4






                      I won't recommend you ssh-add (which need to open a ssh-agent) at login. This is because you can't control when the ssh-agent section ends, and can create security risk when you need not use the keyfiles at one login section.



                      Rather, I recommend to write a script which opens a ssh-agent's section sub-shell, with all keyfiles auto added, and be called when needed to use ssh. If you could adopt so, read on.



                      You would have two choices:




                      1. Remove all passphrases for your keys, which have weak security if your key files are stolen. (thus not recommended)


                      2. Use the same passphrase for your keys. Then when you ssh-add keyfile1 keyfile2 ..., you will only need to type the passphrase once, per section.



                      In both cases, you could write such script file "ssh_keys_section.sh" as below:



                      #!/bin/bash
                      # This script run a ssh-agent on a sub-shell and automatically ssh-add all keyfiles at once.
                      # This agent ends when you type `exit` to close the sub-shell.
                      exec ssh-agent bash -c "ssh-add /path/to/keyfile1 /path/to/keyfile2 ...; exec bash"


                      Remarks:




                      • Command to change or delete passphrase: ssh-keygen -p -f keyfile

                      • Within the sub-shell, you might even fork more terminals which share the same unlocked keys, by using maybe a command like /path/to/yourterminal & (depends on OS)






                      share|improve this answer














                      I won't recommend you ssh-add (which need to open a ssh-agent) at login. This is because you can't control when the ssh-agent section ends, and can create security risk when you need not use the keyfiles at one login section.



                      Rather, I recommend to write a script which opens a ssh-agent's section sub-shell, with all keyfiles auto added, and be called when needed to use ssh. If you could adopt so, read on.



                      You would have two choices:




                      1. Remove all passphrases for your keys, which have weak security if your key files are stolen. (thus not recommended)


                      2. Use the same passphrase for your keys. Then when you ssh-add keyfile1 keyfile2 ..., you will only need to type the passphrase once, per section.



                      In both cases, you could write such script file "ssh_keys_section.sh" as below:



                      #!/bin/bash
                      # This script run a ssh-agent on a sub-shell and automatically ssh-add all keyfiles at once.
                      # This agent ends when you type `exit` to close the sub-shell.
                      exec ssh-agent bash -c "ssh-add /path/to/keyfile1 /path/to/keyfile2 ...; exec bash"


                      Remarks:




                      • Command to change or delete passphrase: ssh-keygen -p -f keyfile

                      • Within the sub-shell, you might even fork more terminals which share the same unlocked keys, by using maybe a command like /path/to/yourterminal & (depends on OS)







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited Feb 11 '15 at 3:58

























                      answered Feb 11 '15 at 3:34









                      Johnny WongJohnny Wong

                      20613




                      20613























                          3














                          Here is a workaround to automate your SSH passphrase.





                          1. Create a one-liner script which prints your passphrase to standard output, e.g.:



                             echo 'echo MY_SSH_PASSWORD' > ~/.print_ssh_password && chmod 700 ~/.print_ssh_password


                            Important: Ensure you copy the leading space to prevent storing your password to your history.




                          And use one of the below methods.





                          • using a standard input approach:



                            cat ~/.ssh/id_rsa | SSH_ASKPASS=~/.print_ssh_password ssh-add -



                          • or named pipe approach:





                            1. Create a named pipe (you could also try a process substitution):



                              mkfifo --mode 0600 ~/.ssh_fifo



                            2. Run ssh-add by specifying the program used for the authentication:



                              cat ~/.ssh/id_rsa >~/.ssh_fifo | SSH_ASKPASS=~/.print_ssh_password ssh-add ~/.ssh_fifo



                            See: man ssh-add to read more about SSH_ASKPASS.








                          share|improve this answer



















                          • 1




                            The echo my_passphrase is a big security hole. First after you have typed it, the password is in clear text in the history file of what ever shell you use. And second command line arguments are world readable on Unix (ps -ef). Never put passwords in command line arguments!
                            – ceving
                            Aug 24 '16 at 9:03






                          • 1




                            @ceving Adding extra leading space solves the problem with the history file. Added extra info.
                            – kenorb
                            Aug 24 '16 at 9:25










                          • @kenorb: That doesn't solve the bigger problem of the password visible in ps output. The history file is typically only readable by the owning user anyway, but the command lines are readable by all users on a system.
                            – Thomas Nyman
                            Nov 23 '16 at 14:37
















                          3














                          Here is a workaround to automate your SSH passphrase.





                          1. Create a one-liner script which prints your passphrase to standard output, e.g.:



                             echo 'echo MY_SSH_PASSWORD' > ~/.print_ssh_password && chmod 700 ~/.print_ssh_password


                            Important: Ensure you copy the leading space to prevent storing your password to your history.




                          And use one of the below methods.





                          • using a standard input approach:



                            cat ~/.ssh/id_rsa | SSH_ASKPASS=~/.print_ssh_password ssh-add -



                          • or named pipe approach:





                            1. Create a named pipe (you could also try a process substitution):



                              mkfifo --mode 0600 ~/.ssh_fifo



                            2. Run ssh-add by specifying the program used for the authentication:



                              cat ~/.ssh/id_rsa >~/.ssh_fifo | SSH_ASKPASS=~/.print_ssh_password ssh-add ~/.ssh_fifo



                            See: man ssh-add to read more about SSH_ASKPASS.








                          share|improve this answer



















                          • 1




                            The echo my_passphrase is a big security hole. First after you have typed it, the password is in clear text in the history file of what ever shell you use. And second command line arguments are world readable on Unix (ps -ef). Never put passwords in command line arguments!
                            – ceving
                            Aug 24 '16 at 9:03






                          • 1




                            @ceving Adding extra leading space solves the problem with the history file. Added extra info.
                            – kenorb
                            Aug 24 '16 at 9:25










                          • @kenorb: That doesn't solve the bigger problem of the password visible in ps output. The history file is typically only readable by the owning user anyway, but the command lines are readable by all users on a system.
                            – Thomas Nyman
                            Nov 23 '16 at 14:37














                          3












                          3








                          3






                          Here is a workaround to automate your SSH passphrase.





                          1. Create a one-liner script which prints your passphrase to standard output, e.g.:



                             echo 'echo MY_SSH_PASSWORD' > ~/.print_ssh_password && chmod 700 ~/.print_ssh_password


                            Important: Ensure you copy the leading space to prevent storing your password to your history.




                          And use one of the below methods.





                          • using a standard input approach:



                            cat ~/.ssh/id_rsa | SSH_ASKPASS=~/.print_ssh_password ssh-add -



                          • or named pipe approach:





                            1. Create a named pipe (you could also try a process substitution):



                              mkfifo --mode 0600 ~/.ssh_fifo



                            2. Run ssh-add by specifying the program used for the authentication:



                              cat ~/.ssh/id_rsa >~/.ssh_fifo | SSH_ASKPASS=~/.print_ssh_password ssh-add ~/.ssh_fifo



                            See: man ssh-add to read more about SSH_ASKPASS.








                          share|improve this answer














                          Here is a workaround to automate your SSH passphrase.





                          1. Create a one-liner script which prints your passphrase to standard output, e.g.:



                             echo 'echo MY_SSH_PASSWORD' > ~/.print_ssh_password && chmod 700 ~/.print_ssh_password


                            Important: Ensure you copy the leading space to prevent storing your password to your history.




                          And use one of the below methods.





                          • using a standard input approach:



                            cat ~/.ssh/id_rsa | SSH_ASKPASS=~/.print_ssh_password ssh-add -



                          • or named pipe approach:





                            1. Create a named pipe (you could also try a process substitution):



                              mkfifo --mode 0600 ~/.ssh_fifo



                            2. Run ssh-add by specifying the program used for the authentication:



                              cat ~/.ssh/id_rsa >~/.ssh_fifo | SSH_ASKPASS=~/.print_ssh_password ssh-add ~/.ssh_fifo



                            See: man ssh-add to read more about SSH_ASKPASS.









                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Feb 6 '18 at 15:23









                          Vlastimil

                          7,8271261134




                          7,8271261134










                          answered Oct 11 '15 at 12:51









                          kenorbkenorb

                          8,391370106




                          8,391370106








                          • 1




                            The echo my_passphrase is a big security hole. First after you have typed it, the password is in clear text in the history file of what ever shell you use. And second command line arguments are world readable on Unix (ps -ef). Never put passwords in command line arguments!
                            – ceving
                            Aug 24 '16 at 9:03






                          • 1




                            @ceving Adding extra leading space solves the problem with the history file. Added extra info.
                            – kenorb
                            Aug 24 '16 at 9:25










                          • @kenorb: That doesn't solve the bigger problem of the password visible in ps output. The history file is typically only readable by the owning user anyway, but the command lines are readable by all users on a system.
                            – Thomas Nyman
                            Nov 23 '16 at 14:37














                          • 1




                            The echo my_passphrase is a big security hole. First after you have typed it, the password is in clear text in the history file of what ever shell you use. And second command line arguments are world readable on Unix (ps -ef). Never put passwords in command line arguments!
                            – ceving
                            Aug 24 '16 at 9:03






                          • 1




                            @ceving Adding extra leading space solves the problem with the history file. Added extra info.
                            – kenorb
                            Aug 24 '16 at 9:25










                          • @kenorb: That doesn't solve the bigger problem of the password visible in ps output. The history file is typically only readable by the owning user anyway, but the command lines are readable by all users on a system.
                            – Thomas Nyman
                            Nov 23 '16 at 14:37








                          1




                          1




                          The echo my_passphrase is a big security hole. First after you have typed it, the password is in clear text in the history file of what ever shell you use. And second command line arguments are world readable on Unix (ps -ef). Never put passwords in command line arguments!
                          – ceving
                          Aug 24 '16 at 9:03




                          The echo my_passphrase is a big security hole. First after you have typed it, the password is in clear text in the history file of what ever shell you use. And second command line arguments are world readable on Unix (ps -ef). Never put passwords in command line arguments!
                          – ceving
                          Aug 24 '16 at 9:03




                          1




                          1




                          @ceving Adding extra leading space solves the problem with the history file. Added extra info.
                          – kenorb
                          Aug 24 '16 at 9:25




                          @ceving Adding extra leading space solves the problem with the history file. Added extra info.
                          – kenorb
                          Aug 24 '16 at 9:25












                          @kenorb: That doesn't solve the bigger problem of the password visible in ps output. The history file is typically only readable by the owning user anyway, but the command lines are readable by all users on a system.
                          – Thomas Nyman
                          Nov 23 '16 at 14:37




                          @kenorb: That doesn't solve the bigger problem of the password visible in ps output. The history file is typically only readable by the owning user anyway, but the command lines are readable by all users on a system.
                          – Thomas Nyman
                          Nov 23 '16 at 14:37











                          2














                          if [ ! -S ${HOME}/.ssh/ssh_auth_sock ]; then
                          eval $(ssh-agent)
                          ln -sf "${SSH_AUTH_SOCK}" ${HOME}/.ssh/ssh_auth_sock
                          fi
                          export SSH_AUTH_SOCK=${HOME}/.ssh/ssh_auth_sock

                          ssh_keys=$(find -E ~/.ssh -type f -regex '.*(rsa$|pem)')
                          ssh_agent_keys=$(ssh-add -l | awk '{key=NF-1; print $key}')

                          for k in "${ssh_keys}"; do
                          for l in "${ssh_agent_keys}"; do
                          if [[ ! "${k}" = "${l}" ]]; then
                          ssh-add "${k}" > /dev/null 2>&1
                          fi
                          done
                          done





                          share|improve this answer




























                            2














                            if [ ! -S ${HOME}/.ssh/ssh_auth_sock ]; then
                            eval $(ssh-agent)
                            ln -sf "${SSH_AUTH_SOCK}" ${HOME}/.ssh/ssh_auth_sock
                            fi
                            export SSH_AUTH_SOCK=${HOME}/.ssh/ssh_auth_sock

                            ssh_keys=$(find -E ~/.ssh -type f -regex '.*(rsa$|pem)')
                            ssh_agent_keys=$(ssh-add -l | awk '{key=NF-1; print $key}')

                            for k in "${ssh_keys}"; do
                            for l in "${ssh_agent_keys}"; do
                            if [[ ! "${k}" = "${l}" ]]; then
                            ssh-add "${k}" > /dev/null 2>&1
                            fi
                            done
                            done





                            share|improve this answer


























                              2












                              2








                              2






                              if [ ! -S ${HOME}/.ssh/ssh_auth_sock ]; then
                              eval $(ssh-agent)
                              ln -sf "${SSH_AUTH_SOCK}" ${HOME}/.ssh/ssh_auth_sock
                              fi
                              export SSH_AUTH_SOCK=${HOME}/.ssh/ssh_auth_sock

                              ssh_keys=$(find -E ~/.ssh -type f -regex '.*(rsa$|pem)')
                              ssh_agent_keys=$(ssh-add -l | awk '{key=NF-1; print $key}')

                              for k in "${ssh_keys}"; do
                              for l in "${ssh_agent_keys}"; do
                              if [[ ! "${k}" = "${l}" ]]; then
                              ssh-add "${k}" > /dev/null 2>&1
                              fi
                              done
                              done





                              share|improve this answer














                              if [ ! -S ${HOME}/.ssh/ssh_auth_sock ]; then
                              eval $(ssh-agent)
                              ln -sf "${SSH_AUTH_SOCK}" ${HOME}/.ssh/ssh_auth_sock
                              fi
                              export SSH_AUTH_SOCK=${HOME}/.ssh/ssh_auth_sock

                              ssh_keys=$(find -E ~/.ssh -type f -regex '.*(rsa$|pem)')
                              ssh_agent_keys=$(ssh-add -l | awk '{key=NF-1; print $key}')

                              for k in "${ssh_keys}"; do
                              for l in "${ssh_agent_keys}"; do
                              if [[ ! "${k}" = "${l}" ]]; then
                              ssh-add "${k}" > /dev/null 2>&1
                              fi
                              done
                              done






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Nov 26 '17 at 21:55

























                              answered Nov 26 '17 at 21:36









                              Diego Roberto dos SantosDiego Roberto dos Santos

                              214




                              214























                                  1














                                  SSH_ENV="$HOME/.ssh/environment"

                                  function start_agent {
                                  echo "Initialising new SSH agent..."
                                  /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
                                  echo succeeded
                                  chmod 600 "${SSH_ENV}"
                                  . "${SSH_ENV}" > /dev/null
                                  /usr/bin/ssh-add;
                                  }

                                  # Source SSH settings, if applicable

                                  if [ -f "${SSH_ENV}" ]; then
                                  . "${SSH_ENV}" > /dev/null
                                  #ps ${SSH_AGENT_PID} doesn't work under cywgin
                                  ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
                                  start_agent;
                                  }
                                  else
                                  start_agent;
                                  fi


                                  Giving credit here: https://www.cygwin.com/ml/cygwin/2001-06/msg00537.html



                                  This solution is also endorsed here: http://mah.everybody.org/docs/ssh






                                  share|improve this answer


























                                    1














                                    SSH_ENV="$HOME/.ssh/environment"

                                    function start_agent {
                                    echo "Initialising new SSH agent..."
                                    /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
                                    echo succeeded
                                    chmod 600 "${SSH_ENV}"
                                    . "${SSH_ENV}" > /dev/null
                                    /usr/bin/ssh-add;
                                    }

                                    # Source SSH settings, if applicable

                                    if [ -f "${SSH_ENV}" ]; then
                                    . "${SSH_ENV}" > /dev/null
                                    #ps ${SSH_AGENT_PID} doesn't work under cywgin
                                    ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
                                    start_agent;
                                    }
                                    else
                                    start_agent;
                                    fi


                                    Giving credit here: https://www.cygwin.com/ml/cygwin/2001-06/msg00537.html



                                    This solution is also endorsed here: http://mah.everybody.org/docs/ssh






                                    share|improve this answer
























                                      1












                                      1








                                      1






                                      SSH_ENV="$HOME/.ssh/environment"

                                      function start_agent {
                                      echo "Initialising new SSH agent..."
                                      /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
                                      echo succeeded
                                      chmod 600 "${SSH_ENV}"
                                      . "${SSH_ENV}" > /dev/null
                                      /usr/bin/ssh-add;
                                      }

                                      # Source SSH settings, if applicable

                                      if [ -f "${SSH_ENV}" ]; then
                                      . "${SSH_ENV}" > /dev/null
                                      #ps ${SSH_AGENT_PID} doesn't work under cywgin
                                      ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
                                      start_agent;
                                      }
                                      else
                                      start_agent;
                                      fi


                                      Giving credit here: https://www.cygwin.com/ml/cygwin/2001-06/msg00537.html



                                      This solution is also endorsed here: http://mah.everybody.org/docs/ssh






                                      share|improve this answer












                                      SSH_ENV="$HOME/.ssh/environment"

                                      function start_agent {
                                      echo "Initialising new SSH agent..."
                                      /usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
                                      echo succeeded
                                      chmod 600 "${SSH_ENV}"
                                      . "${SSH_ENV}" > /dev/null
                                      /usr/bin/ssh-add;
                                      }

                                      # Source SSH settings, if applicable

                                      if [ -f "${SSH_ENV}" ]; then
                                      . "${SSH_ENV}" > /dev/null
                                      #ps ${SSH_AGENT_PID} doesn't work under cywgin
                                      ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
                                      start_agent;
                                      }
                                      else
                                      start_agent;
                                      fi


                                      Giving credit here: https://www.cygwin.com/ml/cygwin/2001-06/msg00537.html



                                      This solution is also endorsed here: http://mah.everybody.org/docs/ssh







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered May 9 '16 at 16:35









                                      steampoweredsteampowered

                                      1112




                                      1112























                                          1














                                          Single sign on solution for SSH could lead me to pam_ssh.



                                          According to this article, the concept is:




                                          If you work with multiple *nix-based machines via ssh, you are probably tired of constantly having to enter your password every time you want to access another box. There is a secure way to allow you to access every machine, that you have ssh access to, without having to enter another password (other than the one you signed on with originally.)







                                          This is actually quite simple to do, you basically just create a public/private key pair to authenticate yourself to your other machines, then have PAM spawn an agent to load your keys after you logon, providing a single signon solution to accessing all your remote machines. This guide will walk you through setting this up.




                                          I have not verified this would actually work.






                                          share|improve this answer




























                                            1














                                            Single sign on solution for SSH could lead me to pam_ssh.



                                            According to this article, the concept is:




                                            If you work with multiple *nix-based machines via ssh, you are probably tired of constantly having to enter your password every time you want to access another box. There is a secure way to allow you to access every machine, that you have ssh access to, without having to enter another password (other than the one you signed on with originally.)







                                            This is actually quite simple to do, you basically just create a public/private key pair to authenticate yourself to your other machines, then have PAM spawn an agent to load your keys after you logon, providing a single signon solution to accessing all your remote machines. This guide will walk you through setting this up.




                                            I have not verified this would actually work.






                                            share|improve this answer


























                                              1












                                              1








                                              1






                                              Single sign on solution for SSH could lead me to pam_ssh.



                                              According to this article, the concept is:




                                              If you work with multiple *nix-based machines via ssh, you are probably tired of constantly having to enter your password every time you want to access another box. There is a secure way to allow you to access every machine, that you have ssh access to, without having to enter another password (other than the one you signed on with originally.)







                                              This is actually quite simple to do, you basically just create a public/private key pair to authenticate yourself to your other machines, then have PAM spawn an agent to load your keys after you logon, providing a single signon solution to accessing all your remote machines. This guide will walk you through setting this up.




                                              I have not verified this would actually work.






                                              share|improve this answer














                                              Single sign on solution for SSH could lead me to pam_ssh.



                                              According to this article, the concept is:




                                              If you work with multiple *nix-based machines via ssh, you are probably tired of constantly having to enter your password every time you want to access another box. There is a secure way to allow you to access every machine, that you have ssh access to, without having to enter another password (other than the one you signed on with originally.)







                                              This is actually quite simple to do, you basically just create a public/private key pair to authenticate yourself to your other machines, then have PAM spawn an agent to load your keys after you logon, providing a single signon solution to accessing all your remote machines. This guide will walk you through setting this up.




                                              I have not verified this would actually work.







                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Feb 6 '18 at 15:04









                                              Vlastimil

                                              7,8271261134




                                              7,8271261134










                                              answered Aug 21 '17 at 22:57









                                              MichaelMichael

                                              111




                                              111























                                                  1














                                                  I used to use the script mentioned by steampowered, I've made the below one now, because it doesn't leave files lying around.



                                                  Working on zsh shell only.



                                                  #!/bin/sh

                                                  AGENT_BIN=`which ssh-agent`
                                                  AGENT_ADD_BIN=`which ssh-add`
                                                  AGENT_PID=`ps -fe | grep ${AGENT_BIN} | awk -vuser=$USER -vcmd="$AGENT_BIN" '$1==user && $8==cmd{print $2;exit;}'`
                                                  if [ -z "$AGENT_BIN" ]; then
                                                  echo "no ssh agent found!";
                                                  return
                                                  fi
                                                  if [ "" -eq "$AGENT_PID" ]; then
                                                  if read -sq "YN?Do you want to unlock your ssh keys?"; then
                                                  echo ""
                                                  output=`$AGENT_BIN | sed 's/echo/#echo/g'`
                                                  eval $output
                                                  $AGENT_ADD_BIN
                                                  fi
                                                  else
                                                  for f in "/proc/"*
                                                  do
                                                  cmdline=`cat "$f/cmdline"`
                                                  if [ "${AGENT_BIN}" -ef "${cmdline}" ]; then
                                                  export SSH_AUTH_SOCK=`cat $f/net/unix | grep --binary-file=text -oP '((/[^/]*?)+/ssh-[^/]+/agent.d+$)'`
                                                  export SSH_AGENT_PID=${f##*/}
                                                  break;
                                                  fi
                                                  done
                                                  fi





                                                  share|improve this answer




























                                                    1














                                                    I used to use the script mentioned by steampowered, I've made the below one now, because it doesn't leave files lying around.



                                                    Working on zsh shell only.



                                                    #!/bin/sh

                                                    AGENT_BIN=`which ssh-agent`
                                                    AGENT_ADD_BIN=`which ssh-add`
                                                    AGENT_PID=`ps -fe | grep ${AGENT_BIN} | awk -vuser=$USER -vcmd="$AGENT_BIN" '$1==user && $8==cmd{print $2;exit;}'`
                                                    if [ -z "$AGENT_BIN" ]; then
                                                    echo "no ssh agent found!";
                                                    return
                                                    fi
                                                    if [ "" -eq "$AGENT_PID" ]; then
                                                    if read -sq "YN?Do you want to unlock your ssh keys?"; then
                                                    echo ""
                                                    output=`$AGENT_BIN | sed 's/echo/#echo/g'`
                                                    eval $output
                                                    $AGENT_ADD_BIN
                                                    fi
                                                    else
                                                    for f in "/proc/"*
                                                    do
                                                    cmdline=`cat "$f/cmdline"`
                                                    if [ "${AGENT_BIN}" -ef "${cmdline}" ]; then
                                                    export SSH_AUTH_SOCK=`cat $f/net/unix | grep --binary-file=text -oP '((/[^/]*?)+/ssh-[^/]+/agent.d+$)'`
                                                    export SSH_AGENT_PID=${f##*/}
                                                    break;
                                                    fi
                                                    done
                                                    fi





                                                    share|improve this answer


























                                                      1












                                                      1








                                                      1






                                                      I used to use the script mentioned by steampowered, I've made the below one now, because it doesn't leave files lying around.



                                                      Working on zsh shell only.



                                                      #!/bin/sh

                                                      AGENT_BIN=`which ssh-agent`
                                                      AGENT_ADD_BIN=`which ssh-add`
                                                      AGENT_PID=`ps -fe | grep ${AGENT_BIN} | awk -vuser=$USER -vcmd="$AGENT_BIN" '$1==user && $8==cmd{print $2;exit;}'`
                                                      if [ -z "$AGENT_BIN" ]; then
                                                      echo "no ssh agent found!";
                                                      return
                                                      fi
                                                      if [ "" -eq "$AGENT_PID" ]; then
                                                      if read -sq "YN?Do you want to unlock your ssh keys?"; then
                                                      echo ""
                                                      output=`$AGENT_BIN | sed 's/echo/#echo/g'`
                                                      eval $output
                                                      $AGENT_ADD_BIN
                                                      fi
                                                      else
                                                      for f in "/proc/"*
                                                      do
                                                      cmdline=`cat "$f/cmdline"`
                                                      if [ "${AGENT_BIN}" -ef "${cmdline}" ]; then
                                                      export SSH_AUTH_SOCK=`cat $f/net/unix | grep --binary-file=text -oP '((/[^/]*?)+/ssh-[^/]+/agent.d+$)'`
                                                      export SSH_AGENT_PID=${f##*/}
                                                      break;
                                                      fi
                                                      done
                                                      fi





                                                      share|improve this answer














                                                      I used to use the script mentioned by steampowered, I've made the below one now, because it doesn't leave files lying around.



                                                      Working on zsh shell only.



                                                      #!/bin/sh

                                                      AGENT_BIN=`which ssh-agent`
                                                      AGENT_ADD_BIN=`which ssh-add`
                                                      AGENT_PID=`ps -fe | grep ${AGENT_BIN} | awk -vuser=$USER -vcmd="$AGENT_BIN" '$1==user && $8==cmd{print $2;exit;}'`
                                                      if [ -z "$AGENT_BIN" ]; then
                                                      echo "no ssh agent found!";
                                                      return
                                                      fi
                                                      if [ "" -eq "$AGENT_PID" ]; then
                                                      if read -sq "YN?Do you want to unlock your ssh keys?"; then
                                                      echo ""
                                                      output=`$AGENT_BIN | sed 's/echo/#echo/g'`
                                                      eval $output
                                                      $AGENT_ADD_BIN
                                                      fi
                                                      else
                                                      for f in "/proc/"*
                                                      do
                                                      cmdline=`cat "$f/cmdline"`
                                                      if [ "${AGENT_BIN}" -ef "${cmdline}" ]; then
                                                      export SSH_AUTH_SOCK=`cat $f/net/unix | grep --binary-file=text -oP '((/[^/]*?)+/ssh-[^/]+/agent.d+$)'`
                                                      export SSH_AGENT_PID=${f##*/}
                                                      break;
                                                      fi
                                                      done
                                                      fi






                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      edited Feb 6 '18 at 15:29









                                                      Vlastimil

                                                      7,8271261134




                                                      7,8271261134










                                                      answered Jul 19 '16 at 7:16









                                                      rmcrmc

                                                      1192




                                                      1192























                                                          0














                                                          Add this to your ~/.bashrc file:



                                                          ssh-add -L|grep identities > /dev/null && ssh-add /path/to/ssh/private/key





                                                          share|improve this answer























                                                          • I don't see how this relates to the question, which is about not being prompted for the password on subsequent logins.
                                                            – Chris Down
                                                            Jan 6 '14 at 13:23


















                                                          0














                                                          Add this to your ~/.bashrc file:



                                                          ssh-add -L|grep identities > /dev/null && ssh-add /path/to/ssh/private/key





                                                          share|improve this answer























                                                          • I don't see how this relates to the question, which is about not being prompted for the password on subsequent logins.
                                                            – Chris Down
                                                            Jan 6 '14 at 13:23
















                                                          0












                                                          0








                                                          0






                                                          Add this to your ~/.bashrc file:



                                                          ssh-add -L|grep identities > /dev/null && ssh-add /path/to/ssh/private/key





                                                          share|improve this answer














                                                          Add this to your ~/.bashrc file:



                                                          ssh-add -L|grep identities > /dev/null && ssh-add /path/to/ssh/private/key






                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Jan 6 '14 at 13:26









                                                          Kevdog777

                                                          2,092123259




                                                          2,092123259










                                                          answered Jan 6 '14 at 12:47









                                                          AbukamelAbukamel

                                                          192




                                                          192












                                                          • I don't see how this relates to the question, which is about not being prompted for the password on subsequent logins.
                                                            – Chris Down
                                                            Jan 6 '14 at 13:23




















                                                          • I don't see how this relates to the question, which is about not being prompted for the password on subsequent logins.
                                                            – Chris Down
                                                            Jan 6 '14 at 13:23


















                                                          I don't see how this relates to the question, which is about not being prompted for the password on subsequent logins.
                                                          – Chris Down
                                                          Jan 6 '14 at 13:23






                                                          I don't see how this relates to the question, which is about not being prompted for the password on subsequent logins.
                                                          – Chris Down
                                                          Jan 6 '14 at 13:23













                                                          0














                                                          In order to add a (possibly passwordless) key and ensure that ssh-add will not prompt for a password, no matter what, even when running under X:



                                                          DISPLAY= ssh-add -k /path/to/key </dev/null &>/dev/null


                                                          Exit status indicates success or failure.






                                                          share|improve this answer


























                                                            0














                                                            In order to add a (possibly passwordless) key and ensure that ssh-add will not prompt for a password, no matter what, even when running under X:



                                                            DISPLAY= ssh-add -k /path/to/key </dev/null &>/dev/null


                                                            Exit status indicates success or failure.






                                                            share|improve this answer
























                                                              0












                                                              0








                                                              0






                                                              In order to add a (possibly passwordless) key and ensure that ssh-add will not prompt for a password, no matter what, even when running under X:



                                                              DISPLAY= ssh-add -k /path/to/key </dev/null &>/dev/null


                                                              Exit status indicates success or failure.






                                                              share|improve this answer












                                                              In order to add a (possibly passwordless) key and ensure that ssh-add will not prompt for a password, no matter what, even when running under X:



                                                              DISPLAY= ssh-add -k /path/to/key </dev/null &>/dev/null


                                                              Exit status indicates success or failure.







                                                              share|improve this answer












                                                              share|improve this answer



                                                              share|improve this answer










                                                              answered Feb 11 '15 at 1:56









                                                              Keith CascioKeith Cascio

                                                              32125




                                                              32125























                                                                  0














                                                                  If you are running seahorse as your password manager
                                                                  ... Which you probably are ;D



                                                                  Another solution that achieves the goal you are looking for is simply adding the ssh keys to seahorse for automatic unlock upon login. The major benefit to this is that you never have to enter a password for the keys after you login through gdm, or whatever your loging in with even if the keys have a password. This REQUIRES both the private key and the public key. They also MUST follow a naming convention for seahorse. The default is acceptable (id_rsa for private key and id_rsa.pub for public key... Really anything that is privatekeyname and privatekeyname.pub)



                                                                  To add you ssh key to seahorse for automatic unlock upon login;
                                                                  (on fedora25, I'm not sure where the path is on other distros though its most likely very similar)



                                                                  /lib64/seahorse/seahorse-ssh-askpass /path/to/keys/here


                                                                  For me, it was



                                                                  /lib64/seahorse/seahorse-ssh-askpass ~/.ssh/id_rsa


                                                                  (seahorse will automatically assume that the public key in my case was id_rsa.pub)



                                                                  After executing the command, seahorse will pop open a cute little gtk password field to enter the password for the private key into. or just leave it blank if you generated the key without a password.



                                                                  Seahorse won't prompt you if everything went okay. You will need to attempt to ssh into the target machine. Then seahorse will prompt you to unlock the key with a password graphically (THIS WILL ONLY HAPPEN ONCE) again but it should look a little different this time ;P (this is also the part where seahorse does some seahorse to ssh-add magic I believe), and offer the OPTION to unlock the key upon login, you must check this option to achieve your goal.



                                                                  Just because I didn't read all the answers, I would recommend undoing what everyone told you to do with ssh-add before attempting this answer. Doing so otherwise might result in something bad happening to your keys, idk.






                                                                  share|improve this answer


























                                                                    0














                                                                    If you are running seahorse as your password manager
                                                                    ... Which you probably are ;D



                                                                    Another solution that achieves the goal you are looking for is simply adding the ssh keys to seahorse for automatic unlock upon login. The major benefit to this is that you never have to enter a password for the keys after you login through gdm, or whatever your loging in with even if the keys have a password. This REQUIRES both the private key and the public key. They also MUST follow a naming convention for seahorse. The default is acceptable (id_rsa for private key and id_rsa.pub for public key... Really anything that is privatekeyname and privatekeyname.pub)



                                                                    To add you ssh key to seahorse for automatic unlock upon login;
                                                                    (on fedora25, I'm not sure where the path is on other distros though its most likely very similar)



                                                                    /lib64/seahorse/seahorse-ssh-askpass /path/to/keys/here


                                                                    For me, it was



                                                                    /lib64/seahorse/seahorse-ssh-askpass ~/.ssh/id_rsa


                                                                    (seahorse will automatically assume that the public key in my case was id_rsa.pub)



                                                                    After executing the command, seahorse will pop open a cute little gtk password field to enter the password for the private key into. or just leave it blank if you generated the key without a password.



                                                                    Seahorse won't prompt you if everything went okay. You will need to attempt to ssh into the target machine. Then seahorse will prompt you to unlock the key with a password graphically (THIS WILL ONLY HAPPEN ONCE) again but it should look a little different this time ;P (this is also the part where seahorse does some seahorse to ssh-add magic I believe), and offer the OPTION to unlock the key upon login, you must check this option to achieve your goal.



                                                                    Just because I didn't read all the answers, I would recommend undoing what everyone told you to do with ssh-add before attempting this answer. Doing so otherwise might result in something bad happening to your keys, idk.






                                                                    share|improve this answer
























                                                                      0












                                                                      0








                                                                      0






                                                                      If you are running seahorse as your password manager
                                                                      ... Which you probably are ;D



                                                                      Another solution that achieves the goal you are looking for is simply adding the ssh keys to seahorse for automatic unlock upon login. The major benefit to this is that you never have to enter a password for the keys after you login through gdm, or whatever your loging in with even if the keys have a password. This REQUIRES both the private key and the public key. They also MUST follow a naming convention for seahorse. The default is acceptable (id_rsa for private key and id_rsa.pub for public key... Really anything that is privatekeyname and privatekeyname.pub)



                                                                      To add you ssh key to seahorse for automatic unlock upon login;
                                                                      (on fedora25, I'm not sure where the path is on other distros though its most likely very similar)



                                                                      /lib64/seahorse/seahorse-ssh-askpass /path/to/keys/here


                                                                      For me, it was



                                                                      /lib64/seahorse/seahorse-ssh-askpass ~/.ssh/id_rsa


                                                                      (seahorse will automatically assume that the public key in my case was id_rsa.pub)



                                                                      After executing the command, seahorse will pop open a cute little gtk password field to enter the password for the private key into. or just leave it blank if you generated the key without a password.



                                                                      Seahorse won't prompt you if everything went okay. You will need to attempt to ssh into the target machine. Then seahorse will prompt you to unlock the key with a password graphically (THIS WILL ONLY HAPPEN ONCE) again but it should look a little different this time ;P (this is also the part where seahorse does some seahorse to ssh-add magic I believe), and offer the OPTION to unlock the key upon login, you must check this option to achieve your goal.



                                                                      Just because I didn't read all the answers, I would recommend undoing what everyone told you to do with ssh-add before attempting this answer. Doing so otherwise might result in something bad happening to your keys, idk.






                                                                      share|improve this answer












                                                                      If you are running seahorse as your password manager
                                                                      ... Which you probably are ;D



                                                                      Another solution that achieves the goal you are looking for is simply adding the ssh keys to seahorse for automatic unlock upon login. The major benefit to this is that you never have to enter a password for the keys after you login through gdm, or whatever your loging in with even if the keys have a password. This REQUIRES both the private key and the public key. They also MUST follow a naming convention for seahorse. The default is acceptable (id_rsa for private key and id_rsa.pub for public key... Really anything that is privatekeyname and privatekeyname.pub)



                                                                      To add you ssh key to seahorse for automatic unlock upon login;
                                                                      (on fedora25, I'm not sure where the path is on other distros though its most likely very similar)



                                                                      /lib64/seahorse/seahorse-ssh-askpass /path/to/keys/here


                                                                      For me, it was



                                                                      /lib64/seahorse/seahorse-ssh-askpass ~/.ssh/id_rsa


                                                                      (seahorse will automatically assume that the public key in my case was id_rsa.pub)



                                                                      After executing the command, seahorse will pop open a cute little gtk password field to enter the password for the private key into. or just leave it blank if you generated the key without a password.



                                                                      Seahorse won't prompt you if everything went okay. You will need to attempt to ssh into the target machine. Then seahorse will prompt you to unlock the key with a password graphically (THIS WILL ONLY HAPPEN ONCE) again but it should look a little different this time ;P (this is also the part where seahorse does some seahorse to ssh-add magic I believe), and offer the OPTION to unlock the key upon login, you must check this option to achieve your goal.



                                                                      Just because I didn't read all the answers, I would recommend undoing what everyone told you to do with ssh-add before attempting this answer. Doing so otherwise might result in something bad happening to your keys, idk.







                                                                      share|improve this answer












                                                                      share|improve this answer



                                                                      share|improve this answer










                                                                      answered Dec 20 '16 at 16:25









                                                                      enconnenconn

                                                                      93116




                                                                      93116























                                                                          0














                                                                          Here is the definitive script.



                                                                          Update $PASSW, then copy-paste it in your Terminal



                                                                          # <sshpass> via typinator
                                                                          # Updated: 2017-01-18_21h36
                                                                          #
                                                                          # apt-get update -y; apt-get install expect -qy

                                                                          # Pass this value to ssh-add
                                                                          PASSW="myfancypass123"

                                                                          # Define a name for this script
                                                                          THIS_SCRIPT="$(date +%Y-%m-%d_%H-%M-%S-%N)".sh

                                                                          # Create a fresh directory to work from / Clean up
                                                                          rm -rf ~/temp; mkdir -p ~/temp; cd ~/temp; ls -la


                                                                          # Output our bash script file - BEGIN
                                                                          cat <<< '
                                                                          #!/bin/bash

                                                                          set -u # Stop if an unbound variable is referenced
                                                                          set -e # Stop on first error
                                                                          export HISTIGNORE="expect*";

                                                                          # Normal CMDs
                                                                          echo && echo "The process should take about 10 seconds:" && echo
                                                                          eval "$(ssh-agent -s)"; sleep 0.5;

                                                                          # Define VAR passed when this bash-script was launched
                                                                          password="$@"

                                                                          # Launch the expect magic
                                                                          expect -c "
                                                                          spawn ssh-add /root/.ssh/id_rsa
                                                                          expect "?assword:"
                                                                          send "$passwordr"
                                                                          expect "?password:"
                                                                          send "$passwordr"
                                                                          expect eof"

                                                                          export HISTIGNORE="";
                                                                          export password="";
                                                                          ' > $THIS_SCRIPT
                                                                          # Output our bash script file - END


                                                                          # Ensure we are in the right path
                                                                          cd ~/temp; ls -la; sleep 1;

                                                                          # Run the bash script
                                                                          chmod +x ./$THIS_SCRIPT; ./$THIS_SCRIPT "$PASSW"; unset password;

                                                                          # Clean up
                                                                          rm -rf ~/temp; mkdir -p ~/temp; cd ~/temp; ls -la





                                                                          share|improve this answer




























                                                                            0














                                                                            Here is the definitive script.



                                                                            Update $PASSW, then copy-paste it in your Terminal



                                                                            # <sshpass> via typinator
                                                                            # Updated: 2017-01-18_21h36
                                                                            #
                                                                            # apt-get update -y; apt-get install expect -qy

                                                                            # Pass this value to ssh-add
                                                                            PASSW="myfancypass123"

                                                                            # Define a name for this script
                                                                            THIS_SCRIPT="$(date +%Y-%m-%d_%H-%M-%S-%N)".sh

                                                                            # Create a fresh directory to work from / Clean up
                                                                            rm -rf ~/temp; mkdir -p ~/temp; cd ~/temp; ls -la


                                                                            # Output our bash script file - BEGIN
                                                                            cat <<< '
                                                                            #!/bin/bash

                                                                            set -u # Stop if an unbound variable is referenced
                                                                            set -e # Stop on first error
                                                                            export HISTIGNORE="expect*";

                                                                            # Normal CMDs
                                                                            echo && echo "The process should take about 10 seconds:" && echo
                                                                            eval "$(ssh-agent -s)"; sleep 0.5;

                                                                            # Define VAR passed when this bash-script was launched
                                                                            password="$@"

                                                                            # Launch the expect magic
                                                                            expect -c "
                                                                            spawn ssh-add /root/.ssh/id_rsa
                                                                            expect "?assword:"
                                                                            send "$passwordr"
                                                                            expect "?password:"
                                                                            send "$passwordr"
                                                                            expect eof"

                                                                            export HISTIGNORE="";
                                                                            export password="";
                                                                            ' > $THIS_SCRIPT
                                                                            # Output our bash script file - END


                                                                            # Ensure we are in the right path
                                                                            cd ~/temp; ls -la; sleep 1;

                                                                            # Run the bash script
                                                                            chmod +x ./$THIS_SCRIPT; ./$THIS_SCRIPT "$PASSW"; unset password;

                                                                            # Clean up
                                                                            rm -rf ~/temp; mkdir -p ~/temp; cd ~/temp; ls -la





                                                                            share|improve this answer


























                                                                              0












                                                                              0








                                                                              0






                                                                              Here is the definitive script.



                                                                              Update $PASSW, then copy-paste it in your Terminal



                                                                              # <sshpass> via typinator
                                                                              # Updated: 2017-01-18_21h36
                                                                              #
                                                                              # apt-get update -y; apt-get install expect -qy

                                                                              # Pass this value to ssh-add
                                                                              PASSW="myfancypass123"

                                                                              # Define a name for this script
                                                                              THIS_SCRIPT="$(date +%Y-%m-%d_%H-%M-%S-%N)".sh

                                                                              # Create a fresh directory to work from / Clean up
                                                                              rm -rf ~/temp; mkdir -p ~/temp; cd ~/temp; ls -la


                                                                              # Output our bash script file - BEGIN
                                                                              cat <<< '
                                                                              #!/bin/bash

                                                                              set -u # Stop if an unbound variable is referenced
                                                                              set -e # Stop on first error
                                                                              export HISTIGNORE="expect*";

                                                                              # Normal CMDs
                                                                              echo && echo "The process should take about 10 seconds:" && echo
                                                                              eval "$(ssh-agent -s)"; sleep 0.5;

                                                                              # Define VAR passed when this bash-script was launched
                                                                              password="$@"

                                                                              # Launch the expect magic
                                                                              expect -c "
                                                                              spawn ssh-add /root/.ssh/id_rsa
                                                                              expect "?assword:"
                                                                              send "$passwordr"
                                                                              expect "?password:"
                                                                              send "$passwordr"
                                                                              expect eof"

                                                                              export HISTIGNORE="";
                                                                              export password="";
                                                                              ' > $THIS_SCRIPT
                                                                              # Output our bash script file - END


                                                                              # Ensure we are in the right path
                                                                              cd ~/temp; ls -la; sleep 1;

                                                                              # Run the bash script
                                                                              chmod +x ./$THIS_SCRIPT; ./$THIS_SCRIPT "$PASSW"; unset password;

                                                                              # Clean up
                                                                              rm -rf ~/temp; mkdir -p ~/temp; cd ~/temp; ls -la





                                                                              share|improve this answer














                                                                              Here is the definitive script.



                                                                              Update $PASSW, then copy-paste it in your Terminal



                                                                              # <sshpass> via typinator
                                                                              # Updated: 2017-01-18_21h36
                                                                              #
                                                                              # apt-get update -y; apt-get install expect -qy

                                                                              # Pass this value to ssh-add
                                                                              PASSW="myfancypass123"

                                                                              # Define a name for this script
                                                                              THIS_SCRIPT="$(date +%Y-%m-%d_%H-%M-%S-%N)".sh

                                                                              # Create a fresh directory to work from / Clean up
                                                                              rm -rf ~/temp; mkdir -p ~/temp; cd ~/temp; ls -la


                                                                              # Output our bash script file - BEGIN
                                                                              cat <<< '
                                                                              #!/bin/bash

                                                                              set -u # Stop if an unbound variable is referenced
                                                                              set -e # Stop on first error
                                                                              export HISTIGNORE="expect*";

                                                                              # Normal CMDs
                                                                              echo && echo "The process should take about 10 seconds:" && echo
                                                                              eval "$(ssh-agent -s)"; sleep 0.5;

                                                                              # Define VAR passed when this bash-script was launched
                                                                              password="$@"

                                                                              # Launch the expect magic
                                                                              expect -c "
                                                                              spawn ssh-add /root/.ssh/id_rsa
                                                                              expect "?assword:"
                                                                              send "$passwordr"
                                                                              expect "?password:"
                                                                              send "$passwordr"
                                                                              expect eof"

                                                                              export HISTIGNORE="";
                                                                              export password="";
                                                                              ' > $THIS_SCRIPT
                                                                              # Output our bash script file - END


                                                                              # Ensure we are in the right path
                                                                              cd ~/temp; ls -la; sleep 1;

                                                                              # Run the bash script
                                                                              chmod +x ./$THIS_SCRIPT; ./$THIS_SCRIPT "$PASSW"; unset password;

                                                                              # Clean up
                                                                              rm -rf ~/temp; mkdir -p ~/temp; cd ~/temp; ls -la






                                                                              share|improve this answer














                                                                              share|improve this answer



                                                                              share|improve this answer








                                                                              edited Jan 19 '17 at 2:46

























                                                                              answered Jan 19 '17 at 2:40









                                                                              Pascal AndyPascal Andy

                                                                              284




                                                                              284






























                                                                                  draft saved

                                                                                  draft discarded




















































                                                                                  Thanks for contributing an answer to Unix & Linux Stack Exchange!


                                                                                  • Please be sure to answer the question. Provide details and share your research!

                                                                                  But avoid



                                                                                  • Asking for help, clarification, or responding to other answers.

                                                                                  • Making statements based on opinion; back them up with references or personal experience.


                                                                                  To learn more, see our tips on writing great answers.





                                                                                  Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                                                                  Please pay close attention to the following guidance:


                                                                                  • Please be sure to answer the question. Provide details and share your research!

                                                                                  But avoid



                                                                                  • Asking for help, clarification, or responding to other answers.

                                                                                  • Making statements based on opinion; back them up with references or personal experience.


                                                                                  To learn more, see our tips on writing great answers.




                                                                                  draft saved


                                                                                  draft discarded














                                                                                  StackExchange.ready(
                                                                                  function () {
                                                                                  StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f90853%2fhow-can-i-run-ssh-add-automatically-without-a-password-prompt%23new-answer', 'question_page');
                                                                                  }
                                                                                  );

                                                                                  Post as a guest















                                                                                  Required, but never shown





















































                                                                                  Required, but never shown














                                                                                  Required, but never shown












                                                                                  Required, but never shown







                                                                                  Required, but never shown

































                                                                                  Required, but never shown














                                                                                  Required, but never shown












                                                                                  Required, but never shown







                                                                                  Required, but never shown







                                                                                  Popular posts from this blog

                                                                                  Accessing regular linux commands in Huawei's Dopra Linux

                                                                                  Can't connect RFCOMM socket: Host is down

                                                                                  Kernel panic - not syncing: Fatal Exception in Interrupt