Newer
Older
tsshbatch / tsshbatch.py
#!/usr/bin/env python
# Non-Interactive ssh Connection
# $Id: tsshbatch.py,v 1.107 2010/12/15 16:30:32 tundra Exp $

import paramiko
import socket
import sys


#####
# Constants And Literals
#####

INDENTWIDTH = 8
PADWIDTH    = 30
FAILURE     = "Command Failed"
SEPARATOR   = " --->  "
USAGE       = "Usage:  sshlogin.py username password hostname command"


#####
# Error Messages
#####

eNOCONNECT    =  "Cannot Connect! (Name/Address Bad?  Destination Unreachable?)"
eNOLOGIN      =  "Cannot Login! (Login/Password Bad?)"

#####
# Print Message(s) To stdout
#####

# Expects an iterable object as input

def PrintStdout(messages, TERMINATOR="\n"):

    for msg in messages:
        sys.stdout.write(INDENT + 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

INDENT = ""
PrintStdout([host + SEPARATOR])
INDENT += " " * INDENTWIDTH

# 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.readlines())
    
except paramiko.AuthenticationException:
    PrintStdout([eNOLOGIN])

except socket.gaierror:
    PrintStdout([eNOCONNECT])

except socket.error:
    PrintStdout([eNOCONNECT])