sshがリモートコマンドを正しくエスケープできないのは本当ですか?

sshがリモートコマンドを正しくエスケープできないのは本当ですか?

私はBashで次の簡単な例を紹介します。

echo a "b  c"  d

正しい出力は次のとおりです。

a b  c d

これは3つの引数配列で内部的に「エンコード」され、中間引数(bsumを含むc)は4文字の長さで、2つのスペースを含みます。これはset -xBashで有効になったときのデバッグ出力です(ダッシュではありません)。

echo a "b  c"  d
+ echo a 'b  c' d
a b  c d

sshコマンドはこれを完全に無視し、内部的に間違った文字列にリンクするようです。それ以外の場合は結果を解釈できません。

$ ssh user@remotehost -- echo a "b  c"  d
+ ssh user@remotehost -- echo a 'b  c' d
a b c d
$ ssh user@remotehost echo a "b  c"  d
+ ssh user@remotehost echo a 'b  c' d
a b c d
$ ssh user@remotehost 'echo a "b  c"  d'
+ ssh user@remotehost 'echo a "b  c"  d'
a b  c d

ご覧のとおり、最後の行が最もうまく機能しますが、次のように文字列がより複雑になると問題が発生します。

$ text="doesn't work"
+ text='doesn'\''t work'

$ echo "$text"
+ echo 'doesn'\''t work'
doesn't work

$ ssh user@remotehost echo "$text"
+ ssh user@remotehost echo 'doesn'\''t work'
bash: -c: line 0: unexpected EOF while looking for matching `''
bash: -c: line 1: syntax error: unexpected end of file

$ ssh user@remotehost "echo $text"
+ ssh user@remotehost 'echo doesn'\''t work'
bash: -c: line 0: unexpected EOF while looking for matching `''
bash: -c: line 1: syntax error: unexpected end of file

$ ssh user@remotehost "echo \'$text\'"
+ ssh user@remotehost 'echo \'\''doesn'\''t work\'\'''
'doesnt work\

$ ssh user@remotehost "echo '$text'"
+ ssh user@remotehost 'echo '\''doesn'\''t work'\'''
bash: -c: line 0: unexpected EOF while looking for matching `''
bash: -c: line 1: syntax error: unexpected end of file

問題は私がどこにいるのかということです。どのリモートコマンドを実行し、ベストプラクティスで変数を渡す方法("$variable"複数のパラメータ)、だからこそ内容を気にする必要はありません。、またはその内容は危険ですか?

問題の原因となる可能性があるのと同じ制限が適用されるように見え、sh -c他のコマンドはより良い操作を実行します(シェルを使用する代わりにバイナリを直接呼び出します)。

$ sudo -- echo a 'b  c' d
[sudo] password for user: 
a b  c d

$ nohup echo a 'b  c' d
nohup: ignoring input and appending output to 'nohup.out'
$ cat nohup.out
a b  c d

ベストアンサー1

おすすめ記事