Автозапуск ssh agent ubuntu

Обновлено: 06.07.2024

Completely brand new to linux and Ubnuntu. Setting up a machine to do deep learning/neural networks. So far it is going well. Got everything installed and running. I want to be able to ssh from my Mac laptop to use the system. I installed openssh and got that working.

However when I restart the machine, the ssh server doesn't restart. I check with sudo service ssh status and it reports and error. I can then start it and everything works fine.

My first thought was I need to tell it to start on reboot, and I found this thread which says that it should start by default and I don't need to add a chrontab or anything like that. So I don't think that is it.

Then I found this thread which suggest using the command sudo update-rc.d ssh defaults , but that thread is quite old and it seems that answer was maybe not right even back then?

So then I found this thread which suggest commenting out the ListenAddress line in the sshd_config file. Basically it says if the ListenAddress is used it may try to get the IP before it has been assigned by the DCHP and so start up fails. Which makes sense. But I need that parameter to make my port forwarding work over my home network.

This documentation under the entry for ListenAddress says that

So maybe I don't need it to make port forwarding work?

I followed the previous thread to this bug report which is also quite old, but suggests to use network manager to restart ssh every time netmanager gets a new IP.

That is a lot more than this noobie can evaluate at this point. Is that safe? Is that the way to do this? Has something else been worked out in the last 7 years?

Any advice would be great. Thanks.


375 1 1 gold badge 2 2 silver badges 9 9 bronze badges Gee, I simply installed the openssh-server package and configured it properly. My ssh server has automatically started properly every time since. No need for any extra fiddling at all.

3 Answers 3

Have you tried just simply setting

That's how I have my ssh set to run at start up.

****I'm leaving in the above part of the answer in case it's helpful for others who come across this post****

Quoting my comment from above:

How do you have your port forwarding setup? I don't use the ListenAddress at all and things work fine on my home server. My router forwards anything that comes in on a port I specify (22 if you want the standard port, but you can use anything as long as it doesn't conflict with other services on your intl. network) to the computer I want. For example anything that comes in on port 12345 gets forwarded to port 22 on my CentOS server. Anything that comes in on 12346 gets forwarded to port 22 of my headless RasPi. Anything that comes in on 12347 goes to port 6697 for the IRC bouncer on my RasPi

Let us say you have total 8 public IP address and one private IP address. You >would like to bind sshd to one selected public IP (ex 70.5.xx.xx) and private >IP (10.1.5.1) only.

Luckily there is an easy way to achieve this using ListenAddress option. It >specifies the local addresses sshd should listen on. If this directive is >skipped from configuration file sshd will bind or list on all available IP >address.

It's to allow one some of your multiple IPs to accept ssh connections. I'm guessing you set the ListenAddress to either your public IP or your router's internal IP - I'm guessing if you set that to your server's local IP it would have worked fine. Regardless, now you know how ListenAddress works and you'll be ready if you have to configure a more complicated server. Glad to hear you got things working.

Is there a way to set ssh agent permanently? Or does windows has a good way to manage the ssh keys?

I'm a new guy, please give me detailed tutorial, thanks!

3,053 4 4 gold badges 30 30 silver badges 48 48 bronze badges 1,894 2 2 gold badges 11 11 silver badges 8 8 bronze badges For people reaching this question and if your ssh -Tv git@server-host-name works, in my case, it was the GIT_SSH environment variable that was set to Putty Plink from Tortoise Git. Deleting GIT_SSH did the trick. TortoiseGit still working fine.

10 Answers 10

In a git bash session, you can add a script to

being usually set to %USERPROFILE% ), in order for said session to launch automatically the ssh-agent . If the file doesn't exist, just create it.

The "Auto-launching ssh-agent on Git for Windows" section of that article has a robust script that checks if the agent is running or not. Below is just a snippet, see the GitHub article for the full solution.

"Getting ssh-agent to work with git run from windows command shell" has a similar script, but I'd refer to the GitHub article above primarily, which is more robust and up to date.

24.8k 7 7 gold badges 67 67 silver badges 87 87 bronze badges


1.1m 459 459 gold badges 3828 3828 silver badges 4506 4506 bronze badges

P.S: These instructions are in context of a Bash shell opened in Windows 10 Linux Subsystem and doesn't mention about sym-linking SSH keys generated in Windows with Bash on Ubuntu on Windows

1) Update your .bashrc by adding following in it

2) Then run $ source

/.bashrc to reload your config.

3) Create a SSH config file, if not present. Use following command for creating a new one: .ssh$ touch config

4) Add following to

5) Add your key to SSH agent using command $ ssh-add

/.ssh/id_work_gmail and then you should be able to connect to your github account or remote host using ssh. For e.g. in context of above code examples:

This adding of key to the SSH agent should be required to be performed only one-time.

6) Now logout of your Bash session on Windows Linux Subsystem i.e. exit all the Bash consoles again and start a new console again and try to SSH to your Github Host or other host as configured in SSH config file and it should work without needing any extra steps.

If you face Bad owner or permissions on

/.ssh/config then update the permissions using the command chmod 600

The same details can be found in the gist Windows 10 Linux Subsystem SSH-agent issues


5,650 4 4 gold badges 48 48 silver badges 84 84 bronze badges Just a quick note that if you want to load an SSH key other than the default, change the "/usr/bin/ssh-add" line to "/usr/bin/ssh-add <your key name>"

I found the smoothest way to achieve this was using Pageant as the SSH agent and plink.

You need to have a putty session configured for the hostname that is used in your remote.

You will also need plink.exe which can be downloaded from the same site as putty.

And you need Pageant running with your key loaded. I have a shortcut to pageant in my startup folder that loads my SSH key when I log in.

When you install git-scm you can then specify it to use tortoise/plink rather than OpenSSH.

The net effect is you can open git-bash whenever you like and push/pull without being challenged for passphrases.

Same applies with putty and WinSCP sessions when pageant has your key loaded. It makes life a hell of a lot easier (and secure).

If the goal is to be able to push to a GitHub repo whenever you want to, then in Windows under C:\Users\tiago\.ssh where the keys are stored (at least in my case), create a file named config and add the following in it

Then simply open Git Bash and you'll be able to push without having to manually start the ssh-agent and adding the key.


11.6k 14 14 gold badges 68 68 silver badges 94 94 bronze badges

As I don't like using putty in Windows as a workaround, I created a very simple utility ssh-agent-wrapper. It scans your .ssh folders and adds all your keys to the agent. You simply need to put it into Windows startup folder for it to work.

Assumptions:

  • ssh-agent in path
  • shh-add in path (both by choosing the "RED" option when installing git
  • private keys are in %USERPROFILE%/.ssh folder
  • private keys names start with id (e.g. id_rsa)
2,597 2 2 gold badges 22 22 silver badges 32 32 bronze badges Nice! +1. I always work with openssh (not putty), so it is an interesting solution for private keys with passphrases. As you are on github already, then why not just make the source a git repository?

I could not get this to work based off the best answer, probably because I'm such a PC noob and missing something obvious. But just FYI in case it helps someone as challenged as me, what has FINALLY worked was through one of the links here (referenced in the answers). This involved simply pasting the following to my .bash_profile :

I probably have something configured weird, but was not successful when I added it to my .profile or .bashrc . The other real challenge I've run into is I'm not an admin on this computer and can't change the environment variables without getting it approved by IT, so this is a solution for those that can't access that.

You know it's working if you're prompted for your ssh password when you open git bash. Hallelujah something finally worked.

Put this in your

/.bashrc (or a file that's source'd from it) which will stop it from being run multiple times unnecessarily per shell:

And then add "AddKeysToAgent yes" to

ssh to your server (or git pull) normally and you'll only be asked for password/passphrase once per session.

The readme contains instructions on how to set the script up, so that each time you open a new window/tab the private key is added to ssh-agent automatically, and you don't have to worry about this, if you're working with remote git repositories.

Я вручную запускаю ssh-агент:

затем я добавляю агент:

затем он появляется, когда я делаю:

и я готов идти. Есть ли способ автоматизировать этот процесс, чтобы мне не приходилось делать это каждый раз при входе в систему? Сервер работает в RedHat 6.2 (Сантьяго).

пожалуйста, пройдите через эту статью. Вы можете найти это очень полезно:

на всякий случай, если вышеуказанная ссылка исчезнет когда-нибудь, я захватываю основную часть решения ниже:

данное решение от Reagle Джозеф М. путем Дэниел уставился:

добавьте это в свой .bash_profile

эта версия особенно приятно, так как он увидит, если вы уже запустили ssh-agent и, если он не может его найти, запустит его и сохранит настройки, чтобы они были полезны при следующем запуске оболочки.

в Arch Linux следующие работы действительно великолепны (должны работать на всех дистрибутивах на основе systemd):

создайте службу пользователя systemd, поместив следующее в

Setup shell, чтобы иметь переменную среды для сокета ( .bash_profile, .zshrc, . ):

включите службу, поэтому она будет запущена автоматически при входе в систему и запустите ее:

добавьте следующий параметр конфигурации в файл конфигурации ssh

/.ssh/config (эта работает с SSH 7.2):

это проинструктирует клиента ssh всегда добавлять ключ к работающему агенту, поэтому нет необходимости ssh-добавлять его заранее.

принятое решение имеет следующие недостатки:

  • сложно поддерживать;
  • он оценивает файл хранения, который может привести к ошибкам или нарушению безопасности;
  • он запускает агент, но не останавливает его, что близко эквивалентно оставлению ключа в зажигании.

если ваши ключи не требуют ввода пароля, я предлагаю следующее решение. Добавьте к вашему .bash_profile конец (отредактируйте список ключей потребности):

Он имеет следующие преимущества:

  • гораздо более простое решение;
  • сеанс агента заканчивается, когда сеанс bash заканчивается.

у него есть возможные недостатки:

  • интерактивные ssh-add команда будет влиять только на один сеанс, что на самом деле является проблемой только в очень нетипичных обстоятельствах;
  • непригодно, если требуется ввести пароль;
  • начатая оболочка становится не-логином (который не влияет ни на что AFAIK).

обратите внимание, что несколько ssh-agent процессы не являются недостатком, потому что они не занимают больше памяти или времени процессора.

старый вопрос, но я столкнулся с подобной ситуацией. Не думайте, что приведенный выше ответ полностью достигает того, что необходимо. Недостающая часть - keychain ; установите его, если он еще не установлен.

затем добавьте следующую строку в ваш

запуск ssh-agent если он не работает, подключитесь к нему, если это так, загрузите ssh-agent переменные среды в вашу оболочку и загрузите ключ ssh.

изменить id_rsa в зависимости от того, что частная ключ

/.ssh вы хотите загрузить.

ссылка

добавьте это в ваш

Это должно запрашивать пароль только при первом входе в систему после каждой перезагрузки. Он будет продолжать повторно использовать ssh-agent пока он работает.

поэтому я использовал описанные выше подходы, но я предпочитаю, чтобы агент умер, когда закончится мой последний сеанс bash. Это немного дольше, чем другие решения, но это мой предпочтительный подход. Основная идея заключается в том, что первый сеанс bash запускает ssh-агент. Затем каждый дополнительный сеанс bash проверяет файл конфигурации (

/.ssh/.agent_env ). Если это есть, и есть сеанс работает, то источник среды и создать жесткую ссылку на файл сокета в /tmp (должен быть на та же файловая система, что и исходный файл сокета). По мере завершения сеансов bash каждый удаляет свою собственную жесткую ссылку. Последний сеанс для закрытия обнаружит, что жесткие ссылки имеют 2 ссылки (hardlink и оригинал), удаление собственного сокета процессов и убийство процесса приведет к 0, оставив чистую среду после закрытия последнего сеанса bash.

извините за опоздание:

пользователи рыбы оболочки можно использовать скрипт сделать то же самое.

чтобы добавить еще одно решение: P, я пошел с комбинацией решений @spheenik и @collin-anderson.

может быть немного более элегантным, но простым и читаемым. Это решение:

  • обеспечивает AddKeysToAgent yes находится в вашей конфигурации ssh, поэтому ключи будут автоматически добавлены при использовании
  • не предлагает вам вводить какие-либо парольные фразы при входе в систему (опять же, одноразовый ввод парольной фразы происходит при первом использовании)
  • молча начинает ssh-agent, если он еще не запустил один

Я решил это, добавив это в/etc / profile - system wide (или к локальному пользователю .профиль или. файл).

это запускает новый ssh-агент, если он не работает для пользователя, или повторно устанавливает параметр ssh-agent env при запуске.

Как ваши ответы большое. Он сделал работу из cygwin / linux хозяева намного проще. Я объединил функции start и end, чтобы сделать его безопасным.

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.

1,045 1 1 gold badge 8 8 silver badges 10 10 bronze badges 3,227 4 4 gold badges 12 12 silver badges 8 8 bronze badges @steampowered yes - but I think the top answer given here is better and Unix SE is a more appropriate place for this question

18 Answers 18

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:

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

or the following to

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

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

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 "passphrase\n" | 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:

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.

Читайте также: