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

Posted 灬魑魅魍魉灬

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了远程执行命令,下载文件,上传文件(并记录日志)相关的知识,希望对你有一定的参考价值。

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)

 

以上是关于远程执行命令,下载文件,上传文件(并记录日志)的主要内容,如果未能解决你的问题,请参考以下文章

python3 远程Linux服务器执行命令和上传下载文件

Python使用paramiko远程连接服务器及上传文件

Python Paramiko实现sftp文件上传下载以及远程执行命令

python 实现ssh远程执行命令 上传下载文件

python写的批量操作远程主机脚本(命令执行,上传下载文件)

Python远程登录Linux操作系统,执行命令创建目录上传及下载文件