Linux – How to Copy File from One User to Another

cpfileslinuxsudousers

I'm trying to copy a file from my home directory to another user's directory. I have a sudo access for the other user with no password. I tried doing something like:

sudo secondUser cp /home/firstUser/file /home/secondUser 

is there a way to do that? also I have no root access and I don't know the password of the secondUser.

Best Answer

EDIT: There is a way to do this quickly and easily with no additional setup.

cat ~firstUser/file | sudo -u secondUser tee ~secondUser/file >/dev/null

This will transfer all the file's content exactly. If you care about having the file permissions and/or timestamps match the original, you will need to fix those separately using chmod and touch.


ORIGINAL ANSWER:

The problem here is that:

  • secondUser doesn't have access to your home directory.
  • You don't have access to secondUser's home directory.

As such, regardless of whether you run the cp command as yourself or as secondUser, it can't perform the file copy.

Given that you said you don't have root access, the obvious answer is to copy the file through an intermediate world-readable location such as /tmp and change the permissions of the file to world-readable. If the data in the file is sensitive you may not want to do this, however, because anyone on the server will be able to read the file while it is in transit. If it's not sensitive data, just do:

cp file /tmp/
chmod a+r /tmp/file
sudo -u secondUser cp /tmp/file ~secondUser
rm /tmp/file

A better option, if you can arrange it, is to make a group that contains only you and secondUser, and chgrp the copy of the file in /tmp to be owned by that group. This way you don't need to make the file world-readable, but only readable by the group (with chmod g+r /tmp/file). However, groupadd itself requires root access, so this is unlikely to be easy to arrange. Depending on the circumstances (if you are frequently trying to share/collaborate with secondUser it might be applicable), you could consider asking your administrator to set up this group for future use.

Related Question