Shell script calls sudo; how do I suppress the password prompt - linux

I am writing a simple shell script which changes the mac address of the network hardware.
One of the line is :
sudo ifconfig eth0 hw ether 00:99:99:00:00:00
My problem is with sudo the script prompts for password. Is there any way that I could do this without prompting the user for password ???

Most definitely, if you don't mind making that particular command 'free for use' for that particular user:
See basically my other answer here: Shell script - Sudo-permissions lost over time
The simplest thing that may work is
myuser = NOPASSWD: /sbin/ifconfig
Also, you could sudo an arbitrary command on the same terminal (tty/vty), and sudo will cache the authentication for a while (or until sudo -k), so you may start the script and it will 'remember' the credentials from your earlier sudo invocation. I sometimes do this when composing pipes with sudo (just preceded them with sudo true)

echo "password" | sudo -S ifconfig eth0 hw ether 00:99:99:00:00:00

You need a sudo configuration line which allows for the command to be executed by the user without password prompt.
You can disable the password prompt for a whole user (more dangerous, but perhaps ok if you are the only user on your desktop -- DONT do this on a server ):
yourusername ALL=(ALL) NOPASSWD: ALL
or more restrictive, only allowing the ifconfig command:
yourusername ALL= NOPASSWD: /sbin/ifconfig
See: man sudoers , man sudo
http://ubuntuforums.org/showthread.php?t=1132821
http://www.linuxhelp.net/guides/sudo/

A safer way to do it would be:
sudo visudo -f sudoers
then add
myuser ALL=NOPASSWD:/sbin/ifconfig
to the editor window that appeared. Once you are done, use :x to quit

Here is a Zenity dialog that does something similar to Tman's comment,
though the password isn't stored in history...
This may be a good alternative
#!/bin/bash
ENTRY=`zenity --password`
case $? in
0)
pw=$(echo $ENTRY | cut -d'|' -f1)
;;
1)
echo "Stop login.";;
-1)
echo "An unexpected error has occurred.";;
esac
TMP=$(echo "${pw}" | sudo -Sv)
TMP=0

Related

How to demand root privileges in a shell script? [duplicate]

This question already has answers here:
How to check if running as root in a bash script
(21 answers)
Closed 7 years ago.
Say you have a shell script that could potentially require root privileges. You don't want to force the user to run it as sudo. However, if it does require that privilege, you want to prompt the user to enter their password, rather than complaining and forcing them to re-enter the command with sudo.
How would you go about doing this in a Bash script? sudo true seems to work, but it feels like a hack. Is there a better way?
Here's what I often do. This is loose pseudo-code but should give you the idea:
# myscript -- possibly execute as sudo
if (passed -e option) then
read variables from envfile
else
...
need_root = ...
# set variables ...
if ($need_root && $uid != 0) then
env [or whatever] > /tmp/envfile
exec sudo myscript -e/tmp/envfile ...
fi
fi
# stuff to execute as root [or not] ...
The command
sudo -nv
checks whether the user has current sudo credentials (-v), but will fail rather than prompting if access has expired (-n).
So this:
if sudo -nv 2>/dev/null && sudo -v ; then
sudo whoami
else
echo No access
fi
will check whether the user's sudo credentials are current, and prompt for a password only if they're not.
There is a possible race condition: the user's credentials could expire just after the check.
As ghoti points out in a comment, this may not work if the sudoers file is set up to allow only certain commands to be executed. For that and other reasons, be sure to check whether each sudo command succeeded or failed.
If your plan is to use sudo for privilege escalation, one wrinkle you may have to deal with is that that sudo can be set up to permit root access to some commands and not others. For example let's imagine you've got a server that runs VirtualBox, with different people managing the applications than are managing the OS. Your sudoers file might contain something like the following:
Cmnd_Alias SAFE = /bin/true, /bin/false, /usr/bin/id, /usr/bin/who*
Cmnd_Alias SHUTDOWN = /sbin/shutdown, /sbin/halt, /sbin/reboot
Cmnd_Alias SU = /bin/su, /usr/bin/vi*, /usr/sbin/visudo
Cmnd_Alias SHELLS = /bin/sh, /bin/bash, /bin/csh, /bin/tcsh
Cmnd_Alias VBOX = /usr/bin/VBoxManage
%wheel ALL=(ALL) ALL, !SU, !SHELLS, !SHUTDOWN
%staff ALL=(ALL) !SU, !SHELLS, NOPASSWD: SAFE
%operator ALL=(ALL) SAFE, SHUTDOWN
%vboxusers ALL=(ALL) NOPASSWD: VBOX
In this case, a member of the vboxusers unix group will always get a successful response to a sudo -nv, because of the existence of the NOPASSWD entry for that group. But a member of that group running any other command than VBoxManage will get a password challenge and a security warning.
So you need to determine whether the command you need to run can be run without a password prompt. If you don't know how sudo is configured on the system where your script is running, the canonical test is to run the command. Running sudo -nv will only tell you whether you are authenticated; it won't tell you what commands you have access to.
That said, if you can safely rely on a sudo configuration where, say, membership in wheel group gives you access to all commands, for example with:
%wheel ALL=(ALL) ALL
then you can use sudo -nv to test for escalation capabilities. But your script might have some things that it runs as root, and some things it doesn't. You might also want to consider other tools besides sudo for privilege escalation.
One strategy might be to set a variable to preface commands if the need is there, but leave the variable blank if you're already root (i.e. running the entire script inside sudo).
if ! which sudo >/dev/null 2>/dev/null; then
PM_SU_CMD="su - root -c"
elif sudo -nv 2>/dev/null; then
PM_SU_CMD="sudo"
else
echo "ERROR: I can't get root." >&2
exit 1
fi
Of course, if we are already root, unset this to avoid potential conflict:
[ `ps -o uid= $$` -eq 0 ] && unset PM_SU_CMD
(Note that this is a query of the system's process table; we don't want to rely on the shell's environment, because that can be spoofed.)
Then, certain system utilities might be made more easily available using functions:
# Superuser versions for commands that need root privileges
find_s () { $PM_SU_CMD "/usr/bin/find $*"; }
mkdir_s () { $PM_SU_CMD "/bin/mkdir -p $1"; }
rm_s () { $PM_SU_CMD "/bin/rm $*"; }
Then within your script, you'd simply use the _s version of things that need to be run with root privileges.
This is of course by no means the only way to solve this problem.

How to run sudo under su?

I have this:
su $username -c ./script.sh
The problem is that within script I have 'sudo' commands and they says me
sudo: no tty present and no askpass program specified
How to do this right?
UPD: I need both sudo and su. What I need to do is run script as USER $username and be able to run certain commands within script as root (for example, pacman -S)
SOLUTION: I've added NOPASSWD option to /etc/sudoers before running script and delete this entry using sed after script finished.
First set chmod +x to your scripts
try:
#!/bin/bash
echo "hello"
su - <your-user> -c /path/to/script.sh
echo "good bye"
UPDATE:
You should find a way to force bash to use pseudo-tty
Force pseudo-tty allocation. This can be used to execute arbitrary screen-based programs on a remote machine, which can be very useful, e.g. when implementing menu services. Multiple -t options force tty allocation, even if ssh has no local tty.
If the user is not as sudoers do the following steps:
This is what you need to do in /etc/sudoers:
# User privilege specification
root ALL=(ALL:ALL) ALL
newuser ALL=(ALL:ALL) ALL
you have also ways to do:
you can pipe password if it has password:
echo "yourpassword" | sudo -S
OR
You can run the following script:
#!/usr/bin/expect -f
spawn sudo -s <<EOF
expect "assword for username:"
send -- "user-password\r"
expect eof
Also you can do that:
sudo -kS bash - << EOF
password
whoami
echo "Not a good idea to have a password encoded in plain text"
EOF

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.

Clear cache in remote server using ssh

I had been trying to clear cache in a remote server and i got these commands.
First login as root user and execute
sync; echo 3 > /proc/sys/vm/drop_caches
But I had to automate this in a script, so i used this
ssh user#ipaddress "sudo su; sync; echo 3 > /proc/sys/vm/drop_caches";
But I am not able to get the root user privileges by sudo su and I thought removing sudo su and instead use
ssh user#ipaddress "sudo sync;sudo echo 3 > /proc/sys/vm/drop_caches";
But this says it dose'nt have enough permissions.
What am I missing??
When you do this sudo echo 3 > .... only echo will be with "sudo" user permissions, redirection is with current user.
try something like this :
ssh user#ipaddress "sudo sh -c \"sync; echo 3 > /proc/sys/vm/drop_caches\"";
Use tee as an alternate to redirection that works well with sudo:
ssh user#ipaddress 'echo 3 | sudo tee /proc/sys/vm/drop_caches > /dev/null'
The redirection to /dev/null is optional, if you want to avoid "3" being echoed to your terminal as well.
Also If you experience this message
>> sudo: sorry, you must have a tty to run sudo
as I had, you can fix it by editing /etc/sudoers and comment Defaults requiretty -> #Defaults requiretty.

How to pass the password to su/sudo/ssh without overriding the TTY?

I'm writing a C Shell program that will be doing su or sudo or ssh. They all want their passwords in console input (the TTY) rather than stdin or the command line.
Does anybody know a solution?
Setting up password-less sudo is not an option.
expect could be an option, but it's not present on my stripped-down system.
For sudo there is a -S option for accepting the password from standard input. Here is the man entry:
-S The -S (stdin) option causes sudo to read the password from
the standard input instead of the terminal device.
This will allow you to run a command like:
echo myPassword | sudo -S ls /tmp
As for ssh, I have made many attempts to automate/script it's usage with no success. There doesn't seem to be any build-in way to pass the password into the command without prompting. As others have mentioned, the "expect" utility seems like it is aimed at addressing this dilemma but ultimately, setting up the correct private-key authorization is the correct way to go when attempting to automate this.
I wrote some Applescript which prompts for a password via a dialog box and then builds a custom bash command, like this:
echo <password> | sudo -S <command>
I'm not sure if this helps.
It'd be nice if sudo accepted a pre-encrypted password, so I could encrypt it within my script and not worry about echoing clear text passwords around. However this works for me and my situation.
For ssh you can use sshpass: sshpass -p yourpassphrase ssh user#host.
You just need to download sshpass first :)
$ apt-get install sshpass
$ sshpass -p 'password' ssh username#server
For sudo you can do this too:
sudo -S <<< "password" command
I've got:
ssh user#host bash -c "echo mypass | sudo -S mycommand"
Works for me.
The usual solution to this problem is setuiding a helper app that performs the task requiring superuser access:
http://en.wikipedia.org/wiki/Setuid
Sudo is not meant to be used offline.
Later edit: SSH can be used with private-public key authentication. If the private key does not have a passphrase, ssh can be used without prompting for a password.
Maybe you can use an expect command?:
expect -c 'spawn ssh root#your-domain.com;expect password;send "your-password\n";interact
That command gives the password automatically.
This can be done by setting up public/private keys on the target hosts you will be connecting to.
The first step would be to generate an ssh key for the user running the script on the local host, by executing:
ssh-keygen
Enter file in which to save the key (/home/myuser/.ssh/id_rsa): <Hit enter for default>
Overwrite (y/n)? y
Then enter a blank password. After that, copy your ssh key onto the target host which you will be connecting to.
ssh-copy-id <remote_user>#<other_host>
remote_user#other_host's password: <Enter remote user's password here>
After registering the ssh keys, you would be able to perform a silent ssh remote_user#other_host from you local host.
When there's no better choice (as suggested by others), then man socat can help:
(sleep 5; echo PASSWORD; sleep 5; echo ls; sleep 1) |
socat - EXEC:'ssh -l user server',pty,setsid,ctty
EXEC’utes an ssh session to server. Uses a pty for communication
between socat and ssh, makes it ssh’s controlling tty (ctty),
and makes this pty the owner of a new process group (setsid), so
ssh accepts the password from socat.
All of the pty,setsid,ctty complexity is necessary and, while you might not need to sleep as long, you will need to sleep. The echo=0 option is worth a look too, as is passing the remote command on ssh's command line.
Take a look at expect linux utility.
It allows you to send output to stdio based on simple pattern matching on stdin.
ssh -t -t me#myserver.io << EOF
echo SOMEPASSWORD | sudo -S do something
sudo do something else
exit
EOF
Set SSH up for Public Key Authentication, with no pasphrase on the Key. Loads of guides on the net. You won't need a password to login then. You can then limit connections for a key based on client hostname. Provides reasonable security and is great for automated logins.
echo <password> | su -c <command> <user>
This is working.
a better sshpass alternative is: passh
https://github.com/clarkwang/passh
Login to a remote server
$ passh -p password ssh user#host
Run a command on remote server
$ passh -p password ssh user#host date
other methods to pass the password
-p The password (Default: `password')
-p env: Read password from env var
-p file: Read password from file
here I explained why it is better than sshpass, and other solutions.
You can also pass various parameters as follows:
echo password | echo y | sudo -S pacman -Syu
(Although that's a bad idea, it's just an example)
I had the same problem. dialog script to create directory on remote pc.
dialog with ssh is easy. I use sshpass (previously installed).
dialog --inputbox "Enter IP" 8 78 2> /tmp/ip
IP=$(cat /tmp/ip)
dialog --inputbox "Please enter username" 8 78 2> /tmp/user
US=$(cat /tmp/user)
dialog --passwordbox "enter password for \"$US\" 8 78 2> /tmp/pass
PASSWORD = $(cat /tmp/pass)
sshpass -p "$PASSWORD" ssh $US#$IP mkdir -p /home/$US/TARGET-FOLDER
rm /tmp/ip
rm /tmp/user
rm /tmp/pass
greetings from germany
titus
Building on #Jahid's answer, this worked for me on macOS 10.13:
ssh <remote_username>#<remote_server> sudo -S <<< <remote_password> cat /etc/sudoers
I once had a use case where I needed to run Sudo and ssh in the same command without stdin specifying all the variables needed.
This is the command I used
echo sudopassword | sudo -S -u username sshpass -p extsshpassword ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no username#ipaddress " CMD on external machine"
Breaking that command into pieces!
This will allow you to run commands through your machine using Superuser:
echo password | sudo -S -u username
This will allow you to pass ssh password and execute commands on external machines:
sshpass -p sshpassword ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no username#ipaddress " CMD on external machine"
make sure you install the sudo and openssh packages on your machine.
One way would be to use read -s option .. this way the password characters are not echoed back to the screen. I wrote a small script for some use cases and you can see it in my blog:
http://www.datauniv.com/blogs/2013/02/21/a-quick-little-expect-script/
USE:
echo password | sudo command
Example:
echo password | sudo apt-get update; whoami
Hope It Helps..
You can provide password as parameter to expect script.
su -c "Command" < "Password"
Hope it is helpful.

Resources