Created
May 11, 2014 16:07
-
-
Save ntrrgc/e9e550dca2aa394ea300 to your computer and use it in GitHub Desktop.
Run commands with ssh even if arguments contain spaces
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
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