zoukankan      html  css  js  c++  java
  • 简单主机管理

    题目:简单主机批量管理工具

    需求:

    1. 主机分组
    2. 主机信息配置文件用configparser解析
    3. 可批量执行命令、发送文件,结果实时返回,执行格式如下 
      1. batch_run  -h h1,h2,h3   -g web_clusters,db_servers    -cmd  "df -h" 
      2. batch_scp   -h h1,h2,h3   -g web_clusters,db_servers  -action put  -local test.py  -remote /tmp/ 
    4. 主机用户名密码、端口可以不同
    5. 执行远程命令使用paramiko模块
    6. 批量命令需使用multiprocessing并发
    import threading, os, sys
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.append(base_dir)
    from core import control
    from core import local
    from conf import setting
    
    if __name__ == '__main__':
    
        for host in setting.hosts.keys():
            host_tuple = local.options()
            print('33[42;1m[put file or inter system command.]33[0m')
            while True:
                cmd = input('>>>').strip()
                if len(cmd) == 0: continue
                t_list = []
                for host in host_tuple:
                    remote_control = control.RemoteControl(cmd, *host)
                    t = threading.Thread(target=remote_control.run,)
                    t.setDaemon(True)
                    t.start()
                    t_list.append(t)
                for t in t_list:
                    t.join()
    hosts = {'测试系统':(('10.0.0.11', 22, 'root', '123456'),
                         ('10.0.0.12', 22, 'root', '123456'),
                        ),
    
              '生产系统':(('10.0.0.12', 22, 'root', '123456'),
                        ),
              }
    import  paramiko
    
    class RemoteControl(object):
        def __init__(self, cmd, *kw):
            self.hostname = kw[0]
            self.port = kw[1]
            self.username = kw[2]
            self.password = kw[3]
            self.cmd = cmd
    
        def run(self):
            cmd = self.cmd.split()[0]
            if hasattr(self, cmd):
                getattr(self, cmd)()
            else:
                setattr(self, cmd, self.command)
                getattr(self, cmd)()
    
        def put(self):
            '''上传文件'''
            # try:
            transport = paramiko.Transport(self.hostname, self.port)
            transport.connect(username=self.username, password=self.password)
            sftp = paramiko.SFTPClient.from_transport(transport)
            sftp.put(self.cmd.split()[1], self.cmd.split()[2])
            transport.close()
            print('33[32;1m【%s】上传文件【%s】成功!' %(self.hostname, self.cmd.split()[1]))
            # except Exception as e:
            #     print('33[31;1m错误:【%s】: 【%s】33[0m' %(self.hostname, e))
    
        def command(self):
            '''执行系统静态命令'''
            ssh = paramiko.SSHClient()
            ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh.connect(hostname=self.hostname, port=self.port, username=self.username,
                        password=self.password)
            stdin, stdout, stderr = ssh.exec_command(self.cmd)
            res, err = stdout.read(), stderr.read()
            result = res if res else err
            print('33[32;1m%s33[0m'.center(50, '-') % self.hostname)
            print(result.decode())
            ssh.close()
    import os, sys
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    sys.path.append(base_dir)
    from conf import setting
    def options():
        for host in setting.hosts.keys():
            print(host)
        while True:
            choice = input('please choice groupname:')
            if len(choice) ==0: continue
            if choice in setting.hosts.keys():
                for host in setting.hosts[choice]:
                    print(host[0])
                return setting.hosts[choice]
            else:
                print('groupname not exist.')
                break
  • 相关阅读:
    PHP删除文件
    PHP定时执行任务
    PHP设置30秒内对页面的访问次数
    PHP抓取网页内容的几种方法
    QQ,新浪,SNS等公众平台的登录及api操作
    php,javascript设置和读取cookie
    php验证邮箱,手机号是否正确
    php自定义加密和解密
    Linux下安装启动多个Mysql
    linux-gcc 编译时头文件和库文件搜索路径
  • 原文地址:https://www.cnblogs.com/wangmengzhu/p/7453493.html
Copyright © 2011-2022 走看看