【发布时间】:2011-06-03 06:48:30
【问题描述】:
如何在 paramiko 中运行管道命令?我正在这样做:
statement = 'grep thing file | grep thing2 | tail -1'
last_msg = conn.execute(statement)
我只得到grep thing file 的输出。
【问题讨论】:
如何在 paramiko 中运行管道命令?我正在这样做:
statement = 'grep thing file | grep thing2 | tail -1'
last_msg = conn.execute(statement)
我只得到grep thing file 的输出。
【问题讨论】:
因为grep 不知道如何处理|。为一些讨厌的逃跑做好准备:
statement = """sh -c 'grep thing file | grep thing2 | tail -1'"""
这会在另一端创建一个 shell,并要求它解释字符串 grep thing file | grep thing2 | tail -1。单引号是必需的,因为 sh -c 只接受一个参数。
这样,shell 将为您创建管道,运行所有命令。您最好确保文件名file 不包含空格。如果是,请尝试"file"。
如您所见,这很快就会变得非常难看。我建议您将管道放入 shell 脚本中。然后您可以避免使用引号,只需使用 sh -c script.sh 运行脚本即可。
【讨论】:
statement = """... grep %s file | grep %s ...""" % ("thing", "thing2") 记得真的检查你的输入,因为你可以让它在另一端执行你想要的anything,如果你可以改变任何参数。
xxx file ; rm -rf . ; 的文件。请记住,在 unix 文件名中只有两个非法字符是 0 字节和 /。
pid 是一个我希望获得其内存消耗的进程,所以我希望编写命令:pmap <pid> | grep total | awk '{print$2}'。所以我在成功打开连接后运行以下命令(注意我使用的是 paramiko 的“不同”命令):command = """sh -c pmap %s | grep total | awk '{print$2}'""" % (str(pid)) 然后:stdout_, stderr_ = paramiko.SSHClient().exec_command(command) - 但没有运气。任何帮助都会很棒!谢谢!!
sh -c 需要一个“单词”作为参数。因此,在您的情况下,您将“pmap”传递给 sh 选项 -c 然后 sh 看到 %s 这不是一个有效的参数。对于您的情况,我建议您将管道放入 shell 脚本中。然后,您可以避免使用引号,只需使用 sh -c ./script.sh 运行脚本。