Created
March 4, 2015 19:06
-
-
Save dserodio/bc41a725030ad339d75f to your computer and use it in GitHub Desktop.
Fabric and ssh-agent, see https://www.leepa.io/2010/11/09/fabric-and-ssh-agent-aka-running-git-in-fabric
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def _shell_escape(string): | |
""" Escape double quotes, backticks and | |
dollar signs in given ``string``. | |
For example: | |
>>> _shell_escape('abc$') 'abc\\\\$' | |
>>> _shell_escape('"') '\\\\"' | |
""" | |
for char in ('"', '$', '`'): | |
string = string.replace(char, '\%s' % char) | |
return string | |
def sshagent_run(cmd, shell=True): | |
""" Helper function. Runs a command with SSH agent forwarding enabled. | |
Note:: Fabric (and paramiko) can't forward your SSH agent. This helper uses | |
your system's ssh to do so. """ | |
real_command = cmd | |
# We have to grab the env['cwd'] and then munge it blank | |
# otherwise the call to local() will not run as it'll try and | |
# do a local cd - that is not desired. | |
cwd = env.get('cwd', '') env['cwd'] = '' | |
if shell: | |
# Handle cwd munging via 'cd' context manager | |
cwd_cmd = '' | |
if cwd: | |
cwd_cmd = 'cd %s && ' % _shell_escape(cwd) | |
# Construct final real, full command | |
real_command = '%s \\"%s\\"' % (env.shell, _shell_escape(cwd_cmd + real_command)) | |
print("[%s] sshagent_run: %s" % (env.host_string, cmd)) | |
try: | |
print local('ssh -p %s -A %s@%s "%s"' % (env.port, env.user, env.host, real_command), capture=False) | |
except ValueError, v: | |
print v | |
finally: | |
# Put the cwd back if needed | |
env['cwd'] = cwd |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment