【问题标题】:Python Paramiko log output of commands to a filePython Paramiko 将命令输出到文件
【发布时间】:2015-09-13 08:04:03
【问题描述】:

我正在编写一个脚本,它将获取服务器列表并运行service something restart ; service something status 命令。 我正在使用 paramiko SSHClient 来做到这一点,具有以下功能:

def restart_service(node_name):
    print('='*30 + '  Starting to work on ' + node_name + '  ' + '='*30 + '\n')
    logging.info('Connecting to %s in order to restart %s...', node_name, service_name)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.load_system_host_keys()
    ssh.connect(node_name)
    channel = ssh.get_transport().open_session()
    channel.exec_command(command)
    while True:
        if channel.exit_status_ready():
            break
        rl, wl, xl = select.select([channel], [], [], 0.0)
        if len(rl) > 0:
            print channel.recv(1024)
    ssh.get_transport().close()
    ssh.close()

我的问题是:如何设置 paramiko 记录器以将我的命令输出也写入日志?我不需要获取所有调试信息,我只关心文件中还有服务重启和服务状态命令的结果。

我设置的记录器配置是:

logging.basicConfig(filename='./log_restartService.log', level=logging.INFO, format='%(asctime)s  %(levelname)s: %(message)s')
logging.getLogger("paramiko").setLevel(logging.INFO)

我也尝试按照我发现的其他线程中的建议使用logger = paramiko.util.logging.getLogger(),但这也无济于事..

谢谢!

【问题讨论】:

    标签: python logging paramiko


    【解决方案1】:

    不要使用 paramiko 记录器。而是创建自己的。

    import logging
    logger = logging.getLogger(__name__)
    
    def restart_service(node_name):
        print('='*30 + '  Starting to work on ' + node_name + '  ' + '='*30 + '\n')
        logging.info('Connecting to %s in order to restart %s...', node_name, service_name)
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.load_system_host_keys()
        ssh.connect(node_name)
        channel = ssh.get_transport().open_session()
        channel.exec_command(command)
        while True:
            if channel.exit_status_ready():
                break
            rl, wl, xl = select.select([channel], [], [], 0.0)
            if len(rl) > 0:
                # Log output
                logger.info(channel.recv(1024))
        ssh.get_transport().close()
        ssh.close()
    

    通过这种方式,您可以精确控制要记录的内容以及哪些信息对您很重要

    【讨论】:

    • 谢谢!这确实按预期工作,但是现在我在运行脚本时看不到输出,这不方便在脚本运行时实时监控输出。我是否可以选择保留之前的“print(channel.recv(1024))”设置以及您建议的记录器配置?
    • 知道了!在这里找到答案:stackoverflow.com/questions/14058453/…
    猜你喜欢
    • 1970-01-01
    • 2017-02-26
    • 2012-06-29
    • 2018-01-28
    • 2021-05-05
    • 1970-01-01
    • 1970-01-01
    • 2015-06-26
    • 2020-11-04
    相关资源
    最近更新 更多