#!/usr/local/bin/python3.4
# Copyright (c) 2015,
#
# This module is free software; you can redistribute it and/or modify it
# under the terms of GNU General Public License (GPL) version 2.

import logging
import paramiko
import socket


def invokeSshCommand(host,userid,password,command):
    """
    Logins in, runs a single command and exits.
    Returns the stdout of the command run.
    raises paramiko.AuthenticationException
    raises socket.timeout
    """
    _METHOD_ = "invokeSshCommand"
    try:
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(host, username=userid,
                       password=password, timeout=30)
        (stdin, stdout, stderr) = client.exec_command(command)
        stdin.close()
        return stdout.read().decode('ascii')
    except paramiko.AuthenticationException:
        logging.error("%s::userid/password combination not valid. host=%s userid=%s",
                _METHOD_,host,userid)
        raise
    except socket.timeout:
        logging.error("%s::Connection timed out. Address=%s",_METHOD_,host)
        raise
    finally:
        client.close()

