#!/usr/bin/python
# -*- coding:utf -*-

import paramiko, os


class ParamikoTools(object):
    def __init__(self, ip, port, user, password=None, key=None, timeout=5):
        self.host = ip
        self.port = port
        self.user = user
        self.password = password
        self.key = key
        self.timeout = timeout

    def cmd(self, cmd):
        try:
            if self.key:
                k = paramiko.RSAKey.from_private_key_file(self.key)
                ssh = paramiko.SSHClient()
                ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                ssh.connect(hostname=self.host, username=self.user, pkey=k, timeout=self.timeout)
            elif self.password:
                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)
            else:
                raise Exception(u"Lack of parameter!")
            stdin, stdout, stderr = ssh.exec_command(cmd)
            return stdout.read()
            ssh.close()
        except Exception, e:
            raise Exception ("%s exec command except:%s" % (self.host, e))

    def download(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.get(remotefile, localfile)
            print "Download file fished:%s"%localfile
            transport.close()
        except Exception, e:
            raise Exception( "Download file from %s to local %s,%s" % (remotefile, localfile, e))

    def upload(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 "Upload file fished:%s"%remotefile
        except Exception, e:
            raise Exception( "Upload local file to remote host execpt, localfile:%s-- remotedir:%s--except:%s" % (
            localfile, remotefile, e))