具有预先存在的连接的非交互式 SSH GPG 代理转发

Non-interactive SSH GPG Agent forwarding with pre-existing connection

我这里遇到了一些先有鸡还是先有蛋的问题。

问题

我想通过 SSH 连接到远程机器并转发我的本地 gpg-agent。问题是远程机器上的 gpg-agent 只有在建立 SSH 连接后才会启动。虽然 gpg-agent 在远程机器上没有 运行ning,但在指定转发时我无法通过 SSH 连接到远程机器。

鉴于此,此命令不起作用,因为远程 gpg-agent 不是 运行ning,因此 /run/user/1000/gnupg/S.gpg-agent还不存在。

ssh -R /run/user/1000/gnupg/S.gpg-agent:/run/user/1000/gnupg/S.gpg-agent user@remotemachine

解决方法

另一种方法是交互式/手动,如下所示。

ssh user@remotemachine

我现在通过 SSH 连接,作为副作用,gpg-agent 也自动启动了。

当我现在更新现有的 SSH 连接时,通过打开 SSH PTY:

[enter]
~C
ssh> -R /run/user/1000/gnupg/S.gpg-agent:/run/user/1000/gnupg/S.gpg-agent
Forwarding port.
[enter]

我现在可以 运行 通过使用本地 gpg-agent 在远程机器上执行我的 GPG 命令。

目标

我希望将上述解决方法自动化。基本上我想使用 ssh user@remotemachine 通过 SSH 连接到远程机器,然后远程机器会自动将 SSH 转发添加到现有的 SSH 连接。

问题

如何让远程机器自动更新新建立的SSH连接并添加gpg-agent转发?

由于您使用了 expect 标签,这里有一个简单的 expect 脚本应该足够了。

#!/usr/bin/expect -f
spawn ssh user@remotemachine
expect {$ }
send "date\r"
expect {$ }
send "~C"
expect "ssh> "
send -- "-R /run/user/1000/gnupg/S.gpg-agent:/run/user/1000/gnupg/S.gpg-agent\r"
expect -timeout 5  timeout exit   "\r\n"
send "echo ok\r"
expect "\nok\r"
expect {$ }
interact

将其放入文件中并对其执行 chmod +x。出于某种原因,我发现我没有从 -R 命令中收到 Forwarding port 消息,除非我启用 ssh -v,所以我只检查 \r\n,但你可以更改这个。另外,我假设来自远程的 shell 提示是 $,所以您可能也需要更改它,但是如果您的提示是 [enter] 那么您需要说

expect -ex {[enter]}

避免字符串被解释为正则表达式。