【问题标题】:How to write a subprocess.Popen terminal execution如何写一个subprocess.Popen终端执行
【发布时间】:2019-11-08 12:12:49
【问题描述】:

我想与另一个用户一起杀死远程服务器上的一个进程,该用户通过 python 使用subprocess.Popen 命令创建了该进程。但是我一定做错了,因为我跑步时什么都没有发生:

subprocess.Popen(['sudo','kill','-9',str(pid)], stdout=subprocess.PIPE)

在终端 sudo kill -9 pid 工作正常。

【问题讨论】:

  • 你有什么错误吗?你是如何传递sudo 密码的?
  • 试试os.system('sudo kill -9 pid')
  • @heemayl 没有错误,但你是对的,我以某种方式通过了 sudo 密码'但是如何?
  • @Legorooj 也试过这个,没有任何反应,我认为 heemayl 是对的我需要以某种方式传递 sudo 密码
  • @Sav Varlor 可能不希望无密码 sudo 作为他们机器上的默认设置。

标签: python subprocess popen terminate


【解决方案1】:

您的答案有效。更正式的方式是这样的

from subprocess import Popen, PIPE


def kill(pid, passwd):
    pipe = Popen(['sudo', '-S', 'kill', '-9', str(pid)], 
                 stdout=PIPE, 
                 stdin=PIPE, 
                 stderr=PIPE)
    pipe.stdin.write(bytes(passwd + '\n', encoding='utf-8'))
    pipe.stdin.flush()
    # at this point, the process is killed, return output and errors
    return (str(pipe.stdout.read()), str(pipe.stderr.read()))

如果我是为生产系统编写此代码,我会添加一些异常处理,因此将其视为概念验证。

【讨论】:

  • 绝对是一种改进——从安全角度来看更安全。
【解决方案2】:

好的,感谢 Legorooj 的评论,我得到了答案。

from subprocess import call
import os
command = 'kill -9 '+str(pid)
#p = os.system('echo {}|sudo -S {}'.format(password, command))
call('echo {} | sudo -S {}'.format(password, command), shell=True) 

【讨论】:

  • 很高兴知道我提供了帮助!顺便说一句,您应该选择这个作为正确答案,这样它就会显示为已回答。
猜你喜欢
  • 2019-08-06
  • 1970-01-01
  • 1970-01-01
  • 2011-03-28
  • 1970-01-01
  • 2020-01-05
  • 2012-01-30
  • 2012-05-09
  • 1970-01-01
相关资源
最近更新 更多