【问题标题】:Paramiko exec_command stdout, stderr, stdin to logging loggerParamiko exec_command stdout、stderr、stdin 到日志记录器
【发布时间】:2019-07-01 18:57:35
【问题描述】:

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

有没有办法使用 python 日志记录 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())

【问题讨论】:

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


    【解决方案1】:

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

    您应该只阅读stdoutstderr

    【讨论】: