Adilicious
Adilicious

Reputation: 1713

Executing sudo command with space through python

Hi guys and gal's I have a problem.

I'm executing a python script that needs to run a sudo command to continue. This is the command:

sudo /etc/init.d/test restart

The issue is that no matter how I execute this it only runs sudo and /etc/init.d/test and returns:

sudo: /etc/init.d/test: command not found

The issue seems to be that restart is not sent along with the command.

These are the ways I've tried running the command:

Attempt 1 using os

os.system('sudo /etc/init.d/test restart')

Attempt 2 using subprocess

x = subprocess.Popen(['sudo','/etc/init.d/test','restart'])
x.communicate()

Attempt 3 using subprocess again

x = subprocess.Popen(['sudo','/etc/init.d/test restart'])
x.communicate()

This actually returned:

sudo: /etc/init.d/test restart: command not found

Which doesn't make sense since if I execute the command directly on the system it works.
Any ideas as to how I could do this?

Upvotes: 1

Views: 7324

Answers (2)

Ian Rose
Ian Rose

Reputation: 677

If you get this:

sudo: /etc/init.d/test: command not found

it indicates that /etc/init.d/test doesn't exist. Try it yourself like this from the command line:

> sudo blarg whatever whatever
sudo: blarg: command not found

So just make sure that the command you are trying to execute really exists:

ls -l /etc/init.d/test

If you still have problems, then try to simplify things by first just getting it to execute 'sudo whoami' -- once you get that working, change it to your "real" command.

Upvotes: 0

Hal Canary
Hal Canary

Reputation: 2240

#!/usr/bin/env python
import subprocess,getpass
password = getpass.getpass()
#proc = subprocess.Popen(
#  ['sudo','-p','','-S','/etc/init.d/test','restart'],
#   stdin=subprocess.PIPE)
proc = subprocess.Popen(
    ['sudo','-p','','-S','echo','restart'],
    stdin=subprocess.PIPE)
proc.stdin.write(password+'\n')
proc.stdin.close()
proc.wait()

Upvotes: 3

Related Questions