Deploy data to multiple servers with Python


One of easiest way to upload files into multiple servers via ssh is using a script that send data uses scp/sshpass and a list of connection data. For this purpose I like to use a Python language.

Firstly, define an array with IP and pasword data in logindata.py file:

ip_list = [('5.1.1.2', 'password1'),
   ('5.1.1.3', 'password2'),...
   ('5.1.1.N', 'passwordN')]

Using separate file for logina data is preferred because you can use multiple similar files with different data, and/or multiple scripts with uses that data to connect.

Okay, now we can create upload script (e.g. multi-scp.py) itself:

from subprocess import call
from logindata import ip_list

user = 'root'
local_path = 'uploads/*'
remote_path = '/root/'

for (ip, password) in ip_list:
    print("--------------\nMoving to %s" % ip)
    call(['sshpass -p%s scp -r %s %s@%s:%s' %
          (password, local_path, user, ip, remote_path)], shell=True)

Here we read ip_list array set by set and use IP address and password for substitution into a sshpass command. Username, local and remote paths are hardcoded in this case.

And now, to upload 20 files to 20 different servers is enough to run only one this script once:

./multi-scp.py

To be continued...

 

Comments

Popular posts from this blog

Installing and using a free GeoIP database

Create custom Spinner on ActionBar