當前位置: 首頁>>代碼示例>>Python>>正文


Python ansible_api.MyRunner類代碼示例

本文整理匯總了Python中jperm.ansible_api.MyRunner的典型用法代碼示例。如果您正苦於以下問題:Python MyRunner類的具體用法?Python MyRunner怎麽用?Python MyRunner使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了MyRunner類的11個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: download

def download(request):
    user = request.user
    assets = get_group_user_perm(user).get('asset').keys()
    asset_select = []
    if request.method == 'POST':
        remote_ip = request.META.get('REMOTE_ADDR')
        asset_ids = request.POST.getlist('asset_ids', '')
        file_path = request.POST.get('file_path')
        date_now = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        upload_dir = get_tmp_dir()
        for asset_id in asset_ids:
            asset_select.append(get_object(Asset, id=asset_id))

        if not set(asset_select).issubset(set(assets)):
            illegal_asset = set(asset_select).issubset(set(assets))
            return HttpResponse(u'沒有權限的服務器 %s' % ','.join([asset.hostname for asset in illegal_asset]))

        res = gen_resource({'user': user, 'asset': asset_select})
        runner = MyRunner(res)
        runner.run('fetch', module_args='src=%s dest=%s' % (file_path, upload_dir), pattern='*')
        FileLog(user=request.user.username, host=' '.join([asset.hostname for asset in asset_select]),
                filename=file_path, type='download', remote_ip=remote_ip, result=runner.results).save()
        logger.debug(runner.results)
        os.chdir('/tmp')
        tmp_dir_name = os.path.basename(upload_dir)
        tar_file = '%s.tar.gz' % upload_dir
        bash('tar czf %s %s' % (tar_file, tmp_dir_name))
        f = open(tar_file)
        data = f.read()
        f.close()
        response = HttpResponse(data, content_type='application/octet-stream')
        response['Content-Disposition'] = 'attachment; filename=%s' % os.path.basename(tar_file)
        return response

    return render_to_response('download.html', locals(), context_instance=RequestContext(request))
開發者ID:Felix-YuJing,項目名稱:jumpserver,代碼行數:35,代碼來源:views.py

示例2: asset_ansible_update

def asset_ansible_update(obj_list, name=''):
    resource = gen_resource(obj_list)
    ansible_instance = MyRunner(resource)
    ansible_asset_info = ansible_instance.run(module_name='setup', pattern='*')
    logger.debug('獲取硬件信息: %s' % ansible_asset_info)
    for asset in obj_list:
        try:
            setup_info = ansible_asset_info['contacted'][asset.hostname]['ansible_facts']
        except KeyError:
            continue
        else:
            asset_info = get_ansible_asset_info(asset.ip, setup_info)
            other_ip, mac, cpu, memory, disk, sn, system_type, system_version, brand, system_arch = asset_info
            asset_dic = {"other_ip": other_ip,
                         "mac": mac,
                         "cpu": cpu,
                         "memory": memory,
                         "disk": disk,
                         "sn": sn,
                         "system_type": system_type,
                         "system_version": system_version,
                         "system_arch": system_arch,
                         "brand": brand
                         }

            ansible_record(asset, asset_dic, name)
開發者ID:ljb-2000,項目名稱:jumpserver-1,代碼行數:26,代碼來源:asset_api.py

示例3: asset_ansible_update

def asset_ansible_update(obj_list, name=''):
    resource = gen_resource(obj_list)
    ansible_instance = MyRunner(resource)
    ansible_asset_info = ansible_instance.run(module_name='setup', pattern='*')
    logger.debug('獲取硬件信息: %s' % ansible_asset_info)
    for asset in obj_list:
        try:
            setup_info = ansible_asset_info['contacted'][asset.hostname]['ansible_facts']
            logger.debug("setup_info: %s" % setup_info)
        except KeyError, e:
            logger.error("獲取setup_info失敗: %s" % e)
            continue
        else:
            try:
                asset_info = get_ansible_asset_info(asset.ip, setup_info)
                print asset_info
                other_ip, mac, cpu, memory, disk, sn, system_type, system_version, brand, system_arch = asset_info
                asset_dic = {"other_ip": other_ip,
                             "mac": mac,
                             "cpu": cpu,
                             "memory": memory,
                             "disk": disk,
                             "sn": sn,
                             "system_type": system_type,
                             "system_version": system_version,
                             "system_arch": system_arch,
                             "brand": brand
                             }

                ansible_record(asset, asset_dic, name)
            except Exception as e:
                logger.error("save setup info failed! %s" % e)
                traceback.print_exc()
開發者ID:X-Mars,項目名稱:jumpserver,代碼行數:33,代碼來源:asset_api.py

示例4: download

    def download(self):
        while True:
            if not self.user_perm:
                self.user_perm = get_group_user_perm(self.user)
            try:
                print "進入批量下載模式"
                print "請輸入主機名或ansible支持的pattern, 多個主機:分隔,q退出"
                pattern = raw_input("\033[1;32mPattern>:\033[0m ").strip()
                if pattern == 'q':
                    break
                else:
                    assets = self.user_perm.get('asset').keys()
                    res = gen_resource({'user': self.user, 'asset': assets}, perm=self.user_perm)
                    runner = MyRunner(res)
                    asset_name_str = ''
                    print "匹配主機:\n"
                    for inv in runner.inventory.get_hosts(pattern=pattern):
                        asset_name_str += '%s ' % inv.name
                        print ' %s' % inv.name
                    if not asset_name_str:
                        color_print('沒有匹配主機')
                        continue
                    print
                    while True:
                        tmp_dir = get_tmp_dir()
                        logger.debug('Download tmp dir: %s' % tmp_dir)
                        print "請輸入文件路徑(不支持目錄)"
                        file_path = raw_input("\033[1;32mPath>:\033[0m ").strip()
                        if file_path == 'q':
                            break

                        if not file_path:
                            color_print("文件路徑為空")
                            continue

                        runner.run('fetch', module_args='src=%s dest=%s' % (file_path, tmp_dir), pattern=pattern)
                        ret = runner.results
                        FileLog(user=self.user.name, host=asset_name_str, filename=file_path, type='download',
                                remote_ip=remote_ip, result=ret).save()
                        logger.debug('Download file result: %s' % ret)
                        os.chdir('/tmp')
                        tmp_dir_name = os.path.basename(tmp_dir)
                        if not os.listdir(tmp_dir):
                            color_print('下載全部失敗')
                            continue
                        bash('tar czf %s.tar.gz %s && sz %s.tar.gz' % (tmp_dir, tmp_dir_name, tmp_dir))

                        if ret.get('failed'):
                            error = '文件名稱: %s \n下載失敗: [ %s ] \n下載成功 [ %s ]' % \
                                    ('%s.tar.gz' % tmp_dir_name, ', '.join(ret.get('failed').keys()), ', '.join(ret.get('ok').keys()))
                            color_print(error)
                        else:
                            msg = '文件名稱: %s \n下載成功 [ %s ]' % ('%s.tar.gz' % tmp_dir_name, ', '.join(ret.get('ok').keys()))
                            color_print(msg, 'green')
                        print
            except IndexError:
                pass
開發者ID:277800076,項目名稱:jumpserver,代碼行數:57,代碼來源:connect.py

示例5: upload

    def upload(self):
        while True:
            if not self.user_perm:
                self.user_perm = get_group_user_perm(self.user)
            try:
                print "進入批量上傳模式"
                print "請輸入主機名或ansible支持的pattern, 多個主機:分隔 q退出"
                pattern = raw_input("\033[1;32mPattern>:\033[0m ").strip()
                if pattern == 'q':
                    break
                else:
                    assets = self.user_perm.get('asset').keys()
                    res = gen_resource({'user': self.user, 'asset': assets}, perm=self.user_perm)
                    runner = MyRunner(res)
                    asset_name_str = ''
                    print "匹配主機:"
                    for inv in runner.inventory.get_hosts(pattern=pattern):
                        print inv.name
                        asset_name_str += '%s ' % inv.name

                    if not asset_name_str:
                        color_print('沒有匹配主機')
                        continue
                    tmp_dir = get_tmp_dir()
                    logger.debug('Upload tmp dir: %s' % tmp_dir)
                    os.chdir(tmp_dir)
                    bash('rz')
                    filename_str = ' '.join(os.listdir(tmp_dir))
                    if not filename_str:
                        color_print("上傳文件為空")
                        continue
                    logger.debug('上傳文件: %s' % filename_str)

                    runner = MyRunner(res)
                    runner.run('copy', module_args='src=%s dest=%s directory_mode'
                                                     % (tmp_dir, tmp_dir), pattern=pattern)
                    ret = runner.results
                    FileLog(user=self.user.name, host=asset_name_str, filename=filename_str,
                            remote_ip=remote_ip, type='upload', result=ret).save()
                    logger.debug('Upload file: %s' % ret)
                    if ret.get('failed'):
                        error = '上傳目錄: %s \n上傳失敗: [ %s ] \n上傳成功 [ %s ]' % (tmp_dir,
                                                                             ', '.join(ret.get('failed').keys()),
                                                                             ', '.join(ret.get('ok').keys()))
                        color_print(error)
                    else:
                        msg = '上傳目錄: %s \n傳送成功 [ %s ]' % (tmp_dir, ', '.join(ret.get('ok').keys()))
                        color_print(msg, 'green')
                    print

            except IndexError:
                pass
開發者ID:277800076,項目名稱:jumpserver,代碼行數:52,代碼來源:connect.py

示例6: asset_ansible_update

def asset_ansible_update(obj_list, name=''):
    resource = gen_resource(obj_list)
    ansible_instance = MyRunner(resource)
    ansible_asset_info = ansible_instance.run(module_name='setup', pattern='*')
    logger.debug('獲取硬件信息: %s' % ansible_asset_info)
    for asset in obj_list:
        try:
            setup_info = ansible_asset_info['contacted'][asset.hostname]['ansible_facts']
            logger.debug("setup_info: %s" % setup_info)
        except KeyError, e:
            logger.error("獲取setup_info失敗: %s" % e)
            continue
        else:
            try:
                asset_info = get_ansible_asset_info(asset.ip, setup_info)
                print asset_info
		# modified by jox Thu Aug 11-12 
                #other_ip, mac, cpu, memory, disk, sn, system_type, system_version, brand, system_arch = asset_info
                other_ip, mac, cpu, memory, disk, sn, system_type, system_version, brand, system_arch,os_version, kernel_version, physical_cpu, cpu_core, timezone, nameserver, domain, search = asset_info
                asset_dic = {"other_ip": other_ip,
                             "mac": mac,
                             "cpu": cpu,
                             "memory": memory,
                             "disk": disk,
                             "sn": sn,
                             "system_type": system_type,
                             "system_version": system_version,
                             "system_arch": system_arch,
                             "brand": brand,
		# added by jox Thu Aug 11 13:28:18 CST 2016
                             "os_version": os_version,
                             "kernel_version": kernel_version,
                             "physical_cpu": physical_cpu,
                             "cpu_core": cpu_core,
		# added bu jox Fri Aug 12 12:27:08 CST 2016
                             "timezone": timezone,
                             "nameserver": nameserver,
                             "domain": domain,
                             "search": search
                             }
		# over

                ansible_record(asset, asset_dic, name)
            except Exception as e:
                logger.error("save setup info failed! %s" % e)
                traceback.print_exc()
開發者ID:nnit-unix-cn,項目名稱:Janus,代碼行數:46,代碼來源:asset_api.py

示例7: upload

def upload(request):
    user = request.user
    assets = get_group_user_perm(user).get('asset').keys()
    asset_select = []
    if request.method == 'POST':
        remote_ip = request.META.get('REMOTE_ADDR')
        asset_ids = request.POST.getlist('asset_ids', '')
        upload_files = request.FILES.getlist('file[]', None)
        date_now = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
        upload_dir = get_tmp_dir()
        # file_dict = {}
        for asset_id in asset_ids:
            asset_select.append(get_object(Asset, id=asset_id))

        if not set(asset_select).issubset(set(assets)):
            illegal_asset = set(asset_select).issubset(set(assets))
            return HttpResponse('沒有權限的服務器 %s' % ','.join([asset.hostname for asset in illegal_asset]))

        for upload_file in upload_files:
            file_path = '%s/%s' % (upload_dir, upload_file.name)
            with open(file_path, 'w') as f:
                for chunk in upload_file.chunks():
                    f.write(chunk)

        res = gen_resource({'user': user, 'asset': asset_select})
        runner = MyRunner(res)
        runner.run('copy', module_args='src=%s dest=%s directory_mode'
                                        % (upload_dir, upload_dir), pattern='*')
        ret = runner.results
        logger.debug(ret)
        FileLog(user=request.user.username, host=' '.join([asset.hostname for asset in asset_select]),
                filename=' '.join([f.name for f in upload_files]), type='upload', remote_ip=remote_ip,
                result=ret).save()
        if ret.get('failed'):
            error = u'上傳目錄: %s <br> 上傳失敗: [ %s ] <br>上傳成功 [ %s ]' % (upload_dir,
                                                                             ', '.join(ret.get('failed').keys()),
                                                                             ', '.join(ret.get('ok').keys()))
            return HttpResponse(error, status=500)
        msg = u'上傳目錄: %s <br> 傳送成功 [ %s ]' % (upload_dir, ', '.join(ret.get('ok').keys()))
        return HttpResponse(msg)
    return my_render('upload.html', locals(), request)
開發者ID:Felix-YuJing,項目名稱:jumpserver,代碼行數:41,代碼來源:views.py

示例8: exec_cmd

    def exec_cmd(self):
        """
        批量執行命令
        """
        while True:
            roles = self.user_perm.get('role').keys()
            if len(roles) > 1:  # 授權角色數大於1
                color_print('[%-2s] %-15s' % ('ID', '係統用戶'),  'info')
                role_check = dict(zip(range(len(roles)), roles))

                for i, r in role_check.items():
                    print '[%-2s] %-15s' % (i, r.name)
                print
                print "請輸入運行命令所關聯係統用戶的ID, q退出"

                try:
                    role_id = raw_input("\033[1;32mRole>:\033[0m ").strip()
                    if role_id == 'q':
                        break
                except (IndexError, ValueError):
                    color_print('錯誤輸入')
                else:
                    role = role_check[int(role_id)]
            elif len(roles) == 1:  # 授權角色數為1
                role = roles[0]
            else:
                color_print('當前用戶未被授予角色,無法執行任何操作,如有疑問請聯係管理員。')
                return
            assets = list(self.user_perm.get('role', {}).get(role).get('asset'))  # 獲取該用戶,角色授權主機
            print "授權包含該係統用戶的所有主機"
            for asset in assets:
                print ' %s' % asset.hostname
            print
            print "請輸入主機名或ansible支持的pattern, 多個主機:分隔, q退出"
            pattern = raw_input("\033[1;32mPattern>:\033[0m ").strip()
            if pattern == 'q':
                break
            else:
                res = gen_resource({'user': self.user, 'asset': assets, 'role': role}, perm=self.user_perm)
                runner = MyRunner(res)
                asset_name_str = ''
                print "匹配主機:"
                for inv in runner.inventory.get_hosts(pattern=pattern):
                    print ' %s' % inv.name
                    asset_name_str += '%s ' % inv.name
                print

                while True:
                    print "請輸入執行的命令, 按q退出"
                    command = raw_input("\033[1;32mCmds>:\033[0m ").strip()
                    if command == 'q':
                        break
                    elif not command:
                        color_print('命令不能為空...')
                        continue
                    runner.run('shell', command, pattern=pattern)
                    ExecLog(host=asset_name_str, user=self.user.username, cmd=command, remote_ip=remote_ip,
                            result=runner.results).save()
                    for k, v in runner.results.items():
                        if k == 'ok':
                            for host, output in v.items():
                                color_print("%s => %s" % (host, 'Ok'), 'green')
                                print output
                                print
                        else:
                            for host, output in v.items():
                                color_print("%s => %s" % (host, k), 'red')
                                color_print(output, 'red')
                                print
                    print "~o~ Task finished ~o~"
                    print
開發者ID:280455936,項目名稱:jumpserver,代碼行數:71,代碼來源:connect.py

示例9: download

    def download(self):
        while True:
            if not self.user_perm:
                self.user_perm = get_group_user_perm(self.user)
            try:
                print "進入批量下載模式"
                print "請輸入主機名或ansile支持的pattern, 多個主機:分隔,q退出"
                pattern = raw_input("\033[1;32mPattern>:\033[0m ").strip()
                if pattern == "q":
                    break
                else:
                    assets = self.user_perm.get("asset").keys()
                    res = gen_resource({"user": self.user, "asset": assets}, perm=self.user_perm)
                    runner = MyRunner(res)
                    asset_name_str = ""
                    print "匹配主機:\n"
                    for inv in runner.inventory.get_hosts(pattern=pattern):
                        asset_name_str += "%s " % inv.name
                        print " %s" % inv.name
                    if not asset_name_str:
                        color_print("沒有匹配主機")
                        continue
                    print
                    while True:
                        tmp_dir = get_tmp_dir()
                        logger.debug("Download tmp dir: %s" % tmp_dir)
                        print "請輸入文件路徑(不支持目錄)"
                        file_path = raw_input("\033[1;32mPath>:\033[0m ").strip()
                        if file_path == "q":
                            break

                        if not file_path:
                            color_print("文件路徑為空")
                            continue

                        runner.run("fetch", module_args="src=%s dest=%s" % (file_path, tmp_dir), pattern=pattern)
                        ret = runner.results
                        FileLog(
                            user=self.user.name,
                            host=asset_name_str,
                            filename=file_path,
                            type="download",
                            remote_ip=remote_ip,
                            result=ret,
                        ).save()
                        logger.debug("Download file result: %s" % ret)
                        os.chdir("/tmp")
                        tmp_dir_name = os.path.basename(tmp_dir)
                        if not os.listdir(tmp_dir):
                            color_print("下載全部失敗")
                            continue
                        bash("tar czf %s.tar.gz %s && sz %s.tar.gz" % (tmp_dir, tmp_dir_name, tmp_dir))

                        if ret.get("failed"):
                            error = "文件名稱: %s \n下載失敗: [ %s ] \n下載成功 [ %s ]" % (
                                "%s.tar.gz" % tmp_dir_name,
                                ", ".join(ret.get("failed").keys()),
                                ", ".join(ret.get("ok").keys()),
                            )
                            color_print(error)
                        else:
                            msg = "文件名稱: %s \n下載成功 [ %s ]" % (
                                "%s.tar.gz" % tmp_dir_name,
                                ", ".join(ret.get("ok").keys()),
                            )
                            color_print(msg, "green")
                        print
            except IndexError:
                pass
開發者ID:cn27001,項目名稱:jumpserver,代碼行數:69,代碼來源:connect.py

示例10: upload

    def upload(self):
        while True:
            if not self.user_perm:
                self.user_perm = get_group_user_perm(self.user)
            try:
                print "進入批量上傳模式"
                print "請輸入主機名或ansile支持的pattern, 多個主機:分隔 q退出"
                pattern = raw_input("\033[1;32mPattern>:\033[0m ").strip()
                if pattern == "q":
                    break
                else:
                    assets = self.user_perm.get("asset").keys()
                    res = gen_resource({"user": self.user, "asset": assets}, perm=self.user_perm)
                    runner = MyRunner(res)
                    asset_name_str = ""
                    print "匹配主機:"
                    for inv in runner.inventory.get_hosts(pattern=pattern):
                        print inv.name
                        asset_name_str += "%s " % inv.name

                    if not asset_name_str:
                        color_print("沒有匹配主機")
                        continue
                    tmp_dir = get_tmp_dir()
                    logger.debug("Upload tmp dir: %s" % tmp_dir)
                    os.chdir(tmp_dir)
                    bash("rz")
                    filename_str = " ".join(os.listdir(tmp_dir))
                    if not filename_str:
                        color_print("上傳文件為空")
                        continue
                    logger.debug("上傳文件: %s" % filename_str)

                    runner = MyRunner(res)
                    runner.run(
                        "copy", module_args="src=%s dest=%s directory_mode" % (tmp_dir, tmp_dir), pattern=pattern
                    )
                    ret = runner.results
                    FileLog(
                        user=self.user.name,
                        host=asset_name_str,
                        filename=filename_str,
                        remote_ip=remote_ip,
                        type="upload",
                        result=ret,
                    ).save()
                    logger.debug("Upload file: %s" % ret)
                    if ret.get("failed"):
                        error = "上傳目錄: %s \n上傳失敗: [ %s ] \n上傳成功 [ %s ]" % (
                            tmp_dir,
                            ", ".join(ret.get("failed").keys()),
                            ", ".join(ret.get("ok").keys()),
                        )
                        color_print(error)
                    else:
                        msg = "上傳目錄: %s \n傳送成功 [ %s ]" % (tmp_dir, ", ".join(ret.get("ok").keys()))
                        color_print(msg, "green")
                    print

            except IndexError:
                pass
開發者ID:cn27001,項目名稱:jumpserver,代碼行數:61,代碼來源:connect.py

示例11: exec_cmd

    def exec_cmd(self):
        """
        批量執行命令
        """
        while True:
            if not self.user_perm:
                self.user_perm = get_group_user_perm(self.user)

            roles = self.user_perm.get("role").keys()
            if len(roles) > 1:  # 授權角色數大於1
                color_print("[%-2s] %-15s" % ("ID", "係統用戶"), "info")
                role_check = dict(zip(range(len(roles)), roles))

                for i, r in role_check.items():
                    print "[%-2s] %-15s" % (i, r.name)
                print
                print "請輸入運行命令所關聯係統用戶的ID, q退出"

                try:
                    role_id = raw_input("\033[1;32mRole>:\033[0m ").strip()
                    if role_id == "q":
                        break
                except (IndexError, ValueError):
                    color_print("錯誤輸入")
                else:
                    role = role_check[int(role_id)]
            elif len(roles) == 1:  # 授權角色數為1
                role = roles[0]
            assets = list(self.user_perm.get("role", {}).get(role).get("asset"))  # 獲取該用戶,角色授權主機
            print "授權包含該係統用戶的所有主機"
            for asset in assets:
                print " %s" % asset.hostname
            print
            print "請輸入主機名或ansile支持的pattern, 多個主機:分隔, q退出"
            pattern = raw_input("\033[1;32mPattern>:\033[0m ").strip()
            if pattern == "q":
                break
            else:
                res = gen_resource({"user": self.user, "asset": assets, "role": role}, perm=self.user_perm)
                runner = MyRunner(res)
                asset_name_str = ""
                print "匹配主機:"
                for inv in runner.inventory.get_hosts(pattern=pattern):
                    print " %s" % inv.name
                    asset_name_str += "%s " % inv.name
                print

                while True:
                    print "請輸入執行的命令, 按q退出"
                    command = raw_input("\033[1;32mCmds>:\033[0m ").strip()
                    if command == "q":
                        break
                    runner.run("shell", command, pattern=pattern)
                    ExecLog(
                        host=asset_name_str,
                        user=self.user.username,
                        cmd=command,
                        remote_ip=remote_ip,
                        result=runner.results,
                    ).save()
                    for k, v in runner.results.items():
                        if k == "ok":
                            for host, output in v.items():
                                color_print("%s => %s" % (host, "Ok"), "green")
                                print output
                                print
                        else:
                            for host, output in v.items():
                                color_print("%s => %s" % (host, k), "red")
                                color_print(output, "red")
                                print
                    print "~o~ Task finished ~o~"
                    print
開發者ID:cn27001,項目名稱:jumpserver,代碼行數:73,代碼來源:connect.py


注:本文中的jperm.ansible_api.MyRunner類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。