How to run Linux commands on multiple targets

Home > Search > How-to
  by

This Python script can be used to execute a Linux command on multiple targets. This assumes a single username and password can be used on the targets.

This script will only work if you are able to make an SSH connection to the target server with a username and password. If the SSH server is configured to only accept connections using a public/private key pair, this script will not be able to connect to the SSH server.

#!/usr/bin/python
###############
# MODULES
###############
import paramiko
import sys
import getpass

###################
# VARIABLES
###################
myUsername = "root"
myPassword = getpass.getpass("Enter your SSH password: ")
target_servers = ('server1' 'server2' 'server3')

################################
# FOR EACH LOOP
################################
for myServers in target_servers:
  servers = myServers.rstrip()
  ssh = paramiko.SSHClient()
  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  ssh.connect(server,username=myUsername,password=myPassword)

  # Enter Linux command inside the double quotes
  stdin, stdout, stderr = ssh.exec_command("")

  out = stdout.readlines()
  filtered = filter(lambda x:not '256\\nAlias' in x, out)
  print bcolors.YELLO + "Server Name: " + server + bcolors.ENDC
  print bcolors.FAIL + ''.join(filtered) + bcolors.ENDC
  ssh.close()

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments