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.

7
  • 1
    Do you get any error? How are you passing the sudo password? Commented Jun 26, 2019 at 14:02
  • try os.system('sudo kill -9 pid') Commented Jun 26, 2019 at 14:03
  • @heemayl No error, but you are right I have somehow pass the sudo password' But how? Commented Jun 26, 2019 at 14:07
  • @Legorooj Tried this one too, nothing happens, I think heemayl is right I need to pass the sudo password somehow Commented Jun 26, 2019 at 14:08
  • 1
    @Sav Varlor probably doesn't want passwordless sudo as a default on their machine. Commented Jun 26, 2019 at 14:12

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Definitely an improvement - much safer from a security point of view.
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) 

1 Comment

Good to know that I helped! Btw you should select this as the correct answer, that way it'll show up as answered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.