# Path: jperm/ansible_api.py
# class MyRunner(MyInventory):
#     """
#     This is a General object for parallel execute modules.
#     """
#     def __init__(self, *args, **kwargs):
#         super(MyRunner, self).__init__(*args, **kwargs)
#         self.results_raw = {}
# 
#     def run(self, module_name='shell', module_args='', timeout=10, forks=10, pattern='*',
#             become=False, become_method='sudo', become_user='root', become_pass='', transport='paramiko'):
#         """
#         run module from andible ad-hoc.
#         module_name: ansible module_name
#         module_args: ansible module args
#         """
#         hoc = Runner(module_name=module_name,
#                      module_args=module_args,
#                      timeout=timeout,
#                      inventory=self.inventory,
#                      pattern=pattern,
#                      forks=forks,
#                      become=become,
#                      become_method=become_method,
#                      become_user=become_user,
#                      become_pass=become_pass,
#                      transport=transport
#                      )
#         self.results_raw = hoc.run()
#         logger.debug(self.results_raw)
#         return self.results_raw
# 
#     @property
#     def results(self):
#         """
#         {'failed': {'localhost': ''}, 'ok': {'jumpserver': ''}}
#         """
#         result = {'failed': {}, 'ok': {}}
#         dark = self.results_raw.get('dark')
#         contacted = self.results_raw.get('contacted')
#         if dark:
#             for host, info in dark.items():
#                 result['failed'][host] = info.get('msg')
# 
#         if contacted:
#             for host, info in contacted.items():
#                 if info.get('invocation').get('module_name') in ['raw', 'shell', 'command', 'script']:
#                     if info.get('rc') == 0:
#                         result['ok'][host] = info.get('stdout') + info.get('stderr')
#                     else:
#                         result['failed'][host] = info.get('stdout') + info.get('stderr')
#                 else:
#                     if info.get('failed'):
#                         result['failed'][host] = info.get('msg')
#                     else:
#                         result['ok'][host] = info.get('changed')
#         return result


import uuid
import urllib
import paramiko
import zipfile
from django.db.models import Count
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseNotFound
from django.http import HttpResponse
from jumpserver.api import *
from jumpserver.models import Setting
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from jlog.models import Log, FileLog
from jperm.perm_api import get_group_user_perm, gen_resource
from jasset.models import Asset, IDC
from jperm.ansible_api import MyRunner
                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)


@login_required(login_url='/login')
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})

# Path: jperm/ansible_api.py
# class MyRunner(MyInventory):
#     """
#     This is a General object for parallel execute modules.
#     """
#     def __init__(self, *args, **kwargs):
#         super(MyRunner, self).__init__(*args, **kwargs)
#         self.results_raw = {}
# 
#     def run(self, module_name='shell', module_args='', timeout=10, forks=10, pattern='*',
#             become=False, become_method='sudo', become_user='root', become_pass='', transport='paramiko'):
#         """
#         run module from andible ad-hoc.
#         module_name: ansible module_name
#         module_args: ansible module args
#         """
#         hoc = Runner(module_name=module_name,
#                      module_args=module_args,
#                      timeout=timeout,
#                      inventory=self.inventory,
#                      pattern=pattern,
#                      forks=forks,
#                      become=become,
#                      become_method=become_method,
#                      become_user=become_user,
#                      become_pass=become_pass,
#                      transport=transport
#                      )
#         self.results_raw = hoc.run()
#         logger.debug(self.results_raw)
#         return self.results_raw
# 
#     @property
#     def results(self):
#         """
#         {'failed': {'localhost': ''}, 'ok': {'jumpserver': ''}}
#         """
#         result = {'failed': {}, 'ok': {}}
#         dark = self.results_raw.get('dark')
#         contacted = self.results_raw.get('contacted')
#         if dark:
#             for host, info in dark.items():
#                 result['failed'][host] = info.get('msg')
# 
#         if contacted:
#             for host, info in contacted.items():
#                 if info.get('invocation').get('module_name') in ['raw', 'shell', 'command', 'script']:
#                     if info.get('rc') == 0:
#                         result['ok'][host] = info.get('stdout') + info.get('stderr')
#                     else:
#                         result['failed'][host] = info.get('stdout') + info.get('stderr')
#                 else:
#                     if info.get('failed'):
#                         result['failed'][host] = info.get('msg')
#                     else:
#                         result['ok'][host] = info.get('changed')
#         return result


# Path: jumpserver/views.py
import uuid
import urllib
import paramiko
import zipfile
from django.db.models import Count
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.http import HttpResponseNotFound
from django.http import HttpResponse
from jumpserver.api import *
from jumpserver.models import Setting
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from jlog.models import Log, FileLog
from jperm.perm_api import get_group_user_perm, gen_resource
from jasset.models import Asset, IDC
from jperm.ansible_api import MyRunner

                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)


@login_required(login_url='/login')
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)