How to copy a directory which root can’t access to a directory that only root can access

file-copypermissionsroot

I have a directory on an nfs mount, which on the server is at /home/myname/.rubies

Root cannot access this directory:

[mitchell.usher@server ~]$ stat /home/mitchell.usher/.rubies
  File: `/home/mitchell.usher/.rubies'
  Size: 4096            Blocks: 8          IO Block: 32768  directory
Device: 15h/21d Inode: 245910      Links: 3
Access: (0755/drwxr-xr-x)  Uid: (  970/mitchell.usher)   Gid: (  100/   users)
Access: 2016-08-22 15:06:15.000000000 +0000
Modify: 2016-08-22 14:55:00.000000000 +0000
Change: 2016-08-22 14:55:00.000000000 +0000

[mitchell.usher@server ~]$ sudo !!
sudo stat /home/mitchell.usher/.rubies
stat: cannot stat `/home/mitchell.usher/.rubies': Permission denied

I am attempting to copy something from within that directory to /opt which only root has access to:

[mitchell.usher@server ~]$ cp .rubies/ruby-2.1.3/ -r /opt
cp: cannot create directory `/opt/ruby-2.1.3': Permission denied

[mitchell.usher@server ~]$ sudo !!
sudo cp .rubies/ruby-2.1.3/ -r /opt
cp: cannot stat `.rubies/ruby-2.1.3/': Permission denied

Obviously I can do the following (and is what I've done for the time being):

[mitchell.usher@server ~]$ cp -r .rubies/ruby-2.1.3/ /tmp/
[mitchell.usher@server ~]$ sudo cp -r /tmp/ruby-2.1.3/ /opt/

Is there any way to do this that wouldn't involve copying it as an intermediary step or changing permissions?

Best Answer

You can use tar as a buffer process

cd .rubies
tar cf - ruby-2.1.3 | ( cd /opt && sudo tar xvfp - )

The first tar runs as you and so can read your home directory; the second tar runs under sudo and so can write to /opt.

Related Question