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
.
ssh-copy-id
to do things properly. And of courseStrictHostKeyChecking no
is not a good idea.accept-new
instead ofno
would at least keep some level of protections. – Patrick Mevzek Mar 18 '21 at 15:35