#!/usr/bin/env python # Non-Interactive ssh Connection # $Id: tsshbatch.py,v 1.109 2010/12/15 21:18:35 tundra Exp $ ##### # Suppress Deprecation Warnings until Paramiko catches up # to latest Python modules ##### import warnings warnings.filterwarnings("ignore", "", DeprecationWarning) ##### # Imports ##### import getpass import paramiko import socket import sys ##### # Constants And Literals ##### FAILURE = "FAILURE" INDENTWIDTH = 8 PADWIDTH = 30 SEPARATOR = " ---> " SUCCESS = "SUCCESS" TRAILER = ": " USAGE = "Usage: sshlogin.py serverlistfile command" ##### # Error Messages ##### eBADFILE = "Cannot open '%s'!" eNOCONNECT = "Cannot Connect! (Name/Address Bad? Destination Unreachable?)" eNOLOGIN = "Cannot Login! (Login/Password Bad?)" ##### # Prompts ##### pPASS = "Password: " pUSER = "Username: " ##### # Print Message(s) To stdout ##### def PrintStdout(msg, TERMINATOR="\n"): sys.stdout.write(msg + TERMINATOR) # End of 'PrintStdout()' ##### # Display An Error Message And Exit ##### def ErrorExit(msg): PrintStdout(msg) sys.exit() # End Of 'ErrorExit()' ##### # Process A Command On A Host ##### def HostCommand(host, user, pw, command): ssh = paramiko.SSHClient() # Connect and run the command, reporting results as we go try: ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, username=user, password=pw) stdin, stdout, stderr = ssh.exec_command(command) PrintReport([host, SUCCESS] + stdout.readlines() + stderr.readlines()) except paramiko.AuthenticationException: PrintReport([host, FAILURE, eNOLOGIN]) except socket.gaierror: PrintReport([host, FAILURE, eNOCONNECT]) except socket.error: PrintReport([host, FAILURE, eNOCONNECT]) ssh.close() # End of 'HostCommand()' ##### # Print Report ##### # Expects input as [host, success/failure message, result1, result2, ...] def PrintReport(results): PrintStdout(SEPARATOR + results[0] + TRAILER + (PADWIDTH - len(results[0])) * " " + results[1]) for r in results[2:]: # Command Results PrintStdout(INDENTWIDTH * " " + r.strip()) # End of 'PrintReport()' ##### # Program Entry Point ##### # Make sure we have sufficient command line args if len(sys.argv[1:]) < 2: ErrorExit(USAGE) # Get the list of hosts try: f = open(sys.argv[1]) hosts = f.readlines() f.close() except: ErrorExit(eBADFILE % sys.argv[1]) # Create the command cmd = " ".join(sys.argv[2:]) # Get user name & password uname = raw_input(pUSER) pword = getpass.getpass(pPASS) # Iterate over the list of hosts, executing the command for host in hosts: host = host.strip() if host: HostCommand(host, uname, pword, cmd)