Use sudo without password INSIDE a script - linux

For some reason I need, as user, to run without sudo a script script.sh which needs root privileges to work.
I saw as the only solution to put sudo INSIDE script.sh. Let's take an example :
script.sh :
#!/bin/sh
sudo apt-get update
Of course, if I execute this script, I get a prompt asking me for a password. Then I added to my sudoers file (at the end to override everything else) :
user ALL=(ALL:ALL) NOPASSWD:/path/to/script.sh
By the way, I also tried the line :
user ALL=(ALL) NOPASSWD:/path/to/script.sh
(I think I didn't fully understand the difference)
But this doesn't solve my problem if I don't use sudo to execute this script :
# ./script.sh
[sudo] password for user:
# sudo ./script.sh
Starts updating...
Well, so I say to myself "Ok, that means that if I have a file refered in sudoers as I did, it will work without prompt only if I call him with sudo, what is not what I want".
So, ok, I create another script script2.sh as following :
script2.sh
#!/bin/sh
sudo /path/to/script.sh
In fact it works. But I am not truly satisfied of this solution, particularly by the fact that I have to use 2 scripts for every command.
This post is then for helping people having this problem and searching for the same solution (I didn't find a good post on it), and perhaps have better solutions coming from you guys.
Feel free to share your ideas !
EDIT 1 :
I want to insist on the fact that this "apt-get update" was just an example FAR from whhat my script actually is. My script has a lot of commands (with some cd to root-access-only config files), and the solution can't be "Well, just do it directly with apt-get".
The principle of an example is to help the understanding, not to be excuse to simplify the answer of the general problem.

From my blog: IDMRockstar.com:
The kicker is that sometimes, I need to run commands as root. Here's the quick and dirty way I accomplish that without divulging the passwords:
#! /bin/bash
read -s -p "Enter Password for sudo: " sudoPW
echo $sudoPW | sudo -S yum update
This way the user is prompted for the password (and hidden from terminal) and then passed into commands as needed, so I'm not running the entire script as root =)
If you have a better, way, I'd love to hear it! I'm not a shell scripting expert by any means.
Cheers!
.: Adam

If you want to run sudo /usr/bin/apt-get update without a password, you need to have the sudoers entry:
user ALL=(ALL:ALL) NOPASSWD:/usr/bin/apt-get update
For the larger issue of the script as a whole, there are two possible approaches:
Approach 1
For each command in the script that needs sudo, create a line in sudoers specifically for that command. In this case, the script can be called normally:
./script1.sh
Approach 2
Place a line in sudoers for the script as a whole. When this is done, the individual commands do not need sudo. However, sudo must be used to start the script as in:
sudo ./script.sh

If your password isn't something you want to be very secure about, (maybe some testing server in the company etc.) you can elevate to sudo in the script via echo like:
echo YourPasswordHere | sudo -S Command
The prompt still prints the "enter password" text to output though. So don't expect it to be neat.
See this Askubuntu post

As you noted, the file that must appear in the sudoers configuration is the one that is launched by sudo, and not the one that runs sudo.
That being said, what we often do, is having something like
user ALL=(ALL:ALL) NOPASSWD:/path/to/script.sh
in the sudo configuration, where script.sh has all the commands that the script has to do.
Then we define either a Bash function or an alias so that script.sh is actually
sudo /path/to/script.sh
The only issue is if some commands must not be run as root, you need to insert some su - user -c "command" commands in the script.

In new /etc/sudoers.d/apt-get file, put single line:
user ALL=(ALL:ALL) NOPASSWD:/usr/bin/apt-get update
Fully qualified path to executable is required here.
Then use following in your script:
sudo apt-get update
Here, fully specified name is not required. Sudo uses PATH environment variable for executable resolution.
While changing and checking sudoers configuration, be sure to keep another root session open for error recovery.

I suggest you look at the sudo environment variables - specifically you can use (and check for) $SUDO_USER. Call your script with sudo (1 entry in sudoers), then do user stuff as SUDO_USER and root stuff as root.

As mentioned by Basilevs you need to add your user to the sudoers file in order to avoid that sudo commands in the script get stuck awaiting the password.
On Ubuntu 16, there is a simpler way: just add the user to the sudo group, like this:
sudo usermod -aG sudo *username*
From then on, it should work like a charm.
Note:
This works only on the condition that the following line is in file /etc/sudoers:
%sudo ALL=NOPASSWD: ALL
(such line gives passwordless sudo privileges at group level, in this case to the sudo group)
(if this line is not present and you want to add it, make sure you use visudo)

Simply, in order to execute commands as root you must use su (even sudo uses su)
As long as you execute sudo ./script2.sh successfully just instead :
sudo su
"#" //commands as root here
"#" exit
//commands as use here
you can make it a shell function with the name sudo, but no other better way i think,however it's the case with scripts inti,rc android ..etc
must be tidy ;)
however this requires you to put NOPASSWD: su wich is totaly secure indeed
any way here just lacks POISX permissions principle which is filtering so dont enable something to all users or vice versa
simply, call sudo as much as you want with no additional thing then:
chown root script.sh
chmod 0755 script.sh
chgrp sudo script.sh
"make root owner of .sh"
"make it read only and exec for others"
"and put it in sudo group"
of course under sudo
that's it

Related

Add sudo permission to a group of users for specific shell file

I have been looking for an answer for a while now, but I cannot find it.
I have a shell script located at: /home/myuser/shell.sh, which requires sudo to be run. I want all my users from mygroup to be able to run it without password.
So I executed: visudo, and added this line at the end of the file:
%mygroup ALL=(ALL) NOPASSWD: /home/myuser/shell.sh
The problem is that it is not working. When I try to execute sh /home/myuser/shell.sh as one of the users of mygroup, it asks me for the sudo password.
Can you help me?
Thanks a lot!
Run it with sudo
visudo affects sudo behaviour, so you have to use it.
But don't use sh /.../shell.sh, make the script executable first
chmod +x /home/myuser/shell.sh
then you'll be able to do
sudo /home/myuser/shell.sh
without the password. Then remove all sudo calls in the script.
Make sure the users are in the group to allow sudo.

How to execute 'iftop' without sudo

I have a script that runs iftop in text mode, cuts down the output to what I'm concerned in, and saves it to a text file along with the output of the date command (I am monitoring network usage on various interfaces over time). Only problem I'm having is I'm trying to run my script every 15 minutes via the crontab, and in order to run the iftop command I need sudo permissions. Does anyone know some way to change the permissions of iftop to make it so I don't need sudo permissions?
Alternatively if I can give the script the ability to run the command with sudo that would be fine by me as well. I tried adding the script to the sudoers file via sudo visudo and adding the line:
user ALL=(ALL) NOPASSWD: /home/user/network_usage.sh
but that didn't work...perhaps a result of executing from the crontab?
Thanks,
-Eric
A more granular approach would be to use:
# setcap cap_net_raw=eip $(which iftop)
This lets iftop capture packets but does not give the process full root privileges. In case of a security problem or bug with "iftop" its side effects would be much more limited.
Related: https://unix.stackexchange.com/questions/189750/how-can-i-run-script-without-root-to-sniff-network-libpcap
If you have root access on the machine the quick and dirty way:
chmod +s $(which iftop)
This will make it run w/ root privileges no matter who invokes it.
But I still think your sudo like should work.
You may use root's crontab to run the script.
If instead of crontab -e you use sudo crontab -e you will edit root's crontab. Tasks specified in that file will run under root's account and privileges.
Alternatively, you can set the setuid access flag for your script file. To do so first change the owner of the file to root, then enable setuid like this:
sudo chown root /home/user/network_usage.sh
sudo chmod +s-w /home/user/network_usage.sh
The setuid bit makes an executable file run with the effective UID of its owner.
Regardless of what approach you take, be very careful.
Make your script owned by root and don't let any other user write to it, otherwise it could ease a privilege escalation.
Be aware of the side effects of your setuid programs. If the script has setuid and may create or modify files, it might be used by someone else to modify or create files they aren't supposed to. Always check the manual before giving setuid to any program you haven't written.

How to supply sudo with password from script?

Please note: this is a guest VM (VBox) running on my local machine, and I'm not worried about security.
I am writing a script that will be executed on a Linux (Ubuntu) VM as the myuser user. This script will create a very large directory tree under /etc/myapp. Currently I have to do all this manually, and it starts with me giving myuser recrusive rwx permissions under /etc like so:
sudo chmod -R 777 /etc
[sudo] password for myuser: <now I enter the password and hit ENTER>
My question: how do I write a bash script that supplies the sudo command with my password so that I can just execute bash myscript.sh and it will make the necessary permission changes for me?
(BASH)
OK, if you've gotta do it, (keeping security warnings in mind):
$ sudo -S < <(echo "<your password>") <your sudo command>
If, as you say, you completely don't care about security...
Run visudo to edit /etc/sudoers with validation in place. Add the following line:
ALL ALL=(ALL) NOPASSWD: ALL
This will prevent sudo from ever asking for a password, for any user, for any command.
You can use expect or autoexpect. It's a bad idea, though.
Never put system passwords into writing. At least, not on a file on said system. Much less on an install script known to require root access. You're making yourself an easy target.
What you do instead, is configure sudo via /etc/sudoers/ to allow exactly that user to execute exactly that script without a password:
myuser ALL=(ALL) NOPASSWD : /path/to/script
Note:
If you remove the /path/to/script part, myuser will be able to sudo anything with no password.
If you change myuser for ALL, everyone will be able to run that script with no password.

How to fix 'sudo: no tty present and no askpass program specified' error?

I am trying to compile some sources using a makefile. In the makefile there is a bunch of commands that need to be ran as sudo.
When I compile the sources from a terminal all goes fine and the make is paused the first time a sudo command is ran waiting for password. Once I type in the password, make resumes and completes.
But I would like to be able to compile the sources in NetBeans. So, I started a project and showed netbeans where to find the sources, but when I compile the project it gives the error:
sudo: no tty present and no askpass program specified
The first time it hits a sudo command.
I have looked up the issue on the internet and all the solutions I found point to one thing: disabling the password for this user. Since the user in question here is root. I do not want to do that.
Is there any other solution?
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!
Try:
Use NOPASSWD line for all commands, I mean:
jenkins ALL=(ALL) NOPASSWD: ALL
Put the line after all other lines in the sudoers file.
That worked for me (Ubuntu 14.04).
Try:
ssh -t remotehost "sudo <cmd>"
This will remove the above errors.
After all alternatives, I found:
sudo -S <cmd>
The -S (stdin) option causes sudo to read the password from the standard input instead of the terminal device.
Source
Above command still needs password to be entered. To remove entering password manually, in cases like jenkins, this command works:
echo <password> | sudo -S <cmd>
sudo by default will read the password from the attached terminal. Your problem is that there is no terminal attached when it is run from the netbeans console. So you have to use an alternative way to enter the password: that is called the askpass program.
The askpass program is not a particular program, but any program that can ask for a password. For example in my system x11-ssh-askpass works fine.
In order to do that you have to specify what program to use, either with the environment variable SUDO_ASKPASS or in the sudo.conf file (see man sudo for details).
You can force sudo to use the askpass program by using the option -A. By default it will use it only if there is not an attached terminal.
Try this one:
echo '' | sudo -S my_command
For Ubuntu 16.04 users
There is a file you have to read with:
cat /etc/sudoers.d/README
Placing a file with mode 0440 in /etc/sudoers.d/myuser with following content:
myuser ALL=(ALL) NOPASSWD: ALL
Should fix the issue.
Do not forget to:
chmod 0440 /etc/sudoers.d/myuser
Login into your linux. Fire following commands. Be careful, as editing sudoer is a risky proposition.
$ sudo visudo
Once vi editor opens make the following changes:
Comment out Defaults requiretty
# Defaults requiretty
Go to the end of the file and add
jenkins ALL=(ALL) NOPASSWD: ALL
If by any chance you came here because you can't sudo inside the Ubuntu that comes with Windows10
Edit the /etc/hosts file from Windows (with Notepad), it'll be located at: %localappdata\lxss\rootfs\etc, add 127.0.0.1 WINDOWS8, this will get rid of the first error that it can't find the host.
To get rid of the no tty present error, always do sudo -S <command>
This worked for me:
echo "myuser ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
where your user is "myuser"
for a Docker image, that would just be:
RUN echo "myuser ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
In Jenkins:
echo '<your-password>' | sudo -S command
Eg:-
echo '******' | sudo -S service nginx restart
You can use Mask Password Plugin to hide your password
Make sure the command you're sudoing is part of your PATH.
If you have a single (or multi, but not ALL) command sudoers entry, you'll get the sudo: no tty present and no askpass program specified when the command is not part of your path (and the full path is not specified).
You can fix it by either adding the command to your PATH or invoking it with an absolute path, i.e.
sudo /usr/sbin/ipset
Instead of
sudo ipset
Command sudo fails as it is trying to prompt on root password and there is no pseudo-tty allocated (as it's part of the script).
You need to either log-in as root to run this command or set-up the following rules in your /etc/sudoers
(or: sudo visudo):
# Members of the admin group may gain root privileges.
%admin ALL=(ALL) NOPASSWD:ALL
Then make sure that your user belongs to admin group (or wheel).
Ideally (safer) it would be to limit root privileges only to specific commands which can be specified as %admin ALL=(ALL) NOPASSWD:/path/to/program
I think I can help someone with my case.
First, I changed the user setting in /etc/sudoers referring to above answer. But It still didn't work.
myuser ALL=(ALL) NOPASSWD: ALL
%mygroup ALL=(ALL:ALL) ALL
In my case, myuser was in the mygroup.
And I didn't need groups. So, deleted that line.
(Shouldn't delete that line like me, just marking the comment.)
myuser ALL=(ALL) NOPASSWD: ALL
It works!
Running shell scripts that have contain sudo commands in them from jenkins might not run as expected. To fix this, follow along
Simple steps:
On ubuntu based systems, run " $ sudo visudo "
this will open /etc/sudoers file.
If your jenkins user is already in that file, then modify to look like this:
jenkins ALL=(ALL) NOPASSWD: ALL
save the file
Relaunch your jenkins job
you shouldnt see that error message again :)
This error may also arise when you are trying to run a terminal command (that requires root password) from some non-shell script, eg sudo ls (in backticks) from a Ruby program. In this case, you can use Expect utility (http://en.wikipedia.org/wiki/Expect) or its alternatives.
For example, in Ruby to execute sudo ls without getting sudo: no tty present and no askpass program specified, you can run this:
require 'ruby_expect'
exp = RubyExpect::Expect.spawn('sudo ls', :debug => true)
exp.procedure do
each do
expect "[sudo] password for _your_username_:" do
send _your_password_
end
end
end
[this uses one of the alternatives to Expect TCL extension: ruby_expect gem].
For the reference, in case someone else encounter the same issue, I was stuck during a good hour with this error which should not happen since I was using the NOPASSWD parameter.
What I did NOT know was that sudo may raise the exact same error message when there is no tty and the command the user try to launch is not part of the allowed command in the /etc/sudoers file.
Here a simplified example of my file content with my issue:
bguser ALL = NOPASSWD: \
command_a arg_a, \
command_b arg_b \
command_c arg_c
When bguser will try to launch "sudo command_b arg_b" without any tty (bguser being used for some daemon), then he will encounter the error "no tty present and no askpass program specified".
Why?
Because a comma is missing at the end of line in the /etc/sudoers file...
(I even wonder if this is an expected behavior and not a bug in sudo since the correct error message for such case shoud be "Sorry, user bguser is not allowed to execute etc.")
I was getting this error because I had limited my user to only a single executable 'systemctl' and had misconfigured the visudo file.
Here's what I had:
jenkins ALL=NOPASSWD: systemctl
However, you need to include the full path to the executable, even if it is on your path by default, for example:
jenkins ALL=NOPASSWD: /bin/systemctl
This allows my jenkins user to restart services but not have full root access
If you add this line to your /etc/sudoers (via visudo) it will fix this problem without having to disable entering your password and when an alias for sudo -S won't work (scripts calling sudo):
Defaults visiblepw
Of course read the manual yourself to understand it, but I think for my use case of running in an LXD container via lxc exec instance -- /bin/bash its pretty safe since it isn't printing the password over a network.
Using pipeline:
echo your_pswd | sudo -S your_cmd
Using here-document:
sudo -S cmd <<eof
pwd
eof
#remember to put the above two lines without "any" indentations.
Open a terminal to ask password (whichever works):
gnome-terminal -e "sudo cmd"
xterm -e "sudo cmd"
I faced this issue when working on an Ubuntu 20.04 server.
I was trying to run a sudo command from a remote machine to deploy an app to the server. However when I run the command I get the error:
sudo: no tty present and no askpass program specified
The remote script failed with exit code 1
Here's how I fixed it:
The issue is caused by executing a sudo command which tries to request for a password, but sudo does not have access to a tty to prompt the user for a passphrase. As it can’t find a tty, sudo falls back to an askpass method but can’t find an askpass command configured, so the sudo command fails.
To fix this you need to be able to run sudo for that specific user with no password requirements. The no password requirements is configured in the /etc/sudoers file. To configure it run either of the commands below:
sudo nano /etc/sudoers
OR
sudo visudo
Note: This opens the /etc/sudoers file using your default editor.
Next, Add the following line at the bottom of the file:
# Allow members to run all commands without a password
my_user ALL=(ALL) NOPASSWD:ALL
Note: Replace my_user with your actual user
If you want the user to run specific commands you can specify them
# Allow members to run specific commands without a password
my_user ALL=(ALL) NOPASSWD:/bin/myCommand
OR
# Allow members to run specific commands without a password
my_user ALL=(ALL) NOPASSWD: /bin/myCommand, /bin/myCommand, /bin/myCommand
Save the changes and exit the file.
For more help, read the resource in this link: sudo: no tty present and no askpass program specified
That's all.
I hope this helps
The solution to the problem is
If you came across this issue anywhere else apart from the Jenkins instance follow this from the 2nd step. The first step is for the user who is having issue with the Jenkins instance.
Go to Jenkins instance of Google Cloud Console.
Enter the commands
sudo su
visudo -f /etc/sudoers
Add following line at the end
jenkins ALL= NOPASSWD: ALL
Checkout here to understand the rootcause of this issue
No one told what could cause this error, in case of migration from one host to another, remember about checking hostname in sudoers file:
So this is my /etc/sudoers config
User_Alias POWERUSER = user_name
Cmnd_Alias SKILL = /root/bin/sudo_auth_wrapper.sh
POWERUSER hostname=(root:root) NOPASSWD: SKILL
if it doesn't match
uname -a
Linux other_hostname 3.10.17 #1 SMP Wed Oct 23 16:28:33 CDT 2013 x86_64 Intel(R) Core(TM) i3-4130T CPU # 2.90GHz GenuineIntel GNU/Linux
it will pop up this error:
no tty present and no askpass program specified
Other options, not based on NOPASSWD:
Start Netbeans with root privilege ((sudo netbeans) or similar) which will presumably fork the build process with root and thus sudo will automatically succeed.
Make the operations you need to do suexec -- make them owned by root, and set mode to 4755. (This will of course let any user on the machine run them.) That way, they don't need sudo at all.
Creating virtual hard disk files with bootsectors shouldn't need sudo at all. Files are just files, and bootsectors are just data. Even the virtual machine shouldn't necessarily need root, unless you do advanced device forwarding.
Although this question is old, it is still relevant for my more or less up-to-date system. After enabling debug mode of sudo (Debug sudo /var/log/sudo_debug all#info in /etc/sudo.conf) I was pointed to /dev: "/dev is world writable". So you might need to check the tty file permissions, especially those of the directory where the tty/pts node resides in.
I was able to get this done but please make sure to follow the steps properly.
This is for the anyone who is getting import errors.
Step1: Check if files and folders have got execute permission issue.
Linux user use:
chmod 777 filename
Step2: Check which user has the permission to execute it.
Step3: open terminal type this command.
sudo visudo
add this lines to the code below
www-data ALL=(ALL) NOPASSWD:ALL
nobody ALL=(ALL) NOPASSWD:/ALL
this is to grant permission to execute the script and allow it to use all the libraries. The user generally is 'nobody' or 'www-data'.
now edit your code as
echo shell_exec('sudo -u the_user_of_the_file python your_file_name.py 2>&1');
go to terminal to check if the process is running
type this there...
ps aux | grep python
this will output all the process running in python.
Add Ons:
use the below code to check the users in your system
cut -d: -f1 /etc/passwd
Thank You!
1 open /etc/sudoers
type sudo vi /etc/sudoers. This will open your file in edit mode.
2 Add/Modify linux user
Look for the entry for Linux user. Modify as below if found or add a new line.
<USERNAME> ALL=(ALL) NOPASSWD: ALL
3 Save and Exit from edit mode
I had the same error message when I was trying to mount sshfs which required sudo : the command is something like this :
sshfs -o sftp_server="/usr/bin/sudo /usr/lib/openssh/sftp-server" user#my.server.tld:/var/www /mnt/sshfs/www
by adding the option -o debug
sshfs -o debug -o sftp_server="/usr/bin/sudo /usr/lib/openssh/sftp-server" user#my.server.tld:/var/www /mnt/sshfs/www
I had the same message of this question :
sudo: no tty present and no askpass program specified
So by reading others answer I became to make a file in /etc/sudoer.d/user on my.server.tld with :
user ALL=NOPASSWD: /usr/lib/openssh/sftp-server
and now I able to mount the drive without giving too much extra right to my user.
Below actions work for on ubuntu20
edit /etc/sudoers
visudo
or
vi /etc/sudoers
add below content
userName ALL=(ALL) NOPASSWD: ALL
%sudo ALL=(ALL:ALL) NOPASSWD:ALL
I'm not sure if this is a more recent change, but I just had this problem and sudo -S worked for me.

bash script executing sudo and chmod command not working properly

I am trying to create a bash script that starts with the user executing a sudo -s command.
This is my script:
#!/bin/bash
SSH_USER=testuser
SUDO_PASSWD=secretpassword
FILE=/www/a/logs/service.log
MACHINES=( 'machine1' );
for HOST in ${MACHINES[#]}; do
ssh -t -l "$SSH_USER" "$HOST" "echo '$SUDO_PASSWD' | sudo -Ss chmod 777 $FILE"
done
I feel like this script should not prompt me for the password but it does. I do not want to have to input the password 30 different times. I have tried multiple versions where I hard code the password into the script but I still get prompted to enter in a password. HELP ME PLEASE. I'm VERY new at creating bash scripts and need some serious guidance.
The idea you have there will never work as sudo(1) does not read passwords from standard input unless it's a terminal. Hardcoding passwords into a script is also very bad idea, as pointed out repeatedly in comments.
If you really want to make this happen (I recommend against it), you should do edit /etc/sudoers in your target machine to let you run sudo(1) without it asking a password for things you need to be done without a password. For that you should not let yourself run any chmod command lines without a password, but instead create a script in target machine (for example ´/usr/local/bin/do-my-promiscuous-chmod`) then tell sudo to let you run just that script without asking a password.
For example adding the following to /etc/sudoers will let user "foo" run /usr/local/sbin/do-unsafe without a password and with root privileges:
foo ALL = (root) NOPASSWD: /usr/local/sbin/do-unsafe
Agree with Sami, no hardcoding password in scripts.
more suggestions.
If the script needn't run as root, and can be run by some other application admin account, such as DBA, you should nominate to that user only to limit the permissions, such as:
foo ALL = (dba) NOPASSWD: /usr/local/sbin/do-unsafe
Secondly, don't give any files with 777 permissions, it is unsafe. Think some others way, such as ACL permission set.
chmod 777 $FILE

Resources