[英]Subprocess remote command execution in python
I am trying to execute remote command using subprocess: 我正在尝试使用子进程执行远程命令:
import subprocess
x=subprocess.Popen(['ssh','15.24.13.14', ' ps -ef | grep -i upgrade | wc -l'],stdout=subprocess.PIPE)
y=x.stdout.read()
print y
print '\n'
z=int(y)
print z
I need to get number of processes runing with 'upgrade' in their name. 我需要获取名称中带有“ upgrade”的进程。 But for some reason, script is not executed well.
但是由于某种原因,脚本执行得不好。 I get message: "Warning: Permanently added '15.24.13.14' (RSA) to the list of known hosts."
我收到消息:“警告:将'15 .24.13.14'(RSA)永久添加到已知主机列表中。” And then nothing happens.
然后什么也没有发生。 Where is the problem?
问题出在哪儿?
The problem is that if you are connecting for the first time via ssh to the given host, it asks you to add this host to the known hosts list and user has to confirm this by pressing 'y'. 问题是,如果您是第一次通过ssh连接到给定的主机,它将要求您将该主机添加到已知主机列表中,而用户必须通过按“ y”确认。 Since you didn't, than it hangs and does nothing.
既然没有,那么它将挂起并且什么也不做。
You should either: 您应该:
ssh -o "StrictHostKeyChecking no" user@host
ssh -o "StrictHostKeyChecking no" user@host
Because you didn't specify any stderr
to the subprocess.Popen
, the standard error will be directly print to your display. 因为您没有为
subprocess.Popen
指定任何stderr
,所以标准错误将直接打印到您的显示器上。 This is why you will always have the Warning: Permanently added '<hostname>' (ECDSA) to the list of known hosts.
这就是为什么您将始终显示
Warning: Permanently added '<hostname>' (ECDSA) to the list of known hosts.
message until you clearly redirect stderr
to a subprocess.PIPE
(or /dev/null) 消息,直到您将
stderr
明确重定向到subprocess.PIPE
(或/ dev / null)
Also, to avoid hosts file issues, here is a little trick (be careful with it, it's kind of dangerous) : 另外,为避免主机文件问题,这是一个小技巧(请谨慎操作,这很危险):
from subprocess import Popen, PIPE
p = Popen(['ssh', '-o', 'UserKnownHostsFile=/dev/null', '-o', 'StrictHostKeyChecking=no', hostname, 'ps aux | grep -i upgrade | wc -l'], stdout=PIPE, stderr=PIPE)
result = int(p.communicate()[0][:-1]) # don't forget there's the \n at the end.
Why is it dangerous ? 为什么会有危险? Because in case of MITM attack , you don't have any knowledge base of the remote, so you considere the attacker as your remote destination.
因为在发生MITM攻击的情况下,您没有远程的任何知识库,所以您将攻击者视为远程目标。 Be careful about over-using this feature.
注意过度使用此功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.