Reputation: 1471
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.
Upvotes: 0
Views: 532
Reputation: 15125
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.
Upvotes: 1
Reputation: 1471
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)
Upvotes: 0