code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def get_config_value(value):
"""
Helper function to handle string, dict, and enum cases of configuration values
"""
if isinstance(value, str):
return value
elif isinstance(value, dict):
return value
else:
return value.value |
Helper function to handle string, dict, and enum cases of configuration values
| get_config_value | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
def get_search_params(search_api: str, search_api_config: Optional[Dict[str, Any]]) -> Dict[str, Any]:
"""
Filters the search_api_config dictionary to include only parameters accepted by the specified search API.
Args:
search_api (str): The search API identifier (e.g., "exa", "tavily").
sea... |
Filters the search_api_config dictionary to include only parameters accepted by the specified search API.
Args:
search_api (str): The search API identifier (e.g., "exa", "tavily").
search_api_config (Optional[Dict[str, Any]]): The configuration dictionary for the search API.
Returns:
... | get_search_params | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
def format_sections(sections: list[Section]) -> str:
""" Format a list of sections into a string """
formatted_str = ""
for idx, section in enumerate(sections, 1):
formatted_str += f"""
{'='*60}
Section {idx}: {section.name}
{'='*60}
Description:
{section.description}
Requires Research:
{section.re... | Format a list of sections into a string | format_sections | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def tavily_search_async(search_queries, max_results: int = 5, topic: Literal["general", "news", "finance"] = "general", include_raw_content: bool = True):
"""
Performs concurrent web searches with the Tavily API
Args:
search_queries (List[str]): List of search queries to process
max_r... |
Performs concurrent web searches with the Tavily API
Args:
search_queries (List[str]): List of search queries to process
max_results (int): Maximum number of results to return
topic (Literal["general", "news", "finance"]): Topic to filter results by
include_raw_content (bool): ... | tavily_search_async | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def azureaisearch_search_async(search_queries: list[str], max_results: int = 5, topic: str = "general", include_raw_content: bool = True) -> list[dict]:
"""
Performs concurrent web searches using the Azure AI Search API.
Args:
search_queries (List[str]): list of search queries to process
... |
Performs concurrent web searches using the Azure AI Search API.
Args:
search_queries (List[str]): list of search queries to process
max_results (int): maximum number of results to return for each query
topic (str): semantic topic filter for the search.
include_raw_content (bool... | azureaisearch_search_async | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
def perplexity_search(search_queries):
"""Search the web using the Perplexity API.
Args:
search_queries (List[SearchQuery]): List of search queries to process
Returns:
List[dict]: List of search responses from Perplexity API, one per query. Each response has format:
{
... | Search the web using the Perplexity API.
Args:
search_queries (List[SearchQuery]): List of search queries to process
Returns:
List[dict]: List of search responses from Perplexity API, one per query. Each response has format:
{
'query': str, ... | perplexity_search | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def exa_search(search_queries, max_characters: Optional[int] = None, num_results=5,
include_domains: Optional[List[str]] = None,
exclude_domains: Optional[List[str]] = None,
subpages: Optional[int] = None):
"""Search the web using the Exa API.
... | Search the web using the Exa API.
Args:
search_queries (List[SearchQuery]): List of search queries to process
max_characters (int, optional): Maximum number of characters to retrieve for each result's raw content.
If None, the text parameter will be set to... | exa_search | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def arxiv_search_async(search_queries, load_max_docs=5, get_full_documents=True, load_all_available_meta=True):
"""
Performs concurrent searches on arXiv using the ArxivRetriever.
Args:
search_queries (List[str]): List of search queries or article IDs
load_max_docs (int, optional): Ma... |
Performs concurrent searches on arXiv using the ArxivRetriever.
Args:
search_queries (List[str]): List of search queries or article IDs
load_max_docs (int, optional): Maximum number of documents to return per query. Default is 5.
get_full_documents (bool, optional): Whether to fetch fu... | arxiv_search_async | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def linkup_search(search_queries, depth: Optional[str] = "standard"):
"""
Performs concurrent web searches using the Linkup API.
Args:
search_queries (List[SearchQuery]): List of search queries to process
depth (str, optional): "standard" (default) or "deep". More details here https:... |
Performs concurrent web searches using the Linkup API.
Args:
search_queries (List[SearchQuery]): List of search queries to process
depth (str, optional): "standard" (default) or "deep". More details here https://docs.linkup.so/pages/documentation/get-started/concepts
Returns:
Lis... | linkup_search | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def google_search_async(search_queries: Union[str, List[str]], max_results: int = 5, include_raw_content: bool = True):
"""
Performs concurrent web searches using Google.
Uses Google Custom Search API if environment variables are set, otherwise falls back to web scraping.
Args:
search_que... |
Performs concurrent web searches using Google.
Uses Google Custom Search API if environment variables are set, otherwise falls back to web scraping.
Args:
search_queries (List[str]): List of search queries to process
max_results (int): Maximum number of results to return per query
... | google_search_async | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def scrape_pages(titles: List[str], urls: List[str]) -> str:
"""
Scrapes content from a list of URLs and formats it into a readable markdown document.
This function:
1. Takes a list of page titles and URLs
2. Makes asynchronous HTTP requests to each URL
3. Converts HTML content to mar... |
Scrapes content from a list of URLs and formats it into a readable markdown document.
This function:
1. Takes a list of page titles and URLs
2. Makes asynchronous HTTP requests to each URL
3. Converts HTML content to markdown
4. Formats all content with clear source attribution
Ar... | scrape_pages | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def tavily_search(
queries: List[str],
max_results: Annotated[int, InjectedToolArg] = 5,
topic: Annotated[Literal["general", "news", "finance"], InjectedToolArg] = "general",
config: RunnableConfig = None
) -> str:
"""
Fetches results from Tavily search API.
Args:
queries (Lis... |
Fetches results from Tavily search API.
Args:
queries (List[str]): List of search queries
max_results (int): Maximum number of results to return
topic (Literal['general', 'news', 'finance']): Topic to filter results by
Returns:
str: A formatted string of search results
... | tavily_search | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def azureaisearch_search(queries: List[str], max_results: int = 5, topic: str = "general") -> str:
"""
Fetches results from Azure AI Search API.
Args:
queries (List[str]): List of search queries
Returns:
str: A formatted string of search results
"""
# Use azur... |
Fetches results from Azure AI Search API.
Args:
queries (List[str]): List of search queries
Returns:
str: A formatted string of search results
| azureaisearch_search | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def select_and_execute_search(search_api: str, query_list: list[str], params_to_pass: dict) -> str:
"""Select and execute the appropriate search API.
Args:
search_api: Name of the search API to use
query_list: List of search queries to execute
params_to_pass: Parameters to pas... | Select and execute the appropriate search API.
Args:
search_api: Name of the search API to use
query_list: List of search queries to execute
params_to_pass: Parameters to pass to the search API
Returns:
Formatted string containing search results
Raises:... | select_and_execute_search | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
async def load_mcp_server_config(path: str) -> dict:
"""Load MCP server configuration from a file."""
def _load():
with open(path, "r") as f:
config = json.load(f)
return config
config = await asyncio.to_thread(_load)
return config | Load MCP server configuration from a file. | load_mcp_server_config | python | langchain-ai/open_deep_research | src/open_deep_research/utils.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/utils.py | MIT |
def pytest_addoption(parser):
"""Add command-line options to pytest."""
parser.addoption("--research-agent", action="store", help="Agent type: multi_agent or graph")
parser.addoption("--search-api", action="store", help="Search API to use")
parser.addoption("--eval-model", action="store", help="Model fo... | Add command-line options to pytest. | pytest_addoption | python | langchain-ai/open_deep_research | tests/conftest.py | https://github.com/langchain-ai/open_deep_research/blob/master/tests/conftest.py | MIT |
def add_model_configs(cmd, args):
"""Add model configuration arguments to command."""
if args.supervisor_model:
cmd.append(f"--supervisor-model={args.supervisor_model}")
if args.researcher_model:
cmd.append(f"--researcher-model={args.researcher_model}")
if args.planner_provider:
... | Add model configuration arguments to command. | add_model_configs | python | langchain-ai/open_deep_research | tests/run_test.py | https://github.com/langchain-ai/open_deep_research/blob/master/tests/run_test.py | MIT |
def get_evaluation_llm(eval_model=None):
"""Create and return an evaluation LLM.
Args:
eval_model: Model identifier to use for evaluation
Format: "provider:model_name" (e.g., "anthropic:claude-3-7-sonnet-latest")
If None, it will use environment variable or d... | Create and return an evaluation LLM.
Args:
eval_model: Model identifier to use for evaluation
Format: "provider:model_name" (e.g., "anthropic:claude-3-7-sonnet-latest")
If None, it will use environment variable or default
Returns:
Structured LLM ... | get_evaluation_llm | python | langchain-ai/open_deep_research | tests/test_report_quality.py | https://github.com/langchain-ai/open_deep_research/blob/master/tests/test_report_quality.py | MIT |
def models(request, research_agent):
"""Get model configurations based on agent type."""
if research_agent == "multi_agent":
return {
"supervisor_model": (
request.config.getoption("--supervisor-model") or
os.environ.get("SUPERVISOR_MODEL", "anthropic:claude-... | Get model configurations based on agent type. | models | python | langchain-ai/open_deep_research | tests/test_report_quality.py | https://github.com/langchain-ai/open_deep_research/blob/master/tests/test_report_quality.py | MIT |
def test_response_criteria_evaluation(research_agent, search_api, models, eval_model):
"""Test if a report meets the specified quality criteria."""
console.print(Panel.fit(
f"[bold blue]Testing {research_agent} report generation with {search_api} search[/bold blue]",
title="Test Configuration"
... | Test if a report meets the specified quality criteria. | test_response_criteria_evaluation | python | langchain-ai/open_deep_research | tests/test_report_quality.py | https://github.com/langchain-ai/open_deep_research/blob/master/tests/test_report_quality.py | MIT |
async def generate_report_multi_agent(
messages: list[MessageLikeRepresentation],
process_search_results: Literal["summarize", "split_and_rerank"] | None = None,
include_source: bool = True,
summarization_model: str = summarization_model,
summarization_model_provider: str = summarization_model_provi... | Generate a report using the open deep research multi-agent architecture | generate_report_multi_agent | python | langchain-ai/open_deep_research | tests/evals/run_evaluate.py | https://github.com/langchain-ai/open_deep_research/blob/master/tests/evals/run_evaluate.py | MIT |
async def generate_report_workflow(
query: str,
process_search_results: Literal["summarize", "split_and_rerank"] | None = None,
include_source: bool = True
):
"""Generate a report using the open deep research workflow"""
graph = builder.compile(checkpointer=MemorySaver())
config = {
"con... | Generate a report using the open deep research workflow | generate_report_workflow | python | langchain-ai/open_deep_research | tests/evals/target.py | https://github.com/langchain-ai/open_deep_research/blob/master/tests/evals/target.py | MIT |
def write_file_prefix(f: IO[Any], interpreter: str) -> None:
"""Write a shebang line.
:param f: An open file handle.
:param interpreter: A path to a python interpreter.
"""
# if the provided path is too long for a shebang we should error out
if len(interpreter) > BINPRM_BUF_SIZE:
sys.ex... | Write a shebang line.
:param f: An open file handle.
:param interpreter: A path to a python interpreter.
| write_file_prefix | python | linkedin/shiv | src/shiv/builder.py | https://github.com/linkedin/shiv/blob/master/src/shiv/builder.py | BSD-2-Clause |
def write_to_zipapp(
archive: zipfile.ZipFile,
arcname: str,
data: bytes,
date_time: Tuple[int, int, int, int, int, int],
compression: int,
stat: Optional[os.stat_result] = None,
) -> None:
"""Write a file or a bytestring to a ZipFile as a separate entry and update contents_hash as a side ef... | Write a file or a bytestring to a ZipFile as a separate entry and update contents_hash as a side effect. | write_to_zipapp | python | linkedin/shiv | src/shiv/builder.py | https://github.com/linkedin/shiv/blob/master/src/shiv/builder.py | BSD-2-Clause |
def rglob_follow_symlinks(path: Path, glob: str) -> Generator[Path, None, None]:
"""Path.rglob extended to follow symlinks, while we wait for Python 3.13."""
for p in path.rglob('*'):
if p.is_symlink() and p.is_dir():
yield from chain([p], rglob_follow_symlinks(p, glob))
else:
... | Path.rglob extended to follow symlinks, while we wait for Python 3.13. | rglob_follow_symlinks | python | linkedin/shiv | src/shiv/builder.py | https://github.com/linkedin/shiv/blob/master/src/shiv/builder.py | BSD-2-Clause |
def create_archive(
sources: List[Path], target: Path, interpreter: str, main: str, env: Environment, compressed: bool = True
) -> None:
"""Create an application archive from SOURCE.
This function is a heavily modified version of stdlib's
`zipapp.create_archive <https://docs.python.org/3/library/zipapp... | Create an application archive from SOURCE.
This function is a heavily modified version of stdlib's
`zipapp.create_archive <https://docs.python.org/3/library/zipapp.html#zipapp.create_archive>`_
| create_archive | python | linkedin/shiv | src/shiv/builder.py | https://github.com/linkedin/shiv/blob/master/src/shiv/builder.py | BSD-2-Clause |
def find_entry_point(site_packages_dirs: List[Path], console_script: str) -> str:
"""Find a console_script in a site-packages directory.
Console script metadata is stored in entry_points.txt per setuptools
convention. This function searches all entry_points.txt files and
returns the import string for a... | Find a console_script in a site-packages directory.
Console script metadata is stored in entry_points.txt per setuptools
convention. This function searches all entry_points.txt files and
returns the import string for a given console_script argument.
:param site_packages_dirs: Paths to site-packages di... | find_entry_point | python | linkedin/shiv | src/shiv/cli.py | https://github.com/linkedin/shiv/blob/master/src/shiv/cli.py | BSD-2-Clause |
def console_script_exists(site_packages_dirs: List[Path], console_script: str) -> bool:
"""Return true if the console script with provided name exists in one of the site-packages directories.
Console script is expected to be in the 'bin' directory of site packages.
:param site_packages_dirs: Paths to site... | Return true if the console script with provided name exists in one of the site-packages directories.
Console script is expected to be in the 'bin' directory of site packages.
:param site_packages_dirs: Paths to site-packages directories on disk.
:param console_script: A console script name.
| console_script_exists | python | linkedin/shiv | src/shiv/cli.py | https://github.com/linkedin/shiv/blob/master/src/shiv/cli.py | BSD-2-Clause |
def copytree(src: Path, dst: Path) -> None:
"""A utility function for syncing directories.
This function is based on shutil.copytree. In Python versions that are
older than 3.8, shutil.copytree would raise FileExistsError if the "dst"
directory already existed.
"""
# Make our target (if it do... | A utility function for syncing directories.
This function is based on shutil.copytree. In Python versions that are
older than 3.8, shutil.copytree would raise FileExistsError if the "dst"
directory already existed.
| copytree | python | linkedin/shiv | src/shiv/cli.py | https://github.com/linkedin/shiv/blob/master/src/shiv/cli.py | BSD-2-Clause |
def main(
output_file: str,
entry_point: Optional[str],
console_script: Optional[str],
python: Optional[str],
site_packages: Optional[str],
build_id: Optional[str],
compressed: bool,
compile_pyc: bool,
extend_pythonpath: bool,
reproducible: bool,
no_modify: bool,
preamble... |
Shiv is a command line utility for building fully self-contained Python zipapps
as outlined in PEP 441, but with all their dependencies included!
| main | python | linkedin/shiv | src/shiv/cli.py | https://github.com/linkedin/shiv/blob/master/src/shiv/cli.py | BSD-2-Clause |
def main(print_as_json, pyz):
"""A simple utility to print debugging information about PYZ files created with ``shiv``"""
zip_file = zipfile.ZipFile(pyz)
data = json.loads(zip_file.read("environment.json"))
if print_as_json:
click.echo(json.dumps(data, indent=4, sort_keys=True))
else:
... | A simple utility to print debugging information about PYZ files created with ``shiv`` | main | python | linkedin/shiv | src/shiv/info.py | https://github.com/linkedin/shiv/blob/master/src/shiv/info.py | BSD-2-Clause |
def clean_pip_env() -> Generator[None, None, None]:
"""A context manager for temporarily removing 'PIP_REQUIRE_VIRTUALENV' from the environment.
Since shiv installs via `--target`, we need to ignore venv requirements if they exist.
"""
require_venv = os.environ.pop(PIP_REQUIRE_VIRTUALENV, None)
t... | A context manager for temporarily removing 'PIP_REQUIRE_VIRTUALENV' from the environment.
Since shiv installs via `--target`, we need to ignore venv requirements if they exist.
| clean_pip_env | python | linkedin/shiv | src/shiv/pip.py | https://github.com/linkedin/shiv/blob/master/src/shiv/pip.py | BSD-2-Clause |
def install(args: List[str]) -> None:
"""`pip install` as a function.
Accepts a list of pip arguments.
.. code-block:: py
>>> install(['numpy', '--target', 'site-packages'])
Collecting numpy
Downloading numpy-1.13.3-cp35-cp35m-manylinux1_x86_64.whl (16.9MB)
100% || 16.... | `pip install` as a function.
Accepts a list of pip arguments.
.. code-block:: py
>>> install(['numpy', '--target', 'site-packages'])
Collecting numpy
Downloading numpy-1.13.3-cp35-cp35m-manylinux1_x86_64.whl (16.9MB)
100% || 16.9MB 53kB/s
Installing collected packa... | install | python | linkedin/shiv | src/shiv/pip.py | https://github.com/linkedin/shiv/blob/master/src/shiv/pip.py | BSD-2-Clause |
def acquire_nix(lock_file): # pragma: no cover
"""Acquire a lock file on linux or osx."""
fd = os.open(lock_file, OPEN_MODE)
try:
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except (IOError, OSError):
os.close(fd)
else:
return fd | Acquire a lock file on linux or osx. | acquire_nix | python | linkedin/shiv | src/shiv/bootstrap/filelock.py | https://github.com/linkedin/shiv/blob/master/src/shiv/bootstrap/filelock.py | BSD-2-Clause |
def run(module): # pragma: no cover
"""Run a module in a scrubbed environment.
If a single pyz has multiple callers, we want to remove these vars as we no longer need them
and they can cause subprocesses to fail with a ModuleNotFoundError.
:param Callable module: The entry point to invoke the pyz wit... | Run a module in a scrubbed environment.
If a single pyz has multiple callers, we want to remove these vars as we no longer need them
and they can cause subprocesses to fail with a ModuleNotFoundError.
:param Callable module: The entry point to invoke the pyz with.
| run | python | linkedin/shiv | src/shiv/bootstrap/__init__.py | https://github.com/linkedin/shiv/blob/master/src/shiv/bootstrap/__init__.py | BSD-2-Clause |
def current_zipfile():
"""A function to vend the current zipfile, if any"""
if zipfile.is_zipfile(sys.argv[0]):
with zipfile.ZipFile(sys.argv[0]) as fd:
yield fd
else:
yield None | A function to vend the current zipfile, if any | current_zipfile | python | linkedin/shiv | src/shiv/bootstrap/__init__.py | https://github.com/linkedin/shiv/blob/master/src/shiv/bootstrap/__init__.py | BSD-2-Clause |
def import_string(import_name):
"""Returns a callable for a given setuptools style import string
:param str import_name: A console_scripts style import string
"""
import_name = str(import_name).replace(":", ".")
try:
import_module(import_name)
except ImportError:
if "." not in... | Returns a callable for a given setuptools style import string
:param str import_name: A console_scripts style import string
| import_string | python | linkedin/shiv | src/shiv/bootstrap/__init__.py | https://github.com/linkedin/shiv/blob/master/src/shiv/bootstrap/__init__.py | BSD-2-Clause |
def cache_path(archive, root_dir, build_id):
"""Returns a ~/.shiv cache directory for unzipping site-packages during bootstrap.
:param ZipFile archive: The zipfile object we are bootstrapping from.
:param str root_dir: Optional, either a path or environment variable pointing to a SHIV_ROOT.
:param str ... | Returns a ~/.shiv cache directory for unzipping site-packages during bootstrap.
:param ZipFile archive: The zipfile object we are bootstrapping from.
:param str root_dir: Optional, either a path or environment variable pointing to a SHIV_ROOT.
:param str build_id: The build id generated at zip creation.
... | cache_path | python | linkedin/shiv | src/shiv/bootstrap/__init__.py | https://github.com/linkedin/shiv/blob/master/src/shiv/bootstrap/__init__.py | BSD-2-Clause |
def extract_site_packages(archive, target_path, compile_pyc=False, compile_workers=0, force=False):
"""Extract everything in site-packages to a specified path.
:param ZipFile archive: The zipfile object we are bootstrapping from.
:param Path target_path: The path to extract our zip to.
:param bool comp... | Extract everything in site-packages to a specified path.
:param ZipFile archive: The zipfile object we are bootstrapping from.
:param Path target_path: The path to extract our zip to.
:param bool compile_pyc: A boolean to dictate whether we pre-compile pyc.
:param int compile_workers: An int representi... | extract_site_packages | python | linkedin/shiv | src/shiv/bootstrap/__init__.py | https://github.com/linkedin/shiv/blob/master/src/shiv/bootstrap/__init__.py | BSD-2-Clause |
def extend_python_path(environ, additional_paths):
"""Create or extend a PYTHONPATH variable with the frozen environment we are bootstrapping with."""
# we don't want to clobber any existing PYTHONPATH value, so check for it.
python_path = environ["PYTHONPATH"].split(os.pathsep) if "PYTHONPATH" in environ ... | Create or extend a PYTHONPATH variable with the frozen environment we are bootstrapping with. | extend_python_path | python | linkedin/shiv | src/shiv/bootstrap/__init__.py | https://github.com/linkedin/shiv/blob/master/src/shiv/bootstrap/__init__.py | BSD-2-Clause |
def ensure_no_modify(site_packages, hashes):
"""Compare the sha256 hash of the unpacked source files to the files when they were added to the pyz."""
for path in site_packages.rglob("**/*.py"):
if hashlib.sha256(path.read_bytes()).hexdigest() != hashes.get(str(path.relative_to(site_packages))):
... | Compare the sha256 hash of the unpacked source files to the files when they were added to the pyz. | ensure_no_modify | python | linkedin/shiv | src/shiv/bootstrap/__init__.py | https://github.com/linkedin/shiv/blob/master/src/shiv/bootstrap/__init__.py | BSD-2-Clause |
def test_extend_path_existing_pythonpath(self):
"""When PYTHONPATH exists, extending it preserves the existing values."""
env = {"PYTHONPATH": "hello"}
extend_python_path(env, ["test", ".pth"])
assert env["PYTHONPATH"] == os.pathsep.join(["hello", "test", ".pth"]) | When PYTHONPATH exists, extending it preserves the existing values. | test_extend_path_existing_pythonpath | python | linkedin/shiv | test/test_bootstrap.py | https://github.com/linkedin/shiv/blob/master/test/test_bootstrap.py | BSD-2-Clause |
def test_find_entry_point(self, tmpdir, package_location):
"""Test that we can find console_script metadata."""
install(["-t", str(tmpdir), str(package_location)])
assert find_entry_point([Path(tmpdir)], "hello") == "hello:main" | Test that we can find console_script metadata. | test_find_entry_point | python | linkedin/shiv | test/test_cli.py | https://github.com/linkedin/shiv/blob/master/test/test_cli.py | BSD-2-Clause |
def test_console_script_exists(self, tmp_path, package_location):
"""Test that we can check console_script presence."""
install_dir = tmp_path / "install"
install(["-t", str(install_dir), str(package_location)])
empty_dir = tmp_path / "empty"
empty_dir.mkdir()
assert con... | Test that we can check console_script presence. | test_console_script_exists | python | linkedin/shiv | test/test_cli.py | https://github.com/linkedin/shiv/blob/master/test/test_cli.py | BSD-2-Clause |
def test_no_args(self, runner):
"""This should fail with a warning about supplying pip arguments"""
result = runner([])
assert result.exit_code == 1
assert NO_PIP_ARGS_OR_SITE_PACKAGES in result.output | This should fail with a warning about supplying pip arguments | test_no_args | python | linkedin/shiv | test/test_cli.py | https://github.com/linkedin/shiv/blob/master/test/test_cli.py | BSD-2-Clause |
def test_no_outfile(self, runner):
"""This should fail with a warning about not providing an outfile"""
result = runner(["-e", "test", "flask"])
assert result.exit_code == 1
assert NO_OUTFILE in result.output | This should fail with a warning about not providing an outfile | test_no_outfile | python | linkedin/shiv | test/test_cli.py | https://github.com/linkedin/shiv/blob/master/test/test_cli.py | BSD-2-Clause |
def test_disallowed_args(self, runner, arg):
"""This method tests that all the potential disallowed arguments match their error messages."""
# run shiv with a disallowed argument
result = runner(["-o", "tmp", arg])
# get the 'reason' message:
reason = next(iter([DISALLOWED_ARGS... | This method tests that all the potential disallowed arguments match their error messages. | test_disallowed_args | python | linkedin/shiv | test/test_cli.py | https://github.com/linkedin/shiv/blob/master/test/test_cli.py | BSD-2-Clause |
def test_preamble_no_pip(self, shiv_root, runner, package_location, tmp_path):
"""Test that the preamble script is created even with no pip installed packages."""
output_file = shiv_root / "test.pyz"
target = tmp_path / "target"
preamble = tmp_path / "preamble.py"
preamble.write... | Test that the preamble script is created even with no pip installed packages. | test_preamble_no_pip | python | linkedin/shiv | test/test_cli.py | https://github.com/linkedin/shiv/blob/master/test/test_cli.py | BSD-2-Clause |
def test_alternate_root(self, runner, package_location, tmp_path):
"""Test that the --root argument properly sets the extraction root."""
output_file = tmp_path / "test.pyz"
shiv_root = tmp_path / "root"
result = runner(
["-e", "hello:main", "--root", str(shiv_root), "-o", s... | Test that the --root argument properly sets the extraction root. | test_alternate_root | python | linkedin/shiv | test/test_cli.py | https://github.com/linkedin/shiv/blob/master/test/test_cli.py | BSD-2-Clause |
def test_alternate_root_environment_variable(self, runner, package_location, tmp_path, env_var):
"""Test that the --root argument works with environment variables."""
output_file = tmp_path / "test.pyz"
shiv_root_var = "NEW_ROOT"
shiv_root_path = tmp_path / 'new_root'
result = r... | Test that the --root argument works with environment variables. | test_alternate_root_environment_variable | python | linkedin/shiv | test/test_cli.py | https://github.com/linkedin/shiv/blob/master/test/test_cli.py | BSD-2-Clause |
def forward(self, inputs, outputs, labels):
"""
Args:
inputs: The original inputs that are feed to the teacher model
outputs: the outputs of the model to be trained. It is expected to be
either a Tensor, or a Tuple[Tensor, Tensor], with the original output
... |
Args:
inputs: The original inputs that are feed to the teacher model
outputs: the outputs of the model to be trained. It is expected to be
either a Tensor, or a Tuple[Tensor, Tensor], with the original output
in the first position and the distillation pre... | forward | python | facebookresearch/deit | losses.py | https://github.com/facebookresearch/deit/blob/master/losses.py | Apache-2.0 |
def _load_checkpoint_for_ema(model_ema, checkpoint):
"""
Workaround for ModelEma._load_checkpoint to accept an already-loaded object
"""
mem_file = io.BytesIO()
torch.save({'state_dict_ema':checkpoint}, mem_file)
mem_file.seek(0)
model_ema._load_checkpoint(mem_file) |
Workaround for ModelEma._load_checkpoint to accept an already-loaded object
| _load_checkpoint_for_ema | python | facebookresearch/deit | utils.py | https://github.com/facebookresearch/deit/blob/master/utils.py | Apache-2.0 |
def __init__(
self,
target: Target,
user: str,
dns: Optional[str] = None,
upn: Optional[str] = None,
sam: Optional[str] = None,
spns: Optional[str] = None,
passw: Optional[str] = None,
group: Optional[str] = None,
connection: Optional[LDAPC... |
Initialize account management with target and account options.
Args:
target: Target environment information (domain, credentials)
user: Username for the account to manage
dns: DNS hostname for the account
upn: UserPrincipalName to set
sam: sA... | __init__ | python | ly4k/Certipy | certipy/commands/account.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/account.py | MIT |
def connection(self) -> LDAPConnection:
"""
Get or establish an LDAP connection to the target.
Returns:
Active LDAP connection
"""
if self._connection is not None:
return self._connection
self._connection = LDAPConnection(self.target)
sel... |
Get or establish an LDAP connection to the target.
Returns:
Active LDAP connection
| connection | python | ly4k/Certipy | certipy/commands/account.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/account.py | MIT |
def create(self) -> bool:
"""
Create a new computer account in Active Directory.
This method creates a computer account with the specified properties,
or with reasonable defaults if not provided.
Returns:
True if account creation succeeded, False otherwise
"... |
Create a new computer account in Active Directory.
This method creates a computer account with the specified properties,
or with reasonable defaults if not provided.
Returns:
True if account creation succeeded, False otherwise
| create | python | ly4k/Certipy | certipy/commands/account.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/account.py | MIT |
def read(self) -> bool:
"""
Read and display account attributes.
This method retrieves and displays key attributes of the specified account.
Returns:
True if account was found and attributes read, False otherwise
"""
# Get user object
user = self.con... |
Read and display account attributes.
This method retrieves and displays key attributes of the specified account.
Returns:
True if account was found and attributes read, False otherwise
| read | python | ly4k/Certipy | certipy/commands/account.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/account.py | MIT |
def update(self) -> bool:
"""
Update an existing account's attributes.
This method modifies specified attributes of an existing account.
Returns:
True if account was successfully updated, False otherwise
"""
# Get user object
user = self.connection.g... |
Update an existing account's attributes.
This method modifies specified attributes of an existing account.
Returns:
True if account was successfully updated, False otherwise
| update | python | ly4k/Certipy | certipy/commands/account.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/account.py | MIT |
def delete(self) -> bool:
"""
Delete an account from Active Directory.
This method permanently removes the specified account.
Returns:
True if account was successfully deleted, False otherwise
"""
# Get user object
user = self.connection.get_user(sel... |
Delete an account from Active Directory.
This method permanently removes the specified account.
Returns:
True if account was successfully deleted, False otherwise
| delete | python | ly4k/Certipy | certipy/commands/account.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/account.py | MIT |
def entry(options: argparse.Namespace) -> None:
"""
Entry point for the 'account' command.
This function creates the Account object and dispatches to the appropriate method
based on the specified action.
Args:
options: Command line options
"""
# Create target from command line opti... |
Entry point for the 'account' command.
This function creates the Account object and dispatches to the appropriate method
based on the specified action.
Args:
options: Command line options
| entry | python | ly4k/Certipy | certipy/commands/account.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/account.py | MIT |
def __init__(self, tcp_shell: Any, domain_dumper: Any, client: Any):
"""
Initialize the LDAP shell.
Args:
tcp_shell: Shell to use for I/O
domain_dumper: Domain information provider
client: LDAP client connection
"""
super().__init__(tcp_shell,... |
Initialize the LDAP shell.
Args:
tcp_shell: Shell to use for I/O
domain_dumper: Domain information provider
client: LDAP client connection
| __init__ | python | ly4k/Certipy | certipy/commands/auth.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/auth.py | MIT |
def truncate_key(value: bytes, keysize: int) -> bytes:
"""
Truncate a key to the specified size using SHA1 hashing.
Args:
value: Input key material
keysize: Desired key size in bytes
Returns:
Truncated key of exactly keysize bytes
"""
output = b""
current_num = 0
... |
Truncate a key to the specified size using SHA1 hashing.
Args:
value: Input key material
keysize: Desired key size in bytes
Returns:
Truncated key of exactly keysize bytes
| truncate_key | python | ly4k/Certipy | certipy/commands/auth.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/auth.py | MIT |
def __init__(
self,
target: Target,
pfx: Optional[str] = None,
username: Optional[str] = None,
domain: Optional[str] = None,
password: Optional[str] = None,
cert: Optional[x509.Certificate] = None,
key: Optional[PrivateKeyTypes] = None,
no_save: bo... |
Initialize authentication parameters.
Args:
target: Target information (domain, DC IP, etc.)
pfx: Path to PFX/P12 certificate file
username: Username to authenticate as
domain: Domain to authenticate to
password: Password for PFX file
... | __init__ | python | ly4k/Certipy | certipy/commands/auth.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/auth.py | MIT |
def authenticate(
self,
username: Optional[str] = None,
domain: Optional[str] = None,
is_key_credential: bool = False,
) -> Union[str, bool, None]:
"""
Authenticate using a certificate.
This is the main entry point for authentication. It will determine
... |
Authenticate using a certificate.
This is the main entry point for authentication. It will determine
whether to use LDAP or Kerberos authentication based on configuration.
Args:
username: Username to authenticate as
domain: Domain to authenticate to
... | authenticate | python | ly4k/Certipy | certipy/commands/auth.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/auth.py | MIT |
def _check_identity_mismatches(
self,
username: Optional[str],
domain: Optional[str],
cert_username: Optional[str],
cert_domain: Optional[str],
) -> Optional[bool]:
"""
Check for mismatches between provided identity and certificate identity.
Args:
... |
Check for mismatches between provided identity and certificate identity.
Args:
username: Provided username
domain: Provided domain
cert_username: Username from certificate
cert_domain: Domain from certificate
Returns:
None if checks ... | _check_identity_mismatches | python | ly4k/Certipy | certipy/commands/auth.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/auth.py | MIT |
def ldap_authentication(self, domain: Optional[str] = None) -> bool:
"""
Authenticate to LDAP using a certificate.
Args:
domain: Domain to authenticate to
Returns:
True if successful, False otherwise
"""
if self.key is None:
raise Val... |
Authenticate to LDAP using a certificate.
Args:
domain: Domain to authenticate to
Returns:
True if successful, False otherwise
| ldap_authentication | python | ly4k/Certipy | certipy/commands/auth.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/auth.py | MIT |
def kerberos_authentication(
self,
username: str,
domain: str,
is_key_credential: bool = False,
id_type: Optional[str] = None,
identity: Optional[str] = None,
object_sid: Optional[str] = None,
upn: Optional[str] = None,
) -> Union[str, bool, None]:
... |
Authenticate to Kerberos using PKINIT with a certificate.
Args:
username: Username to authenticate as
domain: Domain to authenticate to
is_key_credential: Whether we're using a key credential
id_type: Type of identity in certificate
identity:... | kerberos_authentication | python | ly4k/Certipy | certipy/commands/auth.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/auth.py | MIT |
def entry(options: argparse.Namespace) -> None:
"""
Entry point for the 'auth' command.
Args:
options: Command-line arguments
"""
# Ensure we don't try to use password authentication
options.no_pass = True
# Create target from options
target = Target.from_options(options, dc_as... |
Entry point for the 'auth' command.
Args:
options: Command-line arguments
| entry | python | ly4k/Certipy | certipy/commands/auth.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/auth.py | MIT |
def request(self, req: Any, *args, **kwargs): # type: ignore
"""
Send a request to the CA service.
Args:
req: Request object
*args: Additional arguments
**kwargs: Additional keyword arguments
Returns:
Response from the CA service
... |
Send a request to the CA service.
Args:
req: Request object
*args: Additional arguments
**kwargs: Additional keyword arguments
Returns:
Response from the CA service
Raises:
DCERPCException: If the RPC call fails
| request | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def __init__(
self,
target: Target,
ca: Optional[str] = None,
template: Optional[str] = None,
officer: Optional[str] = None,
request_id: Optional[int] = None,
connection: Optional[LDAPConnection] = None,
scheme: str = "ldaps",
dynamic: bool = False... |
Initialize CA management object.
Args:
target: Target information (hostname, credentials, etc.)
ca: CA name
template: Certificate template name
officer: Officer username
request_id: Certificate request ID
connection: Existing LDAP... | __init__ | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def connection(self) -> LDAPConnection:
"""
Get or create an LDAP connection to the domain.
Returns:
Active LDAP connection
Raises:
ValueError: If target resolution fails
"""
if self._connection:
return self._connection
targe... |
Get or create an LDAP connection to the domain.
Returns:
Active LDAP connection
Raises:
ValueError: If target resolution fails
| connection | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def cert_admin(self) -> ICertAdminD:
"""
Get or create an ICertAdminD interface.
Returns:
ICertAdminD interface
"""
if self._cert_admin is not None:
return self._cert_admin
dcom = get_dcom_connection(self.target)
interface = dcom.CoCreate... |
Get or create an ICertAdminD interface.
Returns:
ICertAdminD interface
| cert_admin | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def cert_admin2(self) -> ICertAdminD2:
"""
Get or create an ICertAdminD2 interface.
Returns:
ICertAdminD2 interface
"""
if self._cert_admin2 is not None:
return self._cert_admin2
dcom = get_dcom_connection(self.target)
interface = dcom.Co... |
Get or create an ICertAdminD2 interface.
Returns:
ICertAdminD2 interface
| cert_admin2 | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def cert_request2(self) -> ICertRequestD2:
"""
Get or create an ICertRequestD2 interface.
Returns:
ICertRequestD2 interface
"""
if self._cert_request2 is not None:
return self._cert_request2
dcom = get_dcom_connection(self.target)
interfa... |
Get or create an ICertRequestD2 interface.
Returns:
ICertRequestD2 interface
| cert_request2 | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def rrp_dce(self):
"""
Get or create a connection to the remote registry service.
Returns:
RRP DCE/RPC connection or None if connection fails
"""
if self._rrp_dce is not None:
return self._rrp_dce
dce = get_dce_rpc_from_string_binding(
... |
Get or create a connection to the remote registry service.
Returns:
RRP DCE/RPC connection or None if connection fails
| rrp_dce | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def get_exchange_certificate(self) -> x509.Certificate:
"""
Get the CA exchange certificate.
Returns:
CA exchange certificate
Raises:
Exception: If the certificate retrieval fails
"""
request = ICertRequestD2GetCAProperty()
request["pwszA... |
Get the CA exchange certificate.
Returns:
CA exchange certificate
Raises:
Exception: If the certificate retrieval fails
| get_exchange_certificate | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def get_config_rrp(self) -> "CAConfiguration":
"""
Get CA configuration via the Remote Registry Protocol.
Used as a fallback when CSRA fails.
This method navigates the Windows registry structure to extract CA configuration
settings including policy modules, edit flags, request d... |
Get CA configuration via the Remote Registry Protocol.
Used as a fallback when CSRA fails.
This method navigates the Windows registry structure to extract CA configuration
settings including policy modules, edit flags, request disposition,
disabled extensions, interface flags, ... | get_config_rrp | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def get_config(self) -> Optional["CAConfiguration"]:
"""
Get CA configuration using the Remote Registry Protocol (RRP).
This method attempts to retrieve the CA configuration using RRP
and handles any exceptions that might occur during the process.
Returns:
CAConfigu... |
Get CA configuration using the Remote Registry Protocol (RRP).
This method attempts to retrieve the CA configuration using RRP
and handles any exceptions that might occur during the process.
Returns:
CAConfiguration object containing configuration settings or None if retri... | get_config | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def issue(self) -> bool:
"""
Issue (approve) a pending certificate request.
Returns:
True if successful, False otherwise
"""
if self.request_id is None:
logging.error(
"A request ID (-request-id) is required in order to issue a pending or ... |
Issue (approve) a pending certificate request.
Returns:
True if successful, False otherwise
| issue | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def deny(self) -> bool:
"""
Deny a pending certificate request.
Returns:
True if successful, False otherwise
"""
if self.request_id is None:
logging.error(
"A request ID (-request-id) is required in order to deny a pending certificate requ... |
Deny a pending certificate request.
Returns:
True if successful, False otherwise
| deny | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def get_templates(self) -> Optional[List[str]]:
"""
Get list of templates enabled on the CA.
Returns:
List of template names and their OIDs
Returns False if the operation fails
"""
if self.ca is None:
logging.error("A CA (-ca) is required")
... |
Get list of templates enabled on the CA.
Returns:
List of template names and their OIDs
Returns False if the operation fails
| get_templates | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def list_templates(self) -> None:
"""
List templates enabled on the CA.
Prints the list of templates to stdout.
"""
certificate_templates = self.get_templates()
if certificate_templates is None:
return
if len(certificate_templates) == 1:
... |
List templates enabled on the CA.
Prints the list of templates to stdout.
| list_templates | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def enable(self, disable: bool = False) -> bool:
"""
Enable or disable a template on the CA.
Args:
disable: If True, disable the template; otherwise enable it
Returns:
True if successful, False otherwise
"""
if self.ca is None:
loggin... |
Enable or disable a template on the CA.
Args:
disable: If True, disable the template; otherwise enable it
Returns:
True if successful, False otherwise
| enable | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def _modify_ca_security(
self, user: str, right: int, right_type: str, remove: bool = False
) -> Union[bool, None]:
"""
Add or remove rights for a user on the CA.
Args:
user: Username
right: Right to add/remove (from CERTIFICATION_AUTHORITY_RIGHTS)
... |
Add or remove rights for a user on the CA.
Args:
user: Username
right: Right to add/remove (from CERTIFICATION_AUTHORITY_RIGHTS)
right_type: Description of the right (for logging)
remove: If True, remove the right; otherwise add it
Returns:
... | _modify_ca_security | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def add_officer(self, officer: str) -> Union[bool, None]:
"""
Add certificate officer rights for a user.
Officers can approve/deny certificate requests.
Args:
officer: Username to add as an officer
Returns:
True if successful, False if failed, None if us... |
Add certificate officer rights for a user.
Officers can approve/deny certificate requests.
Args:
officer: Username to add as an officer
Returns:
True if successful, False if failed, None if user not found
| add_officer | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def remove_officer(self, officer: str) -> Union[bool, None]:
"""
Remove certificate officer rights from a user.
Args:
officer: Username to remove as an officer
Returns:
True if successful, False if failed, None if user not found
"""
return self.r... |
Remove certificate officer rights from a user.
Args:
officer: Username to remove as an officer
Returns:
True if successful, False if failed, None if user not found
| remove_officer | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def remove_manager(self, manager: str) -> Union[bool, None]:
"""
Remove certificate manager rights from a user.
Args:
manager: Username to remove as a manager
Returns:
True if successful, False if failed, None if user not found
"""
return self.re... |
Remove certificate manager rights from a user.
Args:
manager: Username to remove as a manager
Returns:
True if successful, False if failed, None if user not found
| remove_manager | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def get_enrollment_services(self) -> List[LDAPEntry]:
"""
Get all enrollment services in the domain.
Returns:
List of enrollment service objects
"""
enrollment_services = self.connection.search(
"(&(objectClass=pKIEnrollmentService))",
search_... |
Get all enrollment services in the domain.
Returns:
List of enrollment service objects
| get_enrollment_services | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def get_enrollment_service(self, ca: str) -> Optional[LDAPEntry]:
"""
Get a specific enrollment service.
Args:
ca: CA name
Returns:
Enrollment service object or None if not found
"""
enrollment_services = self.connection.search(
f"(&(... |
Get a specific enrollment service.
Args:
ca: CA name
Returns:
Enrollment service object or None if not found
| get_enrollment_service | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def get_backup(self) -> Optional[bytes]:
"""
Retrieve CA backup file from the target.
Returns:
PFX data as bytes or None if retrieval fails
"""
# Connect to SMB share
smbclient = SMBConnection(
self.target.remote_name,
self.target.targ... |
Retrieve CA backup file from the target.
Returns:
PFX data as bytes or None if retrieval fails
| get_backup | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def backup(self) -> bool:
"""
Create a backup of the CA key and certificate.
Returns:
True if successful, False otherwise
"""
# Connect to service control manager
dce = get_dce_rpc(
scmr.MSRPC_UUID_SCMR, # type: ignore
"\\pipe\\svcctl... |
Create a backup of the CA key and certificate.
Returns:
True if successful, False otherwise
| backup | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def __init__(
self,
active_policy: str,
edit_flags: int,
disable_extension_list: List[str],
request_disposition: int,
interface_flags: int,
security: CASecurity,
):
"""
Initialize a CA configuration object.
Args:
active_pol... |
Initialize a CA configuration object.
Args:
active_policy: Name of the active policy module (typically CertificateAuthority_MicrosoftDefault.Policy)
edit_flags: Policy edit flags that control certificate issuance behavior
disable_extension_list: List of disabled cer... | __init__ | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def entry(options: argparse.Namespace) -> None:
"""
Entry point for the 'ca' command.
Args:
options: Command-line arguments
"""
target = Target.from_options(options)
options.__delattr__("target")
ca = CA(target, **vars(options))
# Validate CA name if required
if not option... |
Entry point for the 'ca' command.
Args:
options: Command-line arguments
| entry | python | ly4k/Certipy | certipy/commands/ca.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/ca.py | MIT |
def load_certificate_file(file_path: str) -> bytes:
"""
Load certificate data from a file.
Args:
file_path: Path to certificate file
Returns:
Certificate data as bytes
"""
logging.debug(f"Loading certificate from {file_path!r}")
try:
with open(file_path, "rb") as f:... |
Load certificate data from a file.
Args:
file_path: Path to certificate file
Returns:
Certificate data as bytes
| load_certificate_file | python | ly4k/Certipy | certipy/commands/cert.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/cert.py | MIT |
def load_key_file(file_path: str) -> bytes:
"""
Load private key data from a file.
Args:
file_path: Path to private key file
Returns:
Private key data as bytes
"""
logging.debug(f"Loading private key from {file_path!r}")
try:
with open(file_path, "rb") as f:
... |
Load private key data from a file.
Args:
file_path: Path to private key file
Returns:
Private key data as bytes
| load_key_file | python | ly4k/Certipy | certipy/commands/cert.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/cert.py | MIT |
def parse_certificate(cert_data: bytes) -> x509.Certificate:
"""
Parse certificate data from PEM or DER format.
Args:
cert_data: Raw certificate data
Returns:
Parsed certificate object
"""
try:
# Try PEM format first
return pem_to_cert(cert_data)
except Exce... |
Parse certificate data from PEM or DER format.
Args:
cert_data: Raw certificate data
Returns:
Parsed certificate object
| parse_certificate | python | ly4k/Certipy | certipy/commands/cert.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/cert.py | MIT |
def parse_key(key_data: bytes) -> PrivateKeyTypes:
"""
Parse private key data from PEM or DER format.
Args:
key_data: Raw private key data
Returns:
Parsed private key object
"""
try:
# Try PEM format first
return pem_to_key(key_data)
except Exception:
... |
Parse private key data from PEM or DER format.
Args:
key_data: Raw private key data
Returns:
Parsed private key object
| parse_key | python | ly4k/Certipy | certipy/commands/cert.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/cert.py | MIT |
def write_output(data: Union[bytes, str], output_path: Optional[str] = None) -> None:
"""
Write data to a file or stdout.
Args:
data: Data to write
output_path: Path to output file or None for stdout
"""
if output_path:
# Determine if we need binary mode
mode = "wb" ... |
Write data to a file or stdout.
Args:
data: Data to write
output_path: Path to output file or None for stdout
| write_output | python | ly4k/Certipy | certipy/commands/cert.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/cert.py | MIT |
def entry(options: argparse.Namespace) -> None:
"""
Entry point for the 'cert' command.
Processes certificates and private keys according to specified options.
Args:
options: Command-line arguments
"""
cert, key = None, None
# Validate inputs
if not any([options.pfx, options.c... |
Entry point for the 'cert' command.
Processes certificates and private keys according to specified options.
Args:
options: Command-line arguments
| entry | python | ly4k/Certipy | certipy/commands/cert.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/cert.py | MIT |
def connection(self) -> LDAPConnection:
"""
Get or create an LDAP connection.
Returns:
Active LDAP connection to the target
"""
if self._connection is not None:
return self._connection
self._connection = LDAPConnection(self.target)
self._... |
Get or create an LDAP connection.
Returns:
Active LDAP connection to the target
| connection | python | ly4k/Certipy | certipy/commands/find.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py | MIT |
def user_sids(self) -> Set[str]:
"""
Get current user's SIDs.
Returns:
Set of SIDs associated with the current user
"""
if self._user_sids is None:
self._user_sids: Optional[Set[str]] = self.connection.get_user_sids(
self.target.username, ... |
Get current user's SIDs.
Returns:
Set of SIDs associated with the current user
| user_sids | python | ly4k/Certipy | certipy/commands/find.py | https://github.com/ly4k/Certipy/blob/master/certipy/commands/find.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.