Moshe Vayner
Moshe Vayner

Reputation: 798

Python Paramiko log output of commands to a file

I am writing a script that will get a list of servers and run service something restart ; service something status commands. I am using paramiko SSHClient in order to do that, with the below function:

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()

My question is: How can I set the paramiko logger to write the output of my commands to the log as well? I don't need to get all the debug info, all I care about it that I'll have the results of service restart and service status commands in the file as well.

The logger configuration I've set is:

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

I've also tried to use logger = paramiko.util.logging.getLogger() as suggested in other threads I've found, but that didn't help either..

Thanks!

Upvotes: 0

Views: 11218

Answers (1)

Ciaran Liedeman
Ciaran Liedeman

Reputation: 779

Don't use the paramiko logger. Rather create your own.

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()

This way you can have fine grained control about exactly what you want to log and which information is important to you

Upvotes: 2

Related Questions