0

I'm working on a script that needs to copy some files from a local machine to a directory on a remote server. The problem I'm running into is that the directory (/etc/init.d) is owned by root so I get permission exceptions if I try to copy files into it. That means I can't use scp without logging in as root.

The closest solution I have found so far is this answer: https://askubuntu.com/a/872537/798391 . Unfortunately, the answer as given doesn't quite work and none of the suggestion given in the comments seem to fix it. If I run

cat myscript.sh | ssh foo@myserver "sudo tee -a /etc/init.d/myscript.sh"

I get the error

sudo: no tty present and no askpass program specified

One of the comments suggested adding -t to the ssh command

cat myscript.sh | ssh -t foo@myserver "sudo tee -a /etc/init.d/myscript.sh"

but that resulted in the error

Pseudo-terminal will not be allocated because stdin is not a terminal.

Another suggested option was to use the -S argument of sudo

cat myscript.sh | ssh foo@myserver "sudo -S tee -a /etc/init.d/myscript.sh"

That at least prompts for the password, but it times out and asks again before the password can be entered completely.

At this point I'm out of ideas. Is there some way to get this command to work? Is there a better alternative solution for copying files to a protected remote location?

pbuchheit
  • 103
  • 1
  • 4

1 Answers1

0

There can be various methods to achieve what you want, it depends on detailed configuration on both machines.

The simplest method would be (if this is possible) to configure key-based ssh authentication so that your local user can ssh as root to the remote machine.

Another method is to use expect to write a script that logs interactively via ssh to the remote machine, does sudo -i (and types the appropriate password) and then copies the file doing scp in reverse direction (ie. scp is executed on the remote server towards your local machine - it must have a ssh server active).

The solution that is probably closest to what you originally tried is the following:

  1. prepare a script (let's call it /tmp/password) with the following content:

     #!/bin/sh
     echo password
    

    where password is the actual password for user foo on remote server.

  2. chmod 700 /tmp/password so that the file is executable and nobody except owner can access it

  3. copy the file (preserving permissions) to remote server with scp -p /tmp/password foo@myserver:/tmp

  4. use the following command:

     cat myscript.sh | ssh foo@myserver "SUDO_ASKPASS=/tmp/password sudo -A tee -a /etc/init.d/myscript.sh"
    
raj
  • 11,409