Bashkuto is a lightweight Python library that transforms Bash environments into agent-friendly runtimes. It provides AI agents with safe, structured, and efficient command execution capabilities with built-in safeguards for production use.
Features
- Command Execution: Safe subprocess execution with timing and error tracking
- Pipe Chains: Full support for complex Bash pipelines
- Overflow Handling: Graceful handling of large outputs with automatic file spill-over and cleanup
- Binary Guards: Automatic detection and suppression of binary output
- Structured Output: Multiple output formats optimized for LLM consumption (string, dict, JSON)
- Security: Regex-based command blocking with customizable allowlists/blocklists
- Timeout Support: Configurable command timeouts to prevent hanging
- Cross-Platform: Works on Windows, Linux, and macOS
- Zero Dependencies: Pure Python 3.12+ with no external requirements
Installation
pip install bashkuto
For development:
pip install -e ".[dev]"
Quick Start
from bashkuto import BashRuntime, run
# Simple usage with default runtime
result = run("echo hello")
print(result)
# Output:
# hello
# [exit:0 | 1ms]
# Advanced usage with custom runtime
runtime = BashRuntime(
timeout_sec=30,
max_output_chars=8000,
blocked_substrings=["rm -rf"],
)
result = runtime.run("ls -la")
print(result.output)
print(result.exit_code)
print(result.duration_ms)
API Reference
BashRuntime
Main class for executing bash commands safely.
from bashkuto import BashRuntime
runtime = BashRuntime(
shell=None, # Shell executable (default: platform default)
timeout_sec=None, # Command timeout in seconds
max_output_chars=8000, # Max output before truncation
blocked_substrings=None, # Additional blocked substrings
blocked_patterns=None, # Additional blocked regex patterns
overflow_dir=".bashkuto_overflow", # Overflow file directory
overflow_max_age_hours=24, # Max age of overflow files
overflow_max_size_mb=100, # Max size of overflow directory
cwd=None, # Working directory for commands
env=None, # Environment variables
)
result = runtime.run("your-command")
🐚 Shell Compatibility Note
Bashkuto uses your system's shell executables. For the best experience with BashSession persistence and state tracking:
- Unix/Linux/macOS: Use POSIX-compliant shells like
bash(preferred),sh, orzsh. - Windows: Use
cmd.exe(preferred).
While other shells like fish or PowerShell can be used for single commands, their unique syntax may interfere with automatic state tracking (like cd persistence) in BashSession.
CommandResult
Dataclass containing command execution results.
@dataclass
class CommandResult:
output: str # stdout
stderr: str # stderr
exit_code: int # Exit code
duration_ms: int # Execution duration
truncated: bool # Was output truncated?
overflow_file: str # Path to overflow file (if any)
Methods:
to_agent_string()- Format for LLM consumption (legacy format)to_dict()- Convert to dictionaryto_json(indent=2)- Convert to JSON stringsuccessproperty - True if exit_code == 0
OutputFormatter
Format command results for optimal agent consumption.
from bashkuto import OutputFormatter, format_result
formatter = OutputFormatter(max_context_lines=50)
formatted = formatter.format_for_agent(
result,
include_stderr=True,
include_metadata=True,
compact=False
)
# Or use convenience function
formatted = format_result(result, max_context_lines=50)
Security
Customize security rules:
from bashkuto import BashRuntime, SecurityError
runtime = BashRuntime(
blocked_substrings=["dangerous_cmd"],
blocked_patterns=[
r"rm\s+-rf\s+/", # Block rm -rf /
r"curl.*\|\s*sh", # Block curl | sh
]
)
try:
runtime.run("rm -rf /")
except SecurityError as e:
print(f"Blocked: {e}")
Exceptions
from bashkuto import (
BashkutoError, # Base exception
SecurityError, # Security check failed
TimeoutError, # Command timed out
BinaryOutputError, # Binary output detected
OverflowError, # Overflow handling failed
)
Examples
Basic Command Execution
from bashkuto import BashRuntime
runtime = BashRuntime()
# Simple command
result = runtime.run("echo hello")
assert result.success
assert "hello" in result.output
# Pipe chains
result = runtime.run("echo hello | grep hello")
assert result.success
# Failed command
result = runtime.run("false")
assert not result.success
assert result.exit_code == 1
Structured Output
from bashkuto import BashRuntime
import json
runtime = BashRuntime()
result = runtime.run("ls -la")
# Access as dictionary
data = result.to_dict()
print(data["stdout"])
print(data["exit_code"])
# Access as JSON
json_str = result.to_json()
parsed = json.loads(json_str)
# Check success
if result.success:
print("Command succeeded!")
Timeout Handling
from bashkuto import BashRuntime, TimeoutError
runtime = BashRuntime(timeout_sec=5)
try:
result = runtime.run("long-running-command")
except TimeoutError as e:
print(f"Command timed out: {e}")
Output Truncation
from bashkuto import BashRuntime
runtime = BashRuntime(max_output_chars=1000)
result = runtime.run("cat large_file.txt")
if result.truncated:
print(f"Output truncated, see: {result.overflow_file}")
# Full output saved to overflow file
Custom Security Rules
from bashkuto import BashRuntime, SecurityError
# Add custom blocked commands
runtime = BashRuntime(
blocked_substrings=["malicious"],
blocked_patterns=[
r"wget.*-O-.*\|.*sh", # wget | sh
r"dd\s+.*of=/dev/", # dd to disk
]
)
try:
runtime.run("malicious_command")
except SecurityError:
print("Command blocked!")
Security Model
Bashkuto uses a blocklist-based security model:
Default Blocked Commands
rm -rf- Recursive force delete:(){ :|:& };:- Fork bombrm -rf /- Root directory deletion (regex)chmod -R 777 /- Dangerous permissions (regex)> /dev/sd[a-z]- Disk overwriting (regex)mkfs.*- Filesystem creation (regex)dd.*of=/dev/- Low-level disk writing (regex)shutdown -h now- Immediate shutdown (regex)reboot -f- Force reboot (regex)curl.*|.*sh- Remote script execution (regex)wget.*-O-.*|.*sh- Remote wget execution (regex)
Adding Custom Rules
runtime = BashRuntime(
blocked_substrings=["custom_cmd"],
blocked_patterns=[r"dangerous_\w+"],
)
⚠️ Security Warning
Bashkuto runs commands with your user's permissions. For untrusted code:
- Use containerization (Docker, etc.)
- Run in a sandboxed environment
- Implement additional allowlisting
- Enable audit logging
Logging
Bashkuto uses Python's standard logging:
import logging
logging.basicConfig(level=logging.INFO)
logging.getLogger("bashkuto").setLevel(logging.DEBUG)
from bashkuto import BashRuntime
runtime = BashRuntime()
runtime.run("echo test") # Logs execution details
Architecture
┌─────────────────────────────────────┐
│ Agent Interface │
│ (api.py - run(), BashRuntime) │
├─────────────────────────────────────┤
│ Presentation Layer │
│ (formatter.py, truncation.py, │
│ binary_guard.py) │
├─────────────────────────────────────┤
│ Execution Layer │
│ (executor.py, guards.py, result.py,│
│ runtime.py) │
└─────────────────────────────────────┘
Running Tests
# Install dev dependencies
pip install -e ".[dev]"
# Run all tests
pytest tests/ -v
# Run with coverage
pytest tests/ -v --cov=bashkuto --cov-report=html
Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
License
MIT License - see LICENSE file for details.
Author
Mohamed Sofiene Kadri ms.kadri.dev@gmail.com
Acknowledgments
Built for the AI agent community to provide safe, reliable Bash execution environments.
Metadata
Release files for bashkuto 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| bashkuto-0.1.0.tar.gz | 159.3 kB | Without provenance | Details for bashkuto-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| bashkuto-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for bashkuto-0.1.0-py3-none-any.whl |
Total release size: 177.7 kB
Release files / bashkuto-0.1.0.tar.gz
| Download URL | bashkuto-0.1.0.tar.gz |
|---|---|
| Size | 159.3 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
d22763f54f3bb74e993e7d4a84ceba4836dfd7a815389b9f9388ce0496a48d1a
|
|
BLAKE2b-256 checksum How to use checksums |
48aaf72747a3a3742a4a392a42953fb865b5276defd1974ab3ef3a860ab7e86b
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.7.19
|
Release files / bashkuto-0.1.0-py3-none-any.whl
| Download URL | bashkuto-0.1.0-py3-none-any.whl |
|---|---|
| Size | 18.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
ef05e187996c6c70728bed55cdaf299dea95a97f71de15601ea7c46140ddeef2
|
|
BLAKE2b-256 checksum How to use checksums |
cfe01b128ed83bc21b6ce8d143495d7ca61af7265134c2c68de65e4da620e876
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.7.19
|
Security for bashkuto 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.