代码之家  ›  专栏  ›  技术社区  ›  Moshe Shitrit

Python Paramiko将命令输出记录到文件

  •  0
  • Moshe Shitrit  · 技术社区  · 9 年前

    我正在编写一个脚本,该脚本将获取服务器列表并运行 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() 正如我发现的其他线程中所建议的,但这也无济于事。。

    谢谢

    1 回复  |  直到 9 年前
        1
  •  1
  •   Ciaran Liedeman    9 年前

    不要使用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()
    

    这样,您就可以精确地控制要记录的内容以及哪些信息对您很重要