如何将命令作为参数传递给 ssh

How to pass commands as arguments to ssh

我需要让这个命令起作用:

sshpass -p XXXX ssh -oStrictHostKeyChecking=no wsuser@192.168.0.100 sudo docker exec -u postgres postgres-container /bin/bash -c \" psql -d crawl-configuration -c 'select * from schema_version'\"

但结果表明 * 被 shell 扩展并且所有匹配的文件都作为参数传递给 psql 命令。所以我搜索了如何保护命令不被扩展,但没有成功。

我的实验给出了以下结果。

A - 以下命令有效,TOTO 显示在我的 shell

sshpass -p XXXX ssh -oStrictHostKeyChecking=no wsuser@192.168.0.100 sudo docker exec -u postgres postgres-container /bin/bash -c \"echo TOTO\"

B - 以下命令不起作用,我的 shell

上显示了一个空行
sshpass -p XXXX ssh -oStrictHostKeyChecking=no wsuser@192.168.0.100 sudo docker exec -u postgres postgres-container /bin/bash -c "echo TOTO"

C - 这行得通,显示了 ls 的结果。我不明白为什么它有效但情况 B 无效?

sshpass -p XXXX ssh -oStrictHostKeyChecking=no wsuser@192.168.0.100 sudo docker exec -u postgres postgres-container /bin/bash -c "ls"

D - 这行得通,我得到了预期的结果

sshpass -p XXXX ssh -oStrictHostKeyChecking=no wsuser@192.168.0.100 sudo docker exec -u postgres postgres-container /bin/bash -c \" psql -d crawl-configuration -c \'select version from schema_version\' \"

E - 在不通过 ssh 的情况下在主机上执行此命令有效

sudo docker exec -u postgres postgres-container /bin/bash -c " psql -d crawl-configuration -c 'select * from schema_version'"

让我的第一个命令起作用的解决方案是什么?

我会这样说:

sshpass -p XXXX ssh -oStrictHostKeyChecking=no wsuser@192.168.0.100 \
  "sudo docker exec -u postgres postgres-container \
  /bin/bash -c \"psql -d crawl-configuration -c 'select * from schema_version'\""

双引号将由 ssh 执行的整个命令,然后在命令内转义双引号。

或者,使用此处文档:

sshpass -p XXXX ssh -T -oStrictHostKeyChecking=no wsuser@192.168.0.100 <<-'EOF'
    sudo docker exec -u postgres postgres-container \
    /bin/bash -c "psql -d crawl-configuration -c 'select * from schema_version'"
EOF

由于引用了 'EOF' 分隔符,因此无需引用。 -T 禁用伪终端的分配。