paramiko 批量执行命令和上传下载

# coding:utf-8

import paramiko
from threading import Thread


class TypeError(Exception):
    pass


class Linux(object):

    def __init__(self, host, username, password, remotePath=None, localPath=None, _shell=None, Type=None, port=22):
        self._host = host
        self._port = port
        self._username = username
        self._password = password
        self._remotePath = remotePath
        self._localPath = localPath
        self._shell = _shell
        self._type = Type

    def ssh(self):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            ssh.connect(self._host, self._port, self._username,
                        self._password, timeout=2)
            stdin, stdout, stderr = ssh.exec_command(self._shell)
            return stdout.read()
        except Exception:
            pass
        finally:
            ssh.close()

    def sftp(self):
        trans = paramiko.Transport((self._host, self._port))
        try:
            trans.connect(username=self._username, password=self._password)
            sftp_client = paramiko.SFTPClient.from_transport(trans)
            if self._type == "upload":
                sftp_client.put(self._localPath, self._remotePath)
            elif self._type == "download":
                sftp_client.get(self._remotePath, self._localPath)
            else:
                raise TypeError
        except TypeError:
            print("sftp not support this %s type" % (self._type))
        except Exception:
            pass
        finally:
            trans.close()


class Linux_Execute(threading.Thread):

    def __init__(self, host):
        super(Linux_Execute, self).__init__()
        self._host = host

    def run(self):
        linux = Linux(host=self._host, user=USERNAME,
                      password=PASSWORD, _shell=_SHELL)
        print linux.ssh()


SERVER_LIST = ["salt-master", "salt-minion", "salt-test"]
USERNAME = "root"
PASSWORD = "root"
_SHELL = "uptime"

if __name__ == "__main__":
    threads = []
    for host in SERVER_LIST:
        threads.append(Linux_Execute(host))

    for threadobj in threads:
        threadobj.start()

    for threadobj in threads:
        threadobj.join()

    print("Over")

 

posted on 2016-04-27 14:16  漫步的影子  阅读(536)  评论(0编辑  收藏  举报