#!/usr/bin/evn python # coding:utf-8 import paramiko,os class ParamikoTools(object): def __init__(self,ip, port, user, password, key, timeout): self.host = ip self.port = port self.user = user self.password = password self .key = key self.timeout = timeout def sshs(self,cmd): try: ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=self.host,port=self.port,username=self.user,password=self.password,timeout=self.timeout) stdin, stdout, stderr = ssh.exec_command(cmd) return stdout.read() ssh.close() except Exception,e: print "%s exec command except:%s"%(self.host,e) def sshkey(self,key,cmd): try: k = paramiko.RSAKey.from_private_key_file(key) c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect(hostname=self.host, username=self.user, pkey=k,timeout=self.timeout) stdin, stdout, stderr = c.exec_command(cmd) return stdout.read() c.close() except Exception,e: print "%s exec command except:%s" &(self.host,e) def getRemoteFiles(self, localfile, remotefile): try: # ssh = paramiko.SSHClient() # ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # ssh.connect(hostname=self.host, port=self.port, username=self.user, password=self.password, # timeout=self.timeout) transport = paramiko.Transport((self.host,self.port)) transport.connect(username=self.user,password=self.password) sftp = paramiko.SFTPClient.from_transport(transport) sftp.get(remotefile, localfile) print "Transport file fished !" transport.close() except Exception,e: print "Get file from %s to local %s,%s"%(remotefile, localfile, e) def putLocalToRemote(self, localfile, remotefile): try: transport = paramiko.Transport((self.host,self.port)) transport.connect(username=self.user,password=self.password) sftp = paramiko.SFTPClient.from_transport(transport) sftp.put(localfile, remotefile) print "Transport file fished !" except Exception,e: print "Put local file to remote host execpt, localfile:%s-- remotedir:%s--except:%s" %(localfile, remotefile, e)
时间: 2024-12-12 14:38:20