longpan 发表于 2018-8-10 13:40:51

python的paramiko模块

import paramiko  
from switch import switch_ip, switch_pwd, switch_username
  
from lib.read_ini import config
  
from lib.logsys import LogSys
  
import threading
  
import time
  

  
class UpDate(object):
  

  
    def __init__(self, dev, pname):
  
      self.cf = config()
  
      self.log = LogSys()
  
      self.pname = pname
  
      self.ip = switch_ip(dev)            # 根据dev获取远程服务器ip
  
      self.username = switch_username(dev)# 获取用户名
  
      self.password = switch_pwd(dev)       # 获取密码
  
      self.port = int(self.cf.getvalue('server_conf', 'port'))
  
      self.localpath = self.cf.getvalue('write_path', 'upfilepath') + self.pname + ".zip"
  
      self.remotepath = self.cf.getvalue('write_path', 'topath') + self.pname + ".zip"
  

  
    def __trans_file(self):                   # 文件传输
  
      try:
  
            tus = (self.ip, self.port)
  
            t = paramiko.Transport(tus)       # 创建传输对象
  
            t.connect(username=self.username, password=self.password)# 连接远程服务器
  
            sftp = paramiko.SFTPClient.from_transport(t)# 创建下载传输对象
  
            sftp.put(self.localpath, self.remotepath)   # 上传文件
  
            t.close()
  
            print "trans_ok"
  
            return 5
  
      except Exception, e:
  
            print "put_file:" + str(e)
  
            return 0
  

  
    def __excuteup(self):                     # 远程操作
  
      ssh = paramiko.SSHClient()
  
      comm = '/root/test.sh ' + self.pname
  
      try:
  
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  
            ssh.connect(self.ip,self.port,self.username,self.password,timeout=10) # 连接远程服务器
  
            stdin, stdout, stderr = ssh.exec_command(comm)# 执行远程服务器上的脚本
  
            out = stdout.readlines()
  
            ssh.close()
  
            return 5
  
      except Exception, e:
  
            errmsg ="excuteup Error.__excute" + str(e)
  
            ssh.close()
  
            self.log.writelog(errmsg)         # 将错误信息保存到日志
  
            return 0
  

  
    def runup(self):                        # 执行上传和远程执行命令的操作
  
      if self.__trans_file():
  
            if self.__excuteup():
  
                print "update success."
  
                return 5
  
            else:
  
                print "trans OK. excute ERR!"
  
                return 1
  
      else:
  
            return 1
页: [1]
查看完整版本: python的paramiko模块