1

I would like to know the sensitivity label of my current Word file, change it with a new value and save my file

I start by opening a Word file

    # Opening a MS Word file in pywin32
    from win32com.client import Dispatch
    myWord = Dispatch('Word.Application')
    myWord.Visible = 1
    myWord.Documents.Open("C:/./TEMP.docx")  # open file

    # SetLabel and GetLabel
    print(myWord.ActiveDocument.SensitivityLabel)
    print(myWord.ActiveDocument.SensitivityLabel.SetLabel)
    print(myWord.ActiveDocument.SensitivityLabel.GetLabel())

    # Create label info
    myLabelInfoNew = myWord.ActiveDocument.SensitivityLabel.CreateLabelInfo()

    # Close Word Application
    myWord.ActiveDocument.SaveAs("C:/./TEMP2.docx")
    myWord.Quit()

How can I fix it?

Thank you for your help

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45

2 Answers2

1

I can't fix it, but I can suggest an alternative.

Use python subprocess module to call powershell, as Microsoft provides powershell tools to read and apply sensitivity labels. These tools are Get-AIPFileStatus and Set-AIPFileLabel. I suggest playing with them in powershell to understand it better before going back to python.

I've just published a gist with this solution in Python.

Here is my function to read the label:

import json
import subprocess

def read_label(
    filepath,
    full_result=False,
    powershell=r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
    stdout_encoding='iso8859-15',
):
    # The command to call in powershell. It includes the powershell tool
    # 'ConvertTo-Json' to make it easier to process the results in Python,
    # specially when the file path is too long, which may break lines.
    command = f"Get-AIPFileStatus -path '{filepath}' | ConvertTo-Json"
    # Executing it
    result = subprocess.Popen([powershell, command], stdout=subprocess.PIPE)
    result_lines = result.stdout.readlines()
    # Processing the results and saving to a dictionary
    clean_lines = [
        line.decode(stdout_encoding).rstrip('\r\n') for line in result_lines
    ]
    json_string = '\n'.join(clean_lines)
    result_dict = json.loads(json_string)
    # If selected, return the full results dictionary
    if full_result:
        return result_dict
    # If not returns only the label_id of interest to apply to other document
    # Per Microsoft documentation if a sensitivity label has both a
    # 'MainLabelId' and a 'SubLabelId', only the 'SubLabelId' should be used
    # with 'Set-AIPFileLabel' tool to to set the label in a new document.
    label_id = (
        result_dict['SubLabelId']
        if result_dict['SubLabelId']
        else result_dict['MainLabelId']
    )
    return label_id

and here is the function to apply it:

import subprocess
import time

def apply_label(
    filepath,
    label_id,
    powershell=r'C:\WINDOWS\system32\WindowsPowerShell\v1.0\powershell.exe',
    stdout_encoding='iso8859-15',
):
    start = time.time()
    # The command to call in powershell
    command = f"(Set-AIPFileLabel -path '{filepath}' -LabelId '{label_id}').Status.ToString()"
    # Executing it
    result = subprocess.Popen([powershell, command], stdout=subprocess.PIPE)
    result_message = (
        result.stdout.readline().decode(stdout_encoding).rstrip('\r\n')
    )
    # If the command is not successful, raises an exception and display the message
    # from 'Set-AIPFileLabel' tool
    if result_message != 'Success':
        raise Exception(result_message)
    end = time.time()
    return end - start
0

This is the code I use with to apply sensitivity to .xlsx documents. Create a .docx file for each sensitivity type your company uses. Run the first function on each sensitivity type document you have to get your company's Sensitivity IDs per type. You then update the dictionary in the second function with the appropriate IDs. For this to work on .docx files you will need to change a few things in the code below. Please see the items below for changes.

  1. 'Excel.Application' to 'Document.Application'
  2. .Workbooks.Open to Documents.Open
  3. .ActiveWorkbook to .ActivateDocument

Update below for docx

from win32com.client import Dispatch
def get_lable(in_xlsx):

    """
    :param in_xlsx: Input file to attach sensitivity label
    """
    myxlsx = Dispatch('Excel.Application')
    myxlsx.Visible = 1
    myxlsx.Workbooks.Open(in_xlsx)

    # Get Label
    label_id = myxlsx.ActiveWorkbook.SensitivityLabel.GetLabel()
    print(str(label_id))
    myxlsx.Application.Quit()
    return str(label_id)

def xlsx_sensitivity_label(in_xlsx, label='Internal'):
    """
    Update XLSX file with sensitivity label
    https://pythoninoffice.com/python-set-sensitivity-label-in-excel/
    :param in_xlsx: path of input .xlsx file to attach sensitivity label
    :param label: Accepted Labels: Public, Internal, Confidential, Restricted
    :return: Adds Microsoft Sensitivity label to spreadsheet
     """
    di_sensitivity = {'Public': 'xxxx-xxx-xxxxxxx-xxxx-xxx-xxx',
                      'Confidential': 'xxxx-xxx-xxxxxxx-xxxx-xxx-xxx',
                      'Internal': 'xxxx-xxx-xxxxxxx-xxxx-xxx-xxx',
                      'Restricted': 'xxxx-xxx-xxxxxxx-xxxx-xxx-xxx'}

    label_id = di_sensitivity[label]
    myxlsx = Dispatch('Excel.Application')
    myxlsx.Visible = 1
    myxlsx.Workbooks.Open(in_xlsx)

    # Set Label
    label_info = myxlsx.ActiveWorkbook.SensitivityLabel.CreateLabelInfo()
    label_info.AssignmentMethod = 2
    label_info.LabelId = label_id
    label_info.LabelName = label
    print(label_info.LabelName)
    myxlsx.ActiveWorkbook.SensitivityLabel.SetLabel(label_info,label_info)
    myxlsx.ActiveWorkbook.Save()
    myxlsx.Application.Quit()
kShort
  • 23
  • 5