Execute particular file from all user as sudo without password - python

my server having a python script file whose user and group is root and i want this file to be executed by all user as sudo without password.
for this i have added this is in /etc/sudoers
username ALL=(ALL) NOPASSWD: /path/to/file.py
but when execute from other user accept root still prompt for password
i execute file like this
sudo python /path/to/file.py
please help me

In sudoers, the command /path/to/file.py is specified, not python.
Execute the command as follow:
sudo /path/to/file.py
NOTE: Make sure the /path/to/file.py is an executable (have proper permission set, containing shebang line (#!/usr/bin/python ...))

Related

Unable to create 'path/to/repo/external/.git/index.lock': Permission denied

I am running a python command that generates some code and checks out some commits using git. However an exception is raised when it tries to create the file .git/index.lock. Root owns the directory so I can't create any file without sudo.
I have tried running the command with sudo (sudo ./run.py ). This also didn't work because then it can't find my ssh key. Can I get around this without changing the ownership of .git, and without creating a root ssh key? Both of these things I do not want. I have seen similar questions like these but none of those answers works here.
fatal: Unable to create '/path/.git/index.lock': Permission denied
Traceback (most recent call last):
File "./run.py", line 155 in <module>
...
...
File "/usr/lib/python3.6/subprocess.py", line 418 in run
output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['git', 'reset', '--hard', <hash>]' returned non-zero exist status 128.
You won't be able to perform any Git checkouts without permissions to write to the repository. However, if you want to use your SSH key, you can try running with sudo -E instead of plain sudo. That will ask sudo to preserve your home directory and any agent variables, which will let you use your SSH key.
Note that on some systems, the ability to preserve the environment is disabled or restricted, and consequently this won't work in those cases. In such an environment, you'd need to edit /etc/sudoers or use some other technique for credentials (such as a root-owned credential store and HTTPS).
Your have to clone git repository using http or https.
And execute below command:
git config —global credential.helper wincred
git fetch
First time it will ask for password and save it.
Next execution of git fetch it will not ask password.
Note: In case of password change you have to do same thing.

Sudo in Fabric2

I would like to reproduce the behavior of my old Fabric1 script running
sudo('useradd -m -u --groups mygroup myuser')
In that case the remote machine (an Ubuntu AWS instance) would prompt me for my sudo password and I was able to type it in. Even the repeated prompt after a wrong input would work. After that Fabric1 would hold on to that password by keeping the connection open.
In my new Fabric 2.x script I am using within a #task
c.sudo('useradd -m -u --groups mygroup myuser')
I am still getting a user prompt but it does not wait for my response, I am not able to type the password, and it fails as expected with
invoke.exceptions.AuthFailure: The password submitted to prompt '[sudo] password: ' was rejected
Using the --prompt-for-sudo-password argument has the same (or no effect).
I also tried
run('sudo useradd -m -u --groups mygroup myuser')
and received
sudo: no tty present and no askpass program specified
I would preferable not set the askpass program on a machine that worked perfectly without on Fabric 1.x (unless I could do that from my script which would require sudo, I guess).
I have been banging my head against the wall trying to use the complicated and not well documented configuration system but with no success.
What am I missing? If there is extra configuration required, I would like to know the syntax of the config file as well as where to place that file so that it get picked up by the fab CLI command.
It seems to matter that the arguments are passed in before the tasks, so make sure you're not just tacking args on the end of the command. For instance, this fails (doesn't prompt for password, then fails sudo authentication):
$ fab -H myhost mysudotask --prompt-for-sudo-password
[sudo] password: Sorry, try again.
[sudo] password: Traceback (most recent call last):
... <snip> ...
File "<string>", line 2, in raise_from
invoke.exceptions.AuthFailure: The password submitted to prompt '[sudo] password: ' was rejected.
While the following works as expected (prompting for password, then executing the sudo task):
$ fab -H myhost --prompt-for-sudo-password mysudotask
Desired 'sudo.password' config value:
[sudo] password: hi 1

Python Change Permission of Dir and all Subdirs

I'm trying to execute the following command in Python:
shutil.rmtree('/var/www')
but that gives me the following error:
PermissionError: [Errno 13] Permission denied: '/var/www'
I've tried executing this command before that command to change permissions on the directory
subprocess.call(['sudo', 'chmod', '-R', '777', '/var/www'])
Which I guess is working because it asks me for my sudo password and doesn't throw an error, however when I then reach the rmtree command it still throws a
Permission denied: '/var/www'
What am I doing wrong? Also I need this to work without asking for my sudo password during execution. Is there a way to put my password into the Python script?
Thanks
You need to check the group ownership of that directory, make sure that your username is added to this group which has write permissions to all files in the path:
chmod -R g+w /var/www/
As for the second pat of your question, sudo can read the password from the standard input using the -S flag which can be included in your script. Here's an example:
$ echo "password" | sudo -S <command>
A quick look at the man sudo page:
-S, --stdin
Write the prompt to the standard error and read the password from the
standard input instead of using the terminal device. The password must
be followed by a newline character.
Another way of doing that (which needs to be added to your script as well):
sudo -S <<< "password" command
Another approach is to disable password prompt by editing the sudoers file using the visudo command and add the following line:
username ALL=(ALL) NOPASSWD: ALL
The above line will allow username to run all commands (the last ALL) under any users without prompting for a password.
A secure and more restricted way of doing that is to use:
username ALL=(ALL) NOPASSWD: /usr/bin/python myscript.py
This time, we have limited the username for that type of execution but for a single command /usr/bin/python myscript.py.
I'd also prefer checking the permissions carefully and testing these commands directly from the shell before using it in your python script. It could save you a lot of time of troubleshooting.

how to login to user in python fabric

I am using Python Fabric. Here is my fabfile.
env.user='XXX'
env.password='XXX'
env.key_filename='/key/path'
env.hosts=[<ip>]
def install():
run('ifconfig')
run('su - hduser')
run('ls')
run('sudo mkdir -p /usr/lib/jvm')
When I run the above fabfile it login to my node and runs 'ifconfig' then i am login into the user hduser and i want to execute all my future command in /home/hduser. But it is executing the commands in root. How can i fix this ? Also if it is asking the password. How can i pass the password in script?
Thanks
Navaz
First Off, every run command is a separate connection to the computer. This means that after you run the
su - hduser
the next command will run as if that was never issued.
To run nested commands you need to use
with settings(user='hduser',password='Passw0rd1'):
run('ls')
will run the 'ls' command as the hduser and in the hduser home directory and with supply the password.
To run commands in a directory you can also use
with cd('/path/to/dir'):
run ('command in path')
http://docs.fabfile.org/en/latest/usage/env.html

Can I prevent fabric from prompting me for a sudo password?

I am using Fabric to run commands on a remote server. The user with which I connect on that server has some sudo privileges, and does not require a password to use these privileges. When SSH'ing into the server, I can run sudo blah and the command executes without prompting for a password. When I try to run the same command via Fabric's sudo function, I get prompted for a password. This is because Fabric builds a command in the following manner when using sudo:
sudo -S -p <sudo_prompt> /bin/bash -l -c "<command>"
Obviously, my user does not have permission to execute /bin/bash without a password.
I've worked around the problem by using run("sudo blah") instead of sudo("blah"), but I wondered if there is a better solution. Is there a workaround for this issue?
Try passing shell=False to sudo. That way /bin/bash won't be added to the sudo command. sudo('some_command', shell=False)
From line 503 of fabric/operations.py:
if (not env.use_shell) or (not shell):
real_command = "%s %s" % (sudo_prefix, _shell_escape(command))
the else block looks like this:
# V-- here's where /bin/bash is added
real_command = '%s %s "%s"' % (sudo_prefix, env.shell,
_shell_escape(cwd + command))
You can use:
from fabric.api import env
# [...]
env.password = 'yourpassword'
In your /etc/sudoers file add
user ALL=NOPASSWD: some_command
where user is your sudo user and some_command the command you want to run with fabric, then on the fabric script run sudo it with shell=False:
sudo('some_command', shell=False)
this works for me
In your /etc/sudoers file, you could add
user ALL=NOPASSWD: /bin/bash
...where user is your Fabric username.
Obviously, you can only do this if you have root access, as /etc/sudoers is only writable by root.
Also obviously, this isn't terribly secure, as being able to execute /bin/bash leaves you open to essentially anything, so if you don't have root access and have to ask a sysadmin to do this for you, they probably won't.
Linux noob here but I found this question while trying to install graphite-fabric onto an EC2 AMI. Fabric kept prompting for a root password.
The evntual trick was to pass in the ssh private key file to fabric.
fab -i key.pem graphite_install -H root#servername
You can also use passwords for multiple machines:
from fabric import env
env.hosts = ['user1#host1:port1', 'user2#host2.port2']
env.passwords = {'user1#host1:port1': 'password1', 'user2#host2.port2': 'password2'}
See this answer: https://stackoverflow.com/a/5568219/552671
I recently faced this same issue, and found Crossfit_and_Beer's answer confusing.
A supported way to achieve this is via using env.sudo_prefix, as documented by this github commit (from this PR)
My example of use:
env.sudo_prefix = 'sudo '

Categories