Copying remote files while changing ownership

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:

  • User samuel, the customer who needed work done
  • User orion, a pseudo-user account associated with his project
  • Host collector, where the source data files live
  • Host analyser, where the data files need to be visible
  • Host filer, the NFS server
  • Filesystem /mnt/datastore on analyser is NFS-mounted from filer

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:

  • The NFS export on filer has the standard root_squash option. So user root on analyser is a completely unprivileged user in the NFS-mounted /mnt/datastore filesystem.

  • User samuel also has no direct login access to filer, so the operation can only happen from analyser.

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.


  • samuel uses ssh to launch tar on collector;
  • GNU tar by default sends its output to stdout, so it gets piped to the second half of the command;
  • on analyser, that input is piped to a tar command owned (thanks to sudo) by user orion.

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.