将SSH命令转换为Python
我正在尝试把下面的ssh命令转换成Python代码。我已经把它转换成Python了,但这段Python代码没有任何输出,所以我觉得我没有正确转换,特别是布尔“与”逻辑部分。有没有人能告诉我哪里出错了?
ssh -p 29418 company.com gerrit query --current-patch-set --commit-message --files 'status:open project:platform/code branch:master label:Developer-Verified=1 AND label:Code-Review>=1'
Python代码:
with open(timedir + "/ids.txt", "wb") as file:
check_call("ssh -p 29418 company.com "
"gerrit query --commit-message --files --current-patch-set "
"status:open project:platform/code branch:master label:Developer-Verified=1 AND label:Code-Review>=1 |"
"grep refs |"
"cut -f4 -d'/'",
shell=True, # need shell due to the pipes
stdout=file) # redirect to a file
2 个回答
1
>=1
可能被理解为重定向到 =1
的文件,这就是为什么在 ids.txt 文件中没有输出的原因。
你在 check_call() 中使用的字符串没有给 gerrit 的参数加引号。可以和第一个命令比较一下,那个命令是给参数加了引号的。
你可以使用 pipes.quote()
来把一个字符串转义成一个完整的命令行参数,这样在命令行中使用时就不会出问题。
1
使用 Paramiko 来通过ssh连接
import paramiko
ssh = paramiko.SSHClient()
ssh.connect('127.0.0.1', username='xxx',
password='xxx')
然后你可以使用 subprocess
这个Python模块来执行系统命令。