### Start Artifact Collection on a Client Source: https://context7.com/velocidex/pyvelociraptor/llms.txt Initiates artifact collection (e.g., Windows.System.Pslist) on a specified client ID. The result is aliased as 'Flow'. ```python result = DataFrameQuery(""" SELECT collect_client( client_id="C.b9bdf1fba596d686", artifacts="Windows.System.Pslist" ) AS Flow FROM scope() ") ``` -------------------------------- ### List All Connected Clients with Pandas Source: https://context7.com/velocidex/pyvelociraptor/llms.txt Retrieves a list of all connected clients and loads them into a pandas DataFrame. Ensure pandas is installed. ```python df = pd.DataFrame(DataFrameQuery("SELECT * FROM clients()")) ``` -------------------------------- ### Launch Artifact Collection on a Client Source: https://github.com/velocidex/pyvelociraptor/blob/master/README.txt VQL query to initiate an artifact collection on a specific client. This example collects the 'Windows.Network.Netstat' artifact from client ID 'C.12345'. ```sql SELECT collect( client_id="C.12345", artifacts="Windows.Network.Netstat") FROM scope() ``` -------------------------------- ### Get Server Metrics with Pandas Source: https://context7.com/velocidex/pyvelociraptor/llms.txt Retrieves server statistics, including preconditions, and loads them into a pandas DataFrame. Setting preconditions=TRUE ensures all relevant metrics are captured. ```python df = pd.DataFrame(DataFrameQuery(""" SELECT * FROM Artifact.Generic.Client.Stats(preconditions=TRUE) """)) ``` -------------------------------- ### Monitor Flow Completion Artifacts Source: https://github.com/velocidex/pyvelociraptor/blob/master/README.txt Example VQL query to monitor and retrieve flow completion information. This query continuously emits rows containing flow details as flows are completed. ```sql SELECT * FROM watch_monitoring(artifact='System.Flow.Completion') ``` -------------------------------- ### Execute Artifacts with run_artifact Source: https://context7.com/velocidex/pyvelociraptor/llms.txt Executes a Velociraptor artifact by hostname and returns results as a pandas DataFrame. Requires a valid configuration file for non-default setups. ```python from pyvelociraptor.wrappers import run_artifact # Run artifact by hostname - finds client ID automatically df = run_artifact("WORKSTATION-001", "Windows.System.Pslist") # Output: # [+] Client ID found: C.869eb611eaa5b899 # [!] Running VQL: SELECT collect_client(...) AS Flow FROM scope() # [+] Got artifact flow ID: F.BVSSIUHNPUV7E # [!] Artifact is running... 0s # [+] Done! 11.0s # Run with custom parameters and timeout df = run_artifact( "SERVER-DC01", "Windows.EventLogs.Evtx", artifact_parameters={"EvtxGlob": "C:/Windows/System32/winevt/Logs/Security.evtx"}, limit=1000, timeout=300, verbose=True ) # Run silently with custom config from pyvelociraptor import LoadConfigFile config = LoadConfigFile("/secure/api_client.yaml") df = run_artifact("LAPTOP-USER", "Windows.Network.Netstat", config=config, verbose=False) if df is not None: print(df.head()) else: print("Collection failed or timed out") ``` -------------------------------- ### Get Hunt Results with Pandas Source: https://context7.com/velocidex/pyvelociraptor/llms.txt Fetches results for a specific hunt ID and artifact, limiting the output to 1000 records. Ensure the hunt_id and artifact are correctly specified. ```python df = pd.DataFrame(DataFrameQuery(""" SELECT * FROM hunt_results( hunt_id='H.12345', artifact='Windows.System.Pslist' ) LIMIT 1000 """)) ``` -------------------------------- ### Interact via Command Line Interface Source: https://context7.com/velocidex/pyvelociraptor/llms.txt Executes VQL queries and manages API configurations directly from the terminal. Requires a valid API client configuration file. ```bash # Generate API client configuration from server velociraptor --config server.config.yaml config api_client --name fred > api_client.yaml # Run VQL query from command line pyvelociraptor --config api_client.yaml "SELECT * FROM info()" # Run query with environment variables pyvelociraptor --config api_client.yaml \ "SELECT *, Foo FROM info()" \ --env Foo=Bar # Run query against specific organization pyvelociraptor --config api_client.yaml \ "SELECT * FROM clients()" \ --org OrgA # Run query with timeout pyvelociraptor --config api_client.yaml \ "SELECT * FROM Artifact.Generic.Client.Stats()" \ --timeout 300 # Push event to artifact queue pyvelociraptor_push_event api_client.yaml Server.Audit.Logs \ '{"Time": "2024-01-15T10:00:00Z", "Event": "External alert"}' # Push event with organization pyvelociraptor_push_event api_client.yaml Custom.Events \ '{"message": "test"}' --org OrgA --client_id server ``` -------------------------------- ### Initialize DataFrameQuery Source: https://context7.com/velocidex/pyvelociraptor/llms.txt Imports the necessary modules to execute VQL queries and return results as pandas DataFrames. ```python from pyvelociraptor.velo_pandas import DataFrameQuery import pandas as pd ``` -------------------------------- ### Create a New Hunt Source: https://context7.com/velocidex/pyvelociraptor/llms.txt Creates a new hunt with specified artifacts and a description. The hunt details are returned aliased as 'Hunt'. ```python result = DataFrameQuery(""" SELECT hunt( artifacts="Windows.Network.Netstat", description="Network connection audit" ) AS Hunt FROM scope() ") ``` -------------------------------- ### Search Clients by Hostname with Pandas Source: https://context7.com/velocidex/pyvelociraptor/llms.txt Searches for clients based on a hostname pattern and returns their ID, hostname, and system information in a pandas DataFrame. The search string is case-insensitive. ```python df = pd.DataFrame(DataFrameQuery(""" SELECT client_id, os_info.hostname, os_info.system FROM clients(search="workstation") """)) ``` -------------------------------- ### Download Flow Uploads with fetch_flow_uploads Source: https://context7.com/velocidex/pyvelociraptor/llms.txt Downloads files uploaded during a specific flow, with support for individual file retrieval or zip exports. Requires gRPC configuration and authentication credentials. ```python import json import grpc import pyvelociraptor from pyvelociraptor import api_pb2 from pyvelociraptor import api_pb2_grpc def fetch_flow_uploads(config, client_id, flow_id, output_path="/tmp/", export_zip=False, org_id=None): """Download all uploaded files from a flow.""" creds = grpc.ssl_channel_credentials( root_certificates=config["ca_certificate"].encode("utf8"), private_key=config["client_private_key"].encode("utf8"), certificate_chain=config["client_cert"].encode("utf8")) options = (('grpc.ssl_target_name_override', "VelociraptorServer",),) # Query to list uploads or create zip export if export_zip: query = """ SELECT create_flow_download(wait=TRUE, client_id=ClientId, flow_id=FlowId).Components AS Components FROM scope() """ else: query = """ SELECT Upload.Components AS Components FROM uploads(flow_id=FlowId, client_id=ClientId) """ with grpc.secure_channel(config["api_connection_string"], creds, options) as channel: stub = api_pb2_grpc.APIStub(channel) request = api_pb2.VQLCollectorArgs( org_id=org_id, max_wait=1, max_row=100, Query=[api_pb2.VQLRequest(Name="Query", VQL=query)], env=[ api_pb2.VQLEnv(key="FlowId", value=flow_id), api_pb2.VQLEnv(key="ClientId", value=client_id), ], ) downloaded_files = [] for response in stub.Query(request): if response.Response: for row in json.loads(response.Response): components = row.get("Components", []) if components: output_file = f"{output_path}/{components[-1]}" print(f"Fetching {components} to {output_file}") # Use VFSGetBuffer to download each file downloaded_files.append(output_file) return downloaded_files # Usage config = pyvelociraptor.LoadConfigFile() # Download individual files from a flow files = fetch_flow_uploads(config, "C.b9bdf1fba596d686", "F.BQK1O12VLHH04", "/tmp/downloads/") # Download as single zip export files = fetch_flow_uploads(config, "C.b9bdf1fba596d686", "F.BQK1O12VLHH04", "/tmp/", export_zip=True) ``` -------------------------------- ### Generate API Client Configuration Source: https://github.com/velocidex/pyvelociraptor/blob/master/README.txt Generates a YAML configuration file for an API client, including necessary certificates for authentication. This file is used to connect to the Velociraptor API endpoint. ```bash $ velociraptor --config server.config.yaml \ config api_client --name fred > freds_api_client.yaml ``` -------------------------------- ### Execute VQL Queries with Pandas Integration Source: https://context7.com/velocidex/pyvelociraptor/llms.txt Executes VQL queries and returns results formatted for direct use with pandas DataFrames. Ideal for Jupyter notebook analysis. Supports parameter passing and explicit configuration loading. ```python import pandas as pd from pyvelociraptor.velo_pandas import DataFrameQuery from pyvelociraptor import LoadConfigFile # Configure pandas display options pd.set_option('display.max_colwidth', None) pd.set_option('display.max_columns', None) pd.set_option('display.max_rows', None) # Basic query - returns dict suitable for DataFrame result = DataFrameQuery("SELECT * FROM info()") df = pd.DataFrame(result) print(df) # Query with parameters passed as keyword arguments hunt_id = "H.380432d0" df = pd.DataFrame(DataFrameQuery(""" SELECT ConsumerDetails, FilterDetails, Fqdn FROM hunt_results(hunt_id=HuntId, artifact='Windows.Persistence.PermanentWMIEvents') WHERE NOT ConsumerDetails.Name =~ '(SCM Event Log Consumer)' LIMIT 50 """, HuntId=hunt_id)) df.head(500) # Query with explicit config config = LoadConfigFile("/path/to/api_client.yaml") df = pd.DataFrame(DataFrameQuery( "SELECT * FROM clients() LIMIT 100", config=config )) ``` -------------------------------- ### Fetch Files using VFSGetBuffer API Source: https://context7.com/velocidex/pyvelociraptor/llms.txt Reads arbitrary files from the Velociraptor server's file store. Handles fetching files in chunks for optimal performance. Requires gRPC credentials and connection details. ```python import grpc import pyvelociraptor from pyvelociraptor import api_pb2 from pyvelociraptor import api_pb2_grpc def fetch_file(config, vfs_path, output_path=None, org_id=None): """Fetch a file from Velociraptor's file store.""" creds = grpc.ssl_channel_credentials( root_certificates=config["ca_certificate"].encode("utf8"), private_key=config["client_private_key"].encode("utf8"), certificate_chain=config["client_cert"].encode("utf8")) options = (('grpc.ssl_target_name_override', "VelociraptorServer",),) with grpc.secure_channel(config["api_connection_string"], creds, options) as channel: stub = api_pb2_grpc.APIStub(channel) data = b"" offset = 0 while True: request = api_pb2.VFSFileBuffer( org_id=org_id, components=vfs_path.split("/"), length=1024 * 1024, # 1MB chunks for optimal performance offset=offset, ) res = stub.VFSGetBuffer(request) if len(res.data) == 0: break data += res.data offset += len(res.data) if output_path: with open(output_path, "wb") as f: f.write(data) print(f"Saved {len(data)} bytes to {output_path}") return data # Usage example config = pyvelociraptor.LoadConfigFile() # Fetch a collected artifact export fetch_file( config, "/downloads/C.b9bdf1fba596d686/F.BQK1O12VLHH04/F.BQK1O12VLHH04.zip", output_path="/tmp/collection.zip" ) ``` -------------------------------- ### LoadConfigFile Source: https://context7.com/velocidex/pyvelociraptor/llms.txt Loads and parses the Velociraptor API client configuration file. It supports encrypted private keys and multiple configuration file sources. ```APIDOC ## LoadConfigFile ### Description Loads and parses the Velociraptor API client configuration file containing SSL certificates and connection details. Supports encrypted private keys with interactive password prompts and multiple configuration file sources. ### Usage ```python import pyvelociraptor # Load from default locations: # 1. VELOCIRAPTOR_API_FILE environment variable # 2. ~/.pyvelociraptorrc config = pyvelociraptor.LoadConfigFile() # Load from specific file path config = pyvelociraptor.LoadConfigFile("/path/to/api_client.yaml") # Config contains these keys: # - ca_certificate: CA certificate for server verification # - client_private_key: Client private key for authentication # - client_cert: Client certificate chain # - api_connection_string: Server address (e.g., "127.0.0.1:8001") print(f"Connecting to: {config['api_connection_string']}") ``` ``` -------------------------------- ### Execute VQL Queries with PyVelociraptor Source: https://context7.com/velocidex/pyvelociraptor/llms.txt Executes VQL queries against the Velociraptor server using the gRPC API. Supports streaming results and environment variable injection for parameterized queries. ```python import json import grpc import pyvelociraptor from pyvelociraptor import api_pb2 from pyvelociraptor import api_pb2_grpc def run_query(config, query, env_dict=None, org_id=None, timeout=0): """Execute a VQL query and return streaming results.""" creds = grpc.ssl_channel_credentials( root_certificates=config["ca_certificate"].encode("utf8"), private_key=config["client_private_key"].encode("utf8"), certificate_chain=config["client_cert"].encode("utf8")) options = (('grpc.ssl_target_name_override', "VelociraptorServer",),) env = [] if env_dict: for k, v in env_dict.items(): env.append(dict(key=k, value=v)) with grpc.secure_channel(config["api_connection_string"], creds, options) as channel: stub = api_pb2_grpc.APIStub(channel) request = api_pb2.VQLCollectorArgs( org_id=org_id, max_wait=1, max_row=100, timeout=timeout, Query=[api_pb2.VQLRequest( Name="Query", VQL=query, )], env=env, ) results = [] for response in stub.Query(request): if response.Response: results.extend(json.loads(response.Response)) elif response.log: print(f"Log: {response.log}") return results # Usage examples config = pyvelociraptor.LoadConfigFile() # Get server information info = run_query(config, "SELECT * FROM info()") print(json.dumps(info, indent=2)) # List all clients clients = run_query(config, "SELECT * FROM clients() LIMIT 10") # Run artifact on specific client results = run_query(config, """ SELECT collect_client( client_id=\"C.12345\", artifacts=\"Windows.Network.Netstat\" ) AS Flow FROM scope()\n""") # Monitor for completed flows (event query - streams continuously) # run_query(config, "SELECT * FROM watch_monitoring(artifact='System.Flow.Completion')") ``` -------------------------------- ### List All Hunts with Pandas Source: https://context7.com/velocidex/pyvelociraptor/llms.txt Retrieves a list of all initiated hunts and loads them into a pandas DataFrame. This is useful for monitoring ongoing or completed hunt operations. ```python df = pd.DataFrame(DataFrameQuery("SELECT * FROM hunts()")) ``` -------------------------------- ### Query API - Execute VQL Queries Source: https://context7.com/velocidex/pyvelociraptor/llms.txt The primary gRPC endpoint for running VQL queries against the Velociraptor server. Supports streaming results for event-based queries and environment variable injection for parameterized queries. ```APIDOC ## Query API - Execute VQL Queries ### Description The primary gRPC endpoint for running VQL queries against the Velociraptor server. Supports streaming results for event-based queries and environment variable injection for parameterized queries. ### Method POST ### Endpoint `/query` (gRPC) ### Parameters #### Request Body - **config** (dict) - Required - Configuration object loaded by `LoadConfigFile`. - **query** (string) - Required - The VQL query to execute. - **env_dict** (dict) - Optional - Dictionary for environment variable injection. - **org_id** (string) - Optional - The organization ID to run the query against. - **timeout** (int) - Optional - Timeout for the query in seconds. ### Request Example ```python import json import grpc import pyvelociraptor from pyvelociraptor import api_pb2 from pyvelociraptor import api_pb2_grpc def run_query(config, query, env_dict=None, org_id=None, timeout=0): """Execute a VQL query and return streaming results.""" creds = grpc.ssl_channel_credentials( root_certificates=config["ca_certificate"].encode("utf8"), private_key=config["client_private_key"].encode("utf8"), certificate_chain=config["client_cert"].encode("utf8")) options = (('grpc.ssl_target_name_override', "VelociraptorServer",),) env = [] if env_dict: for k, v in env_dict.items(): env.append(dict(key=k, value=v)) with grpc.secure_channel(config["api_connection_string"], creds, options) as channel: stub = api_pb2_grpc.APIStub(channel) request = api_pb2.VQLCollectorArgs( org_id=org_id, max_wait=1, max_row=100, timeout=timeout, Query=[api_pb2.VQLRequest( Name="Query", VQL=query, )], env=env, ) results = [] for response in stub.Query(request): if response.Response: results.extend(json.loads(response.Response)) elif response.log: print(f"Log: {response.log}") return results # Usage examples config = pyvelociraptor.LoadConfigFile() # Get server information info = run_query(config, "SELECT * FROM info()") print(json.dumps(info, indent=2)) # List all clients clients = run_query(config, "SELECT * FROM clients() LIMIT 10") # Run artifact on specific client results = run_query(config, """ SELECT collect_client( client_id=\"C.12345\", artifacts=\"Windows.Network.Netstat\" ) AS Flow FROM scope()\n""") # Monitor for completed flows (event query - streams continuously) # run_query(config, "SELECT * FROM watch_monitoring(artifact='System.Flow.Completion')") ``` ### Response #### Success Response (200) - **results** (list) - A list of dictionaries representing the query results. - **log** (string) - Log messages from the server. #### Response Example ```json [ { "column1": "value1", "column2": "value2" } ] ``` ``` -------------------------------- ### Load Velociraptor Configuration Source: https://context7.com/velocidex/pyvelociraptor/llms.txt Loads and parses the Velociraptor API client configuration file. Supports encrypted private keys and multiple configuration sources. ```python import pyvelociraptor # Load from default locations: # 1. VELOCIRAPTOR_API_FILE environment variable # 2. ~/.pyvelociraptorrc config = pyvelociraptor.LoadConfigFile() # Load from specific file path config = pyvelociraptor.LoadConfigFile("/path/to/api_client.yaml") # Config contains these keys: # - ca_certificate: CA certificate for server verification # - client_private_key: Client private key for authentication # - client_cert: Client certificate chain # - api_connection_string: Server address (e.g., "127.0.0.1:8001") print(f"Connecting to: {config['api_connection_string']}") ``` -------------------------------- ### Push Events to Artifact Queues Source: https://context7.com/velocidex/pyvelociraptor/llms.txt Pushes events to Velociraptor artifact queues, enabling external systems to inject data into the Velociraptor event stream. Requires appropriate `publish_queues` permissions. Events are serialized as JSONL. ```python import json import grpc from pyvelociraptor import api_pb2 from pyvelociraptor import api_pb2_grpc def push_event(config, queue, events, client_id="server", org_id=None): """Push events to a Velociraptor artifact queue.""" creds = grpc.ssl_channel_credentials( root_certificates=config["ca_certificate"].encode("utf8"), private_key=config["client_private_key"].encode("utf8"), certificate_chain=config["client_cert"].encode("utf8")) options = (('grpc.ssl_target_name_override', "VelociraptorServer",),) # Serialize events as JSONL if not isinstance(events, list): events = [events] serialized = "" for event in events: serialized += json.dumps(event) + "\n" with grpc.secure_channel(config["api_connection_string"], creds, options) as channel: stub = api_pb2_grpc.APIStub(channel) request = api_pb2.PushEventRequest( artifact=queue, client_id=client_id, jsonl=serialized.encode("utf8"), rows=len(events), org_id=org_id, ) return stub.PushEvents(request) # Usage example import yaml config = yaml.safe_load(open("api_client.yaml").read()) # Push a single event push_event(config, "Server.Audit.Logs", { "Time": "2024-01-15T10:30:00Z", "Event": "External alert triggered", "Source": "SIEM Integration" }) # Push multiple events push_event(config, "Custom.Events.Monitor", [ {"timestamp": 1705312200, "type": "alert", "message": "Suspicious activity"}, {"timestamp": 1705312260, "type": "info", "message": "Investigation started"} ]) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.