如何将命令作为ssh的参数传递 [英] How to pass commands as arguments to ssh
问题描述
我需要使此命令起作用:
My need is to make this command work:
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命令.因此,我研究了如何保护命令以免被扩展,但没有成功.
But the result indicates that * is expanded by the shell and all matching files are passed as arguments to the psql command. So I searched how to protect the command from being expanded, but without success.
我的实验给了我以下结果.
My experimentations gave me the following results.
A-以下命令有效,TOTO显示在我的外壳上
A - The following command works, TOTO is displayed on my 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-以下命令不起作用,我的外壳上显示空白行
B - The following command doesn't work, a blank line is displayed on my 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不行?
C - This works, the result of ls is displayed. I don't understand why it works but not case B ?
sshpass -p XXXX ssh -oStrictHostKeyChecking=no wsuser@192.168.0.100 sudo docker exec -u postgres postgres-container /bin/bash -c "ls"
D-这行得通,我有预期的结果
D - This works, I have the expected result
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传递
E - Execution of this command on the host without passing by ssh works
sudo docker exec -u postgres postgres-container /bin/bash -c " psql -d crawl-configuration -c 'select * from schema_version'"
使我的第一个命令起作用的解决方案是什么?
What is the solution to make my first command work ?
推荐答案
我会这样说:
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要执行的整个命令用双引号引起来,然后在命令中用双引号转义.
Double quote the whole command to be executed by ssh, then escape double quotes within the command.
或者,使用here-doc:
Alternatively, use a here-doc:
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
禁止分配伪终端.
No quoting needed because of the quoted 'EOF'
delimiter. The -T
disables allocation of a pseudo-terminal.
这篇关于如何将命令作为ssh的参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!