0

I need to run a script which needs to be run with root privileges remotely. Therefore I add "sudo su" command at the start of the script. However the ssh just login the remote server and stuck at sudo su command, and it does not continue from next line in the script.

server.sh

sudo -s
sudo apt-get update
sudo apt-get upgrade

client.sh

 scp -i "$key.pem" server.sh "$dns:/tmp"
 ssh -tt -i "$key.pem" $dns  "bash /tmp/server.sh"

server.sh and client.sh is at the same local directory. When I run ./client.sh, server.sh which is run remotely stuck at first line and does not continue with "sudo apt-get update" command. What is the reason of this behavious and is there a solution?

xywz
  • 45
  • 1
  • 5
  • 1
    `sudo` normally prompts for the user's password. It sounds like your script is getting stuck there. – John Bollinger Mar 16 '21 at 12:34
  • 1
    Do you have access to `root` user on **remote server** ? if yes login with that , otherwise with normal user login you cannot access `root` – Shakiba Moshiri Mar 16 '21 at 12:35
  • my root user does not require a password. when I log in, "sudo su" automatically converts terminal to root terminal. However I want to run script from local computer and automate this process. – xywz Mar 16 '21 at 13:12
  • 3
    You should remove `sudo -s`, whch blocks – Philippe Mar 16 '21 at 13:13
  • If I delete, how can I have root permissions and automate then? – xywz Mar 17 '21 at 01:03

3 Answers3

1

When you run the command sudo -s you change the user and the rest of the script is lost because it is in a new shell.

Remove the line sudo -s and try running the script again.

Note: it is important to remember that the user running sudo must be in the /etc/sudoers file with the username ALL=(ALL) NOPASSWD:ALL permissions.

RexRod
  • 51
  • 1
  • 3
0

sudo -s with no command starts a new, interactive shell. The following commands won't execute until it exits. See man sudo.

If you are already running apt-get via sudo, and sudo does not require a password, why do you need the sudo -s?

Wayne Vosberg
  • 1,023
  • 5
  • 7
  • I m trying to configure openvpn server. While configuration, this procedure create a folder that requires root privileges. Since there is no `sudo cd` command, I wonder if there is a way to switch to root user in the middle of shell script. – xywz Mar 18 '21 at 13:58
0

You can use

ssh user@ip '[command]'

to run [command] on the remote host. If you have a user with root privileges (aka. sudo) and if you can use commands without passwords (NOPASSWD:[command,list or ALL]) this is the safest way i can suggest however if you want the script to run on the remote server and triggered by the local computer you can always

ssh user@ip 'sudo /bin/bash /home/[user]/server.sh'

This would work as well. You can also use "scp" command to copy the script and then delete it with ssh again for automated one-script approach.

Catastrophe
  • 322
  • 3
  • 12