Skip to content

Instantly share code, notes, and snippets.

@ntrrgc
Created May 11, 2014 16:07
Show Gist options
  • Save ntrrgc/e9e550dca2aa394ea300 to your computer and use it in GitHub Desktop.
Save ntrrgc/e9e550dca2aa394ea300 to your computer and use it in GitHub Desktop.
Run commands with ssh even if arguments contain spaces
import subprocess
import shlex
if hasattr(shlex, "quote"):
# Python 3
shquote = shlex.quote
else:
# Backport of shlex.quote for Python 2
import re
_find_unsafe = re.compile(r'[^\w@%+=:,./-]').search
def shquote(s):
"""Return a shell-escaped version of the string *s*."""
if not s:
return "''"
if _find_unsafe(s) is None:
return s
# use single quotes, and put single quotes into double quotes
# the string $'b is then quoted as '$'"'"'b'
return "'" + s.replace("'", "'\"'\"'") + "'"
def ssh(machine, args):
escaped_args = " ".join(shquote(a) for a in args)
return subprocess.call(["ssh", machine, escaped_args])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment