0

I want to kill a process on a remote server with another user, who creted the process via python with the subprocess.Popen command. But there is something I must be doing wrong because nothing happens when I run:

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

In terminal sudo kill -9 pid works fine.

Legorooj
  • 2,646
  • 2
  • 15
  • 35
Varlor
  • 1,421
  • 3
  • 22
  • 46

2 Answers2

1

Your answer works. A slightly more formal way of doing this would be something like

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()))

If I were writing this for a production system, I would add some exception handling, so treat this as a proof of concept.

Mad Wombat
  • 14,490
  • 14
  • 73
  • 109
0

Ok i got the answer thanks to the comment by 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) 
Varlor
  • 1,421
  • 3
  • 22
  • 46
  • Good to know that I helped! Btw you should select this as the correct answer, that way it'll show up as answered. – Legorooj Jun 27 '19 at 16:17