zoukankan      html  css  js  c++  java
  • 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")
  • 相关阅读:
    水平拖拽滚动条
    垂直拖拽滚动条
    网页特效_拖拽案例
    js实现倒计时
    权限控制
    Eclipse 项目有红感叹号
    JBPM简单介绍
    开博有感
    各种正则表达式
    Python中读取目录里的文件并按排序列出
  • 原文地址:https://www.cnblogs.com/jachin/p/5438705.html
Copyright © 2011-2022 走看看