使用Python自动更新SSH配置文件的最佳方法是什么?

10 投票
4 回答
4469 浏览
提问于 2025-04-17 07:49

我正在使用Fabric来自动化我的一些工作流程,大部分内容涉及到操作EC2实例。

我想找到一种方法来保持我的.ssh/config文件是最新的,因为我经常启动和关闭EC2实例,如果我能轻松地通过SSH连接到它们进行调试,那对我来说非常有帮助。

我的SSH配置文件中的条目看起来像这样:

Host ins_id
Hostname xxxxxxxx.com
User ubuntu
IdentityFile ~/.ssh/kp.pem

目前,我正在做类似下面的事情(使用Fabricboto),说实话,这种方法并不好:

def my_cool_spin_up_function(self):
    . . .
    . . .
    ssh_conf = os.path.join(homedir, '.ssh/config')
    ssh_info = '\n'.join(['Host %s'         % name,
                          'Hostname %s'     % ins.dns_name,
                          'User %s'         % env.user,
                          'IdentityFile %s' % kp_loc,
                          '\n'])
    w_com = 'echo %s | cat - %s | tee %s > /dev/null' % (ssh_info, ssh_conf, ssh_conf)
    local(w_com)

如你所见,每次调用时,这个方法都会不断地在我的配置文件前面添加内容,这样是可以的,因为SSH会取配置中每个主机的第一部分,但这意味着文件会越来越大……

我在想有没有什么Python库可以让人把.ssh/config当作一个更像配置文件的东西,这样相关的部分可以随时更新。例如,如果你能把.ssh/config当作一个字典来处理,并且把文件的读取和写入过程抽象掉,那就太好了……

谢谢任何建议!

4 个回答

1

我之前也遇到过类似的问题,现在我用这个Python包来解决它。你可以在这里找到它:https://github.com/emileindik/slosh

$ pip install slosh
$ slosh ubuntu@1.1.1.1 --save-as myserver

这个工具可以帮你建立想要的ssh连接,同时还会在你的SSH配置文件里添加一条类似这样的记录:

Host=myserver
    HostName=1.1.1.1
    User=ubuntu

你可以通过使用相同的别名来更新这条记录。例如,给连接添加一个.pem文件:

$ slosh -i ~/.ssh/mykey.pem ubuntu@1.1.1.1 --save-as myserver

目前它支持一些ssh选项,如果你觉得还有其他需要添加的选项,记得告诉我哦!

[免责声明] 我是slosh的创建者

2

这个讨论已经很多年了,但让我来试试,因为我也遇到过同样的问题,而且这个讨论没有被接受的解决方案。

我最后使用了 ssh_config 中的 Include 功能。

     Include
             Include the specified configuration file(s).  Multiple pathnames may be specified and each pathname may contain glob(7) wildcards and, for user configurations, shell-like
             ‘~’ references to user home directories.  Files without absolute paths are assumed to be in ~/.ssh if included in a user configuration file or /etc/ssh if included from the
             system configuration file.  Include directive may appear inside a Match or Host block to perform conditional inclusion.

所以在我的主 ~/.ssh/config 文件里,我有默认的选项,然后在最上面 - 因为有一些 问题,我加了一行。

Include ~/.ssh/config.d/*
...
(rest of the file)

这两个文件是通过一个在定时任务中运行的 bash 脚本自动生成的,使用的是 awsgcloud,这两个是云服务提供商的命令行工具。

这种方法的好处是,它不会修改你的 .ssh/config 文件,因为里面可能有一些敏感信息,你不想被搞乱。

10

对于这种配置,我们会保持一个配置片段的目录,可以根据需要添加或删除这些片段,然后我们会做类似下面的事情:

cat .ssh/config.d/* > .ssh/config

这样做会按照字母顺序来添加内容,这意味着顺序取决于你给文件起的名字。这种方式让我们很容易过期旧的配置,删除特定的项目,以及更好地控制配置文件。

撰写回答