Sometimes I need to quickly copy SSH keys to remote systems in a pinch. I can do this with the Ansible authorized_key module but that’s not always available. I might be on a random system and Ansible or external internet isn’t available and things need to be pushed out quickly. Here’s a simple interactive tool to quickly push SSH keys to many hosts, may you never SSH for loop again.
Copy the Tool
Copy the tool from my github below somewhere local or just clone my repo.
wget https://raw.githubusercontent.com/sadsfae/misc-scripts/master/python/ssh-key-copy.py
Run the Tool
Have a list of hosts handy (one per line) and the SSH public keys you want copied and run the tool. You’ll paste your hosts and SSH keys, hit ENTER to signify an empty line to tell the tool you are done entering the data.
./ssh-key-copy.py
--------------------------- | SSH Key Copier 5000 | --------------------------- Enter Target Hosts
Enter or Copy your Host List
Enter Target Hosts 192.168.122.81 192.168.122.82
Copy your SSH Keys
Enter SSH Keys
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAgEAtX0bAdKVSDeQa4PCN4bLLAqjR0DExUB1lhG1q4jPf9tWwWJ1cRqG3wn7CEqlItiankKdqd+8eZHTGgmBft761il8eRkwNHIFrW+jPzOL8MdPOK66TXUo0myNO/9XhjiXtwR4VkANjAqJUFXTkgSXj9nz0rkrHGVYYWvPBvg5KiZm5/ba+ndvyQWc5vDhv8dIKo17uZ5DC6DOcCQs4y6QhYxxVAiqIZaFeFkgRw4Ebkx+MhZ1VrVByOC2PZtj2drwGAa7ItX2i4idIaKTRBI9pehL4ay4NGbzdUeEP304XTukO8A/q0rCstZEGLqxXgzTaAXTI6DJ0iS8Y0QNk5vwnxBvDBE2oOuZFguQFyNAOkvy+61Tnp6waE05Ss/ZU3J861+fiCJJ1o3waas80qOAIwVTaIwGQ/FTJngZutRcLkdTC21+qaRbW9ZbTIG+bUp1NKAhj84HSsNc8CTcwNEcv8nwi0Cy4ZXY88+DcO5n6CmFFOm7sXTr0umrhBsKThhkCfFrzN8YTuu3KOcr+vVgZWcEJG+vRSXyl3onFL
Keys Are Copied
You’ll see progress as your keys are copied to external systems.
Copying SSH Keys to 192.168.122.81 Copying SSH Keys to 192.168.122.82
Riding Dirty or Ansible?
This is a very simple tool but it’s something I never want to do again with a shell for loop. I would consider things like this to be one-off but repeatable enough to warrant the time to write a tool.
If you’re managing persistent states of systems properly Ansible is a better choice, it is designed for this type of thing. You might manage your public SSH keys in a git repo and have Ansible ensure it matches what is on remote servers.
Below you can simply add/remove keys as the organization changes and Ansible will make sure your systems stay in the correct state.
# Manage Admin Keys - name: Set up authorized_keys for the sysadmins authorized_key: user=admin key="{{ item }}" with_file: - public_keys/ops-mary - public_keys/ops-bob
Update 2019-02: I have written an Ansible playbook that manages this here.
Gonza Rafuls has also authored a better Python/Paramiko way to do this via a standalone tool found here that allows you to pass in the SSH password if you don’t already have your keys on the remote system(s) and doesn’t prompt you.