How to run one-off under systemd → systemd-run

How to Run One-Off Commands Under systemd → systemd-run Table of Contents 1. [Introduction](#introduction) 2. [Prerequisites](#prerequisites) 3. [Understanding systemd-run](#understanding-systemd-run) 4. [Basic Usage and Syntax](#basic-usage-and-syntax) 5. [Common Options and Parameters](#common-options-and-parameters) 6. [Practical Examples](#practical-examples) 7. [Advanced Use Cases](#advanced-use-cases) 8. [Monitoring and Managing One-Off Services](#monitoring-and-managing-one-off-services) 9. [Troubleshooting Common Issues](#troubleshooting-common-issues) 10. [Best Practices and Professional Tips](#best-practices-and-professional-tips) 11. [Security Considerations](#security-considerations) 12. [Conclusion](#conclusion) Introduction The `systemd-run` command is a powerful utility that allows system administrators and users to execute one-off commands or create temporary services under the systemd service manager. This tool provides a convenient way to run processes with specific resource constraints, security settings, and isolation parameters without creating permanent service files. In this comprehensive guide, you'll learn how to effectively use `systemd-run` to execute commands with enhanced control over system resources, security contexts, and process management. Whether you're running maintenance scripts, testing applications, or executing resource-intensive tasks, `systemd-run` offers the flexibility and control needed for modern Linux system administration. By the end of this article, you'll understand how to leverage systemd's process management capabilities for one-time tasks, apply resource limits, configure security settings, and troubleshoot common issues that may arise when using `systemd-run`. Prerequisites Before diving into `systemd-run`, ensure you have the following prerequisites: System Requirements - A Linux distribution with systemd (most modern distributions) - systemd version 220 or later (recommended version 240+) - Basic understanding of Linux command line - Root or sudo privileges for certain operations Knowledge Prerequisites - Familiarity with basic Linux commands - Understanding of process management concepts - Basic knowledge of systemd service concepts - Awareness of Linux security and permissions Verification Commands Check your systemd version: ```bash systemctl --version ``` Verify systemd-run availability: ```bash which systemd-run ``` Check current user privileges: ```bash id ``` Understanding systemd-run What is systemd-run? `systemd-run` is a command-line tool that creates and starts transient systemd units. These units are temporary and exist only for the duration of the command execution. Unlike permanent service files stored in `/etc/systemd/system/` or `/lib/systemd/system/`, transient units are created dynamically and automatically cleaned up after completion. Key Benefits 1. Resource Control: Apply cgroups-based resource limits 2. Security Isolation: Run commands with specific security contexts 3. Process Management: Leverage systemd's process supervision 4. Logging Integration: Automatic integration with systemd journal 5. Dependency Management: Define service dependencies dynamically 6. Environment Control: Set specific environment variables and working directories How systemd-run Works When you execute a command with `systemd-run`, the following process occurs: 1. systemd creates a transient service unit 2. The command is executed within this unit's context 3. systemd applies any specified constraints or settings 4. The process is monitored and logged by systemd 5. Upon completion, the transient unit is automatically removed Basic Usage and Syntax Command Syntax The basic syntax for `systemd-run` is: ```bash systemd-run [OPTIONS] COMMAND [ARGUMENTS] ``` Simple Example Execute a basic command: ```bash systemd-run echo "Hello from systemd-run" ``` This creates a transient service unit, executes the echo command, and returns the output. Running Commands in the Background To run a command as a background service: ```bash systemd-run --remain-after-exit /usr/bin/sleep 300 ``` User vs System Mode Run in user mode (default for non-root users): ```bash systemd-run --user echo "User mode execution" ``` Run in system mode (requires root privileges): ```bash sudo systemd-run --system echo "System mode execution" ``` Common Options and Parameters Unit Naming and Description Specify a custom unit name: ```bash systemd-run --unit=my-task echo "Custom unit name" ``` Add a description: ```bash systemd-run --description="Backup task" rsync -av /home/ /backup/ ``` Service Type Configuration Set service type to oneshot: ```bash systemd-run --service-type=oneshot --remain-after-exit /bin/true ``` Configure as a forking service: ```bash systemd-run --service-type=forking /usr/bin/daemon-command ``` Working Directory and Environment Set working directory: ```bash systemd-run --working-directory=/tmp ls -la ``` Set environment variables: ```bash systemd-run --setenv=MY_VAR=value --setenv=DEBUG=1 /usr/bin/myapp ``` Resource Limitations Memory Limits ```bash systemd-run --property=MemoryLimit=100M memory-intensive-command ``` CPU Limits ```bash systemd-run --property=CPUQuota=50% cpu-intensive-task ``` Combined Resource Limits ```bash systemd-run \ --property=MemoryLimit=512M \ --property=CPUQuota=25% \ --property=TasksMax=10 \ intensive-application ``` Practical Examples Example 1: Running a Backup Script Execute a backup script with resource limits and logging: ```bash systemd-run \ --unit=backup-home \ --description="Home directory backup" \ --working-directory=/home \ --property=MemoryLimit=1G \ --property=CPUQuota=30% \ --setenv=BACKUP_DEST=/mnt/backup \ /usr/local/bin/backup-script.sh ``` Example 2: Temporary Web Server Start a temporary Python web server: ```bash systemd-run \ --unit=temp-webserver \ --remain-after-exit \ --working-directory=/var/www/html \ --property=User=www-data \ --property=Group=www-data \ python3 -m http.server 8080 ``` Example 3: Database Maintenance Run database maintenance with specific user and resource constraints: ```bash systemd-run \ --unit=db-maintenance \ --description="PostgreSQL maintenance task" \ --property=User=postgres \ --property=Group=postgres \ --property=MemoryLimit=2G \ --working-directory=/var/lib/postgresql \ /usr/bin/vacuumdb --all --analyze ``` Example 4: Timed Execution Execute a command with a timeout: ```bash systemd-run \ --unit=timed-task \ --property=TimeoutStartSec=300 \ --property=TimeoutStopSec=60 \ long-running-command ``` Example 5: Secure Sandboxed Execution Run a command in a sandboxed environment: ```bash systemd-run \ --unit=sandboxed-task \ --property=PrivateTmp=true \ --property=ProtectSystem=strict \ --property=ProtectHome=true \ --property=NoNewPrivileges=true \ --working-directory=/tmp \ untrusted-application ``` Advanced Use Cases Creating Timer-Based One-Off Tasks Combine `systemd-run` with timer functionality: ```bash systemd-run \ --on-calendar="--* 02:00:00" \ --unit=daily-cleanup \ /usr/local/bin/cleanup-script.sh ``` Network Namespace Isolation Run a command in an isolated network namespace: ```bash systemd-run \ --unit=isolated-network-task \ --property=PrivateNetwork=true \ network-sensitive-command ``` File System Isolation Execute with read-only file system access: ```bash systemd-run \ --unit=readonly-task \ --property=ProtectSystem=strict \ --property=ReadOnlyPaths=/etc \ --property=ReadWritePaths=/tmp \ file-processing-command ``` Dependency Management Create a one-off service with dependencies: ```bash systemd-run \ --unit=dependent-task \ --property=After=network.target \ --property=Wants=network.target \ network-dependent-command ``` Custom Slice Assignment Assign to a specific systemd slice for resource management: ```bash systemd-run \ --slice=my-custom-slice \ --unit=sliced-task \ resource-intensive-command ``` Monitoring and Managing One-Off Services Viewing Running Services List all running transient services: ```bash systemctl list-units --type=service --state=running | grep -E "run-.*\.service" ``` Checking Service Status Monitor a specific transient service: ```bash systemctl status run-u123.service ``` Viewing Logs Access logs for a transient service: ```bash journalctl -u run-u123.service -f ``` View logs with specific filters: ```bash journalctl -u my-task.service --since="1 hour ago" --no-pager ``` Stopping Running Services Stop a running transient service: ```bash systemctl stop run-u123.service ``` Resource Usage Monitoring Monitor resource usage of running services: ```bash systemd-cgtop ``` Check specific service resource usage: ```bash systemctl show run-u123.service --property=MemoryCurrent,CPUUsageNSec ``` Troubleshooting Common Issues Issue 1: Permission Denied Errors Problem: Commands fail with permission denied errors. Solution: ```bash Check current user permissions id Use appropriate user property systemd-run --property=User=appropriate-user command Or run with sudo for system-level tasks sudo systemd-run --system command ``` Issue 2: Resource Limit Violations Problem: Commands terminated due to resource limits. Symptoms: ```bash journalctl -u failed-service.service Shows: "Process killed by signal KILL" ``` Solution: ```bash Increase memory limits systemd-run --property=MemoryLimit=2G command Check current limits systemctl show service-name --property=MemoryLimit,CPUQuota ``` Issue 3: Environment Variable Issues Problem: Commands can't access required environment variables. Solution: ```bash Explicitly set environment variables systemd-run --setenv=PATH=/usr/local/bin:/usr/bin:/bin command Preserve user environment systemd-run --property=Environment="$(env)" command ``` Issue 4: Working Directory Problems Problem: Commands fail because of incorrect working directory. Solution: ```bash Set explicit working directory systemd-run --working-directory=/correct/path command Verify directory exists and is accessible ls -la /path/to/directory ``` Issue 5: Service Cleanup Issues Problem: Transient services not cleaning up properly. Solution: ```bash Force cleanup of failed units systemctl reset-failed List and manually stop lingering services systemctl list-units --type=service --state=failed systemctl stop problematic-service.service ``` Issue 6: Logging and Output Problems Problem: Can't see command output or logs. Solution: ```bash Use --pty for interactive output systemd-run --pty command Check journal for output journalctl -u service-name --no-pager Combine with wait for synchronous execution systemd-run --wait command ``` Best Practices and Professional Tips 1. Naming Conventions Use descriptive unit names: ```bash systemd-run \ --unit=backup-$(date +%Y%m%d) \ --description="Daily backup $(date)" \ backup-command ``` 2. Resource Planning Always set appropriate resource limits: ```bash systemd-run \ --property=MemoryLimit=1G \ --property=CPUQuota=50% \ --property=TasksMax=100 \ resource-intensive-task ``` 3. Security Hardening Apply security restrictions by default: ```bash systemd-run \ --property=NoNewPrivileges=true \ --property=PrivateTmp=true \ --property=ProtectKernelTunables=true \ security-sensitive-command ``` 4. Logging Strategy Ensure proper logging configuration: ```bash systemd-run \ --property=StandardOutput=journal \ --property=StandardError=journal \ --property=SyslogIdentifier=my-task \ command-with-logging ``` 5. Error Handling Implement proper error handling: ```bash systemd-run \ --property=Restart=no \ --property=RemainAfterExit=true \ --on-failure=notify-admin.service \ potentially-failing-command ``` 6. Performance Optimization Optimize for performance: ```bash systemd-run \ --property=Nice=-10 \ --property=IOSchedulingClass=1 \ --property=IOSchedulingPriority=4 \ high-priority-task ``` 7. Monitoring Integration Integrate with monitoring systems: ```bash systemd-run \ --unit=monitored-task-$(uuidgen) \ --property=OnSuccess=success-notification.service \ --property=OnFailure=failure-notification.service \ monitored-command ``` Security Considerations Privilege Escalation Prevention Always use minimal required privileges: ```bash systemd-run \ --property=User=nobody \ --property=Group=nobody \ --property=NoNewPrivileges=true \ low-privilege-command ``` File System Protection Implement file system restrictions: ```bash systemd-run \ --property=ProtectSystem=strict \ --property=ProtectHome=true \ --property=ReadWritePaths=/var/tmp \ file-access-limited-command ``` Network Security Control network access: ```bash systemd-run \ --property=PrivateNetwork=true \ --property=RestrictAddressFamilies=AF_UNIX \ network-restricted-command ``` Capability Restrictions Limit process capabilities: ```bash systemd-run \ --property=CapabilityBoundingSet= \ --property=AmbientCapabilities= \ capability-restricted-command ``` Audit and Compliance Enable audit logging: ```bash systemd-run \ --property=AuditType=true \ --property=StandardOutput=journal \ audited-command ``` Conclusion The `systemd-run` command is an invaluable tool for modern Linux system administration, providing sophisticated process management capabilities for one-off tasks and temporary services. Throughout this comprehensive guide, we've explored its fundamental concepts, practical applications, and advanced features that make it essential for effective system management. Key takeaways from this guide include: 1. Flexibility: `systemd-run` offers extensive configuration options for resource management, security, and process control 2. Integration: Seamless integration with systemd's logging, monitoring, and management infrastructure 3. Security: Robust security features including sandboxing, privilege restriction, and isolation capabilities 4. Resource Management: Precise control over CPU, memory, and other system resources 5. Monitoring: Built-in logging and monitoring capabilities through systemd journal integration By implementing the best practices and security considerations outlined in this guide, you can leverage `systemd-run` to create more reliable, secure, and maintainable system administration workflows. Whether you're running maintenance scripts, testing applications, or executing resource-intensive tasks, `systemd-run` provides the control and flexibility needed for professional system management. As you continue to work with `systemd-run`, remember to regularly review and update your usage patterns, stay informed about new systemd features, and always prioritize security and resource efficiency in your implementations. The investment in mastering this tool will pay dividends in improved system reliability, security, and operational efficiency. For further learning, consider exploring related systemd tools such as `systemctl`, `journalctl`, and systemd service file creation to build a comprehensive understanding of the systemd ecosystem and its powerful process management capabilities.