python ssh 管理服务器class

# -*- coding: utf-8 -*-
"""
ssh 远程  控制类, 和SCP 文件上传下载
"""

import paramiko

"""
from libs_opsp.ssh_class import *
ssh = ShhClass('192.1.1.1', 'root', '1111', sshtype=3)
print ssh.Errorinfo
#print ssh.getexe('lss /', datatype=2)
a = {"Sfile": "/root/Twisted-13.2.0.tar.bz2", "Dfile": "/root/aa", "Type": 1}
c = {"Sfile": "/root/aa", "Dfile": "/root/dddll.tar.bz2", "Type": 2}
print ssh.batch(1,['ls /etc/', 'pwd'])
print ssh.batch(2,[a, c])
"""
class ShhClass:
    def __init__(self,host,user,pwd,port=22,sshtype=1):
        """ sshtype 链接类型  1 initexe, 2 initscp, 3 initexe and initscp"""
        self.host = host
        self.user = user
        self.pwd = pwd
        self.port = port
        
        self.Error = True
        self.Errorinfo = None
        
        #初始化  链接
        if sshtype == 1:
            self.initexe()
        elif sshtype == 2:
            self.initscp()
        elif sshtype == 3:
            self.initexe()
            self.initscp()
            
        print self.client.set_log_channel('aa')
        
        
        
    def initexe(self): # 远程 命令 执行 链接初始化
        try:
            self.client = paramiko.SSHClient()
            self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.client.load_system_host_keys()
            self.client.connect(self.host,port=self.port,username=self.user,password=self.pwd)
                 
        except paramiko.AuthenticationException as a:
            self.Error = False
            self.Errorinfo = a
            
        except:
            self.Error = False
            self.Errorinfo = 'No route to host or port is no.'
            
            
    def initscp(self): #scp 文件传输  链接初始化
        try:
            self.scpclient = paramiko.Transport((self.host, self.port))
            self.scpclient.connect(username=self.user, password=self.pwd)
        
            self.sftp = paramiko.SFTPClient.from_transport(self.scpclient)
        except paramiko.AuthenticationException as a:
            self.Error = False
            self.Errorinfo = a
            
        except:
            self.Error = False
            self.Errorinfo = 'No route to host or port is no.'
        
        
    def getexe(self, command, datatype=1):
        #执行单条   命令
        dataexe = {}
        dataexe['command'] = command
        if self.Error and type(command) == str:
            
            stdin, stdout, stderr = self.client.exec_command(command)

            isa = stderr.read()
            if isa:
                dataexe['stats'] = False
                dataexe['info'] = isa

            else:
                if datatype == 1:
                    data = stdout.read()
                elif datatype == 2:
                    #按照 行 切分的列表
                    data = stdout.readlines()
                    
                dataexe['stats'] = True
                dataexe['info'] = data
                
        return dataexe
        
        
    def getscp(self, file_dict):
        """
        scp 传输 单条  文件
        #file_dict_list = [{"Sfile": sfile, "Dfile": Dfile, "Type": 1}]   Type 1(上传) 2(下载)
        """
        scpdata = {}
        try:
        
            if file_dict['Type'] == 1:
                a = self.sftp.put(file_dict['Sfile'], file_dict['Dfile'])

            elif file_dict['Type'] == 2:
                a = self.sftp.get(file_dict['Sfile'] , file_dict['Dfile'])
            
            scpdata['stats'] = True
            scpdata['info'] = a 
                
        except OSError as e:
            scpdata['stats'] = False
            scpdata['info'] = str(e)
            
        except IOError as e:
            scpdata['stats'] = False
            if str(e) == "Failure":
                scpdata['info'] = "Failure , Dfile path error"
            else:
                scpdata['info'] = str(e)
                
        return scpdata
        
        
        
    def batch(self, sshtype, batcharge):
        """ 批量执行 或者 传输文件 
        type = 1 执行 命令
        type = 2 scp传输文件
        """
        returnlist = []
        if self.Error and type(batcharge) == list:
            if sshtype == 1:
                for i in batcharge:
                    returnlist.append(self.getexe(i))
                    
            elif sshtype == 2:
                for i in batcharge:
                    returnlist.append(self.getscp(i))
            
            
            
        return returnlist


转载于:https://my.oschina.net/u/214948/blog/277212

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值