seamux
seamux

Reputation: 139

Cannot connect to ssh-agent with automation script in Linux

I'm trying to write a script to automate an rclone process that requires ssh authentication via public key with a passphrase for the private key. The authentication service does not run by default in a new session. Manually I can do

$ eval `ssh-agent`
Agent pid 2335
$ ssh-add
Enter passphrase for /home/user/.ssh/private_key:
Identity added: /home/user/.ssh/private_key (/home/user/.ssh/private_key)

and then I run the rclone process. However, if I run the script, let's call it auth

#!/bin/bash
eval `ssh-agent`
/path/to/scpw

where scpw is an expect script that automates the passphrase input for ssh-add, then I get the same output as manual entry:

$ /path/to/auth
Agent pid 2335
Enter passphrase for /home/user/.ssh/private_key:
Identity added: /home/user/.ssh/private_key (/home/user/.ssh/private_key)

but when I try to run the rclone process now, I get the error message

yyyy/mm/dd hh:mm:ss Failed to create file system for "computer:directory": couldn't 
connect to ssh-agent: SSH agent requested but SSH_AUTH_SOCK not-specified

which is the same error message I get if I didn't run ssh-add at all. I tried several variants such as

eval `ssh-agent` && ssh-add
eval `ssh-agent` && sleep 3 && ssh-add`
eval `ssh-agent` && /path/to/scpw (where scpw waits 3 seconds to enter passphrase)

all of which also worked manually but didn't work in script. I'm pretty baffled.

Upvotes: 1

Views: 1622

Answers (2)

Philippe
Philippe

Reputation: 26850

You should not eval ssh-agent multiple times, that would create multiple instances of ssh-agent.

What you need is

nohup ssh-agent 2>/dev/null | grep -v echo > $HOME/.ssh/sh.pid
ssh-add

and then in your scripts which need ssh-agent, do :

source $HOME/.ssh/sh.pid

Upvotes: 1

VonC
VonC

Reputation: 1329672

Different issues (here or there) point out to the lack of the private key.

In your case, check if:

  • this would work better with a default name key (for testing) id_rsa
  • if the expect script spawns a subshell (in which the private key is added to the agent) but, on the next line, the rclone command would not benefit from that, because the agent is only populated by the scpw expect script in a subshell.

Upvotes: 1

Related Questions