One minute
Python : automate ssh key exchange
Introduction
In this post, I am going to show how powerful python is.
With a simple script, I am going to upload my desktop public key to my servers. The aim of this, is to perform some Ansible automation tasks after our key is present on the targets.
The script
The python script is the following :
#!/usr/bin/env python3
import os
my_servers = ['srv1.demo.fr', 'srv2.demo.fr', 'db.demo.fr', 'poc.demo.fr']
my_users = ['gmancini', 'ansible_user']
for i in my_servers:
for j in my_users:
print('Uploading ssh key for server : ' + i + '\n')
print('Uploading ssh key for user : ' + j + '\n')
os.system('ssh-copy-id ' + j + '@' + i)
Explanations
First, we create a list for our servers. Then, we do the same for our users.
We then have two loops, and for each users we upload the key.
Obviously, this is an example, adapt for your usage.
Execution
We can call for python3 or after a chmod +x
run our script :
Conclusion
Python is a powerful scripting language that all must known.
As you can see, it was really simple and quick to automate some basic tasks.
Note : Mind to use Python3 instead of Python2, as it not supported anymore.