johnnyb
johnnyb

Reputation: 1825

Paramiko exec_command stdout, stderr, stdin to logging logger

I have a client, I run exec_commands against using Paramiko.

Is there a way to log the stderr, stdout, stdin to a logger using pythons logging? I have tried using the below function with no success.

def client_exe(hostname, command, username, password):
    logger = getLogger("EXEC", "log.log")
    #paramiko.util.log_to_file("log.log", level="DEBUG")
    ssh_client = paramiko.SSHClient()
    ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh_client.connect(hostname=hostname, username=username, password=password)
    stdin, stdout, stderr = ssh_client.exec_command(command, get_pty=True)
    logger.info(
        "Remote Machine: {} \n\tCommand: {} \n\tSTDIN: {} \n\tSTDOUT: {} \n\tErrors: {}".format(
        hostname, command,                                                                                                    
        stdin.readlines(),
        stdout.readlines(),
        stderr.readlines()))

The above script raises an IO error saying the file is not open for reading.

The below is my getLogger function:

def getLogger(name, logname):
    logger = logging.getLogger(name)
    fmt = logging.Formatter("%(asctime)s %(levelname)s: %(message)s", datefmt='%m/%d/%Y %I:%M:%S %p')
    fileHandler = logging.FileHandler(logname, mode="a")
    fileHandler.setFormatter(fmt)
    streamHandler = logging.StreamHandler()
    streamHandler.setFormatter(fmt)
    logger.setLevel(logging.DEBUG)
    logger.addHandler(fileHandler)
    logger.addHandler(streamHandler)
    return logger

Approximate output of attempting to use the above:

  File "/home/<MYPATH>/distro.py", line 89, in <module>
    client_exe("192.168.xxx.xxx", "ls -la")
  File "/home/<MYPATH>/distro.py", line 52, in client_exe
    logger.info("Remote Machine: {} \n\tCommand: {} \n\tSTDIN: {} \n\tSTDOUT: {} \n\tErrors: {}".format(hostname, command, stdin.readlines(), stdout.readlines(), stderr.readlines()))
  File "/home/<MYPATH>/venv/lib/python3.7/site-packages/paramiko/file.py", line 349, in readlines
    line = self.readline()
  File "/home/<MYPATH>/venv/lib/python3.7/site-packages/paramiko/file.py", line 257, in readline
    raise IOError("File not open for reading")
OSError: File not open for reading

Process finished with exit code 1

Current Workaround:

print(file=logger.debug("{}\n{}\n{}".format(stdin.readlines(), stdout.readlines(), stderr.readlines())

Upvotes: 1

Views: 2238

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202682

stdin cannot be read. It is write-only.

You should read only the stdout and stderr.

Upvotes: 3

Related Questions