Paramiko exec_command stdout,stderr,stdin到日志记录器

时间:2019-06-29 00:10:21

标签: python python-3.x logging ssh paramiko

我有一个客户端,我反对使用Paramiko运行exec_commands。

是否存在使用pythons日志记录将stderrstdoutstdin记录到记录器的方法?我尝试使用以下功能没有成功。

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()))

上面的脚本引发IO错误,表明文件未打开以供读取。

以下是我的getLogger函数:

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

尝试使用以上方法的大概输出:

  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

当前解决方法:

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

1 个答案:

答案 0 :(得分:1)

stdin无法读取。它是只写的。

您应该只阅读stdoutstderr