Linux – Copy a local file to a remote server, non-root privileges over sudo

file-copylinuxremotesudo

I'd like to do something like:

scp local_file remote_server:/some_directory

But in order to gain privileges to /some_directory, we need to call sudo. I know that a similar question had already been asked quite a few times here, but most of the answers either took advantage of sudo's password caching (which for some reason doesn't seem to work for me in two consecutive ssh calls) or the fact that we're root (so we can set up a passwordless sudo or make SSH let in root).

In the latter, both of the solutions seem insecure, so I'd rather like to assume that we're not calling sudo to become root and thus can't reconfigure the system. What can be done in such a situation to simply copy a file?

Here are my attempts so far:

( 
read -s -p 'Enter password: ' pass; 
echo $pass ; 
tar cf - local_file ) | ssh -t -t remote_server 'sudo tar -C /some_directory' )

Is there a better way?

Best Answer

I have found an elegant way to work around those issues using a named pipe. The idea is to run your tar command on the remote side through a FIFO socket and make that socket readable by your regular user.

Here is an example. On the remote side, you first create the socket:

remote$ sudo -s 
remote# mkfifo -m 600 /home/anarcat/tmpfifo
remote# chown anarcat /home/anarcat/tmpfifo

On the local side, you can already start reading that socket:

local$ ssh example.net "cat tmpfifo" | pv -s 2G | tar xfz -

(The pv -s 2G | part is entirely optional, to get a nice progress bar with pipe viewer.)

Then on the remote side, you can start writing to it:

remote# tar cfz /home/anarcat/tmpfifo files

This will copy files over through that SSH connexion. Of course, you could have also created that tarball directly on the remote server and made it accessible to the user, but then it would require all the space of the archive, which may not be available.

Once this is done, you can remove the fifo as a simple file:

remote$ rm /home/anarcat/tmpfifo
Related Question