使用 Python 自动更新 SSH 配置文件的首选方法?

发布于 2024-12-19 16:59:30 字数 1091 浏览 0 评论 0原文

我使用 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 视为字典并抽象出文件读/写,那就太好了。 。 。

感谢您的任何建议!

I'm using Fabric to automate some of my workflow, most of which involves manipulating EC2 instances.

I'm looking for a way to keep my .ssh/config file up-to-date, as I regularly spin up and shutdown EC2 instances, and it's very helpful to me if I can ssh into them easily for debugging and so on.

Entries within my SSH config file look like this

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

At the moment, I'm doing something like the following (making use of Fabric and boto), which is frankly a rubbish approach:

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)

As you can see, this will just keep prepending to my config file every time it's called, which is fine, because SSH takes the first section for each Host in config, but it means the file builds up and up. . .

I'm wondering if there are any Python libraries that allow one to treat .ssh/config as a more of a configuration file, whose relevant parts can be updated as and when. For example, it would be brilliant if you could simply treat .ssh/config as a dictionary and abstract away the file reading/writing. . .

Thanks for any suggestions!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

丢了幸福的猪 2024-12-26 16:59:30

我们对这种配置所做的就是维护一个配置片段的目录,可以根据需要添加/删除该目录,然后执行以下操作:

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

这将按词汇顺序附加内容,这意味着顺序取决于您的方式选择命名您的文件。这使得旧配置过期、删除特定项目以及以其他方式控制配置文件变得非常容易。

What we do for this sort of configuration is maintain a directory of configuration fragments, which can be added/removed as necessary, and then doing something along the lines of:

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

This will append things in lexical order, which means the ordering depends on how you elect to name your files. This makes it very easy to expire old configurations, remove specific items, and otherwise control the config file.

失眠症患者 2024-12-26 16:59:30

该线程已有很多年历史,但让我尝试一下,因为我遇到了同样的问题,并且该线程没有可接受的解决方案。

我最终在 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)

这两个文件是自动生成的使用来自云提供商的命令行工具 aws 和 gcloud 从 crontab 运行的 bash 脚本中获得。

此方法的优点是它不会触及您的 .ssh/config 文件,因为它可能包含您不希望弄乱的敏感条目。

This thread many years old but let me give a shot at this as I had the same problem and the thread has no accepted solution.

I ended up using the Include feature on ssh_config

     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.

So in my main ~/.ssh/config I have the default options and then at the TOP - because of these issues there is one line

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

These two files are generated automatically from a bash script running out of crontab using aws and gcloud, the command line tools from the cloud providers.

The advantage of this method is that it does not touch your .ssh/config file as it might contain sensitive entries that you do not want messed up.

红ご颜醉 2024-12-26 16:59:30

我有一个类似的问题,现在使用这个 Python 包来解决它。 https://github.com/emileindik/slosh

$ pip install slosh
$ slosh [email protected] --save-as myserver

这将执行所需的 ssh 连接并创建一个SSH 配置文件中的条目看起来像

Host=myserver
    HostName=1.1.1.1
    User=ubuntu

可以使用相同的别名来更新相同的条目。例如,将 .pem 文件添加到连接:

$ slosh -i ~/.ssh/mykey.pem [email protected] --save-as myserver

它当前支持许多 ssh 选项,但请告诉我是否应该添加其他选项!

[免责声明] 我创建了 slosh

I had a similar issue and am now using this Python package to solve it. https://github.com/emileindik/slosh

$ pip install slosh
$ slosh [email protected] --save-as myserver

This will perform the desired ssh connection and also create an entry in your SSH config file that looks like

Host=myserver
    HostName=1.1.1.1
    User=ubuntu

The same entry can be updated by using the same alias name. For example, adding a .pem file to the connection:

$ slosh -i ~/.ssh/mykey.pem [email protected] --save-as myserver

It currently supports a number of ssh options but let me know if there additional options that should be added!

[disclaimer] I created slosh

往事随风而去 2024-12-26 16:59:30

像这样的事情怎么样:

class SSHConfig(object):

    def __init__(self, filename=None):
        if filename is not None:
            self.read(filename)
        else:
            self.conf = dict()

    def read(self, filename):
        self.conf = dict(line.decode("utf-8").rstrip().split(" ", 1) for line in open(filename)) 

    def write(self, filename):
        with open(filename, "w") as f:
            for key, value in self.conf.items():
                f.write("%s %s\n".encode("utf-8") % (key, value))

    def set(self, key, value):
        self.conf[key] = value

    def get(self, key):
        return self.conf.get(key, None)

How about something like this:

class SSHConfig(object):

    def __init__(self, filename=None):
        if filename is not None:
            self.read(filename)
        else:
            self.conf = dict()

    def read(self, filename):
        self.conf = dict(line.decode("utf-8").rstrip().split(" ", 1) for line in open(filename)) 

    def write(self, filename):
        with open(filename, "w") as f:
            for key, value in self.conf.items():
                f.write("%s %s\n".encode("utf-8") % (key, value))

    def set(self, key, value):
        self.conf[key] = value

    def get(self, key):
        return self.conf.get(key, None)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文