Esempio n. 1
0
def export(request):

    pythoncom.CoInitialize()
    context = {}
    if request.method == "POST":
        xlApp = win32.Dispatch('Excel.Application')
        if request.FILES:
            data = request.POST.copy()
            file = request.FILES["excelfile"]
            fs = FileSystemStorage()
            fname = fs.save(file.name, file)
            sheetid = data.get('sheetid')
            sname = data.get('sheetname')
            estart = data.get('excelstartregion')
            gstart = data.get('googlesheetstartregion')
            if file.name == "":
                res_msg = {'msg': 'File Name is Needed'}
                return Response(res_msg, status=400)
                # messages.error(request, 'File Name is Needed')
                # return HttpResponseRedirect('export')
            if sheetid == "" or sname == "" or estart == "" or gstart == "":
                res_msg = {'msg': 'Please Enter all Fields'}
                return Response(res_msg, status=400)
                # messages.warning(request, 'Please Enter all Fields')
                # return HttpResponseRedirect('export')
            if not checkFile(file.name):
                res_msg = {'msg': 'File Extension not Supported'}
                return Response(res_msg, status=400)
                # messages.error(request, 'File Extension not Supported')
                # return HttpResponseRedirect('export')
            else:
                xlApp = win32.Dispatch('Excel.Application')
                wb = xlApp.Workbooks.Open(r"" + os.getcwd() + "/media/" +
                                          fname)
                print(wb)
                try:
                    ws = wb.Worksheets(sname)
                except Exception as e:
                    res_msg = {'msg': 'Error opening worksheet ' + str(e)}
                    return Response(res_msg, status=400)
                    # messages.error(request, 'Error opening worksheet '+ str(e))
                    # return HttpResponseRedirect('export')
                rngData = ws.Range(estart).CurrentRegion()

                #191h4mt1-iSzIdeRdbszAcWaV_m7_gbierp_bLImnWnI
                gsheet_id = sheetid
                CLIENT_SECRET_FILE = '' + os.getcwd() + '/client_token.json'
                API_SERVICE_NAME = 'sheets'
                API_VERSION = 'v4'
                SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
                service = Create_Service(CLIENT_SECRET_FILE, API_SERVICE_NAME,
                                         API_VERSION, SCOPES)

                try:
                    response = service.spreadsheets().values().append(
                        spreadsheetId=gsheet_id,
                        valueInputOption='RAW',
                        range='data!' + gstart,
                        body=dict(majorDimension='ROWS',
                                  values=rngData)).execute()
                except Exception as e:
                    res_msg = {
                        'msg': 'Error Uploading to google sheets: ' + str(e)
                    }
                    return Response(res_msg, status=401)
                    # messages.warning(request, 'Error Uploading to google sheets: '+ str(e))
                    # return HttpResponseRedirect('export')

                res_msg = {
                    'msg': 'Worksheet Succesfully exported to google sheets'
                }
                return Response(res_msg)
                # messages.success(request, 'Worksheet Succesfully exported to google sheets')
                # return HttpResponseRedirect('export')
    res_msg = {'msg': 'Please Upload a File First'}
    return Response(res_msg, status=400)
def pdfviewercopy(request,id):
    
    # curr_path = "/"+str(id)+ "/TAapplication/"
    # curr_path=curr_path.replace('/','\\')
    # new_path = os.path.join(settings.MEDIA_ROOT + curr_path)


    # with open(new_path+'TAapplication.pdf', 'rb') as pdf:
    #     response = HttpResponse(pdf.read(),content_type='application/pdf')
    #     response['Content-Disposition'] = 'filename=some_file.pdf'
    # return response
    taa=TAapplicationmodel.objects.filter(user_id=id).first()
    taf=TAapplicationfiles.objects.filter(user_id=id).exclude(filecategory="TAapplication")
    print('kkkkkkkkkkkkkkkkk')
    if request.POST:
        aesurl=request.POST['path']
        ext=request.POST['ext']
        tafnew=TAapplicationfiles.objects.filter(user_id=id,filepath=aesurl,ext=ext).first()
        fc=tafnew.comments
        print('aesview',aesurl)

        pdfurl=''
        docurl=''
        nameonly=''
        if ext=='.pdf':
            pdfurl = aesurl[:-3]+'pdf'
            print('aesview',aesurl)
            print('pdfview',pdfurl)
            bufferSize = 64 * 1024
            passw = "#EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e"
            encFileSize = stat(aesurl).st_size
            with open(aesurl, "rb") as fIn:
                with open(pdfurl, "wb") as fOut:
                    pyAesCrypt.decryptStream(fIn, fOut, passw, bufferSize, encFileSize)
            print(pdfurl,'pdfurl')
            pdfpath = pdfurl[25:]
            print(pdfpath)
            curr_path=pdfpath
            url='http://127.0.0.1:8000/media'+curr_path
            print(fc,'comments')
            return render(request, 'dealing officer/detail view.html',{'url':url,'id':id,'fc':fc,'taa':taa,'taf':taf,'path':aesurl})
        elif ext=='docx':
        # word to pdf 
            nameonly=aesurl[:-4]
            docurl = aesurl[:-4]+'.docx'
            print('aesview',aesurl)
            print('nameonly',nameonly)
            print('docurl',docurl)
            bufferSize = 64 * 1024
            passw = "#EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e"
            encFileSize = stat(aesurl).st_size
            with open(aesurl, "rb") as fIn:
                with open(docurl, "wb") as fOut:
                    pyAesCrypt.decryptStream(fIn, fOut, passw, bufferSize, encFileSize)

            pythoncom.CoInitialize()
            wdFormatPDF = 17
            in_file = os.path.abspath(docurl)
            word = comtypes.client.CreateObject('Word.Application')
            doc = word.Documents.Open(in_file)
            doc.SaveAs(nameonly+'.pdf', FileFormat=wdFormatPDF)
            doc.Close()
            word.Quit()
            pdfurl=nameonly+'.pdf'
            print(pdfurl,'pdfurl')
            pdfpath = pdfurl[25:]
            print(pdfpath)
            curr_path=pdfpath
            url='http://127.0.0.1:8000/media'+curr_path
            print(fc,'comments')
            os.remove(docurl)
            return render(request, 'dealing officer/detail view.html',{'url':url,'id':id,'fc':fc,'taa':taa,'taf':taf,'path':aesurl})
       
            # with open(nameonly+'.pdf', 'rb') as pdf:
            #     response = HttpResponse(pdf.read(),content_type='application/pdf')
            #     response['Content-Disposition'] = 'filename=some_file.pdf'
            # return response
        # finally:
        #     os.remove(nameonly+'.pdf')
        #     os.remove(docurl)
    else:
        return render(request, 'dealing officer/detail view.html',{'id':id,'taa':taa,'taf':taf})
Esempio n. 3
0
def grep_word(query, fpath, re_flags):
    hlogs = []

    app = None

    try:
        # COM初期化  ※スレッドごとに必要
        pythoncom.CoInitialize()

        # Word起動
        app = win32com.client.DispatchEx('Word.Application')
        app.Visible = False
        app.DisplayAlerts = False

        # ドキュメントオープン
        doc = app.Documents.Open(fpath, ReadOnly=True)

        # 段落/表
        for para in doc.Range().Paragraphs:
            # 段落が表のセルである場合は、cellsプロパティを取得できる
            try:
                cell = rng.cells(1)
            except:
                cell = None

            # 検索
            rng = para.Range
            text = str(rng.Text)
            if re.search(query, text, flags=re_flags):
                # ヒットログを作成
                if cell is None:
                    # 本文の場合
                    # 1:wdActiveEndAdjustedPageNumber, 3:wdFirstCharacterLineNumber
                    l = make_log_hit(
                        'Text', {
                            'Page': str(rng.Information(1)),
                            'Line': str(rng.Information(3))
                        }, query, text, re_flags)
                    hlogs.append(l)
                else:
                    # 表の場合
                    # 1:wdActiveEndAdjustedPageNumber
                    l = make_log_hit(
                        'Table', {
                            'Page':
                            str(rng.Information(1)),
                            'Cell':
                            '(r{},c{})'.format(cell.RowIndex, cell.ColumnIndex)
                        }, query, text, re_flags)
                    hlogs.append(l)

        # # 表
        # for table in doc.Tables:
        #     for cell in table.Range.Cells:
        #         # 検索
        #         rng = cell.Range
        #         text = str(rng.Text)
        #         if re.search(query, text, flags=re_flags):
        #             # ヒットログを作成
        #             # 1:wdActiveEndAdjustedPageNumber
        #             l = make_log_hit('Table', {'Page': str(rng.Information(1)), 'Cell': '(r{},c{})'.format(cell.RowIndex, cell.ColumnIndex)}, query, text, re_flags)
        #             hlogs.append(l)

        # 図形
        for shape in doc.Shapes:
            # 図形種類がオートシェイプ(1:msoAutoShape)またはテキストボックス(17:msoTextBox)であり、
            # 文字列を持っている場合(線などではない場合)
            if (shape.Type == 1
                    or shape.Type == 17) and shape.TextFrame.HasText:
                # 検索
                rng = shape.TextFrame.TextRange
                text = str(rng.Text)
                if re.search(query, text, flags=re_flags):
                    # ヒットログを作成
                    # 1:wdActiveEndAdjustedPageNumber
                    l = make_log_hit('Shape', {
                        'Page': str(rng.Information(1)),
                        'Name': shape.Name
                    }, query, text, re_flags)
                    hlogs.append(l)

        # コメント
        for comment in doc.Comments:
            # 検索
            rng = comment.Range
            scope = comment.Scope
            text = str(rng.Text)
            if re.search(query, text, flags=re_flags):
                # ヒットログを作成
                # 1:wdActiveEndAdjustedPageNumber, 3:wdFirstCharacterLineNumber
                l = make_log_hit(
                    'Comment', {
                        'Page': str(scope.Information(1)),
                        'Line': str(scope.Information(3))
                    }, query, text, re_flags)
                hlogs.append(l)

        if doc is not None: doc.Close()

    except Exception as e:
        print('Error: Failer in Word operation.')
        raise

    finally:
        # アプリケーションを終了
        if app is not None: app.Quit()

    return hlogs
Esempio n. 4
0
 def _set_foreground_window(hwnd):
     import pythoncom
     pythoncom.CoInitialize()
     shell = win32com.client.Dispatch('WScript.Shell')
     shell.SendKeys('%')
     win32gui.SetForegroundWindow(hwnd)
Esempio n. 5
0
def set_wu_settings(level=None,
                    recommended=None,
                    featured=None,
                    elevated=None,
                    msupdate=None,
                    day=None,
                    time=None):
    '''
    Change Windows Update settings. If no parameters are passed, the current
    value will be returned.

    Supported:
        - Windows Vista / Server 2008
        - Windows 7 / Server 2008R2
        - Windows 8 / Server 2012
        - Windows 8.1 / Server 2012R2

    .. note:
        Microsoft began using the Unified Update Platform (UUP) starting with
        Windows 10 / Server 2016. The Windows Update settings have changed and
        the ability to 'Save' Windows Update settings has been removed. Windows
        Update settings are read-only. See MSDN documentation:
        https://msdn.microsoft.com/en-us/library/aa385829(v=vs.85).aspx

    Args:

        level (int):
            Number from 1 to 4 indicating the update level:

            1. Never check for updates
            2. Check for updates but let me choose whether to download and install them
            3. Download updates but let me choose whether to install them
            4. Install updates automatically

        recommended (bool):
            Boolean value that indicates whether to include optional or
            recommended updates when a search for updates and installation of
            updates is performed.

        featured (bool):
            Boolean value that indicates whether to display notifications for
            featured updates.

        elevated (bool):
            Boolean value that indicates whether non-administrators can perform
            some update-related actions without administrator approval.

        msupdate (bool):
            Boolean value that indicates whether to turn on Microsoft Update for
            other Microsoft products

        day (str):
            Days of the week on which Automatic Updates installs or uninstalls
            updates. Accepted values:

            - Everyday
            - Monday
            - Tuesday
            - Wednesday
            - Thursday
            - Friday
            - Saturday

        time (str):
            Time at which Automatic Updates installs or uninstalls updates. Must
            be in the ##:## 24hr format, eg. 3:00 PM would be 15:00. Must be in
            1 hour increments.

    Returns:

        dict: Returns a dictionary containing the results.

    CLI Examples:

    .. code-block:: bash

        salt '*' win_wua.set_wu_settings level=4 recommended=True featured=False
    '''
    # The AutomaticUpdateSettings.Save() method used in this function does not
    # work on Windows 10 / Server 2016. It is called in throughout this function
    # like this:
    #
    #     obj_au = win32com.client.Dispatch('Microsoft.Update.AutoUpdate')
    #     obj_au_settings = obj_au.Settings
    #     obj_au_settings.Save()
    #
    # The `Save()` method reports success but doesn't actually change anything.
    # Windows Update settings are read-only in Windows 10 / Server 2016. There's
    # a little blurb on MSDN that mentions this, but gives no alternative for
    # changing these settings in Windows 10 / Server 2016.
    #
    # https://msdn.microsoft.com/en-us/library/aa385829(v=vs.85).aspx
    #
    # Apparently the Windows Update framework in Windows Vista - Windows 8.1 has
    # been changed quite a bit in Windows 10 / Server 2016. It is now called the
    # Unified Update Platform (UUP). I haven't found an API or a Powershell
    # commandlet for working with the the UUP. Perhaps there will be something
    # forthcoming. The `win_lgpo` module might be an option for changing the
    # Windows Update settings using local group policy.
    ret = {'Success': True}

    # Initialize the PyCom system
    pythoncom.CoInitialize()

    # Create an AutoUpdate object
    obj_au = win32com.client.Dispatch('Microsoft.Update.AutoUpdate')

    # Create an AutoUpdate Settings Object
    obj_au_settings = obj_au.Settings

    # Only change the setting if it's passed
    if level is not None:
        obj_au_settings.NotificationLevel = int(level)
        result = obj_au_settings.Save()
        if result is None:
            ret['Level'] = level
        else:
            ret['Comment'] = "Settings failed to save. Check permissions."
            ret['Success'] = False

    if recommended is not None:
        obj_au_settings.IncludeRecommendedUpdates = recommended
        result = obj_au_settings.Save()
        if result is None:
            ret['Recommended'] = recommended
        else:
            ret['Comment'] = "Settings failed to save. Check permissions."
            ret['Success'] = False

    if featured is not None:
        obj_au_settings.FeaturedUpdatesEnabled = featured
        result = obj_au_settings.Save()
        if result is None:
            ret['Featured'] = featured
        else:
            ret['Comment'] = "Settings failed to save. Check permissions."
            ret['Success'] = False

    if elevated is not None:
        obj_au_settings.NonAdministratorsElevated = elevated
        result = obj_au_settings.Save()
        if result is None:
            ret['Elevated'] = elevated
        else:
            ret['Comment'] = "Settings failed to save. Check permissions."
            ret['Success'] = False

    if day is not None:
        # Check that day is valid
        days = {
            'Everyday': 0,
            'Sunday': 1,
            'Monday': 2,
            'Tuesday': 3,
            'Wednesday': 4,
            'Thursday': 5,
            'Friday': 6,
            'Saturday': 7
        }
        if day not in days:
            ret['Comment'] = "Day needs to be one of the following: Everyday," \
                             "Monday, Tuesday, Wednesday, Thursday, Friday, " \
                             "Saturday"
            ret['Success'] = False
        else:
            # Set the numeric equivalent for the day setting
            obj_au_settings.ScheduledInstallationDay = days[day]
            result = obj_au_settings.Save()
            if result is None:
                ret['Day'] = day
            else:
                ret['Comment'] = "Settings failed to save. Check permissions."
                ret['Success'] = False

    if time is not None:
        # Check for time as a string: if the time is not quoted, yaml will
        # treat it as an integer
        if not isinstance(time, six.string_types):
            ret['Comment'] = "Time argument needs to be a string; it may need to"\
                             "be quoted. Passed {0}. Time not set.".format(time)
            ret['Success'] = False
        # Check for colon in the time
        elif ':' not in time:
            ret['Comment'] = "Time argument needs to be in 00:00 format." \
                             " Passed {0}. Time not set.".format(time)
            ret['Success'] = False
        else:
            # Split the time by :
            t = time.split(":")
            # We only need the hours value
            obj_au_settings.FeaturedUpdatesEnabled = t[0]
            result = obj_au_settings.Save()
            if result is None:
                ret['Time'] = time
            else:
                ret['Comment'] = "Settings failed to save. Check permissions."
                ret['Success'] = False

    if msupdate is not None:
        # Microsoft Update requires special handling
        # First load the MS Update Service Manager
        obj_sm = win32com.client.Dispatch('Microsoft.Update.ServiceManager')

        # Give it a bogus name
        obj_sm.ClientApplicationID = "My App"

        if msupdate:
            # msupdate is true, so add it to the services
            try:
                obj_sm.AddService2('7971f918-a847-4430-9279-4a52d1efe18d', 7,
                                   '')
                ret['msupdate'] = msupdate
            except Exception as error:
                hr, msg, exc, arg = error.args  # pylint: disable=W0633
                # Consider checking for -2147024891 (0x80070005) Access Denied
                ret['Comment'] = "Failed with failure code: {0}".format(exc[5])
                ret['Success'] = False
        else:
            # msupdate is false, so remove it from the services
            # check to see if the update is there or the RemoveService function
            # will fail
            if _get_msupdate_status():
                # Service found, remove the service
                try:
                    obj_sm.RemoveService(
                        '7971f918-a847-4430-9279-4a52d1efe18d')
                    ret['msupdate'] = msupdate
                except Exception as error:
                    hr, msg, exc, arg = error.args  # pylint: disable=W0633
                    # Consider checking for the following
                    # -2147024891 (0x80070005) Access Denied
                    # -2145091564 (0x80248014) Service Not Found (shouldn't get
                    # this with the check for _get_msupdate_status above
                    ret['Comment'] = "Failed with failure code: {0}".format(
                        exc[5])
                    ret['Success'] = False
            else:
                ret['msupdate'] = msupdate

    ret['Reboot'] = get_needs_reboot()

    return ret
Esempio n. 6
0
 def wrapper(*args, **kwargs):
     with suppress(Exception):
         pythoncom.CoInitialize()
     return fn(*args, **kwargs)
Esempio n. 7
0
def speak(audio):
    pythoncom.CoInitialize()
    speaking = Dispatch('SAPI.Spvoice')
    speaking.speak(audio)
Esempio n. 8
0
def install_updates(guid=None):
    """
    Installs updates that match the passed criteria. It may be easier to use the
    list_updates function and set install=True.

    :param guid: list
        A list of GUIDs to be installed

    :return: dict
        A dictionary containing the details about the installed updates

    CLI Examples:

    .. code-block:: bash

        # Normal Usage
        salt '*' win_wua.install_updates
         guid=['12345678-abcd-1234-abcd-1234567890ab',
         '87654321-dcba-4321-dcba-ba0987654321']
    """
    # Check for empty GUID
    if guid is None:
        return 'No GUID Specified'

    # Initialize the PyCom system
    pythoncom.CoInitialize()

    # Create a session with the Windows Update Agent
    wua_session = win32com.client.Dispatch('Microsoft.Update.Session')
    wua_session.ClientApplicationID = 'Salt: Install Update'

    # Create the Searcher, Downloader, Installer, and Collections
    wua_searcher = wua_session.CreateUpdateSearcher()
    wua_download_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl')
    wua_downloader = wua_session.CreateUpdateDownloader()
    wua_install_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl')
    wua_installer = wua_session.CreateUpdateInstaller()

    ret = {}

    # Searching for the GUID
    search_string = ''
    search_list = ''
    log.debug('Searching for updates:')
    for ident in guid:
        log.debug('{0}'.format(ident))
        if search_string == '':
            search_string = 'UpdateID=\'{0}\''.format(ident.lower())
            search_list = '{0}'.format(ident.lower())
        else:
            search_string += ' or UpdateID=\'{0}\''.format(ident.lower())
            search_list += '\n{0}'.format(ident.lower())

    try:
        wua_search_result = wua_searcher.Search(search_string)
        if wua_search_result.Updates.Count == 0:
            log.debug('No Updates found for:\n\t\t{0}'.format(search_list))
            ret['Success'] = False
            ret['Details'] = 'No Updates found: {0}'.format(search_list)
            return ret
    except Exception:
        log.debug('Invalid Search String: {0}'.format(search_string))
        return 'Invalid Search String: {0}'.format(search_string)

    # List updates found
    log.debug('Found the following update:')
    ret['Updates'] = {}
    for update in wua_search_result.Updates:
        # Check to see if the update is already installed
        ret['Updates'][update.Identity.UpdateID] = {}
        ret['Updates'][update.Identity.UpdateID]['Title'] = update.Title
        if update.IsInstalled:
            log.debug('Already Installed: {0}'.format(
                update.Identity.UpdateID))
            log.debug(u'\tTitle: {0}'.format(update.Title))
            ret['Updates'][update.Identity.UpdateID]['AlreadyInstalled'] = True
        # Make sure the EULA has been accepted
        if not update.EulaAccepted:
            log.debug(u'Accepting EULA: {0}'.format(update.Title))
            update.AcceptEula()  # pylint: disable=W0104
        # Add to the list of updates that need to be downloaded
        if update.IsDownloaded:
            log.debug('Already Downloaded: {0}'.format(
                update.Identity.UpdateID))
            log.debug(u'\tTitle: {0}'.format(update.Title))
            ret['Updates'][
                update.Identity.UpdateID]['AlreadyDownloaded'] = True
        else:
            log.debug('To Be Downloaded: {0}'.format(update.Identity.UpdateID))
            log.debug(u'\tTitle: {0}'.format(update.Title))
            ret['Updates'][
                update.Identity.UpdateID]['AlreadyDownloaded'] = False
            wua_download_list.Add(update)

    # Download the updates
    if wua_download_list.Count == 0:
        # Not necessarily a failure, perhaps the update has been downloaded
        # but not installed
        log.debug('No updates to download')
    else:
        # Otherwise, download the update
        log.debug('Downloading...')
        wua_downloader.Updates = wua_download_list

        try:
            wua_downloader.Download()
            log.debug('Download Complete')

        except Exception as error:

            ret['Success'] = False
            ret['Result'] = format(error)

            hr, msg, exc, arg = error.args  # pylint: disable=W0633
            # Error codes found at the following site:
            # https://msdn.microsoft.com/en-us/library/windows/desktop/hh968413(v=vs.85).aspx
            fc = {
                -2145124316: 'No Updates: 0x80240024',
                -2145124284: 'Access Denied: 0x8024044'
            }
            try:
                failure_code = fc[exc[5]]
            except KeyError:
                failure_code = 'Unknown Failure: {0}'.format(error)

            log.debug('Download Failed: {0}'.format(failure_code))
            ret['error_msg'] = failure_code
            ret['location'] = 'Download Section of install_updates'
            ret['file'] = 'win_wua.py'

            return ret

    # Install the updates
    for update in wua_search_result.Updates:
        # Make sure the update has actually been downloaded
        if update.IsDownloaded:
            log.debug(u'To be installed: {0}'.format(update.Title))
            wua_install_list.Add(update)

    if wua_install_list.Count == 0:
        # There are not updates to install
        # This would only happen if there was a problem with the download
        # If this happens often, perhaps some error checking for the download
        log.debug('No updates to install')
        ret['Success'] = False
        ret['Message'] = 'No Updates to install'
        return ret

    wua_installer.Updates = wua_install_list

    # Try to run the installer
    try:
        result = wua_installer.Install()

    except Exception as error:

        # See if we know the problem, if not return the full error
        ret['Success'] = False
        ret['Result'] = format(error)

        hr, msg, exc, arg = error.args  # pylint: disable=W0633
        # Error codes found at the following site:
        # https://msdn.microsoft.com/en-us/library/windows/desktop/hh968413(v=vs.85).aspx
        fc = {
            -2145124316: 'No Updates: 0x80240024',
            -2145124284: 'Access Denied: 0x8024044'
        }
        try:
            failure_code = fc[exc[5]]
        except KeyError:
            failure_code = 'Unknown Failure: {0}'.format(error)

        log.debug('Download Failed: {0}'.format(failure_code))
        ret['error_msg'] = failure_code
        ret['location'] = 'Install Section of install_updates'
        ret['file'] = 'win_wua.py'

        return ret

    rc = {
        0: 'Installation Not Started',
        1: 'Installation In Progress',
        2: 'Installation Succeeded',
        3: 'Installation Succeeded With Errors',
        4: 'Installation Failed',
        5: 'Installation Aborted'
    }
    log.debug(rc[result.ResultCode])

    if result.ResultCode in [2, 3]:
        ret['Success'] = True
        ret['NeedsReboot'] = result.RebootRequired
        log.debug('NeedsReboot: {0}'.format(result.RebootRequired))
    else:
        ret['Success'] = False

    ret['Message'] = rc[result.ResultCode]
    rb = {0: 'Never Reboot', 1: 'Always Reboot', 2: 'Poss Reboot'}
    for i in range(wua_install_list.Count):
        uid = wua_install_list.Item(i).Identity.UpdateID
        ret['Updates'][uid]['Result'] = rc[result.GetUpdateResult(
            i).ResultCode]
        ret['Updates'][uid]['RebootBehavior'] = rb[wua_install_list.Item(
            i).InstallationBehavior.RebootBehavior]

    return ret
Esempio n. 9
0
def set_wu_settings(level=None,
                    recommended=None,
                    featured=None,
                    elevated=None,
                    msupdate=None,
                    day=None,
                    time=None):
    """
    Change Windows Update settings. If no parameters are passed, the current
    value will be returned.

    :param int level:
        Number from 1 to 4 indicating the update level:
            1. Never check for updates
            2. Check for updates but let me choose whether to download and install them
            3. Download updates but let me choose whether to install them
            4. Install updates automatically
    :param bool recommended:
        Boolean value that indicates whether to include optional or recommended
        updates when a search for updates and installation of updates is
        performed.

    :param bool featured:
        Boolean value that indicates whether to display notifications for
        featured updates.

    :param bool elevated:
        Boolean value that indicates whether non-administrators can perform some
        update-related actions without administrator approval.

    :param bool msupdate:
        Boolean value that indicates whether to turn on Microsoft Update for
        other Microsoft products

    :param str day:
        Days of the week on which Automatic Updates installs or uninstalls
        updates.
        Accepted values:
            - Everyday
            - Monday
            - Tuesday
            - Wednesday
            - Thursday
            - Friday
            - Saturday

    :param str time:
        Time at which Automatic Updates installs or uninstalls updates. Must be
        in the ##:## 24hr format, eg. 3:00 PM would be 15:00

    :return: Returns a dictionary containing the results.

    CLI Examples:

    .. code-block:: bash

        salt '*' win_wua.set_wu_settings level=4 recommended=True featured=False

    """
    ret = {}
    ret['Success'] = True

    # Initialize the PyCom system
    pythoncom.CoInitialize()

    # Create an AutoUpdate object
    obj_au = win32com.client.Dispatch('Microsoft.Update.AutoUpdate')

    # Create an AutoUpdate Settings Object
    obj_au_settings = obj_au.Settings

    # Only change the setting if it's passed
    if level is not None:
        obj_au_settings.NotificationLevel = int(level)
        result = obj_au_settings.Save()
        if result is None:
            ret['Level'] = level
        else:
            ret['Comment'] = "Settings failed to save. Check permissions."
            ret['Success'] = False

    if recommended is not None:
        obj_au_settings.IncludeRecommendedUpdates = recommended
        result = obj_au_settings.Save()
        if result is None:
            ret['Recommended'] = recommended
        else:
            ret['Comment'] = "Settings failed to save. Check permissions."
            ret['Success'] = False

    if featured is not None:
        obj_au_settings.FeaturedUpdatesEnabled = featured
        result = obj_au_settings.Save()
        if result is None:
            ret['Featured'] = featured
        else:
            ret['Comment'] = "Settings failed to save. Check permissions."
            ret['Success'] = False

    if elevated is not None:
        obj_au_settings.NonAdministratorsElevated = elevated
        result = obj_au_settings.Save()
        if result is None:
            ret['Elevated'] = elevated
        else:
            ret['Comment'] = "Settings failed to save. Check permissions."
            ret['Success'] = False

    if day is not None:
        # Check that day is valid
        days = {
            'Everyday': 0,
            'Sunday': 1,
            'Monday': 2,
            'Tuesday': 3,
            'Wednesday': 4,
            'Thursday': 5,
            'Friday': 6,
            'Saturday': 7
        }
        if day not in days:
            ret['Comment'] = "Day needs to be one of the following: Everyday," \
                             "Monday, Tuesday, Wednesday, Thursday, Friday, " \
                             "Saturday"
            ret['Success'] = False
        else:
            # Set the numeric equivalent for the day setting
            obj_au_settings.ScheduledInstallationDay = days[day]
            result = obj_au_settings.Save()
            if result is None:
                ret['Day'] = day
            else:
                ret['Comment'] = "Settings failed to save. Check permissions."
                ret['Success'] = False

    if time is not None:
        # Check for time as a string: if the time is not quoted, yaml will
        # treat it as an integer
        if not isinstance(time, six.string_types):
            ret['Comment'] = "Time argument needs to be a string; it may need to"\
                             "be quoted. Passed {0}. Time not set.".format(time)
            ret['Success'] = False
        # Check for colon in the time
        elif ':' not in time:
            ret['Comment'] = "Time argument needs to be in 00:00 format." \
                             " Passed {0}. Time not set.".format(time)
            ret['Success'] = False
        else:
            # Split the time by :
            t = time.split(":")
            # We only need the hours value
            obj_au_settings.FeaturedUpdatesEnabled = t[0]
            result = obj_au_settings.Save()
            if result is None:
                ret['Time'] = time
            else:
                ret['Comment'] = "Settings failed to save. Check permissions."
                ret['Success'] = False

    if msupdate is not None:
        # Microsoft Update requires special handling
        # First load the MS Update Service Manager
        obj_sm = win32com.client.Dispatch('Microsoft.Update.ServiceManager')

        # Give it a bogus name
        obj_sm.ClientApplicationID = "My App"

        if msupdate:
            # msupdate is true, so add it to the services
            try:
                obj_sm.AddService2('7971f918-a847-4430-9279-4a52d1efe18d', 7,
                                   '')
                ret['msupdate'] = msupdate
            except Exception as error:
                hr, msg, exc, arg = error.args  # pylint: disable=W0633
                # Consider checking for -2147024891 (0x80070005) Access Denied
                ret['Comment'] = "Failed with failure code: {0}".format(exc[5])
                ret['Success'] = False
        else:
            # msupdate is false, so remove it from the services
            # check to see if the update is there or the RemoveService function
            # will fail
            if _get_msupdate_status():
                # Service found, remove the service
                try:
                    obj_sm.RemoveService(
                        '7971f918-a847-4430-9279-4a52d1efe18d')
                    ret['msupdate'] = msupdate
                except Exception as error:
                    hr, msg, exc, arg = error.args  # pylint: disable=W0633
                    # Consider checking for the following
                    # -2147024891 (0x80070005) Access Denied
                    # -2145091564 (0x80248014) Service Not Found (shouldn't get
                    # this with the check for _get_msupdate_status above
                    ret['Comment'] = "Failed with failure code: {0}".format(
                        exc[5])
                    ret['Success'] = False
            else:
                ret['msupdate'] = msupdate

    ret['Reboot'] = get_needs_reboot()

    return ret
Esempio n. 10
0
def list_update(name=None, download=False, install=False):
    """
    Returns details for all updates that match the search criteria

    :param str name:
        The name of the update you're searching for. This can be the GUID
        (preferred), a KB number, or the full name of the update. Run list_updates
        to get the GUID for the update you're looking for.

    :param bool download:
        Download the update returned by this function. Run this function first
        to see if the update exists, then set download=True to download the
        update.

    :param bool install:
        Install the update returned by this function. Run this function first
        to see if the update exists, then set install=True to install the
        update. This will override download=True

    :return:
        Returns a dict containing a list of updates that match the name if
        download and install are both set to False. Should usually be a single
        update, but can return multiple if a partial name is given. If download or
        install is set to true it will return the results of
        win_wua.download_updates:

        .. code-block:: cfg

            List of Updates:
            {'<GUID>': {'Title': <title>,
                        'KB': <KB>,
                        'GUID': <the globally unique identifier for the update>
                        'Description': <description>,
                        'Downloaded': <has the update been downloaded>,
                        'Installed': <has the update been installed>,
                        'Mandatory': <is the update mandatory>,
                        'UserInput': <is user input required>,
                        'EULAAccepted': <has the EULA been accepted>,
                        'Severity': <update severity>,
                        'NeedsReboot': <is the update installed and awaiting reboot>,
                        'RebootBehavior': <will the update require a reboot>,
                        'Categories': [ '<category 1>',
                                        '<category 2>',
                                        ...]
                        }
            }

    :return type: dict

    CLI Examples:

    .. code-block:: bash

        # Recommended Usage using GUID without braces
        # Use this to find the status of a specific update
        salt '*' win_wua.list_update 12345678-abcd-1234-abcd-1234567890ab

        # Use the following if you don't know the GUID:

        # Using a KB number (could possibly return multiple results)
        # Not all updates have an associated KB
        salt '*' win_wua.list_update KB3030298

        # Using part or all of the name of the update
        # Could possibly return multiple results
        # Not all updates have an associated KB
        salt '*' win_wua.list_update 'Microsoft Camera Codec Pack'

    """
    if name is None:
        return 'Nothing to list'

    # Initialize the PyCom system
    pythoncom.CoInitialize()

    # Create a session with the Windows Update Agent
    wua_session = win32com.client.Dispatch('Microsoft.Update.Session')

    # Create the searcher
    wua_searcher = wua_session.CreateUpdateSearcher()

    # Create the found update collection
    wua_found = win32com.client.Dispatch('Microsoft.Update.UpdateColl')

    # Try searching for the GUID first
    search_string = 'UpdateID=\'{0}\''.format(name)

    log.debug('Searching for update: {0}'.format(search_string.lower()))
    try:
        found_using_guid = False
        wua_search_result = wua_searcher.Search(search_string.lower())
        if wua_search_result.Updates.Count > 0:
            found_using_guid = True
        else:
            return "No update found"
    except Exception:
        log.debug('GUID not found, searching Title: {0}'.format(name))
        search_string = 'Type=\'Software\' or Type=\'Driver\''
        wua_search_result = wua_searcher.Search(search_string)

    # Populate wua_found
    if found_using_guid:
        # Found using GUID so there should only be one
        # Add it to the collection
        for update in wua_search_result.Updates:
            wua_found.Add(update)
    else:
        # Not found using GUID
        # Try searching the title for the Name or KB
        for update in wua_search_result.Updates:
            if name in update.Title:
                wua_found.Add(update)

    if install:
        guid_list = []
        for update in wua_found:
            guid_list.append(update.Identity.UpdateID)
        return install_updates(guid_list)

    if download:
        guid_list = []
        for update in wua_found:
            guid_list.append(update.Identity.UpdateID)
        return download_updates(guid_list)

    return _list_updates_build_report(wua_found)
Esempio n. 11
0
def download_updates(guid=None):
    """
    Downloads updates that match the list of passed GUIDs. It's easier to use
    this function by using list_updates and setting install=True.

    :param guid:
        A list of GUIDs to be downloaded

    :return:
        A dictionary containing the status, a message, and a list of updates
        that were downloaded.

    CLI Examples:

    .. code-block:: bash

        # Normal Usage
        salt '*' win_wua.download_updates \
                guid=['12345678-abcd-1234-abcd-1234567890ab',\
                      '87654321-dcba-4321-dcba-ba0987654321']
    """
    # Check for empty GUID
    if guid is None:
        return "No GUID Specified"

    # Initialize the PyCom system
    pythoncom.CoInitialize()

    # Create a session with the Windows Update Agent
    wua_session = win32com.client.Dispatch('Microsoft.Update.Session')
    wua_session.ClientApplicationID = 'Salt: Install Update'

    # Create the Searcher, Downloader, Installer, and Collections
    wua_searcher = wua_session.CreateUpdateSearcher()
    wua_download_list = win32com.client.Dispatch('Microsoft.Update.UpdateColl')
    wua_downloader = wua_session.CreateUpdateDownloader()

    ret = {}

    # Searching for the GUID
    search_string = ''
    search_list = ''
    log.debug('Searching for updates:')
    for ident in guid:
        log.debug('{0}'.format(ident))
        if search_string == '':
            search_string = 'UpdateID=\'{0}\''.format(ident.lower())
            search_list = '{0}'.format(ident.lower())
        else:
            search_string += ' or UpdateID=\'{0}\''.format(ident.lower())
            search_list += '\n{0}'.format(ident.lower())

    try:
        wua_search_result = wua_searcher.Search(search_string)
        if wua_search_result.Updates.Count == 0:
            log.debug('No Updates found for:\n\t\t{0}'.format(search_list))
            ret['Success'] = False
            ret['Details'] = 'No Updates found: {0}'.format(search_list)
            return ret
    except Exception:
        log.debug('Invalid Search String: {0}'.format(search_string))
        return 'Invalid Search String: {0}'.format(search_string)

    # List updates found
    log.debug('Found the following updates:')
    ret['Updates'] = {}
    for update in wua_search_result.Updates:
        # Check to see if the update is already installed
        ret['Updates'][update.Identity.UpdateID] = {}
        ret['Updates'][update.Identity.UpdateID]['Title'] = update.Title
        if update.IsInstalled:
            log.debug('Already Installed: {0}'.format(
                update.Identity.UpdateID))
            log.debug(u'\tTitle: {0}'.format(update.Title))
            ret['Updates'][update.Identity.UpdateID]['AlreadyInstalled'] = True
        # Make sure the EULA has been accepted
        if not update.EulaAccepted:
            log.debug(u'Accepting EULA: {0}'.format(update.Title))
            update.AcceptEula()  # pylint: disable=W0104
        # Add to the list of updates that need to be downloaded
        if update.IsDownloaded:
            log.debug('Already Downloaded: {0}'.format(
                update.Identity.UpdateID))
            log.debug(u'\tTitle: {0}'.format(update.Title))
            ret['Updates'][
                update.Identity.UpdateID]['AlreadyDownloaded'] = True
        else:
            log.debug('To Be Downloaded: {0}'.format(update.Identity.UpdateID))
            log.debug(u'\tTitle: {0}'.format(update.Title))
            ret['Updates'][
                update.Identity.UpdateID]['AlreadyDownloaded'] = False
            wua_download_list.Add(update)

    # Check the download list
    if wua_download_list.Count == 0:
        # Not necessarily a failure, perhaps the update has been downloaded
        log.debug('No updates to download')
        ret['Success'] = False
        ret['Message'] = 'No updates to download'
        return ret

    # Download the updates
    log.debug('Downloading...')
    wua_downloader.Updates = wua_download_list

    try:
        result = wua_downloader.Download()

    except Exception as error:

        ret['Success'] = False
        ret['Result'] = format(error)

        hr, msg, exc, arg = error.args  # pylint: disable=W0633
        # Error codes found at the following site:
        # https://msdn.microsoft.com/en-us/library/windows/desktop/hh968413(v=vs.85).aspx
        fc = {
            -2145124316: 'No Updates: 0x80240024',
            -2145124284: 'Access Denied: 0x8024044'
        }
        try:
            failure_code = fc[exc[5]]
        except KeyError:
            failure_code = 'Unknown Failure: {0}'.format(error)

        log.debug('Download Failed: {0}'.format(failure_code))
        ret['error_msg'] = failure_code
        ret['location'] = 'Download Section of download_updates'
        ret['file'] = 'win_wua.py'

        return ret

    log.debug('Download Complete')

    rc = {
        0: 'Download Not Started',
        1: 'Download In Progress',
        2: 'Download Succeeded',
        3: 'Download Succeeded With Errors',
        4: 'Download Failed',
        5: 'Download Aborted'
    }
    log.debug(rc[result.ResultCode])

    if result.ResultCode in [2, 3]:
        ret['Success'] = True
    else:
        ret['Success'] = False

    ret['Message'] = rc[result.ResultCode]

    for i in range(wua_download_list.Count):
        uid = wua_download_list.Item(i).Identity.UpdateID
        ret['Updates'][uid]['Result'] = rc[result.GetUpdateResult(
            i).ResultCode]

    return ret
Esempio n. 12
0
def Main(material, cantidad):
    """
    Function takes material number and quantity and creates a Handling Unit number
    If everything goes right it returns the serial number
    """
    import win32com.client
    import json
    import pythoncom
    try:
        pythoncom.CoInitialize()

        SapGuiAuto = win32com.client.GetObject("SAPGUI")

        application = SapGuiAuto.GetScriptingEngine

        connection = application.Children(0)

        if connection.DisabledByServer == True:
            print("Scripting is disabled by server")
            application = None
            SapGuiAuto = None
            return

        session = connection.Children(0)

        if session.Info.IsLowSpeedConnection == True:
            print("Connection is low speed")
            connection = None
            application = None
            SapGuiAuto = None
            return

        session.findById("wnd[0]/tbar[0]/okcd").text = "/nMFP11"
        session.findById("wnd[0]").sendVKey(0)
        session.findById("wnd[0]/usr/subSPLITTED_SCREEN:SAPLVHUDIAL2:0053/subAREA1:SAPLVHUDIAL2:0110/tabsTABSTRIP1/tabpTAB1/ssubSUB1:SAPLVHUDIAL2:0200/ctxtPLAPPLDATA-MATNR").text = material
        session.findById("wnd[0]/usr/subSPLITTED_SCREEN:SAPLVHUDIAL2:0053/subAREA1:SAPLVHUDIAL2:0110/tabsTABSTRIP1/tabpTAB1/ssubSUB1:SAPLVHUDIAL2:0200/ctxtPLAPPLDATA-WERKS").text = "5210"
        session.findById("wnd[0]/usr/subSPLITTED_SCREEN:SAPLVHUDIAL2:0053/subAREA1:SAPLVHUDIAL2:0110/tabsTABSTRIP1/tabpTAB1/ssubSUB1:SAPLVHUDIAL2:0200/ctxtPLAPPLDATA-LGORT").text = "0014"
        session.findById("wnd[0]/usr/subSPLITTED_SCREEN:SAPLVHUDIAL2:0053/subAREA1:SAPLVHUDIAL2:0110/tabsTABSTRIP1/tabpTAB1/ssubSUB1:SAPLVHUDIAL2:0200/txtPLAPPLDATA-MAXQUA").text = cantidad
        # session.findById("wnd[0]/usr/subSPLITTED_SCREEN:SAPLVHUDIAL2:0053/subAREA1:SAPLVHUDIAL2:0110/tabsTABSTRIP1/tabpTAB1/ssubSUB1:SAPLVHUDIAL2:0200/txtPLAPPLDATA-MAXQUA").setFocus()
        # session.findById("wnd[0]/usr/subSPLITTED_SCREEN:SAPLVHUDIAL2:0053/subAREA1:SAPLVHUDIAL2:0110/tabsTABSTRIP1/tabpTAB1/ssubSUB1:SAPLVHUDIAL2:0200/txtPLAPPLDATA-MAXQUA").caretPosition = 2
        session.findById("wnd[0]").sendVKey(0)
        session.findById("wnd[0]/tbar[0]/btn[11]").press()

        session.findById("wnd[0]/usr/subSPLITTED_SCREEN:SAPLVHUDIAL2:0053/subAREA3:SAPLVHUDIAL2:0072/btnHUEDIT").press()
        serial_num = session.findById(
            "wnd[0]/usr/tabsTS_HU_VERP/tabpUE6POS/ssubTAB:SAPLV51G:6010/tblSAPLV51GTC_HU_001/ctxtV51VE-EXIDV[0,0]").Text
        # session.findById("wnd[0]/usr/tabsTS_HU_VERP/tabpUE6POS/ssubTAB:SAPLV51G:6010/tblSAPLV51GTC_HU_001/ctxtV51VE-EXIDV[0,0]").caretPosition = 3
        # session.findById("wnd[0]").sendVKey(2)
        # session.findById("wnd[0]/tbar[0]/btn[12]").press()
        session.findById("wnd[0]/tbar[0]/btn[12]").press()
        session.findById("wnd[0]/tbar[0]/btn[12]").press()

        response = {"serial_num": serial_num, "result": "OK", "error": "N/A"}

        return json.dumps(response)

    except:
        try:
            error = session.findById("wnd[1]/usr/txtSPOP-TEXTLINE1").Text
            session.findById("wnd[1]/usr/btnSPOP-OPTION2").press()
            session.findById("wnd[0]/tbar[0]/btn[12]").press()
            session.findById("wnd[1]/usr/btnSPOP-OPTION1").press()
        except:
            error = session.findById("wnd[0]/sbar/pane[0]").Text
        response = {"serial_num": "N/A", "result": "N/A", "error": error}

        # session.findById("wnd[1]/usr/btnSPOP-OPTION2").press()
        session.findById("wnd[0]/tbar[0]/okcd").text = "/n"
        session.findById("wnd[0]").sendVKey(0)

        return json.dumps(response)

    finally:
        session = None
        connection = None
        application = None
        SapGuiAuto = None
Esempio n. 13
0
def members(name, members_list):
    '''
    remove a user from a group

    CLI Example:

    .. code-block:: bash

        salt '*' group.members foo 'user1,user2,user3'

    '''

    ret = {
        'name': name,
        'result': True,
        'changes': {
            'Users Added': [],
            'Users Removed': []
        },
        'comment': []
    }

    members_list = [
        __fixlocaluser(thisMember)
        for thisMember in members_list.lower().split(",")
    ]
    if not isinstance(members_list, list):
        ret['result'] = False
        ret['comment'].append('Members is not a list object')
        return ret

    pythoncom.CoInitialize()
    nt = win32com.client.Dispatch('AdsNameSpaces')
    try:
        groupObj = nt.GetObject('', 'WinNT://./' + name + ',group')
    except pywintypes.com_error as com_err:
        if len(com_err.excepinfo) >= 2:
            friendly_error = com_err.excepinfo[2].rstrip('\r\n')
        ret['result'] = False
        ret['comment'].append(
            ('Failure accessing group {0}.  {1}').format(name, friendly_error))
        return ret
    existingMembers = []
    for member in groupObj.members():
        existingMembers.append(
            member.ADSPath.replace('WinNT://', '').replace('/', '\\').encode(
                'ascii', 'backslashreplace').lower())

    existingMembers.sort()
    members_list.sort()

    if existingMembers == members_list:
        ret['result'] = None
        ret['comment'].append(('{0} membership is correct').format(name))
        return ret

    # add users
    for member in members_list:
        if member not in existingMembers:
            try:
                if not __opts__['test']:
                    groupObj.Add('WinNT://' + member.replace('\\', '/'))
                ret['changes']['Users Added'].append(member)
            except pywintypes.com_error as com_err:
                if len(com_err.excepinfo) >= 2:
                    friendly_error = com_err.excepinfo[2].rstrip('\r\n')
                ret['result'] = False
                ret['comment'].append(
                    ('Failed to add {0} to {1}.  {2}').format(
                        member, name, friendly_error))
                #return ret

    # remove users not in members_list
    for member in existingMembers:
        if member not in members_list:
            try:
                if not __opts__['test']:
                    groupObj.Remove('WinNT://' + member.replace('\\', '/'))
                ret['changes']['Users Removed'].append(member)
            except pywintypes.com_error as com_err:
                if len(com_err.excepinfo) >= 2:
                    friendly_error = com_err.excepinfo[2].rstrip('\r\n')
                ret['result'] = False
                ret['comment'].append(
                    ('Failed to remove {0} from {1}.  {2}').format(
                        member, name, friendly_error))
                #return ret

    return ret
Esempio n. 14
0
 def profile(self, resource=set()):
     pythoncom.CoInitialize()
     data = super(Profiler, self).profile(__name__, resource)
     pythoncom.CoUninitialize()
     return data
Esempio n. 15
0
def fileView(request):
    aesurl = request.POST['url']
    ext = request.POST['ext']
    print('aesview', aesurl)

    pdfurl = ''
    docurl = ''
    nameonly = ''
    if ext == '.pdf':
        pdfurl = aesurl[:-3] + 'pdf'
        print('aesview', aesurl)
        print('pdfview', pdfurl)

        # (should store the filename and extension in db for) decrypt the file
        try:
            bufferSize = 64 * 1024
            passw = "#EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e"
            encFileSize = stat(aesurl).st_size
            with open(aesurl, "rb") as fIn:
                with open(pdfurl, "wb") as fOut:
                    pyAesCrypt.decryptStream(fIn, fOut, passw, bufferSize,
                                             encFileSize)
            with open(pdfurl, 'rb') as pdf:
                response = HttpResponse(pdf.read(),
                                        content_type='application/pdf')
                response['Content-Disposition'] = 'filename=some_file.pdf'
            return response
        finally:
            os.remove(pdfurl)

    elif ext == 'docx':
        # word to pdf
        nameonly = aesurl[:-4]
        docurl = aesurl[:-4] + '.docx'
        print('aesview', aesurl)
        print('nameonly', nameonly)
        print('docurl', docurl)

        try:
            bufferSize = 64 * 1024
            passw = "#EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e"
            encFileSize = stat(aesurl).st_size
            with open(aesurl, "rb") as fIn:
                with open(docurl, "wb") as fOut:
                    pyAesCrypt.decryptStream(fIn, fOut, passw, bufferSize,
                                             encFileSize)

            pythoncom.CoInitialize()
            wdFormatPDF = 17
            # print(tempfile.gettempdir(),'temp')

            in_file = os.path.abspath(docurl)
            # out_file = os.path.abspath('D:/cemilac/certa/defence/media/org1.pdf')

            word = comtypes.client.CreateObject('Word.Application')
            doc = word.Documents.Open(in_file)
            doc.SaveAs(nameonly + '.pdf', FileFormat=wdFormatPDF)
            doc.Close()
            word.Quit()
            with open(nameonly + '.pdf', 'rb') as pdf:
                response = HttpResponse(pdf.read(),
                                        content_type='application/pdf')
                response['Content-Disposition'] = 'filename=some_file.pdf'
            return response
        finally:
            os.remove(nameonly + '.pdf')
            os.remove(docurl)
Esempio n. 16
0
def Main(sap_num, quanity, from_Stype, from_S_bin, to_Stype, to_Sbin):
    """
    Function takes a material number and quantity to perform transfer order
    The transfer order is from 102/103 to VUL/V02
    """
    import json
    import win32com.client
    import pythoncom
    try:

        pythoncom.CoInitialize()
        SapGuiAuto = win32com.client.GetObject("SAPGUI")
        application = SapGuiAuto.GetScriptingEngine
        connection = application.Children(0)

        if connection.DisabledByServer == True:
            print("Scripting is disabled by server")
            application = None
            SapGuiAuto = None
            return

        session = connection.Children(0)

        if session.Info.IsLowSpeedConnection == True:
            print("Connection is low speed")
            connection = None
            application = None
            SapGuiAuto = None
            return

        session.findById("wnd[0]/tbar[0]/okcd").text = "/nLT01"
        session.findById("wnd[0]").sendVKey(0)
        session.findById("wnd[0]/usr/ctxtLTAK-LGNUM").text = "521"
        session.findById("wnd[0]/usr/ctxtLTAK-BWLVS").text = "998"
        session.findById("wnd[0]/usr/ctxtLTAP-MATNR").text = sap_num
        session.findById("wnd[0]/usr/txtRL03T-ANFME").text = quanity
        session.findById("wnd[0]/usr/ctxtLTAP-WERKS").text = "5210"
        session.findById("wnd[0]/usr/ctxtLTAP-LGORT").text = "0012"
        session.findById("wnd[0]").sendVKey(0)
        session.findById("wnd[0]/usr/ctxtLTAP-LDEST").text = "dummy"
        session.findById("wnd[0]/usr/ctxtLTAP-VLTYP").text = from_Stype
        session.findById("wnd[0]/usr/ctxtLTAP-VLBER").text = "001"
        session.findById("wnd[0]/usr/txtLTAP-VLPLA").text = from_S_bin
        session.findById("wnd[0]/usr/ctxtLTAP-NLTYP").text = to_Stype
        session.findById("wnd[0]/usr/ctxtLTAP-NLBER").text = "001"
        session.findById("wnd[0]/usr/txtLTAP-NLPLA").text = to_Sbin
        session.findById("wnd[0]").sendVKey(0)
        session.findById("wnd[0]").sendVKey(0)

        result = session.findById("wnd[0]/sbar/pane[0]").Text

        session.findById("wnd[0]/tbar[0]/okcd").text = "/n"
        session.findById("wnd[0]").sendVKey(0)
        try:
            session.findById("wnd[1]/usr/btnSPOP-OPTION2").press()
        except:
            pass
        response = {"serial": "N/A", "result": f'{result}', "error": "N/A"}
        return json.dumps(response)

    except:
        try:
            error = session.findById("wnd[1]/usr/txtSPOP-TEXTLINE1").Text
            session.findById("wnd[1]/usr/btnSPOP-OPTION2").press()
            session.findById("wnd[0]/tbar[0]/btn[12]").press()
            session.findById("wnd[1]/usr/btnSPOP-OPTION1").press()
        except:
            error = session.findById("wnd[0]/sbar/pane[0]").Text
        response = {"serial": "N/A", "result": "N/A", "error": error}

        # session.findById("wnd[1]/usr/btnSPOP-OPTION2").press()
        session.findById("wnd[0]/tbar[0]/okcd").text = "/n"
        session.findById("wnd[0]").sendVKey(0)

        return (json.dumps(response))

    finally:
        session = None
        connection = None
        application = None
        SapGuiAuto = None
Esempio n. 17
0
def __initialize_pythoncom(func, *args, **kwargs):
    """ Function decorator. Initialize Python COM interface before function call
    """
    with suppress(Exception):
        pythoncom.CoInitialize()
    yield func(*args, **kwargs)
Esempio n. 18
0
    def ThreadWorker(self, stopThreadEvent):
        pythoncom.CoInitialize()        
        
        #Attach interface to the OCX
        AxkmkusbT = None
        try:
            AxkmkusbT = win32com.client.Dispatch("KMKUSB5I8OOCX.KMKUSB")
        except: 
            raise eg.Exception(self.text.txt_OCX_CannotBeFound_T)
        if AxkmkusbT != None:
            print self.text.txt_OCX_Found_T
        
        #Address the board...
        AxkmkusbT.device = self.b_nbr
        print self.text.txt_Initiated

        #Open the port        
        AxkmkusbT.port_open_close = 1

        #Set outputs to last known states
        if self.kmkSum != self.kmkSum_trigger:
            AxkmkusbT.out = str(self.kmkSum)
            print self.text.txt_InitOut, self.kmkSum
            self.kmkSum_trigger = self.kmkSum

        while not stopThreadEvent.isSet():
            inputs = str(AxkmkusbT.binary)
            print AxkmkusbT.binary
            print inputs
            
            if inputs!="":
                inputList = []
                
                for i in range(0, len(inputs)):
                    inputList.insert(i, inputs[i])
            
                for i in range (0, len(inputs)):
                    ret = int(inputList[i])
            
                    if ret != self.di_event_trigger[i]:
                        if self.di_event_memory[i] != ret:
                            self.TriggerEvent(
                                self.text.txt_DI+str(i+1)+
                                self.text.txt_State+str(ret)
                            )
                            del self.di_event_memory[i]
                            self.di_event_memory.insert(i, ret)
                            
                    if self.di_event_memory[i] != ret:
                        self.TriggerEvent(
                            self.text.txt_DI+str(i+1)+
                            self.text.txt_State+str(ret)
                        )
                        del self.di_event_memory[i]
                        self.di_event_memory.insert(i, ret)
            else:
                #The board is not responding
                self.TriggerEvent(
                    self.text.txt_boardError+
                    str(self.b_nbr)
                )
                self.__stop__()
            
            if self.kmkSum != self.kmkSum_trigger:
                AxkmkusbT.out = str(self.kmkSum_trigger)
#                print self.text.txt_OutSent, self.kmkSum_trigger
                self.kmkSum = self.kmkSum_trigger

#            print self.di_event_trigger
#            print self.di_event_memory
#            print self.do_state_memory
            #Test to see what gets sent.
            print self.text.txt_OutSet, str(self.kmkSum)
            stopThreadEvent.wait(self.thread_wait)

        AxkmkusbT.port_open_close = 0
        pythoncom.CoUninitialize()
        print self.text.txt_Polling
Esempio n. 19
0
def initThread(threadIndex):
    time.sleep(threadIndex * 0.2)
    # start the COM environment in a MT situation
    pythoncom.CoInitialize()
    # dispatch a COM object to each thread via "request" reserved variable
    request.x=win32com.client.Dispatch("Python.TestServer")
Esempio n. 20
0
def summaryThread(root, PATHS, ver, curDir, initial_information, cnvCompl, text_eve, q, txt):
    while not cnvCompl.isSet() or not initial_information.isSet():
        time.sleep(1)

    global main_logger
    main_logger = logging.getLogger('main')
    main_logger.info("Summarizing Results")

    cur_tk = tools.TkMethods(root)
    start = cur_tk.startLabel(label_start)
    tools.put_text("Starting to summarize results", q, txt)

    files = []
    files.append('{}/{}.pbz2'.format(PATHS["DIR_TREE"][2], cfg.FullGeno))
    files.append('{}/{}.pbz2'.format(PATHS["DIR_TREE"][5], cfg.FullCNV))
    for file in cfg.GenoPickles:
        files.append('{}/{}.pbz2'.format(PATHS["DIR_TREE"][3], file))
    for file in cfg.CNVPickles:
        files.append('{}/{}.pbz2'.format(PATHS["DIR_TREE"][6], file))

    for file in files:
        if not os.path.isfile(file):
             main_logger.error("Missing {} in log directory".format(file))
             app = tools.ProcessError("{} \nMissing".format(file))

    tools.put_text("Aggregating Results", q, txt)

    geno = tools.decompress_pickle(files[0])
    cnv = tools.decompress_pickle(files[1])
    # cnv.rename(columns={'Annotation1': 'Custom Annotation', 'Chromosome': 'Chr',
    #             'Annotation2': 'Custom Annotation 2',
    #             'Annotation3': 'Custom Annotation 3',
    #             'Annotation4': 'Custom Annotation 4'}, inplace=True)
    combained = pd.concat([geno, cnv], ignore_index=True, sort=False)
    combained.insert(0, 'Analysis Date', curDate)
    combained.insert(0, 'Run Name', PATHS["RUN_NAME"])

    # try:
    #     if os.path.isfile("{}.pbz2".format(cfg.AG_DB)):
    #         ag_db = tools.decompress_pickle("{}.pbz2".format(cfg.AG_DB))
    #         ag_db = pd.concat([ag_db, combained], ignore_index=True, sort=False)
    #         ag_db.drop_duplicates(keep='last', inplace=True)
    #     else:
    #         ag_db = combained
    #     tools.compressed_pickle("{}".format(cfg.AG_DB), ag_db)
    #     tools.compressed_pickle("{}/AG_DB_{}".format(PATHS["DIR_TREE"][-1], curDate), ag_db)
    # except Exception as e:
    #     main_logger.info("Failed to aggregate raw results in Appendix\n{}".format(e))

    panels = {}
    for panel in cfg.Panels_names[:-1]:
        if panel != 'Extended':
            cur = "{}{}{}{}".format(cfg.path_to_panel,'\\', panel,'.AGID.pbz2')
            if not os.path.isfile(cur):
                 main_logger.error("Missing {} panel list".format(cur))
                 app = tools.ProcessError("{} \nMissing".format(cur))
            temp = tools.decompress_pickle(cur)
            panels[panel] = [agid for line in temp for agid in line.split('/')]
            panels[panel].append(np.nan)

    results = cfg.full_results
    results.insert(0, 'temp')
    results.insert(0, 'temp')
    writer = pd.ExcelWriter("{}/Results.xlsx".format(PATHS["DIR_TREE"][1]), engine='xlsxwriter')
    for i in range(1, len(files)-2):
        df = tools.decompress_pickle(files[i])
        if i == 1:
            temp = df[['Sample', 'Gender']].drop_duplicates()
        for s, info in PATHS["SAMPLE_DICT"].items():
            sample_panel = info[1]
            if sample_panel != 'Extended':
                # print(s, sample_panel)
                sub = df.where(df.Sample == "{}_{}".format(info[0], s))
                sub.dropna(how = 'all', inplace = True)
                to_remove = []
                for index, row in sub.iterrows():
                    if row.AGID not in panels[sample_panel]:
                        to_remove.append(index)
                df.drop(to_remove, inplace = True)
        if i != 1:
            df.to_excel(writer, sheet_name=results[i], index=False)
        else:
            df = df.merge(temp, how='outer', on=['Sample', 'Gender'])
        tools.compressed_pickle(files[i].split('.pbz2')[0] + '.filtered', df)
        files[i] = files[i].split('.pbz2')[0] + '.filtered.pbz2'
    df = tools.decompress_pickle(files[i+1])
    df.to_excel(writer, sheet_name=results[i+1], index=False)
    df = tools.decompress_pickle(files[i+2])
    df.to_excel(writer, sheet_name=results[i+2], index=False)
    writer.save()

    tools.put_text("Creating Final Reports", q, txt)
    try:
        wordVer = "20{}".format(int(tools.getMicrosoftWordVersion()))
        main_logger.info("Office version {}".format(wordVer))
    except Exception as e:
        main_logger.info("Unable to get word version. Assuming 2016\n{}".format(e))
        tools.put_text("Unable to get word version. Assuming 2016", q, txt)

    try:
        sample_summary = RCv2.MAIN_RCv2wrapper(PATHS["DIR_TREE"][0], wordVer,
                PATHS["BAM_PATH"], PATHS["Hospital"], PATHS['SAMPLE_DICT'],
                cfg.MutPDF, 'main', PATHS["RUN_NAME"], files[3], files[1],
                PATHS["EXTRA_INFO_PATH"])
        sample_summary.to_pickle("{}/raw_sample_summary.pkl".format(PATHS["DIR_TREE"][-1]))
    except Exception as e:
        main_logger.error("Failed to exceute MAIN_RCv2wrapper\n{}".format(e))
        app = tools.ProcessError("Report Creator")
    tools.put_text("Formating Sample Summary", q, txt)

    try:
        sample_summary = formatExcel.AddIgvLink(sample_summary, PATHS["BAM_PATH"], cfg.MyScreen_Ver)
    except Exception as e:
        main_logger.error("Failed to exceute AddIgvLink\n{}".format(e))
    # formatExcel.excel_formatter(sample_summary, PATHS, cfg.MyScreen_Ver)
    try:
        sample_sum_excel, run = formatExcel.excel_formatter(sample_summary, PATHS, cfg.MyScreen_Ver)
    except Exception as e:
        main_logger.error("Failed to exceute format excel\n{}".format(e))
        app = tools.ProcessError("Format Sample Summary")

    csv_file, psv_file = formatCSV.create_summary_csv(All = files[2],
            summary = sample_sum_excel, v = cfg.MyScreen_Ver, r = run, d = curDate,
            out = PATHS["DIR_TREE"][-1])
    try:
        csv_file, psv_file = formatCSV.create_summary_csv(All = files[2],
            summary = sample_sum_excel, v = cfg.MyScreen_Ver, r = run, d = curDate,
            out = PATHS["DIR_TREE"][-1])
    except Exception as e:
        main_logger.error("Failed to exceute format CSV\n{}".format(e))
        app = tools.ProcessError("Format Sample Summary CSV")


    main_logger.info("Additional CSV output directory {}".format(os.path.isdir(cfg.CSV_dir)))
    try:
        shutil.copy(csv_file, os.path.join(cfg.CSV_dir,
            "sample_summary-{}.csv".format(curDate)))
        shutil.copy(psv_file, os.path.join(cfg.CSV_dir,
            "sample_summary-{}.psv".format(curDate)))
        main_logger.info("Outputed CSV and PSV in {}".format(cfg.CSV_dir))
    except IOError as e:
        main_logger.info("Unable to copy file. %s" % e)
    except:
        main_logger.info("Unexpected error:", sys.exc_info())


    if PATHS["Hospital"] != False:
        tools.put_text("Converting Reports to PDF", q, txt)
        try:
            pythoncom.CoInitialize()
            docx2pdf.convert("{}/REPORTS/".format(PATHS["DIR_TREE"][0]))
        except Exception as e:
            main_logger.error("Failed to convert reports to PDF\n{}".format(e))

    start.destroy()

    cur_tk = tools.TkMethods(root)
    start = cur_tk.startLabel("Analysis Completed Successfully")

    text_eve.set()

    def _global_quit():
        root.destroy
        try:
            subprocess.Popen('explorer {}'.format(PATHS["DIR_TREE"][0].replace('/', '\\')))
        except:
            pass
        os._exit(1)

    quit = Button(root, text="Analysis Completed\nPress to open results directory", command=_global_quit, bg = "blue", fg='white')
    quit.place(relx=.5, rely=.8, anchor="c")
Esempio n. 21
0
import sys
if 'win' in sys.platform:
    import pythoncom
    pythoncom.CoInitialize()

import clr

clr.AddReference("System.Xml")
clr.AddReference("PresentationFramework")
clr.AddReference("PresentationCore")
import System
from System.IO import StringReader
from System.Xml import XmlReader
from System.Windows.Markup import XamlReader, XamlWriter
from System.Windows import Window, Application


class HelloWorld():
    def __init__(self, xaml):
        self._xaml = xaml
        xr = XmlReader.Create(StringReader(xaml))
        self.winLoad = XamlReader.Load(xr)
        self._button = self.winLoad.FindName('button')
        self._stakpanel = self.winLoad.FindName('stackPanel')
        self._button.Click += self.onClick

    def onClick(self, sender, e):
        message = System.Windows.Controls.Label()
        message.FontSize = 16
        message.Content = 'Welcome to Dynamo'
        self._stakpanel.Children.Add(message)
Esempio n. 22
0
def join_domain(domain,
                username=None,
                password=None,
                account_ou=None,
                account_exists=False,
                restart=False):
    '''
    Join a computer to an Active Directory domain. Requires reboot.

    :param str domain:
        The domain to which the computer should be joined, e.g.
        ``example.com``

    :param str username:
        Username of an account which is authorized to join computers to the
        specified domain. Need to be either fully qualified like
        ``[email protected]`` or simply ``user``

    :param str password:
        Password of the specified user

    :param str account_ou:
        The DN of the OU below which the account for this computer should be
        created when joining the domain, e.g.
        ``ou=computers,ou=departm_432,dc=my-company,dc=com``

    :param bool account_exists:
        Needs to be set to ``True`` to allow re-using an existing account

    :param bool restart: Restarts the computer after a successful join

        .. versionadded:: 2015.8.2/2015.5.7

    :returns: Returns a dictionary if successful. False if unsuccessful.
    :rtype: dict, bool

    CLI Example:

    .. code-block:: bash

        salt 'minion-id' system.join_domain domain='domain.tld' \\
                         username='******' password='******' \\
                         account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\
                         account_exists=False, restart=True
    '''
    status = get_domain_workgroup()
    if 'Domain' in status:
        if status['Domain'] == domain:
            return 'Already joined to {0}'.format(domain)

    if username and '\\' not in username and '@' not in username:
        username = '******'.format(username, domain)

    if username and password is None:
        return 'Must specify a password if you pass a username'

    # remove any escape characters
    if isinstance(account_ou, str):
        account_ou = account_ou.split('\\')
        account_ou = ''.join(account_ou)

    NETSETUP_JOIN_DOMAIN = 0x1
    NETSETUP_ACCOUNT_CREATE = 0x2
    NETSETUP_DOMAIN_JOIN_IF_JOINED = 0x20
    NETSETUP_JOIN_WITH_NEW_NAME = 0x400

    join_options = 0x0
    join_options |= NETSETUP_JOIN_DOMAIN
    join_options |= NETSETUP_DOMAIN_JOIN_IF_JOINED
    join_options |= NETSETUP_JOIN_WITH_NEW_NAME
    if not account_exists:
        join_options |= NETSETUP_ACCOUNT_CREATE

    pythoncom.CoInitialize()
    c = wmi.WMI()
    comp = c.Win32_ComputerSystem()[0]
    err = comp.JoinDomainOrWorkgroup(Name=domain,
                                     Password=password,
                                     UserName=username,
                                     AccountOU=account_ou,
                                     FJoinOptions=join_options)

    # you have to do this because JoinDomainOrWorkgroup returns a strangely
    # formatted value that looks like (0,)
    if not err[0]:
        ret = {'Domain': domain, 'Restart': False}
        if restart:
            ret['Restart'] = reboot()
        return ret

    log.error(_lookup_error(err[0]))
    return False
Esempio n. 23
0
def get_wu_settings():
    '''
    Get current Windows Update settings.

    Returns:

        dict: A dictionary of Windows Update settings:

        Featured Updates:
            Boolean value that indicates whether to display notifications for
            featured updates.
        Group Policy Required (Read-only):
            Boolean value that indicates whether Group Policy requires the
            Automatic Updates service.
        Microsoft Update:
            Boolean value that indicates whether to turn on Microsoft Update for
            other Microsoft Products
        Needs Reboot:
            Boolean value that indicates whether the machine is in a reboot
            pending state.
        Non Admins Elevated:
            Boolean value that indicates whether non-administrators can perform
            some update-related actions without administrator approval.
        Notification Level:
            Number 1 to 4 indicating the update level:
                1. Never check for updates
                2. Check for updates but let me choose whether to download and
                   install them
                3. Download updates but let me choose whether to install them
                4. Install updates automatically
        Read Only (Read-only):
            Boolean value that indicates whether the Automatic Update
            settings are read-only.
        Recommended Updates:
            Boolean value that indicates whether to include optional or
            recommended updates when a search for updates and installation of
            updates is performed.
        Scheduled Day:
            Days of the week on which Automatic Updates installs or uninstalls
            updates.
        Scheduled Time:
            Time at which Automatic Updates installs or uninstalls updates.

    CLI Examples:

    .. code-block:: bash

        salt '*' win_wua.get_wu_settings
    '''
    ret = {}

    day = [
        'Every Day', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
        'Friday', 'Saturday'
    ]

    # Initialize the PyCom system
    pythoncom.CoInitialize()

    # Create an AutoUpdate object
    obj_au = win32com.client.Dispatch('Microsoft.Update.AutoUpdate')

    # Create an AutoUpdate Settings Object
    obj_au_settings = obj_au.Settings

    # Populate the return dictionary
    ret['Featured Updates'] = obj_au_settings.FeaturedUpdatesEnabled
    ret['Group Policy Required'] = obj_au_settings.Required
    ret['Microsoft Update'] = _get_msupdate_status()
    ret['Needs Reboot'] = get_needs_reboot()
    ret['Non Admins Elevated'] = obj_au_settings.NonAdministratorsElevated
    ret['Notification Level'] = obj_au_settings.NotificationLevel
    ret['Read Only'] = obj_au_settings.ReadOnly
    ret['Recommended Updates'] = obj_au_settings.IncludeRecommendedUpdates
    ret['Scheduled Day'] = day[obj_au_settings.ScheduledInstallationDay]
    # Scheduled Installation Time requires special handling to return the time
    # in the right format
    if obj_au_settings.ScheduledInstallationTime < 10:
        ret['Scheduled Time'] = '0{0}:00'.\
            format(obj_au_settings.ScheduledInstallationTime)
    else:
        ret['Scheduled Time'] = '{0}:00'.\
            format(obj_au_settings.ScheduledInstallationTime)

    return ret
Esempio n. 24
0
def unjoin_domain(username=None,
                  password=None,
                  domain=None,
                  workgroup='WORKGROUP',
                  disable=False,
                  restart=False):
    r'''
    Unjoin a computer from an Active Directory Domain. Requires restart.

    :param username:
        Username of an account which is authorized to manage computer accounts
        on the domain. Need to be fully qualified like ``[email protected]`` or
        ``domain.tld\user``. If domain not specified, the passed domain will be
        used. If computer account doesn't need to be disabled, can be None.

    :param str password:
        Password of the specified user

    :param str domain: The domain from which to unjoin the computer. Can be None

    :param str workgroup: The workgroup to join the computer to. Default is
    ``WORKGROUP``

        .. versionadded:: 2015.8.2/2015.5.7

    :param bool disable:
        Disable the user account in Active Directory. True to disable.

    :param bool restart: Restart the computer after successful unjoin

        .. versionadded:: 2015.8.2/2015.5.7

    :returns: Returns a dictionary if successful. False if unsuccessful.
    :rtype: dict, bool

    CLI Example:

    .. code-block:: bash

        salt 'minion-id' system.unjoin_domain restart=True

        salt 'minion-id' system.unjoin_domain username='******' \\
                         password='******' disable=True \\
                         restart=True
    '''
    status = get_domain_workgroup()
    if 'Workgroup' in status:
        if status['Workgroup'] == workgroup:
            return 'Already joined to {0}'.format(workgroup)

    if username and '\\' not in username and '@' not in username:
        if domain:
            username = '******'.format(username, domain)
        else:
            return 'Must specify domain if not supplied in username'

    if username and password is None:
        return 'Must specify a password if you pass a username'

    NETSETUP_ACCT_DELETE = 0x2

    unjoin_options = 0x0
    if disable:
        unjoin_options |= NETSETUP_ACCT_DELETE

    pythoncom.CoInitialize()
    c = wmi.WMI()
    comp = c.Win32_ComputerSystem()[0]
    err = comp.UnjoinDomainOrWorkgroup(Password=password,
                                       UserName=username,
                                       FUnjoinOptions=unjoin_options)

    # you have to do this because UnjoinDomainOrWorkgroup returns a
    # strangely formatted value that looks like (0,)
    if not err[0]:
        err = comp.JoinDomainOrWorkgroup(Name=workgroup)
        if not err[0]:
            ret = {'Workgroup': workgroup, 'Restart': False}
            if restart:
                ret['Restart'] = reboot()

            return ret
        else:
            log.error(_lookup_error(err[0]))
            log.error('Failed to join the computer to {0}'.format(workgroup))
            return False
    else:
        log.error(_lookup_error(err[0]))
        log.error('Failed to unjoin computer from {0}'.format(
            status['Domain']))
        return False
Esempio n. 25
0
    def __init__(self,
                 categories=None,
                 skipUI=True,
                 skipDownloaded=False,
                 skipInstalled=True,
                 skipReboot=False,
                 skipPresent=False,
                 skipSoftwareUpdates=False,
                 skipDriverUpdates=False,
                 skipHidden=True):
        log.debug('CoInitializing the pycom system')
        pythoncom.CoInitialize()

        self.skipUI = skipUI
        self.skipDownloaded = skipDownloaded
        self.skipInstalled = skipInstalled
        self.skipReboot = skipReboot
        self.skipPresent = skipPresent
        self.skipHidden = skipHidden

        self.skipSoftwareUpdates = skipSoftwareUpdates
        self.skipDriverUpdates = skipDriverUpdates

        # the list of categories that the user wants to be searched for.
        self.categories = categories

        # the list of categories that are present in the updates found.
        self.foundCategories = []
        # careful not to get those two confused.

        log.debug('dispatching update_session to keep the session object.')
        self.update_session = win32com.client.Dispatch(
            'Microsoft.Update.Session')

        log.debug(
            'update_session got. Now creating a win_searcher to seek out the updates'
        )
        self.win_searcher = self.update_session.CreateUpdateSearcher()

        # list of updates that are applicable by current settings.
        self.download_collection = win32com.client.Dispatch(
            'Microsoft.Update.UpdateColl')

        # list of updates to be installed.
        self.install_collection = win32com.client.Dispatch(
            'Microsoft.Update.UpdateColl')

        # the object responsible for fetching the actual downloads.
        self.win_downloader = self.update_session.CreateUpdateDownloader()
        self.win_downloader.Updates = self.download_collection

        # the object responsible for the installing of the updates.
        self.win_installer = self.update_session.CreateUpdateInstaller()
        self.win_installer.Updates = self.install_collection

        # the results of the download process
        self.download_results = None

        # the results of the installation process
        self.install_results = None

        # search results from CreateUpdateSearcher()
        self.search_results = None
Esempio n. 26
0
def user_data_search(account_num, account_pw, is_continue):
    print("접속상태 확인 : ", xa_session)
    if is_connected() == None:
        return ConnectionRefusedError
    

    # 쿼리핸들러를 이용해 DevCenter에 접근하기
    pythoncom.CoInitialize()
    inst_xaquery_t0424 = win_client.DispatchWithEvents("XA_DataSet.XAQuery", XAQueryEventHandlerT0424)
    pythoncom.CoUninitialize()

    # 가져올 데이터가 들어있는 res파일 생성해주기
    inst_xaquery_t0424.ResFileName = "C:\\eBEST\\xingAPI\\Res\\t0424.res"
    
    # 서버에 request보낼 데이터 세팅하기
    # DevCenter1을 열어보면 InBlock에는 데이터를 넣어주어야하는 목록이 적혀있다. 여기에 데이터를 넣어줄 때는 SetFieldData를 쓴다.
    # 파라미터는 1. 블럭명, 2. 요소명, 3. 단일데이터인지 멀티데이터인지 구분(단일이면 0), 4. 집어넣을 값 
    inst_xaquery_t0424.SetFieldData("t0424InBlock", "accno", 0, account_num) # 계좌정보
    inst_xaquery_t0424.SetFieldData("t0424InBlock", "passwd", 0, account_pw)  # 비밀번호
    inst_xaquery_t0424.SetFieldData("t0424InBlock", "prcgb", 0, 1)          # 단가 구분
    inst_xaquery_t0424.SetFieldData("t0424InBlock", "chegb", 0, 0)          # 체결 구분
    inst_xaquery_t0424.SetFieldData("t0424InBlock", "dangb", 0, 0)          # 단일가 구분
    inst_xaquery_t0424.SetFieldData("t0424InBlock", "charge", 0, 1)          # 제비용 포함여부
    inst_xaquery_t0424.SetFieldData("t0424InBlock", "cts_expcode", 0, " ")          # CTS 종목번호

    # 입력한 데이터로 서버에 request요청
    inst_xaquery_t0424.Request(is_continue)
        
    # 응답이 올 때까지 대기
    print("T0424 응답 대기 : ", XAQueryEventHandlerT0424.data_flag)
    result = waiting(XAQueryEventHandlerT0424)
    print("T0424 응답 결과 : ", result)
    if result == TimeoutError:
        return result

    # Response된 응답을 이용해 원하는 데이터 추출하기
    estimated_net_worth = inst_xaquery_t0424.GetFieldData("t0424OutBlock", "sunamt", 0)                     # 추정 순자산
    user_property = estimated_net_worth

    # 보유종목을 담아줄 리스트
    retained_item_list = []

    # 전체 데이터 개수 체크
    retained_item_list_length = inst_xaquery_t0424.GetBlockCount("t0424OutBlock1")
    for i in range(retained_item_list_length):
        expcode = inst_xaquery_t0424.GetFieldData("t0424OutBlock1", "expcode", i)  # 종목번호
        if (expcode == "") :
            break
        hname = inst_xaquery_t0424.GetFieldData("t0424OutBlock1", "hname", i)      # 종목명
        price = inst_xaquery_t0424.GetFieldData("t0424OutBlock1", "price", i)      # 현재가
        mdposqt = inst_xaquery_t0424.GetFieldData("t0424OutBlock1", "mdposqt", i)  # 매도가능수량
        sunikrt = inst_xaquery_t0424.GetFieldData("t0424OutBlock1", "sunikrt", i)  # 수익률
        retained_item = {
            "expcode": expcode,
            "hname": hname,
            "price": price,
            "mdposqt": mdposqt,
            "sunikrt": sunikrt
        }
        retained_item_list.append(retained_item)
    
    print("유저 보유종목은? : ", retained_item_list)
    return [user_property, retained_item_list]
Esempio n. 27
0
def grep_excel(query, fpath, re_flags):
    hlogs = []

    app = None

    try:
        # COM初期化  ※スレッドごとに必要
        pythoncom.CoInitialize()

        # Excel起動
        app = win32com.client.DispatchEx('Excel.Application')
        app.Visible = False
        app.DisplayAlerts = False

        # ブックオープン
        wb = app.Workbooks.Open(fpath, ReadOnly=True)

        # 全シートを処理
        for ws in wb.Worksheets:
            debug_print(ws.Name)
            debug_print(ws.UsedRange.Address)

            # 2: xlSheetVeryHidden (再表示不可) に設定されているシートは対象外
            if ws.Visible == 2:
                continue

            # セル
            #for cell in ws.UsedRange.Cells:
            for cell in [ws.Cells(r, c) for r, c in get_used_range_strict(ws)
                         ]:  # データが疎なシートの高速化
                # 検索
                text = str(cell.Value)
                if re.search(query, text, flags=re_flags):
                    # ヒットログを作成
                    l = make_log_hit('Cell', {
                        'Sheet': ws.Name,
                        'Address': cell.Address.replace('$', '')
                    }, query, text, re_flags)
                    hlogs.append(l)

            # 図形
            for shape in ws.Shapes:
                # 図形種類がオートシェイプ(1:msoAutoShape)またはテキストボックス(17:msoTextBox)であり、
                # 文字列を持っている場合(線などではない場合)
                if (shape.Type == 1
                        or shape.Type == 17) and shape.TextFrame2.HasText:
                    # 検索
                    text = str(shape.TextFrame2.TextRange.Text)
                    if re.search(query, text, flags=re_flags):
                        # ヒットログを作成
                        l = make_log_hit('Shape', {
                            'Sheet': ws.Name,
                            'Name': shape.Name
                        }, query, text, re_flags)
                        hlogs.append(l)

            # コメント
            for comment in ws.Comments:
                # 検索
                text = str(comment.Text())
                if re.search(query, text, flags=re_flags):
                    # ヒットログを作成
                    l = make_log_hit(
                        'Comment', {
                            'Sheet': ws.Name,
                            'Address': comment.Parent.Address.replace('$', '')
                        }, query, text, re_flags)
                    hlogs.append(l)

        if wb is not None: wb.Close()

    except Exception as e:
        print('Error: Failer in Excel operation.')
        raise

    finally:
        # アプリケーションを終了
        if app is not None: app.Quit()

    return hlogs
Esempio n. 28
0
def stock_chart_search(shcode, gubun, ncnt, qrycnt, sdate, edate, is_continue):
    # TODO Print 지우기
    if is_connected() == None:
        return ConnectionRefusedError
    

    # 쿼리핸들러를 이용해 DevCenter에 접근하기
    pythoncom.CoInitialize()
    inst_xaquery_t4201 = win_client.DispatchWithEvents("XA_DataSet.XAQuery", XAQueryEventHandlerT4201)
    pythoncom.CoUninitialize()
    
    # 가져올 데이터가 들어있는 res파일 생성해주기
    inst_xaquery_t4201.ResFileName = "C:\\eBEST\\xingAPI\\Res\\t4201.res"


    # 데이터 단일조회인지 연속
    if is_continue :
        # 서버에 request보낼 데이터 세팅하기
        # 종목명
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "shcode", 0, shcode)
        # 봉구분(0: 틱봉, 1:분봉, 2: 일봉, 3: 주봉, 4: 월봉)
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "gubun", 0, gubun)
        # 봉 단위(gubun이 1이면서 ncnt가 1이면 1분봉 단위로, 2면 2분봉 단위로 30이면 30분봉 단위로 보여줌)
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "ncnt", 0, ncnt)
        # 봉의 개수 (최대 몇개 노출시킬 것인지 결정 => 1 ~ 500까지만 유효)
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "qrycnt", 0, qrycnt)
        # 일자 기준 (0: 전체일자, 1: 오늘만 => 전체를 사용할 예정)
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "tdgb", 0, 0)
        # 시작일, 종료일(최소 일봉부터 이 내용이 적용됌 틱봉, 분봉은 이 내용이 적용되지 않으므로 주의 필요)
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "sdate", 0, sdate)
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "edate", 0, edate)
        # 아래는 기본설정을 이용하면 됌
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "cts_date", 0, " ")
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "cts_time", 0, " ")
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "cts_daygb", 0, " ")

        # 입력한 데이터로 서버에 request요청
        inst_xaquery_t4201.Request(True)


        # 응답이 올 때까지 대기
        print("T4201 응답 대기 : ", XAQueryEventHandlerT4201.data_flag)
        result = waiting(XAQueryEventHandlerT4201)
        print("T4201 응답 결과 : ", result)
        if result == TimeoutError:
            return TimeoutError
    else :
        # 서버에 request보낼 데이터 세팅하기
        # 종목명
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "shcode", 0, shcode)
        # 봉구분(0: 틱봉, 1:분봉, 2: 일봉, 3: 주봉, 4: 월봉)
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "gubun", 0, gubun)
        # 봉 단위(gubun이 1이면서 ncnt가 1이면 1분봉 단위로, 2면 2분봉 단위로 30이면 30분봉 단위로 보여줌)
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "ncnt", 0, ncnt)
        # 봉의 개수 (최대 몇개 노출시킬 것인지 결정 => 1 ~ 500까지만 유효)
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "qrycnt", 0, qrycnt)
        # 일자 기준 (0: 전체일자, 1: 오늘만 => 전체를 사용할 예정)
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "tdgb", 0, 0)
        # 시작일, 종료일(최소 일봉부터 이 내용이 적용됌 틱봉, 분봉은 이 내용이 적용되지 않으므로 주의 필요)
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "sdate", 0, sdate)
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "edate", 0, edate)
        # 아래는 기본설정을 이용하면 됌
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "cts_date", 0, " ")
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "cts_time", 0, " ")
        inst_xaquery_t4201.SetFieldData("t4201InBlock", "cts_daygb", 0, " ")

        # 입력한 데이터로 서버에 request요청
        inst_xaquery_t4201.Request(0)


        # 응답이 올 때까지 대기
        print("T4201 응답 대기 : ", XAQueryEventHandlerT4201.data_flag)
        result = waiting(XAQueryEventHandlerT4201)
        print("T4201 응답 결과 : ", result)
        if result == TimeoutError:
            return TimeoutError

    # 내보낼 데이터 목록
    stock_detail_list = []

    # 전체 데이터가 몇개인지 체크
    count = int(qrycnt)
    # 원하는 만큼 데이터 추출하기
    for i in range(count):
        stock_date = inst_xaquery_t4201.GetFieldData("t4201OutBlock1", "date", i)             # 날짜
        stock_time = inst_xaquery_t4201.GetFieldData("t4201OutBlock1", "time", i)             # 시간
        stock_open = inst_xaquery_t4201.GetFieldData("t4201OutBlock1", "open", i)             # 시가
        stock_high = inst_xaquery_t4201.GetFieldData("t4201OutBlock1", "high", i)             # 고가
        stock_low = inst_xaquery_t4201.GetFieldData("t4201OutBlock1", "low", i)               # 저가
        stock_close = inst_xaquery_t4201.GetFieldData("t4201OutBlock1", "close", i)           # 종가
        stock_jdiff_vol = inst_xaquery_t4201.GetFieldData("t4201OutBlock1", "jdiff_vol", i)   # 거래량
        # stock_value = inst_xaquery_t4201.GetFieldData("t4201OutBlock1", "value", i)           # 거래대금
        # stock_jongchk = inst_xaquery_t4201.GetFieldData("t4201OutBlock1", "jongchk", i)       # 수정구분
        # stock_rate = inst_xaquery_t4201.GetFieldData("t4201OutBlock1", "rate", i)             # 수정비율
        # stock_pricechk = inst_xaquery_t4201.GetFieldData("t4201OutBlock1", "pricechk", i)     # 수정주가반영항목
        # stock_ratevalue = inst_xaquery_t4201.GetFieldData("t4201OutBlock1", "ratevalue", i)   # 수정비율반영거래대금
        if stock_date == "" :
            break
        
        stock_detail = {"stock_date" : stock_date[0:4] + "-" + stock_date[4:6] + "-" + stock_date[6:8], "stock_time" : stock_time, "stock_low" : stock_low, "stock_open" : stock_open, "stock_close" : stock_close, "stock_high" : stock_high, "stock_jdiff_vol" : stock_jdiff_vol}
        stock_detail_list.append(stock_detail)


    return stock_detail_list
Esempio n. 29
0
def data_sheet(request, id):

    idprefix = request.POST['idprefix']
    print(idprefix, 'jjjjjjjjjjjj')

    doc_final_path = 'E:/certa-drdo/certa/TA_Datasheet.docx'
    final_path = 'E:/certa-drdo/certa/'
    # finalpath=final_path.replace('/','\\')
    pdf_final_path = 'E:/certa-drdo/certa/TA_Datasheet.pdf'
    if os.path.isfile(pdf_final_path):
        with open(pdf_final_path, 'rb') as pdf:
            response = HttpResponse(pdf.read(), content_type='application/pdf')
            response['Content-Disposition'] = 'filename=some_file.pdf'
        return response
    elif os.path.isfile(doc_final_path):
        print('mmmmmmmmmmmmmm')
        pythoncom.CoInitialize()
        wdFormatPDF = 17
        # print(tempfile.gettempdir(),'temp')

        in_file = os.path.abspath(doc_final_path)
        # out_file = os.path.abspath('D:/cemilac/certa/defence/media/org1.pdf')

        word = comtypes.client.CreateObject('Word.Application')
        doc = word.Documents.Open(in_file)
        doc.SaveAs('E:/certa-drdo/certa/TA_Datasheet.pdf',
                   FileFormat=wdFormatPDF)
        print('nnnnnnnnnnn')
        doc.Close()
        word.Quit()
        with open(final_path + 'TA_Datasheet.pdf', 'rb') as pdf:
            response = HttpResponse(pdf.read(), content_type='application/pdf')
            response['Content-Disposition'] = 'filename=some_file.pdf'
        return response
    else:
        curr_path = "/" + str(id) + "/" + idprefix + "Annexure 6/"
        curr_path = curr_path.replace('/', '\\')
        new_path = os.path.join(settings.MEDIA_ROOT + curr_path)

        # if os.path.isdir(new_path):
        #     with open(new_path+'TA Datasheet.docx', 'rb') as pdf:
        #         response = HttpResponse(pdf.read(),content_type='application/pdf')
        #         response['Content-Disposition'] = 'filename=some_file.pdf'
        #     return response
        # else:
        taa = TAapplicationmodel.objects.filter(user_id=id).first()

        # template = get_template('dealing officer/Draft TA pdf.html')
        target_file = StringIO()
        template = DocxTemplate(
            "E:/certa-drdo/certa/dashboard/templates/dealing officer/DS template.docx"
        )
        context = {
            'firmname': taa.firmname,
            'addr1': taa.addr1,
            'item_name': taa.item_name,
            'part_no': taa.part_no
        }
        html = template.render(context)
        doc_io = io.BytesIO()  # create a file-like object
        template.save("TA_Datasheet.docx")  # save data to file-like object

        new_path1 = 'E:\certa-drdo\certa\TA_Datasheet.docx'
        # output_path = os.path.join(settings.MEDIA_ROOT) + '/89/result.pdf'
        # new_path=new_path.replace('\','//')

        taa = TAapplicationfiles.objects.filter(user_id=id,
                                                refid=idprefix,
                                                refpath='Annexure 6').first()
        aesurl = taa.filepath
        docurl = aesurl[:-4]
        print('aesview', aesurl)
        print('docurl', docurl)

        bufferSize = 64 * 1024
        passw = "#EX\xc8\xd5\xbfI{\xa2$\x05(\xd5\x18\xbf\xc0\x85)\x10nc\x94\x02)j\xdf\xcb\xc4\x94\x9d(\x9e"
        encFileSize = stat(aesurl).st_size
        with open(aesurl, "rb") as fIn:
            with open(docurl, "wb") as fOut:
                pyAesCrypt.decryptStream(fIn, fOut, passw, bufferSize,
                                         encFileSize)

        templateDoc1 = Document(new_path1)
        templateDoc = Document(docurl)

        # templateDoc1.add_page_break()

        for element in templateDoc.element.body:
            templateDoc1.element.body.append(element)

        templateDoc1.save(new_path1)
        messages.success(
            request,
            'Data_sheet Successfully Prepared, Click again to view the file !')

        reg = TAapplicationmodel.objects.filter(
            file_in_id=str(request.user.id))
        return render(request, 'tcs do/receivedtyperecord.html', {
            'details': reg,
            'status': True
        })
Esempio n. 30
0
    def enableps(machinename, username, password):
        result = None
        conn = None
        pythoncom.CoInitialize()
        try:
            LogHelper.append("try to enable ps on {0} with {1}:{2}".format(
                machinename, username, password))
            conn = wmi.WMI(computer=machinename,
                           user=username,
                           password=password,
                           namespace=r'root\cimv2')
        except Exception as e:
            print(str(e))
            LogHelper.append(str(conn))
            LogHelper.append("connect wmi failed on {0} with {1}:{2}".format(
                machinename, username, password))
            conn == None
            result == False
        if conn != None:
            """
            try:
                ## this need to be change, a service running can't be regarded as PS enabled
                svcs = conn.Win32_Service()
                for svc in svcs:
                    if svc.Name == 'WinRM' and svc.State == 'Running':
                        result = True
                        LogHelper.append("winrm service is running on {0} with {1}:{2}".format(machinename, username, password))
                        break
            except Exception as e:
                print(str(e))
                LogHelper.append("check winrm service failed on {0} with {1}:{2}".format(machinename, username, password))
            if result != True:
            """
            """
            try:
                cmd_call = "cmd /c PowerShell -Command \"Set-WSManQuickConfig -Force\""
                print(cmd_call)
                id, value = conn.Win32_Process.Create(CommandLine=cmd_call)
                print(id,value)
                watcher = conn.watch_for(notification_type="Deletion",
                    wmi_class="Win32_Process",
                    delay_secs=1,
                    ProcessId=id)
                LogHelper.append("waiting Set-WSManQuickConfig process {0} complete on {1}".format(id, machinename))
                try:
                    LogHelper.append("waiting 300 seconds Set-WSManQuickConfig process {0} complete on {1}".format(id, machinename))
                    error_log = watcher(timeout_ms=300000)
                    LogHelper.append(error_log)
                except wmi.x_wmi_timed_out:
                    pythoncom.PumpWaitingMessages()
                    LogHelper.append("timout out Set-WSManQuickConfig process {0} complete on {1} {2}".format(id, machinename, error_log))
                time.sleep(10)
            except Exception as e:
                print(str(e))
                LogHelper.append("Set-WSManQuickConfig failed on {0} with {1}:{2}".format(machinename, username, password))
            """
            try:
                cmd_call = "cmd /c PowerShell -Command \"Enable-PSRemoting -Force\""
                print(cmd_call)
                id, value = conn.Win32_Process.Create(CommandLine=cmd_call)
                print(id, value)
                watcher = conn.watch_for(notification_type="Deletion",
                                         wmi_class="Win32_Process",
                                         delay_secs=1,
                                         ProcessId=id)
                LogHelper.append(
                    "waiting EnablePS process {0} complete on {1}".format(
                        id, machinename))
                try:
                    LogHelper.append(
                        "waiting 300 seconds EnablePS process {0} complete on {1}"
                        .format(id, machinename))
                    error_log = watcher(timeout_ms=300000)
                    LogHelper.append(error_log)
                except wmi.x_wmi_timed_out:
                    pythoncom.PumpWaitingMessages()
                    LogHelper.append(
                        "timout out EnablePS process {0} complete on {1} {2}".
                        format(id, machinename, error_log))

                time.sleep(30)
                LogHelper.append(
                    "enable ps succeed on {0} with {1}:{2}".format(
                        machinename, username, password))
                result = True
            except Exception as e:
                print(str(e))
                LogHelper.append(
                    "enable PSRemoting failed on {0} with {1}:{2}".format(
                        machinename, username, password))
                result = False

        pythoncom.CoUninitialize()
        return result