Search code examples
bashsshsudo

Running sudo via ssh on remote server


I am trying to write a deployment script which after copying the new release to the server should perform a few sudo commands on the remote machine.

#!/bin/bash
app=$1
echo "Deploying application $app"
echo "Copy file to server"
scp -pr $app-0.1-SNAPSHOT-jar-with-dependencies.jar nuc:/tmp/
echo "Execute deployment script"
ssh -tt stefan@nuc ARG1=$app 'bash -s' <<'ENDSSH'
    # commands to run on remote host
    echo Hello world
    echo $ARG1
    sudo ifconfig
    exit
ENDSSH

The file gets copied correctly and the passed argument printed as well. But the prompt for the password shows for two seconds then it says "Sorry, try again" and the second prompt shows the text I enter in plain text (meaning not masked) but also does not work if I enter the password correctly.

stefan@X220:~$ ./deploy.sh photos
Deploying application photos
Copy file to server
photos-0.1-SNAPSHOT-jar-with-dependencies.jar                                         100%   14MB  75.0MB/s   00:00    
Execute deployment script
  # commands to run on remote host
  echo Hello world
  echo $ARG1
  sudo ifconfig
  exit
stefan@nuc:~$   # commands to run on remote host
stefan@nuc:~$   echo Hello world
Hello world
stefan@nuc:~$   echo $ARG1
photos
stefan@nuc:~$   sudo ifconfig
[sudo] password for stefan: 
Sorry, try again.
[sudo] password for stefan: ksdlgfdkgdfg

I tried leaving out the -t flags for ssh as well as using -S for sudo which did not help. Any help is highly appreciated.


Solution

  • I came up with another solution: Create another file with the script to execute on the remote server. Then copy it using scp and in the calling script do a

    ssh -t remoteserver sudo /tmp/deploy_remote.sh parameter1
    

    This works as expected. Of course the separate file is not the most elegant solution, but -t and -tt did not work when inlining the script to execute on the remote machine.