How to run sudo under su? - linux

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

Related

Running commands as different user from bash script

I have 2 users: usr1 and usr2. Neither is a root user.
usr1 starts a bash script. And from the script, I want to run some commands as usr2.
I understand that the way to do it is:
su -l <usr2> -c "command"
The issue is with passing the password. These are 2 different users with different privileges, so, skipping the password for usr2 is not an option.
This script can go interactive, and ask the user for the password. Is there a way to do this in bash script ?
Note: I am not an expert with scripting. And I have done some research before asking this question, but I couldnt find a suitable answer.
You can try using the read read man page command see example below:
#!/bin/bash
read -s -p "Enter your password: " pass
echo $pass
In that case you will need to use /bin/su -c along with sudo -S
#!/bin/bash
user=$1
read -s -p "Enter pass: " pass
cmd=$(echo $pass|sudo -S <some-command>)
su -c '$cmd' - $user
Where user=$1 additional bash argument, in this case the user id for usr2, then jut run it
$sudo bash -x ./password.sh <target-user>

Remote execute bash scripts that needs input

I am using SSH command to execute the bash scripts remotely:
ssh user#server 'bash -s' < $script_dir/script.sh
And inside the script.sh, I will have the command like below:
ssh-keygen -t rsa
ssh-copy-id postgres#$sqlserver
ssh postgres#$sqlserver -C true
And also
printf "Creating user in postgresql server...\n"
createuser -s -P username
Which need user's input, but I found when I execute the command from the remote server, it will skip getting the users' input and failed.
Another one is:
printf "Please enter your barman server name: \n" ; read -s barmanserver
Which cannot read user's input neither
I know that the script seems cannot read the other terminal's input, but can anyone help me find a solution if I need the user input to continue?
Thanks a lot!!
Eva
I have used something like this in the past. I am not quite sure why I installed sshpass though.
apt-get install sshpass -y
echo "Adding users to new VMs"
adduser adminuser
echo "changing user password"
echo "adminuser:password" | chpasswd
adduser adminuser sudo
It does work, but it gives you some warning.

How to sudo run a local script over ssh

I try to sudo run a local script over ssh,
ssh $HOST < script.sh
and I tried
ssh -t $HOST "sudo -s && bash" < script.sh
Actually, I searched a lot in google, find some similar questions, however, I don't find a solution which can sudo run a local script.
Reading the error message of
$ ssh -t $HOST "sudo -s && bash" < script.sh
Pseudo-terminal will not be allocated because stdin is not a terminal.
makes it pretty clear what's going wrong here.
You can't use the ssh parameter -t (which sudo needs to ask for a password) whilst redirecting your script to bash's stdin of your remote session.
If it is acceptable for you, you could transfer the local script via scp to your remote machine and then execute the script without the need of I/O redirection:
scp script.sh $HOST:/tmp/ && ssh -t $HOST "sudo -s bash /tmp/script.sh"
Another way to fix your issue is to use sudo in non-interactive mode -n but for this you need to set NOPASSWD within the remote machine's sudoers file for the executing user. Then you can use
ssh $HOST "sudo -n -s bash" < script.sh
To make Edward Itrich's answer more scalable and geared towards frequent use, you can set up a system where you only run a one line script that can be quickly ported to any host, file or command in the following manner:
Create a script in your Scripts directory if you have one by changing the name you want the script to be (I use this format frequently to change 1 word for my script name and create the file, set permissions and open for editing):
newscript="runlocalscriptonremotehost.sh"
touch $newscript && chmod +x $newscript && nano $newscript
In nano fill out the script as follows placing the directory and name information of the script you want to run remotely in the variable lines of runlocalscriptonremotehost.sh(only need to edit lines 1-3):
HOSTtoCONTROL="sudoadmin#192.168.0.254"
PATHtoSCRIPT="/home/username/Scripts/"
SCRIPTname="scripttorunremotely.sh"
scp $PATHtoSCRIPT$SCRIPTname $HOSTtoCONTROL:/tmp/ && ssh -t $HOSTtoCONTROL "sudo -s bash /tmp/$SCRIPTname"
Then just run:
sh ./runlocalscriptonremotehost.sh
Keep runlocalscriptonremotehost.sh open in a tabbed text editor for quick updating, go ahead and create a bash alias for the script and you have yourself an app-ified version of this frequently used operation.
First of all divide your objective in 2 parts. 1) ssh to the host. 2) run the command you want as sudo. After you are certain that you can 1) access the host and 2) have sudo privileges then you can combine the two commands with &&. What x_cmd && y_cmd does is that the y_cmd gets executed after x_cmd has exited successfully.

How to get root access after ssh in a script? [duplicate]

I have a script which runs another script via SSH on a remote server using sudo. However, when I type the password, it shows up on the terminal. (Otherwise it works fine)
ssh user#server "sudo script"
What's the proper way to do this so I can type the password for sudo over SSH without the password appearing as I type?
Another way is to use the -t switch to ssh:
ssh -t user#server "sudo script"
See man ssh:
-t Force pseudo-tty allocation. This can be used to execute arbi-
trary 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.
I was able to fully automate it with the following command:
echo pass | ssh -tt user#server "sudo script"
Advantages:
no password prompt
won't show password in remote machine bash history
Regarding security: as Kurt said, running this command will show your password on your local bash history, and it's better to save the password in a different file or save the all command in a .sh file and execute it. NOTE: The file need to have the correct permissions so that only the allowed users can access it.
Sudo over SSH passing a password, no tty required:
You can use sudo over ssh without forcing ssh to have a pseudo-tty (without the use of the ssh "-t" switch) by telling sudo not to require an interactive password and to just grab the password off stdin. You do this by using the "-S" switch on sudo. This makes sudo listen for the password on stdin, and stop listening when it sees a newline.
Example 1 - Simple Remote Command
In this example, we send a simple whoami command:
$ ssh user#server cat \| sudo --prompt="" -S -- whoami << EOF
> <remote_sudo_password>
root
We're telling sudo not to issue a prompt, and to take its input from stdin. This makes the sudo password passing completely silent so the only response you get back is the output from whoami.
This technique has the benefit of allowing you to run programs through sudo over ssh that themselves require stdin input. This is because sudo is consuming the password over the first line of stdin, then letting whatever program it runs continue to grab stdin.
Example 2 - Remote Command That Requires Its Own stdin
In the following example, the remote command "cat" is executed through sudo, and we are providing some extra lines through stdin for the remote cat to display.
$ ssh user#server cat \| sudo --prompt="" -S -- "cat" << EOF
> <remote_sudo_password>
> Extra line1
> Extra line2
> EOF
Extra line1
Extra line2
The output demonstrates that the <remote_sudo_password> line is being consumed by sudo, and that the remotely executed cat is then displaying the extra lines.
An example of where this would be beneficial is if you want to use ssh to pass a password to a privileged command without using the command line. Say, if you want to mount a remote encrypted container over ssh.
Example 3 - Mounting a Remote VeraCrypt Container
In this example script, we are remotely mounting a VeraCrypt container through sudo without any extra prompting text:
#!/bin/sh
ssh user#server cat \| sudo --prompt="" -S -- "veracrypt --non-interactive --stdin --keyfiles=/path/to/test.key /path/to/test.img /mnt/mountpoint" << EOF
SudoPassword
VeraCryptContainerPassword
EOF
It should be noted that in all the command-line examples above (everything except the script) the << EOF construct on the command line will cause the everything typed, including the password, to be recorded in the local machine's .bash_history. It is therefore highly recommended that for real-world use you either use do it entirely through a script, like the veracrypt example above, or, if on the command line then put the password in a file and redirect that file through ssh.
Example 1a - Example 1 Without Local Command-Line Password
The first example would thus become:
$ cat text_file_with_sudo_password | ssh user#server cat \| sudo --prompt="" -S -- whoami
root
Example 2a - Example 2 Without Local Command-Line Password
and the second example would become:
$ cat text_file_with_sudo_password - << EOF | ssh va1der.net cat \| sudo --prompt="" -S -- cat
> Extra line1
> Extra line2
> EOF
Extra line1
Extra line2
Putting the password in a separate file is unnecessary if you are putting the whole thing in a script, since the contents of scripts do not end up in your history. It still may be useful, though, in case you want to allow users who should not see the password to execute the script.
Assuming you want no password prompt:
ssh $HOST 'echo $PASSWORD | sudo -S $COMMMAND'
Example
ssh me#localhost 'echo secret | sudo -S echo hi' # outputs 'hi'
The best way is ssh -t user#server "sudo <scriptname>", for example ssh -t user#server "sudo reboot".
It will prompt for password for user first and then root(since we are running the script or command with root privilege.
I hope it helped and cleared your doubt.
NOPASS in the configuration on your target machine is the solution. Continue reading at http://maestric.com/doc/unix/ubuntu_sudo_without_password
echo $VAR_REMOTEROOTPASS | ssh -tt -i $PATH_TO_KEY/id_mykey $VAR_REMOTEUSER#$varRemoteHost
echo \"$varCommand\" | sudo bash
confirming that the answer of #ofirule is working like a charm.
I try ot even with sshpass & it works. This is how to use it with sshpass:
echo $pass | sshpass -p $pass ssh -tt cloud_user#$ip "sudo su -"
you will find yourself in the root shell directly

su command in shell script

I have a script which copies a file, then untar and install it (agent-service) on multiple systems (IPs are read from systems.txt file). In the script, I wanted to start the agent-service as user "test". However after the script execution, when I check the target system, the agent-service is shown as running as "root" user. What could be wrong here? Am I not using su command correct within the script?
~]# ps -ef | grep agent-service
root 23511 15196 0 02:12 pts/3 00:00:00 agent-service
Script>
#!/bin/bash
export AGENT=linux-5.8.1.tar.gz
while read host; do
scp $AGENT root#$host:/opt
ssh -n root#$host 'cd /opt/linux;
tar zxvf linux-5.8.1.tar.gz;
mkdir /opt/hyperic;
useradd -m test;
chown -R test:test /opt/linux;
su - test;
/opt/linux/agent-service start'
done < systems.txt
Using su as you do here spawns a new shell that has nothing to do thus exits immediately.
Either pass the command to su:
su - test -c /opt/linux/agent-service start
Or use sudo in a similar manner:
sudo -u test /opt/linux/agent-service start

Resources