python paramiko和logging的小例子

logging:

import logging

class Log(object):
    """personal log module for study"""

    def __init__(self, path, clevel=logging.DEBUG, flevel=logging.DEBUG):
        self.logger = logging.getLogger(path)
        self.logger.setLevel(logging.DEBUG)
        fmt = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s ', '%Y-%m-%d %H:%M:%S')
        sh = logging.StreamHandler()
        sh.setFormatter(fmt)
        sh.setLevel(clevel)

        fh = logging.FileHandler(path)
        fh.setLevel(flevel)
        fh.setFormatter(fmt)
        self.logger.addHandler(sh)
        self.logger.addHandler(fh)

    def debug(self, msg):
        self.logger.debug(msg)

    def info(self, msg):
        self.logger.info(msg)

        def warn(self, msg):
        self.logger.warning(msg)

    def err(self, msg):
        self.logger.error(msg)

    def crit(self, msg):
        self.logger.critical(msg)

def main():
    log = Log('tst.log', logging.DEBUG, logging.DEBUG)
    log.debug('this is debug msg')
    log.info('this is msg of info')
    log.err('this is msg of error')
    log.warn('this is msg of warning')
    log.crit('this is msg of critical!!!')

if __name__ == '__main__':
    main()

paramiko:

# coding = utf-8

import paramiko
import logging
import logtry

class SSHhandle(object):

    def __init__(self, host, port=22, username='root', password='password'):
        self.host = host
        self.port = port
        self.username = username
        self.password = password

    def connect(self):
        transport = paramiko.Transport(self.host, self.port)
        transport.connect(username=self.username, password=self.password)
        self.__transport = transport

    def close(self):
        self.__transport.close()

    def exc_cmd(self, cmd):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh._transport = self.__transport  # 巧妙的使用了ssh的私有属性
        stdin, stdout, stderr = ssh.exec_command(cmd)
        print('the excute cmd is: %s' %cmd)

        return stdout.read()

    def sftp_put(self, localpath, remotepath):
        sftp = paramiko.SFTPClient.from_transport(self.__transport)
        sftp.put(localpath, remotepath)

 def main():
    sh = SSHhandle('192.168.100.217')
    sh.connect()
    log = logtry.Log('tst.log', logging.DEBUG, logging.DEBUG)
    ret = sh.exc_cmd('ls -l /opt',)
    log.info('The cmd excute result is :%s' % ret)
    sh.sftp_put('test.txt', '/opt/text')
    sh.close()

if __name__ == '__main__':
    main()
  

 

你可能感兴趣的:(python,Python)