码迷,mamicode.com
首页 > Web开发 > 详细

远程执行命令,下载文件,上传文件(并记录日志)

时间:2017-11-23 16:34:38      阅读:320      评论:0      收藏:0      [点我收藏+]

标签:connect   evel   tde   policy   transport   local   tran   user   erro   

import paramiko,os
import logging
class ssh_host(object):
    def __init__(self,host_ip,password,port=22,user=root,log_file=ssh_host.log):
        self.host_ip = host_ip
        self.password = password
        self.port = port
        self.user = user
        self.log_file = log_file

    def __connect(self):
        transport = paramiko.Transport((self.host_ip,self.port))
        transport.connect(username=self.user, password=self.password)
        sftp = paramiko.SFTPClient.from_transport(transport)
        return transport,sftp
    def __Logger(self,method):
        logger = logging.getLogger(method)
        formatter = logging.Formatter(%(asctime)s %(levelname)-8s:%(message)s)
        file_handler = logging.FileHandler(self.log_file)
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)
        logger.setLevel(logging.INFO)
        return logger
    def run_sys(self,command):
        logger = self.__Logger(run_sys)
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(hostname=self.host_ip, port=self.port, username=root, password=self.password)
        stdin, stdout, stderr = ssh.exec_command(command)
        if len(stderr.read().decode()) != 0:
            logger.error("%s:%s<==>%s" % (self.host_ip, command, stderr.read().decode()))
        print(command)
        print(stdout.read().decode())  # 输出结果
        print(stderr.read().decode())
        ssh.close()
        return stdin, stdout, stderr
    def download_file(self,filename,local_path=F://BaiduNetdiskDownload//):
        logger = self.__Logger(download_file)
        connect,sftp = self.__connect()
        sftp.get(filename,local_path+os.path.basename(filename))
        logger.info(%s:%s download %s%(self.host_ip,filename,local_path))
        connect.close()
    def upload_file(self,filename,local_path=F://BaiduNetdiskDownload//):
        logger = self.__Logger(upload_file)
        connect, sftp = self.__connect()
        sftp.put(local_path+os.path.basename(filename),filename)
        logger.info(%s:%s upload %s%(self.host_ip,local_path,filename))
        connect.close()
host1 = ssh_host(192.168.71.3,zedata)
host1.run_sys(pwd)
#host1.upload_file(‘/root/bad.txt‘)
host1.download_file(/root/bad.txt)

 

远程执行命令,下载文件,上传文件(并记录日志)

标签:connect   evel   tde   policy   transport   local   tran   user   erro   

原文地址:http://www.cnblogs.com/chimeiwangliang/p/7885237.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!