Run one script in multiple servers: Difference between revisions

From PedrosBrainDump
 
Line 134: Line 134:
   
   
         print('Executing script')
         print('Executing script')
         stdin, stdout, stderr = client.exec_command(script, timeout=60)
         stdin, stdout, stderr = client.exec_command(script, timeout=600)
   
   
         if user_option == '1':
         if user_option == '1':

Latest revision as of 23:31, 15 November 2024

Using shell script

We will use 3 files to run a single script into multiple server at once.

  • script.sh
  • servers.list
  • run.sh


The file servers.list is a list of all servers you will run the script on.

The file script.sh is the script that will be runned on the servers.

The file run.sh will get all servers into the file serves.list will copy the script.sh to /tmp of each server and execute from the server.

Files

servers.list

server1
server2
server3
.
.
.

script.sh

#!/bin/bash

echo "Hello from $(hostname)"

run.sh

#!/bin/bash

username=USER_USERNAME
password=USER_PASSWORD

list=`cat servers.list`
pack=script.sh

for server in $list; do
        echo ""
        echo $server

        scp_command="sshpass -p "$password" scp -o StrictHostKeyChecking=no -o NumberOfPasswordPrompts=1 -o ConnectTimeout=10 -q $pack $username@$server:/tmp"
        $scp_command

        ssh_command="sshpass -p "$password" ssh -o StrictHostKeyChecking=no -o NumberOfPasswordPrompts=1 -o ConnectTimeout=10 -q $username@$server"

        # running without sudo
        $ssh_command chmod +x /tmp/script.sh
        $ssh_command /bin/sh /tmp/script.sh
        $ssh_command rm -fr /tmp/script.sh

        # running with sudo
        #$ssh_command chmod +x /tmp/script.sh
        #$ssh_command sudo /bin/sh /tmp/script.sh
        #$ssh_command sudo rm -fr /tmp/script.sh

done

Remember that if you want to run the script with sudo on the servers just uncomment what is bellow the "# running with sudo" and comment what is bellow "# running without sudo".

Using python

We will use 3 files to run a single script into multiple server at once.

  • script.sh
  • servers.list
  • run.sh


The file servers.list is a list of all servers you will run the script on.

The file script.sh is the script that will be runned on the servers.

The file run.sh will get all servers into the file serves.list will copy the script.sh to /tmp of each server and execute from the server.

Files

servers.list

server1
server2
server3
.
.
.

script.sh

#!/bin/bash

echo "Hello from $(hostname)"

run.py

import paramiko, datetime

menu = \
"""
1 - Save stdout and stderr to a file
2 - Print stdout and stderr to console
"""

servers_file_path = 'servers.txt'
script_file_path = 'script.sh'

port = 22
username = 'user'
password = 'senha'

while True:
    print("You want to:")
    print(menu)
    user_option = input()
    if user_option == '1':
        break
    elif user_option == '2':
        break
    else:
        print('This option does not exists.')


with open(servers_file_path, 'r') as servers_file:
    servers_list = servers_file.read().lower().split('\n')

with open(script_file_path, 'r') as script_file:
    script = script_file.read()

print("starting the loop")
for server in servers_list:

    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        print('Connecting to server: ', server)
        client.connect(server, port, username, password)

        print('Executing script')
        stdin, stdout, stderr = client.exec_command(script, timeout=600)

        if user_option == '1':
            print('Saving stdout to file')
            for line in stdout:
                with open(f'{server}.txt', 'a+') as asdasd:
                    asdasd.write(line)
            print('Saving stderr to file')
            for line in stderr:
                with open(f'{server}.txt', 'a+') as asdasd:
                    asdasd.write(line)
        else:
            print('Output:')
            for line in stdout:
                print(line)
            for line in stderr:
                print(line)
    except Exception as e:
        print('ERROR: ', e)
    else:
        client.close()

Then just run python3 run.py.