Transferring sudo-accessible files between servers without intermediary files
August 4, 2023(August 23, 2023)
Copy a sudo-accessible file to another server without creating an intermediate file #
One can use the tar
and ssh
commands together to transfer a file that requires sudo access from one server to another without creating an intermediate file.
Here are the steps to accomplish this:
-
On the source server, run the following command:
sudo tar czvf - /path/to/source/file | ssh username@targetserver 'cat > /path/to/destination/file.tar.gz'
This command uses sudo to run the tar command, which archives the file and then sends the archive to another server via ssh.
-
On the target server, run the following command:
sudo tar xzvf /path/to/destination/file.tar.gz -C /final/path/to/destination
This command uses sudo to extract the archive.
Streamlining the process with a single-line command #
The following command performs a series of operations in a single line: it archives a file from the source server, sends it to the target server, and immediately unpacks the archive on the target server.
On the source server, run the following command:
sudo tar czvf - /path/to/source/file | ssh username@targetserver 'sudo tar xzvf - -C /final/path/to/destination'
Note that sudo
on the target server may require a password. This may complicate automation on some systems, so please consult with your administrator for the best solution, such as temporary passwordless sudo.
Note #
Permission requirements for tar extraction #
Whether administrative privileges (sudo
) are required when extracting an archive using the tar
command depends on the permissions set on the directory where the extraction takes place.
If the directory where the extraction takes place allows write access for a general user (e.g. the user logged in via ssh), sudo
is not required. Conversely, if the directory only allows write access to the root user (or a specific group), you have to use sudo
to execute the tar
command.
Note that sudo
is also required when running tar
if the original file is owned by the root user, and you want to preserve that, or if you want to extract a file to a system directory (for example, /etc
or /var
).
The use of the -p
option with the tar
command
#
The -p
(or --preserve-permissions
) option in the tar
command is used to preserve the original file or directory permissions (ownership information and access rights) during the extraction process.
If you need to preserve the original permissions(e.g. you want to keep the owner, group, and other permissions of the files or directories the same), you would use this option.