Paramiko exec_command 标准输出、标准错误、标准输入到日志记录器

Paramiko exec_command stdout, stderr, stdin to logging logger

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

有没有办法使用 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())

stdin 无法读取。是 write-only.

您应该只阅读 stdoutstderr