2017-07-30 13 views
0

私はPythonからいくつかのSSHコマンドを送信しようとしています。それはかなりうまくいくが、引用符が入れ子になるとすぐに混乱する。ssh with Python:エスケープと引用符で正しく取得する方法

だから私はちょうど行う非常に基本的な状況に:今

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

、より複雑な状況で、私は、ユーザーが指定したコマンドを使用したいと思います。私は、ユーザコマンドを中心に、ユーザーコマンドで引用符をエスケープしていることに注意してください:私は2つのホップ上でsshをしようとすると、それも悪くなる

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) 

。私はエスケープに追加の単一引用符と二重引用符で何かをしようとしたことに注意してください:

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

それがさらに悪化得ることができる:スニペットは次のように、user_cmdは、コンソールから​​で読まれるかもしれないスクリプトdo_over_ssh.pyで使用される可能性があります:

$ ./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"''' 

を:あなたが送信しているものを中心に3重引用符を使用してみてください

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\\\"\"" 
""" 
関連する問題