SSH and SCP with another user

Here is the scenario. You need to connect to a remote server to execute some commands, copy files to and copy files from. There are two users: user1 can only login through ssh, but is not allowed to see the files of user2. So, on the fly user change is needed.

It is assumed that, in all scenarios it is necessary to configure sudo command to not require a password to switch to user2.

Here is how to handle three different scenarios with bash and ant examples.

A) Execute commands on the 2nd server as a different user.

i) Simple scenario. If user1 needs no password.
ssh user1@host 'sudo -u user2 ls -l'

ii) Difficult scenario. If user1 needs a password. Since ssh does not have the ability to provide the password on the command line, we will be using the sshpass tool.
sshpass -p 'your_password' ssh user1@host 'sudo -u user2 ls -l'

iii) More difficult scenario. User1 needs a password, you are connecting the host for the first time and you do not want the question to add the host key to your known_hosts file be asked and also you want ssh to be as much as quiet.
sshpass -p 'your_password' ssh -q -o StrictHostKeyChecking=no user1@host 'sudo -u user2 ls -l'

NOTE: If you are using Redhat or CentOS v4, v5 or v6; you will need to edit /etc/sudoers file to allow connecting without tty. If using bash, you can force ssh to allocate a pseudo-tty by the ssh command line option -t or -t -t but for example if you are using ant to execute these commands, usepty might or might not work. So, the best thing is to comment out the following lines in /etc/sudoers file:
# Defaults requiretty
# Defaults !visiblepw

B) Copy file(s) from local server to remote server, connecting to the remote server as user1 but switching to user2 on the fly and that way managing the owner of file(s) to be created be user2.

i) Single file, by using dd command.
dd if=local.file | sshpass -p 'your_password' ssh -q -o StrictHostKeyChecking=no user1@host 'sudo -u user2 /bin/dd of=remote.file'

ii) Multiple files at a certain folder, by using tar command.
tar czf - -C /path/to/certain/folder . | sshpass -p 'your_password' ssh -q -o StrictHostKeyChecking=no user1@host 'sudo -u user2 tar xzf - -C /path/to/extract/folder'

C) Copy file(s) from remote server to local server, connecting to the remote server as user1 but copying files that are owned by user2 and user1 has no authorization to read files owned by user2. A user switch on the fly solves our problem.

i) Single file, by using dd command.
sshpass -p 'your_password' ssh -q -o StrictHostKeyChecking=no user1@host 'sudo -u user2 dd if=/path/to/remote/file' |dd of=/path/to/local/file

Leave a comment