Copying remote files while changing ownership

By Paul Heinlein | Nov 18, 2015

Someone at work encountered an interesting obstacle today. The problem was how to change ownership of files in transit to an NFS filesytem that squashed activity by user root. Solving it required a quirky shell one-liner that you may find interesting.

I’m going to change the names of all the people and machines involved, but here are the players:

The goal: Copy files readable by user samuel from host collector into /mnt/datastore on analyser, changing their ownership to user orion.

User samuel has a full set of sudo rights on the host analyser.

The obstacles:

So samuel can copy files from collector to analyser easily enough if he retained ownership of them. His root privileges, however, don’t allow him to change ownership of those files to user orion, since root is unprivileged in that part of the filesystem.

To shorten a long story, here’s the scriptlet that ended up accomplishing his task:

# done on analyser
(ssh collector tar -cC /source .) | sudo -u orion -s tar -xC /mnt/datastore

As-is, this operation relies on the GNU version of tar. It could be accomplished with a non-GNU version; the subshells would need to include cd commands to make it work.

Essentially,

So the files owned (or at least readable by) user samuel on collector end up on analyser owned by user orion—and all done in one command invocation.