Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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\\"' % (, _shell_escape(cwd_cmd + real_command))
print("[%s] sshagent_run: %s" % (env.host_string, cmd))
print local('ssh -p %s -A %s@%s "%s"' % (env.port, env.user,, real_command), capture=False)
except ValueError, v:
print v
# 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
You can’t perform that action at this time.