2017-07-30 44 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\\\"\"" 
"""