I am trying to overcome some limitations in our environment to write up an authorized SSH file for passwordless ssh keys.

I am requiring to perform an ssh as a to a target system, and then run a "sudo su - , and then update the service account authorized_keys with a key"

This eventually has to go onto my ansible scripts.

I am using "ssh -t user@target "sudo su - service-user" - which actually successfully gets me into a shell for service-user. But I am not able to figure out a way to pass along the file modify commands with the above.

Any tips or alternative options?

Note: I need to use "ssh -t" option as the requiretty is not set on target systems.


  • 3
    Just a side note, doing sudo su - service-user is a bit overkill: it runs the su command as root just to drop down again to a different user. If you want an interactive session, you can get the same effect with sudo -iu service-user. This may allow you to tighten up the sudoers file a bit too. – Tom Shaw Jul 22 '16 at 8:30

Assuming you want to overwrite service-user's authorized_keys file with a completely new version, you could do something like this:

cat master_authorized_keys |
    ssh -t user@target \
        "sudo -u service-user tee ~/.ssh/authorized_keys >/dev/null"

I don't know if the -t there is really necessary, but maybe it is in your environment.

  • Yep had figured out the same as above after much trial and error. Cheers! – user2074161 Jul 25 '16 at 23:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.