how to issue sudo command using python - 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?

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:
Turn off the password verification for the sudo user that is launching this python script. (read about /etc/sudoers)
pipe your password: (unsafe/bad solution but easy)
"echo YOURPASS | sudo ..."
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

Related

Using a Python library to interact with adb and change to su on a device which doesn't have sudo

I'm currently using pure-python-adb to automate a few tasks using Python. The device I'm using is a Busybox based UNIX system, which has limited number of commands. It doesn't have sudo. The task I'm trying to accomplish is change the permission, owner and group of a new file that I have just pushed into the device. The problem right now is that in order to change the permission of a file, I should be in su mode. And to be in su, I have to give the password. This is where I'm stuck at. I'm unable to give the password to su.
This is what I have so far:
from ppadb.client import Client as AdbClient
client = AdbClient(host="127.0.0.1", port=5037)
device = client.device("device-6000")
device.shell("<command>")
I can pass normal commands like ls -lh or cd <PATH>, but I can't change to su. When I do pass su, the console just hangs. So I tried to pass the password along with the command using one of the answers I found online, echo <PW> | su -s, but the error I"m getting is,
'su: must be run from a terminal\r\n'
Is there any way to automate this task using Python?

Getting "must be run from a terminal" when switching to root user using Paramiko module in Python

I am trying to automate a task through a Python script. The idea is to login as a regular user and then send a su command and switch to the root account.
The reason I can't directly login as root is that SSHD doesn't allow root logins.
Here's what I have:
ip='192.168.105.8'
port=22
username='xyz'
password='abc'
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip,port,username,password)
print ("SSH connection established")
stdin,stdout,stderr=ssh.exec_command('sudo fast.sh')
outlines=stdout.readlines()
outlines+=stderr.readlines()
resp=''.join(outlines)
print(resp)
Now, I want to send the su command and echo the root password. I am aware this is not good practice but I need a quick and easy way to test this so I am OK with that.
However, when I do this
stdin,stdout,stderr=ssh.exec_command('su') and provide the password, I get an error
su: must be run from a terminal
Can some one help me to solve this.
I am running Python script on my Windows laptop to ssh into a Linux device and then switch to the root user using the su command and echo the password so that I can run other commands as root.
Thanks.
First, as you know, automating su or sudo is not the correct solution.
The correct solution is to setup a dedicated private key with only privileges needed for your task. See also Allowing automatic command execution as root on Linux using SSH.
Anyway, your command fails because sudo is configured to require an interactive terminal with requiretty option in sudoers configuration file (as a way to deter its automation).
Paramiko (correctly) does not allocate a pseudo terminal for exec channel by default.
Either remove the requiretty option.
If you cannot remove it, you can force Paramiko to allocate pseudo terminal using get_pty parameter of exec_command method:
ssh.exec_command('sudo fast.sh', get_pty=True)
But that's not a good option, as it can bring you lot of nasty side effects. Pseudo terminal is intended for an interactive use, not for automating command execution. For some examples, see
Is there a simple way to get rid of junk values that come when you SSH using Python's Paramiko library and fetch output from CLI of a remote machine?
Remove of unwanted characters when I am using JSch to run command
Removing shell stuff (like prompts) from command output in JSch

Run script in Django [duplicate]

This question already has answers here:
How to fix 'sudo: no tty present and no askpass program specified' error?
(30 answers)
Closed 6 years ago.
I am trying to run a script in Django. This script needs to be run with sudo and I have setup the sudoers file so that the command can be executed without entering the sudo password. When I am using the default test server, ie >python manage.py runserver 0.0.0.0:8000, the script executes with no problem. However, after deploying Django with Nginx and uWSGI, the command fails and returns the response
sudo: no tty present and no askpass program specified
Is there some sort of configuration that I have missed?
I am using subprocess to execute the script and the code inside the Django view is like this:
subprocess.check_output( "sudo /path/to/file/fileName.sh", shell=True)
You need to add the user you are using to the sudoers list:
Granting the user to use that command without prompting for password should resolve the problem. First open a shell console and type:
sudo visudo
Then edit that file to add to the very end:
username ALL = NOPASSWD: /fullpath/to/command, /fullpath/to/othercommand
eg
john ALL = NOPASSWD: /sbin/poweroff, /sbin/start, /sbin/stop
will allow user 'john' to sudo poweroff, start and stop without being prompted for password.
Look at the bottom of the screen for the keystrokes you need to use in visudo - this is not vi by the way - and exit without saving at the first sign of any problem. Health warning: corrupting this file will have serious consequences, edit with care!
source: How to fix 'sudo: no tty present and no askpass program specified' error?

Fabric: Local command usage

I want execute a command which needs sudo in local machine. So as the documentation suggests, I used the local command, but its asking me to enter the password. How can I avoid this? Is there some place where I can save my local machine password?
local('sudo /etc/init.d/tomcat6 start',capture=True)
If you do not plan to share the fabfile you can use:
echo "password\n" | sudo -S /etc/init.d/tomcat6 start
according to the sudo man page:
The -S (stdin) option causes sudo to read the password from
the standard input instead of the terminal device. The
password must be followed by a newline character.
Check the visudo command, which will allow you to edit the /etc/sudoers file, in which you can define users, commands and password-requirements on a machine (e.g. user mlzboy does not need to enter password in order to execute /etc/init.d/tomcat6). Don't forget this can create a security problem.
Sudoers manual
If you want to use sudo but on the loopback ip:
from fabric.api import sudo,env
env.hosts =['127.0.0.1']
sudo('aptitude search fabric')
No need to edit sudoers, given you have an ssh server running locally.

Cannot write a script to "svn export" in Python

I would like to write a script that will tell another server to SVN export a SVN repository.
This is my python script:
import os
# svn export to crawlers
for s in ['work1.main','work2.main']:
cmd = 'ssh %s "cd /home/zes/ ; svn --force export svn+ssh://174.113.224.177/home/svn/dragon-repos"' % s
print cmd
os.system(cmd)
Very simple. It will ssh into work1.main, then cd to a correct directory. Then call SVN export command.
However, when I run this script...
$ python export_to_crawlers.py
ssh work1.main "cd /home/zes/ ; svn --force export svn+ssh://174.113.224.177/home/svn/dragon-repos"
Permission denied, please try again.
Permission denied, please try again.
Permission denied (publickey,gssapi-with-mic,password).
svn: Connection closed unexpectedly
ssh work2.main "cd /home/zes/ ; svn --force export svn+ssh://174.113.224.177/home/svn/dragon-repos"
Host key verification failed.
svn: Connection closed unexpectedly
Why do I get this error and cannot export the directory? I can manually type the commands in the command line and it will work. Why can't it work in the script?
If I change to this...it will not work. and instead, nothing will happen.
cmd = 'ssh %s "cd /home/zes/ ;"' % s
This is a problem with SSH.
Permission denied, please try again.
This means that ssh can't login. Either your ssh agent doesn't have the correct key loaded, you're running the script as a different user or the environment isn't passed on correctly. Check that the variables SSH_AUTH_SOCK and SSH_AGENT_PID are passed to the subprocess of your python script.
Host key verification failed.
This error means that the remote host isn't known to ssh. This means that the host key is not found in the file $HOME/.ssh/known_hosts. Again, make sure that you're checking the home directory of the effective user of the script.
[EDIT] When you run the script, then python will become the "input" of ssh: ssh is no longer connected to a console and will ask python for the password to login. Since python has no idea what ssh wants, it ignores the request. ssh tries three times and dies.
To solve it, run these commands before you run the Python script:
eval $(ssh-agent)
ssh-add path-to-your-private-key
Replace path-to-your-private-key with the path to your private key (the one which you use to login). ssh-add will ask for your password and the ssh-agent will save it in a secure place. It will also modify your environment. So when SSH runs the next time, it will notice that an ssh agent is running and ask it first. Since the ssh-agent knows the password, ssh will login without bothering Python.
To solve the second issue, run the second ssh command manually once. ssh will then add the second host to its files and won't ask again.
[EDIT2] See this howto for a detailed explanation how to login on a remote server via ssh with your private key.
I guess that it is related to ssh. Are you using a public key to automatically connect. I think that your shell knows this key but it is not the case of python.
I am not sure but it's just an idea. I hope it helps
Check out the pxssh module that is part of the pyexpect project:
https://pexpect.readthedocs.org/en/latest/api/pxssh.html
It simplifies dealing with automating ssh-ing into machines.

Categories

Resources