#!/usr/bin/env python # Non-Interactive ssh Connection # $Id: tsshbatch.py,v 1.104 2010/12/14 19:31:11 tundra Exp $ import paramiko import sys ##### # Constants And Literals ##### PADWIDTH = 35 FAILURE = "Command Failed" SEPARATOR = " ---> " USAGE = "Usage: sshlogin.py username password hostname command" ##### # Print Message(s) To stdout ##### # Expects an iterable object as input def PrintStdout(messages, TERMINATOR="\n"): for msg in messages: sys.stdout.write(msg + TERMINATOR) # End of 'PrintStdout()' ##### # Display An Error Message And Exit ##### def ErrorExit(msg): PrintStdout([msg]) sys.exit() # End Of 'ErrorExit()' ##### # Program Entry Point ##### # Unpack command line arguments if len(sys.argv[1:]) >= 4: user, pw, host = sys.argv[1:4] cmd = " ".join(sys.argv[4:]) # Otherwise let the user know else: ErrorExit(USAGE) ssh = paramiko.SSHClient() # Report attempt hostid = host + SEPARATOR PrintStdout(hostid + (" " * (PADWIDTH - len(hostid))), TERMINATOR="") # 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(cmd) PrintStdout(stdout, TERMINATOR="") PrintStdout([""]) except: PrintStdout([FAILURE])