-1

I'm trying to copy a file (contains keys) to remote machine using below script. But the below error

/root/.ssh/authorized_keys: Permission denied

#!/bin/bash

for i in cat hosts

do cat team.keys | sshpass -f pass ssh -t -o "StrictHostKeyChecking no" normal_user@ad@${i} "sudo cat >> /root/.ssh/authorized_keys";

done

-- Please share you suggest to identify solution.

Kusalananda
  • 333,661

1 Answers1

3
sudo cat >> /root/.ssh/authorized_keys

This command will not do what you think it does.

The shell (running as a regular user) will implement the redirection before it even begins to execute the sudo cat command. As a result, the redirection happens as a non-root user, which clearly won't have permission to write into root's authorized_keys file.

The standard workaround is to use the tee command with sudo instead:

#!/bin/bash

for i in $(cat hosts)

do cat team.keys | sshpass -f pass ssh -t -o "StrictHostKeyChecking no" \ normal_user@ad@${i} "sudo tee -a /root/.ssh/authorized_keys >/dev/null"

done

In this version, the remote shell running as normal_user@ad will execute the command as sudo <some parameters for sudo> >/dev/null, and the sudo command will gain root access and execute tee /root/.ssh/authorized_keys.

The tee command will receive the keys piped in from standard input, and will write one copy of its input into the /root/.ssh/authorized_keys file, which it can do because it's running as root, and pass another copy into standard output. The extra copy goes back to the first remote shell running as normal_user@ad, which will then send it to /dev/null.

telcoM
  • 96,466