开发者

Piped commands in paramiko

How do I run piped commands in paramiko? I'm doing this:

statement = 'grep thing f开发者_JAVA技巧ile | grep thing2 | tail -1'
last_msg = conn.execute(statement)

and I get the output of grep thing file only.


Because grep doesn't know how to handle |. Get ready for some nasty escaping:

statement = """sh -c 'grep thing file | grep thing2 | tail -1'"""

This creates a shell on the other side, and asks it to interpret the string grep thing file | grep thing2 | tail -1. The single quotes are necessary since sh -c accepts only a single argument.

That way, a shell will create the pipe for you, running all the commands. And you better be sure that the filename file doesn't contain spaces. If it does, try "file".

As you can see, this quickly gets very ugly. I suggest you put the pipeline into a shell script. Then you can avoid the quotes and just run the script with sh -c script.sh.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜