Python Paramiko将命令的日志输出到fi

2024-04-29 15:05:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个脚本,它将获取服务器列表并运行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(),正如我发现的其他线程中所建议的那样,但这也没有帮助。。

谢谢!


Tags: toname命令nodehostparamikologgingstatus
1条回答
网友
1楼 · 发布于 2024-04-29 15:05:59

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

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

相关问题 更多 >