簡體   English   中英

Paramiko exec_command stdout,stderr,stdin到日志記錄器

[英]Paramiko exec_command stdout, stderr, stdin to logging logger

我有一個客戶端,我反對使用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())

無法讀取stdin 它是只寫的。

您應該只讀取stdoutstderr

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM