Peter Chao
Peter Chao

Reputation: 443

how to issue sudo command using python

I need to issue "sudo service nginx status" to check for service status. I have the following:

import commands
service output = commands.getoutput("sudo service nginx status")

but I am getting "no tty present and no askpass program specified"

Does someone understand this?

Upvotes: 0

Views: 1987

Answers (1)

woockashek
woockashek

Reputation: 1638

using commands.getoutput makes impossible to provide the user input that is required by sudo command. The name is self explainable, you are interested only in the command output. stdin is closed.

There are several solutions for this:

  1. Turn off the password verification for the sudo user that is launching this python script. (read about /etc/sudoers)

  2. pipe your password: (unsafe/bad solution but easy) "echo YOURPASS | sudo ..."

  3. check out subprocess.popen allowing you to provide input either from console or from file https://docs.python.org/2/library/subprocess.html#popen-constructor

Upvotes: 1

Related Questions