Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Be one of the first to start using Fabric Databases. View on-demand sessions with database experts and the Microsoft product team to learn just how easy it is to get started. Watch now

Reply
SylvainN
Frequent Visitor

Try to used script python found from github into powerbi

I found this scipts python from github and try to used with powerbi.

I pretty sure my problem is this line

    print(tabulate(tabular_data=results, headers=keep, tablefmt=cmd_line.table_format))

don't know I to convert into a table

 

the script work in visual code.

 

Thx for your help

 

#!/usr/bin/env python3
r"""
 _______                        __ _______ __        __ __
|   _   .----.-----.--.--.--.--|  |   _   |  |_.----|__|  |--.-----.
|.  1___|   _|  _  |  |  |  |  _  |   1___|   _|   _|  |    <|  -__|
|.  |___|__| |_____|________|_____|____   |____|__| |__|__|__|_____|
|:  1   |                         |:  1   |
|::.. . |                         |::.. . |           FalconPy
`-------'                         `-------'

 __   __  _______  _______  _______
|  | |  ||       ||       ||       |
|  |_|  ||   _   ||  _____||_     _|
|       ||  | |  || |_____   |   |
|       ||  |_|  ||_____  |  |   |
|   _   ||       | _____| |  |   |
|__| |__||_______||_______|  |___|
         _______  ______    _______  __   __  _______  _______
        |       ||    _ |  |       ||  | |  ||       ||       |
        |    ___||   | ||  |   _   ||  | |  ||    _  ||  _____|
        |   | __ |   |_||_ |  | |  ||  |_|  ||   |_| || |_____
        |   ||  ||    __  ||  |_|  ||       ||    ___||_____  |
        |   |_| ||   |  | ||       ||       ||   |     _____| |
        |_______||___|  |_||_______||_______||___|    |_______|

This script will output a list of all Host Groups, for Flight Control
scenarios it will display all the host groups in all child CIDs.
"""
import os
import logging
import pandas as pd
from argparse import ArgumentParser, RawTextHelpFormatter, Namespace
from falconpy import APIHarnessV2, APIError
from tabulate import tabulate


def consume_arguments() -> Namespace:
    """Consume any provided command line arguments."""
    parser = ArgumentParser(description=__doc__, formatter_class=RawTextHelpFormatter)
    parser.add_argument("-d", "--debug",
                        help="Enable API debugging",
                        action="store_true",
                        default=False
                        )
    parser.add_argument("-m", "--mssp",
                        help="List groups in all child CIDs (MSSP parents only)",
                        action="store_true",
                        default=False
                        )
    parser.add_argument("-c", "--child",
                        help="List groups in a specific child CID (MSSP parents only)",
                        default=None
                        )
    parser.add_argument("-t", "--table_format",
                        help="Table format to use for tabular display",
                        default="simple"
                        )
    req = parser.add_argument_group("Required arguments")
    parsed = parser.parse_args()

    return parsed


cmd_line = consume_arguments()

# Activate debugging if requested
if cmd_line.debug:
    logging.basicConfig(level=logging.DEBUG)

# Create our base authentication dictionary (parent / child)
auth = {
    "client_id": "my key",
    "client_secret": "my secret key",
    "debug": cmd_line.debug,
    "pythonic": True
}
# If we are in MSSP mode, retrieve our child CID details
if cmd_line.mssp:
    parent = APIHarnessV2(**auth)
    cids = parent.command("getChildren", ids=parent.command("queryChildren").data)
elif cmd_line.child:
    parent = APIHarnessV2(**auth)
    try:
        cid_name = parent.command("getChildren", ids=cmd_line.child)
    except APIError as api_error:
        # Throw an error if they provided us an invalid CID
        raise SystemExit(api_error.message)
    cids = [{"name": cid_name[0]["name"]}]
else:
    # If not, we'll just run this in our current tenant
    cids = [{"name": "CrowdStrike"}]

# Do the needful for each CID in the list
for cid in cids:
    print(f"\n{cid['name']} host groups")
    if cmd_line.mssp:
        # If we're a parent, add this child's CID to our authentication request
        auth["member_cid"] = cid["child_cid"]
    elif cmd_line.child:
        auth["member_cid"] = cmd_line.child
    # Demonstrating using the SDK interface as a context manager
    # This will automatically discard the bearer token when exiting the context.
    with APIHarnessV2(**auth) as sdk:
        # Fields we want to display
        keep = {"id": "ID", "name": "Name", "description": "Description"}
        # Sometimes list comprehension is ridiculously cool...
        results = [{k: v for k, v in d.items() if k in keep} for d in sdk.command("queryCombinedHostGroups")]
        print(tabulate(tabular_data=results, headers=keep, tablefmt=cmd_line.table_format))
 
   
1 ACCEPTED SOLUTION
v-yohua-msft
Community Support
Community Support

Hi, @SylvainN 

You'll need to convert your script output to a tabular format that Power BI can use, and you can modify the script to save the results to a CSV file instead of printing it out. Power BI makes it easy to import CSV files for further analysis and visualization.
You can refer to the modified code:

import os
import logging
import pandas as pd
from argparse import ArgumentParser, RawTextHelpFormatter, Namespace
from falconpy import APIHarnessV2, APIError
from tabulate import tabulate
import csv

def consume_arguments() -> Namespace:
    """Consume any provided command line arguments."""
    parser = ArgumentParser(description=__doc__, formatter_class=RawTextHelpFormatter)
    parser.add_argument("-d", "--debug",
                        help="Enable API debugging",
                        action="store_true",
                        default=False
                        )
    parser.add_argument("-m", "--mssp",
                        help="List groups in all child CIDs (MSSP parents only)",
                        action="store_true",
                        default=False
                        )
    parser.add_argument("-c", "--child",
                        help="List groups in a specific child CID (MSSP parents only)",
                        default=None
                        )
    parser.add_argument("-t", "--table_format",
                        help="Table format to use for tabular display",
                        default="simple"
                        )
    req = parser.add_argument_group("Required arguments")
    parsed = parser.parse_args()

    return parsed

cmd_line = consume_arguments()

# Activate debugging if requested
if cmd_line.debug:
    logging.basicConfig(level=logging.DEBUG)

# Create our base authentication dictionary (parent / child)
auth = {
    "client_id": "my key",
    "client_secret": "my secret key",
    "debug": cmd_line.debug,
    "pythonic": True
}

# If we are in MSSP mode, retrieve our child CID details
if cmd_line.mssp:
    parent = APIHarnessV2(**auth)
    cids = parent.command("getChildren", ids=parent.command("queryChildren").data)
elif cmd_line.child:
    parent = APIHarnessV2(**auth)
    try:
        cid_name = parent.command("getChildren", ids=cmd_line.child)
    except APIError as api_error:
        # Throw an error if they provided us an invalid CID
        raise SystemExit(api_error.message)
    cids = [{"name": cid_name["name"]}]
else:
    # If not, we'll just run this in our current tenant
    cids = [{"name": "CrowdStrike"}]

# Do the needful for each CID in the list
for cid in cids:
    print(f"\n{cid['name']} host groups")
    if cmd_line.mssp:
        # If we're a parent, add this child's CID to our authentication request
        auth["member_cid"] = cid["child_cid"]
    elif cmd_line.child:
        auth["member_cid"] = cmd_line.child
    # Demonstrating using the SDK interface as a context manager
    # This will automatically discard the bearer token when exiting the context.
    with APIHarnessV2(**auth) as sdk:
        # Fields we want to display
        keep = {"id": "ID", "name": "Name", "description": "Description"}
        # Sometimes list comprehension is ridiculously cool...
        results = [{k: v for k, v in d.items() if k in keep} for d in sdk.command("queryCombinedHostGroups")]
        
        # Define the CSV file name
        csv_file = f"{cid['name']}_host_groups.csv"
        
        # Write results to CSV file
        with open(csv_file, mode='w', newline='') as file:
            writer = csv.DictWriter(file, fieldnames=keep.values())
            writer.writeheader()
            writer.writerows(results)
        
        print(f"Results saved to {csv_file}")

 

Next, import the CSV file into Power BI. Open Power BI Desktop. Click "Get Data" and select "Text/CSV". Select your CSV file and click Open.

vyohuamsft_0-1728525781674.png

 

Preview the data, confirm that it is correct, and click "Load". Model and visualize data in Power BI. This way, the data generated by your Python script can be easily used in Power BI.

 

Alternatively, you can use the Python script connector to enter the code directly. On the home page of Power BI Desktop, click the Get Data button in the upper-left corner.
Select "More...": In the pop-up window, scroll down and select the "More..." option.

vyohuamsft_1-1728526334461.png

vyohuamsft_2-1728526411817.png

 

Make sure your Python scripts can run in Power BI. Because Power BI's Python script connector has some limitations (for example, it doesn't support interactive input), you'll want to make sure that your scripts are self-contained and don't require user interaction. Also make sure you have the correct Python environment configured in Power BI. You can set the installation path for Python in Power BI's options. You can check the following link:

vyohuamsft_3-1728526439824.png

Run Python scripts in Power BI Desktop - Power BI | Microsoft Learn

 

How to Get Your Question Answered Quickly

Best Regards

Yongkang Hua

If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

View solution in original post

1 REPLY 1
v-yohua-msft
Community Support
Community Support

Hi, @SylvainN 

You'll need to convert your script output to a tabular format that Power BI can use, and you can modify the script to save the results to a CSV file instead of printing it out. Power BI makes it easy to import CSV files for further analysis and visualization.
You can refer to the modified code:

import os
import logging
import pandas as pd
from argparse import ArgumentParser, RawTextHelpFormatter, Namespace
from falconpy import APIHarnessV2, APIError
from tabulate import tabulate
import csv

def consume_arguments() -> Namespace:
    """Consume any provided command line arguments."""
    parser = ArgumentParser(description=__doc__, formatter_class=RawTextHelpFormatter)
    parser.add_argument("-d", "--debug",
                        help="Enable API debugging",
                        action="store_true",
                        default=False
                        )
    parser.add_argument("-m", "--mssp",
                        help="List groups in all child CIDs (MSSP parents only)",
                        action="store_true",
                        default=False
                        )
    parser.add_argument("-c", "--child",
                        help="List groups in a specific child CID (MSSP parents only)",
                        default=None
                        )
    parser.add_argument("-t", "--table_format",
                        help="Table format to use for tabular display",
                        default="simple"
                        )
    req = parser.add_argument_group("Required arguments")
    parsed = parser.parse_args()

    return parsed

cmd_line = consume_arguments()

# Activate debugging if requested
if cmd_line.debug:
    logging.basicConfig(level=logging.DEBUG)

# Create our base authentication dictionary (parent / child)
auth = {
    "client_id": "my key",
    "client_secret": "my secret key",
    "debug": cmd_line.debug,
    "pythonic": True
}

# If we are in MSSP mode, retrieve our child CID details
if cmd_line.mssp:
    parent = APIHarnessV2(**auth)
    cids = parent.command("getChildren", ids=parent.command("queryChildren").data)
elif cmd_line.child:
    parent = APIHarnessV2(**auth)
    try:
        cid_name = parent.command("getChildren", ids=cmd_line.child)
    except APIError as api_error:
        # Throw an error if they provided us an invalid CID
        raise SystemExit(api_error.message)
    cids = [{"name": cid_name["name"]}]
else:
    # If not, we'll just run this in our current tenant
    cids = [{"name": "CrowdStrike"}]

# Do the needful for each CID in the list
for cid in cids:
    print(f"\n{cid['name']} host groups")
    if cmd_line.mssp:
        # If we're a parent, add this child's CID to our authentication request
        auth["member_cid"] = cid["child_cid"]
    elif cmd_line.child:
        auth["member_cid"] = cmd_line.child
    # Demonstrating using the SDK interface as a context manager
    # This will automatically discard the bearer token when exiting the context.
    with APIHarnessV2(**auth) as sdk:
        # Fields we want to display
        keep = {"id": "ID", "name": "Name", "description": "Description"}
        # Sometimes list comprehension is ridiculously cool...
        results = [{k: v for k, v in d.items() if k in keep} for d in sdk.command("queryCombinedHostGroups")]
        
        # Define the CSV file name
        csv_file = f"{cid['name']}_host_groups.csv"
        
        # Write results to CSV file
        with open(csv_file, mode='w', newline='') as file:
            writer = csv.DictWriter(file, fieldnames=keep.values())
            writer.writeheader()
            writer.writerows(results)
        
        print(f"Results saved to {csv_file}")

 

Next, import the CSV file into Power BI. Open Power BI Desktop. Click "Get Data" and select "Text/CSV". Select your CSV file and click Open.

vyohuamsft_0-1728525781674.png

 

Preview the data, confirm that it is correct, and click "Load". Model and visualize data in Power BI. This way, the data generated by your Python script can be easily used in Power BI.

 

Alternatively, you can use the Python script connector to enter the code directly. On the home page of Power BI Desktop, click the Get Data button in the upper-left corner.
Select "More...": In the pop-up window, scroll down and select the "More..." option.

vyohuamsft_1-1728526334461.png

vyohuamsft_2-1728526411817.png

 

Make sure your Python scripts can run in Power BI. Because Power BI's Python script connector has some limitations (for example, it doesn't support interactive input), you'll want to make sure that your scripts are self-contained and don't require user interaction. Also make sure you have the correct Python environment configured in Power BI. You can set the installation path for Python in Power BI's options. You can check the following link:

vyohuamsft_3-1728526439824.png

Run Python scripts in Power BI Desktop - Power BI | Microsoft Learn

 

How to Get Your Question Answered Quickly

Best Regards

Yongkang Hua

If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

Helpful resources

Announcements
Las Vegas 2025

Join us at the Microsoft Fabric Community Conference

March 31 - April 2, 2025, in Las Vegas, Nevada. Use code MSCUST for a $150 discount!

Dec Fabric Community Survey

We want your feedback!

Your insights matter. That’s why we created a quick survey to learn about your experience finding answers to technical questions.

ArunFabCon

Microsoft Fabric Community Conference 2025

Arun Ulag shares exciting details about the Microsoft Fabric Conference 2025, which will be held in Las Vegas, NV.

December 2024

A Year in Review - December 2024

Find out what content was popular in the Fabric community during 2024.