2017-07-30 46 views
0

我尝试从Python发送一些SSH命令。它工作得很好,但是一旦嵌套引号,我就会陷入混乱。ssh与Python:如何正确使用转义和引号

所以在很基本情况我只是做:现在

cmd = "ssh -A -t [email protected] \"do_on_host\"")) # notice the escaped quotes 
Popen(cmd, ..., shell=True) 

,在一个更复杂的情况,我想使用用户指定的命令。请注意,我逃过周围的用户命令和用户命令引号:

user_cmd = "prog -arg \"a string arg\"" 
cmd = "ssh -A -t [email protected] \"do_on_host; " + user_cmd + "\"")) # notice the escaped quotes 
Popen(cmd, ..., shell=True) 

它,当我尝试的SSH两个跳变得更糟。请注意,我想更多的东西有单,双引号来转义:

user_cmd = "prog -arg \"a string arg\"" 
cmd = "ssh -A -t [email protected] \"ssh -A -t [email protected] '" + user_cmd + "' \"" 
Popen(cmd, ..., shell=True) 

它可能变得更糟:该片段可能在脚本do_over_ssh.py其中user_cmd可能与​​从控制台读取使用,如:

$ ./do_over_ssh.py my_cmd -arg "a string arg" 

毕竟,我完全困惑。

在Python 3.5中处理嵌套引号的规范和干净的方法是什么?

(重要提示:其他的答案是Python 2.7版!)

+1

为什么不使用Fabric3来运行远程用户命令?多跳也工作,如在这里提到的https://stackoverflow.com/questions/20658874/how-to-do-multihop-ssh-with-fabric –

回答

0

我会使用一个文档字符串进行简化。尝试使用你的周围要发送哪三个报价:

'''Stuff goes here and "literally translates all of the contents automatically"''' 

对于行:

cmd = "ssh -A -t [email protected] \"ssh -A -t [email protected] '" + user_cmd + "' \"" 

这将是简单的使用格式:

cmd = '''ssh -A -t [email protected] "ssh -A [email protected] {}"'''.format(user_cmd) 
+0

在最后一行的''''之前的反斜杠,是一个错字或这是什么意思? – Michael

+0

哦,不,我误解你的字符串,它的固定在上面 –

0

可能是不规范的方式你期待,但如果我有这样的问题,我会尝试建立自己的报价引擎,沿线

import re 

def _quote(s): 
    return re.sub(r'[\"\'\\]', lambda match: "\\" + match.group(0), s) 

def wquote(s): 
    return '"{}"'.format(_quote(s)) 

def quote(s): 
    return "'{}'".format(_quote(s)) 

if __name__ == '__main__': 
    com = 'prog -arg {}'.format(wquote("a string arg")) 
    print(com) 
    com = "ssh -A -t [email protected] {}".format(wquote(com)) 
    print(com) 
    com = "ssh -A -t [email protected] {}".format(wquote(com)) 
    print(com) 

""" --> my output 

prog -arg "a string arg" 
ssh -A -t [email protected] "prog -arg \"a string arg\"" 
ssh -A -t [email protected] "ssh -A -t [email protected] \"prog -arg \\\"a string arg\\\"\"" 
"""