使用Fabric时,连接到〜/ .ssh / config中列出的主机

Fabric遇到麻烦,无法识别~/.ssh/config主机。

我的fabfile.py如下所示:

 from fabric.api import run, env env.hosts = ['lulu'] def whoami(): run('whoami') 

运行$ fab whoami给出:

[lulu]跑步:whoami

致命错误:lulu名称查找失败

lulu的名字在我的~/.ssh/config ,就像这样:

 Host lulu hostname 192.168.100.100 port 2100 IdentityFile ~/.ssh/lulu-key 

我首先想到解决这个问题是添加类似lulu.lulu/etc/hosts (我在Mac上),但是我还必须将身份文件传递到Fabric – 我宁愿保留我的身份validation(即~/.ssh/config )与我的部署分开(即fabfile.py )。

顺便说一句,如果你尝试连接到主机文件中的主机, fabric.contrib.projects.rsync_project似乎没有确认fabric.contrib.projects.rsync_project中的“端口”(即如果你使用hosts.env = [lulu:2100]调用rsync_project似乎尝试连接到lulu:21 )。

Fabric有没有理由不承认这个lulu名字?

从版本1.4.0开始, Fabric使用你的sshconfiguration (部分)。 但是,您需要明确地启用它

 env.use_ssh_config = True 

在你的fabfile的顶部附近。 一旦你这样做了,Fabric应该读取你的sshconfiguration文件(默认是~/.ssh/config ,或者是env.ssh_config_path )。

一个警告:如果您使用的版本早于1.5.4,那么如果env.use_ssh_config被设置,但是没有configuration文件存在,则会发生中止。 在这种情况下,您可以使用以下解决方法:

 if env.ssh_config_path and os.path.isfile(os.path.expanduser(env.ssh_config_path)): env.use_ssh_config = True 

请注意,当名称不在/etc/hosts时也会发生这种情况。 我有同样的问题,不得不将主机名添加到该文件和~/.ssh/config

更新 :这个答案现在已经过时了 。


Fabric目前不支持.ssh / config文件。 你可以在函数中设置这些函数,然后调用cli,例如:fab生产任务; 生产设置用户名,主机名,端口和ssh标识。

至于rsync项目,现在应该有端口设置的能力,如果没有,你总是可以运行local(“rsync …”),因为这基本上是贡献function。

可以使用下面的代码来读取configuration(原始代码取自: http : //markpasc.typepad.com/blog/2010/04/loading-ssh-config-settings-for-fabric.html ):

 from fabric.api import * env.hosts = ['servername'] def _annotate_hosts_with_ssh_config_info(): from os.path import expanduser from paramiko.config import SSHConfig def hostinfo(host, config): hive = config.lookup(host) if 'hostname' in hive: host = hive['hostname'] if 'user' in hive: host = '%s@%s' % (hive['user'], host) if 'port' in hive: host = '%s:%s' % (host, hive['port']) return host try: config_file = file(expanduser('~/.ssh/config')) except IOError: pass else: config = SSHConfig() config.parse(config_file) keys = [config.lookup(host).get('identityfile', None) for host in env.hosts] env.key_filename = [expanduser(key) for key in keys if key is not None] env.hosts = [hostinfo(host, config) for host in env.hosts] for role, rolehosts in env.roledefs.items(): env.roledefs[role] = [hostinfo(host, config) for host in rolehosts] _annotate_hosts_with_ssh_config_info()