Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an ssh agent from emacs in server mode

I am running emacs in server mode as a systemd user service and want to pull from a pubkey-authenticated remote repository using magit. Unfortunately, magit (or its git child process) cannot use my already loaded public key. Apparently, I cannot connect to my ssh-agent from within the context of emacs.

Run from within emacs:

~ ssh-add  
Could not open a connection to your authentication agent.

Is there a known way to solve that issue or do I have to dig into how ssh-agent and clients actually communicate?

like image 681
choeger Avatar asked Feb 09 '17 12:02

choeger


People also ask

How do I use Emacs daemon?

One easy way to start the Emacs daemon is via “Settings > Session and Startup > Application Autostart”. You can also place an init script to place in /etc/init. d/emacsd.

How do I use Emacsclient?

The simplest way to use the emacsclient program is to run the shell command ' emacsclient file ', where file is a file name. This connects to an Emacs server, and tells that Emacs process to visit file in one of its existing frames—either a graphical frame, or one in a text terminal (see Frames and Graphical Displays).


2 Answers

I use keychain to manage ssh-agents. It starts the agent and dumps relevant parameters (agent PID and socket) into a script that can be sourced by a shell. There's an Emacs package keychain-environment that can pull this into Emacs.

~/.bash_profile:

# keychain manages ssh-agents
type keychain >&/dev/null \
    && keychain --agents ssh

This starts runs keychain at login, which will start an ssh-agent and dump its info to a file. keychain is idempotent, so subsequent logins (e.g. logging in with ssh) will not start a new ssh-agent if it's already running.

~/.bashrc:

# keychain keeps track of ssh-agents
[ -f $HOME/.keychain/$HOSTNAME-sh ] \
    && . $HOME/.keychain/$HOSTNAME-sh

This allows any new shell to reuse the agent. I don't think this is actually relevant to Emacs, but is obviously useful.

~/.emacs.d/init.el:

(require 'keychain-environment)
(keychain-refresh-environment)

This loads the agent info into Emacs, so Emacs can talk to it (or more accurately, any ssh process started by Emacs can see the relevant env vars).

like image 196
jpkotta Avatar answered Oct 17 '22 05:10

jpkotta


The ssh-agent must be running in a parent process of the process you want to use it. This is why it is often started as part of the setup for the window manager - all sub-processes of the window manager i.e. terminals and programs run by the user, will be able to use the ssh-agent.

In your case, you could perhaps run ssh-agent as the parent process in your systemd user service that starts emacs, but then of course your agent won't work with other uses, such as from terminals opened under your wm.

like image 32
Tim X Avatar answered Oct 17 '22 06:10

Tim X