К основному содержанию
скилл CX Codex

systemd-services — скилл для Claude Code: что делает и как установить

Помогает создавать и настраивать сервисы systemd, таймеры и сокетную активацию. Пригодится для деплоя фоновых процессов и настройки лимитов ресурсов.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add BagelHole/DevOps-Security-Agent-Skills --skill systemd-services -a claude-code
Открыть на GitHub

Что делает systemd-services

Скилл обучает агента составлять конфигурации для systemd и управлять жизненным циклом демонов в Linux. Он содержит шаблоны юнит-файлов с параметрами перезапуска и директивами изоляции вроде ProtectSystem=strict, NoNewPrivileges и PrivateTmp. Также сюда входят инструкции по настройке зависимостей через After, Requires и Wants с проверкой дерева через systemctl list-dependencies.

Внутри собраны готовые сценарии. Они позволяют заменить задачи cron на таймеры с директивами OnCalendar и Persistent. Скилл показывает, как настраивать сокетную активацию и ограничивать потребление памяти или процессора через сгруппированные оверрайды limits.conf в cgroups v2.

Для работы обязательно нужны права root или sudo, без них агент не сможет записать файлы юнитов в каталог /etc/systemd/system/. Синтаксис календарных выражений таймеров скилл рекомендует проверять через systemd-analyze calendar.

Какие задачи решает

  • запустить бинарник или скрипт как управляемую фоновую службу
  • перенести периодические задания из cron в таймеры systemd
  • задать лимиты памяти и CPU через drop-in конфигурации cgroups v2
  • настроить запуск приложения по входящему сетевому сокету
  • изолировать процесс с помощью параметров ProtectSystem и ProtectHome

Примеры запросов агенту

  • Создай systemd-сервис для приложения с перезапуском при ошибке и лимитом памяти 1G
  • Настрой systemd-таймер для ежедневного запуска backup.service в 02:30
  • Покажи дерево зависимостей и проверь статус службы myapp

Как установить systemd-services

1Через Skills CLI (Vercel)

npx skills add BagelHole/DevOps-Security-Agent-Skills --skill systemd-services -a claude-code

2Вручную: положить файлы

~/.claude/skills/systemd-services/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/systemd-services/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Из того же набора127

linux-administration Скилл для работы с Linux-серверами: пакеты, службы, диски, процессы, cron и логи. Пригодится, когда агент должен выполнять команды на сервере, а не только писать код. CX Codex +1 770установок linux-hardening Скилл проводит агента по CIS-бенчмаркам: настраивает SSH, пользователей, файрвол и параметры ядра. Пригодится, когда сервер готовят к продакшену или аудиту. CX Codex +1 769установок docker-management Набор инструкций для сборки многоэтапных Dockerfile, настройки сетей и отладки контейнеров в Docker. Помогает изолировать окружение и находить ошибки в упавших процессах. CX Codex +1 508установок reverse-proxy Скилл помогает настроить nginx и Traefik как обратные прокси: направить трафик на бэкенды, настроить TLS и выставить лимиты запросов. CX Codex +1 473установок firewall-config Скилл для настройки хостовых и облачных фаерволов: правила iptables, nftables, UFW и security groups. Пригодится, когда закрываешь периметр сервера или делишь сеть на зоны. CX Codex +1 458установок ssh-configuration Настраивает OpenSSH на клиенте и сервере, помогает выпускать ключи Ed25519, пробрасывать порты и поднимать бастион-хосты для безопасного удалённого доступа. CX Codex +1 451установок prometheus-grafana Скилл помогает агенту поднять сбор метрик в Prometheus, писать запросы PromQL и собирать панели Grafana. Пригодится, когда в проект нужно добавить мониторинг. CX Codex +1 449установок windows-server Скилл для администрирования Windows Server: роли и компоненты, сайты IIS, пользователи Active Directory, обновления. Пригодится, когда агент работает с Windows-инфраструктурой. CX Codex +1 449установок

Похожие

system-admin terminal-skills Скилл с командами для проверки состояния Linux-сервера: нагрузка, память, диски, службы systemd. Пригодится, когда агент разбирается с тормозящим сервером. CX Codex +1 561установок debian-linux-triage официальный github Скилл помогает разбирать проблемы Debian Linux через apt, systemd и dpkg, учитывая AppArmor и firewall. Подойдёт для диагностики с пошаговой проверкой. 9 197установок fedora-linux-triage официальный github Скилл помогает разбирать проблемы Fedora через dnf, systemd и проверки SELinux. Подойдёт, когда нужен пошаговый план диагностики с командами. 8 800установок linux-shell-scripting zebbern Скилл с готовыми шаблонами bash-скриптов: бэкапы, мониторинг ресурсов, управление пользователями, разбор логов. Пригодится, когда агенту нужно написать рабочий скрипт, а не набросок. CX Codex +1 ★ 4 676звёзд репо dotnet-devcert-trust Aaronontheweb Разбирает, почему .NET и Aspire не доверяют HTTPS-сертификату разработчика на Linux, и доводит его до системного CA-бандла. CX Codex +1 434установок unauthorized-access-common-services yaklang Скилл для пентеста: разбирает Redis, Rsync, PHP-FPM, AJP/Ghostcat, Hadoop YARN и H2 Console, если они торчат наружу без аутентификации. CX Codex +1 3 400установок

Рядом в теме «DevOps и инфраструктура»

Всё по теме «DevOps и инфраструктура» →

Вопросы о systemd-services

Как установить systemd-services в Claude Code?

Выполните команду npx skills add BagelHole/DevOps-Security-Agent-Skills --skill systemd-services -a claude-code. Она загрузит скилл в конфигурацию агента.

Что делает скилл systemd-services?

Он предоставляет агенту шаблоны юнитов, правила изоляции процессов, схемы настройки сокетов и таймеров, а также команды для управления службами через systemctl.

Что требуется для применения юнитов на сервере?

Нужна система Linux с запущенным systemd и доступ root или sudo. Без повышенных привилегий создать файлы в директории /etc/systemd/system/ нельзя.

Исходный текст

SKILL.md · MIT
---
name: systemd-services
description: Create and manage systemd services and timers. Configure service dependencies and resource limits. Use when managing system services.
license: MIT
metadata:
  author: devops-skills
  version: "1.0"
---

# Systemd Services

Create, manage, and monitor systemd services and timers. Covers unit file authoring, dependency management, socket activation, resource limits, journalctl log analysis, and production hardening.

## When to Use

- Deploying an application as a managed background service
- Replacing cron jobs with systemd timers for better logging and dependency control
- Setting up socket activation for on-demand service startup
- Configuring resource limits (CPU, memory, I/O) for services
- Debugging service startup failures and runtime crashes
- Managing service dependencies and ordering

## Prerequisites

- Linux system running systemd (most modern distributions)
- Root or sudo access for creating system-level unit files
- Application binary or script to run as a service
- Understanding of the application's start/stop lifecycle

## Service Unit File -- Complete Example

```ini
# /etc/systemd/system/myapp.service
[Unit]
Description=MyApp Production Server
Documentation=https://docs.example.com/myapp
After=network-online.target postgresql.service
Wants=network-online.target
Requires=postgresql.service

[Service]
Type=notify
User=myapp
Group=myapp
WorkingDirectory=/opt/myapp

# Environment configuration
EnvironmentFile=/etc/myapp/env
Environment=NODE_ENV=production
Environment=PORT=8080

# Execution
ExecStartPre=/opt/myapp/bin/migrate --check
ExecStart=/opt/myapp/bin/server --config /etc/myapp/config.yaml
ExecStartPost=/opt/myapp/bin/healthcheck.sh
ExecReload=/bin/kill -HUP $MAINPID
ExecStop=/opt/myapp/bin/graceful-stop.sh

# Restart behavior
Restart=on-failure
RestartSec=5
StartLimitIntervalSec=300
StartLimitBurst=5

# Timeouts
TimeoutStartSec=30
TimeoutStopSec=30
WatchdogSec=60

# Security hardening
NoNewPrivileges=true
ProtectSystem=strict
ProtectHome=true
PrivateTmp=true
ReadWritePaths=/var/lib/myapp /var/log/myapp
CapabilityBoundingSet=
AmbientCapabilities=

# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=myapp

[Install]
WantedBy=multi-user.target
```

## Service Management Commands

```bash
# Reload systemd after creating or modifying unit files
systemctl daemon-reload

# Start, stop, restart a service
systemctl start myapp
systemctl stop myapp
systemctl restart myapp

# Reload service configuration without restart (if supported)
systemctl reload myapp

# Enable service to start on boot
systemctl enable myapp

# Enable and start in one command
systemctl enable --now myapp

# Disable and stop
systemctl disable --now myapp

# Check service status
systemctl status myapp

# Check if a service is active, enabled, or failed
systemctl is-active myapp
systemctl is-enabled myapp
systemctl is-failed myapp

# List all running services
systemctl list-units --type=service --state=running

# List all failed services
systemctl list-units --type=service --state=failed

# Show all properties of a service
systemctl show myapp

# Show specific property values
systemctl show myapp -p MainPID,MemoryCurrent,CPUUsageNSec

# Mask a service (prevent it from being started at all)
systemctl mask myapp

# Unmask
systemctl unmask myapp

# Reset a failed service state
systemctl reset-failed myapp
```

## Timer Units (Cron Replacement)

### Timer File

```ini
# /etc/systemd/system/backup.timer
[Unit]
Description=Daily backup timer

[Timer]
# Run daily at 2:30 AM
OnCalendar=*-*-* 02:30:00
# If the system was off at the scheduled time, run when it boots
Persistent=true
# Add random delay up to 15 minutes to avoid thundering herd
RandomizedDelaySec=900
# Associate with a specific service (defaults to same name .service)
Unit=backup.service

[Install]
WantedBy=timers.target
```

### Corresponding Service File

```ini
# /etc/systemd/system/backup.service
[Unit]
Description=Daily backup job
After=network-online.target
Wants=network-online.target

[Service]
Type=oneshot
User=backup
ExecStart=/usr/local/bin/run-backup.sh
StandardOutput=journal
StandardError=journal
```

### Timer Management

```bash
# Common OnCalendar expressions:
# minutely, hourly, daily, weekly, monthly
# *-*-* 06:00:00       Daily at 6 AM
# Mon..Fri *-*-* 09:00 Weekdays at 9 AM
# *:0/15               Every 15 minutes

# Validate calendar expressions
systemd-analyze calendar "Mon..Fri *-*-* 09:00"

# List all active timers
systemctl list-timers --all

# Enable and start a timer
systemctl enable --now backup.timer

# Run the associated service immediately (for testing)
systemctl start backup.service
```

## Socket Activation

```ini
# /etc/systemd/system/myapp.socket
[Unit]
Description=MyApp Socket

[Socket]
ListenStream=8080
Accept=no
# Optionally bind to a specific IP
# ListenStream=10.0.1.10:8080

[Install]
WantedBy=sockets.target
```

```ini
# /etc/systemd/system/myapp.service
[Unit]
Description=MyApp Server
Requires=myapp.socket

[Service]
Type=notify
User=myapp
ExecStart=/opt/myapp/bin/server
# Service receives the socket file descriptor from systemd

[Install]
WantedBy=multi-user.target
```

```bash
# Enable the socket (service starts on first connection)
systemctl enable --now myapp.socket

# Check socket status
systemctl status myapp.socket

# List all listening sockets
systemctl list-sockets
```

## Dependency Management

```bash
# Key [Unit] directives for ordering and dependencies:
# After=            Start after these units (ordering only)
# Requires=         Hard dependency -- fail if this unit cannot start
# Wants=            Soft dependency -- try to start, don't fail if unavailable
# PartOf=           Stop this unit when the parent stops
# Conflicts=        Cannot run alongside this unit

# Visualize the dependency tree for a service
systemctl list-dependencies myapp

# Show reverse dependencies (who depends on this unit)
systemctl list-dependencies myapp --reverse

# Analyze boot order for a service
systemd-analyze critical-chain myapp.service
```

## Resource Limits (cgroups v2)

```ini
# /etc/systemd/system/myapp.service.d/limits.conf
# (drop-in override file)
[Service]
# Memory limits
MemoryMax=1G
MemoryHigh=768M

# CPU limits
CPUQuota=200%          # Up to 2 full CPU cores
CPUWeight=100          # Relative weight (default=100)

# I/O limits
IOWeight=50
IOReadBandwidthMax=/dev/sda 100M
IOWriteBandwidthMax=/dev/sda 50M

# Process limits
LimitNOFILE=65535
LimitNPROC=4096
TasksMax=512

# Disable OOM killer (let the app handle it)
OOMPolicy=continue
```

```bash
# Apply drop-in overrides without editing the main unit file
mkdir -p /etc/systemd/system/myapp.service.d/

cat <<'EOF' > /etc/systemd/system/myapp.service.d/limits.conf
[Service]
MemoryMax=1G
CPUQuota=200%
EOF

systemctl daemon-reload
systemctl restart myapp

# View current resource usage for a service
systemctl status myapp                  # Shows Memory and CPU
systemd-cgtop                          # Real-time cgroup resource usage

# Edit a service's overrides interactively
systemctl edit myapp
# This creates a drop-in file automatically
```

## Journalctl Log Analysis

```bash
# Follow logs for a service in real time
journalctl -u myapp -f

# Show logs since last boot
journalctl -u myapp -b

# Show logs for a specific time range
journalctl -u myapp --since "2025-01-15 08:00" --until "2025-01-15 12:00"

# Show only error and above
journalctl -u myapp -p err

# Show the last 100 lines with full messages (no truncation)
journalctl -u myapp -n 100 --no-pager -l

# Show logs in JSON format (for parsing)
journalctl -u myapp -o json-pretty --no-pager | head -50

# Check journal disk usage and vacuum old entries
journalctl --disk-usage
journalctl --rotate
journalctl --vacuum-time=7d
journalctl --vacuum-size=500M
```

## Troubleshooting

| Symptom | Diagnostic Command | Common Fix |
|---|---|---|
| Service fails to start | `systemctl status myapp`, `journalctl -u myapp -n 50` | Check ExecStart path, permissions, config syntax |
| Service keeps restarting | `journalctl -u myapp --since "5 min ago"` | Check StartLimitBurst; look for crash in logs |
| "Main process exited, code=exited, status=217" | `journalctl -u myapp` | User or group in unit file does not exist |
| "Failed to set up mount namespacing" | Check ProtectSystem/PrivateTmp | Kernel too old or SELinux blocking; relax directives |
| Timer not firing | `systemctl list-timers`, `systemctl status backup.timer` | Ensure timer is enabled; validate OnCalendar expression |
| Service starts before dependency | Check After= and Requires= | Add `After=dependency.service` for ordering |
| OOM killed | `journalctl -k \| grep oom`, `dmesg` | Increase MemoryMax or optimize application memory |
| Cannot bind to port 80 | Check AmbientCapabilities | Add `CAP_NET_BIND_SERVICE` or use a higher port |

## Related Skills

- `linux-administration` -- General system administration context
- `performance-tuning` -- Kernel tuning and resource optimization
- `user-management` -- Service accounts and permissions
- `backup-recovery` -- Scheduling backups with systemd timers

© devops-skills · MIT · BagelHole/DevOps-Security-Agent-Skills

Смотрите также

Спонсоры проекта

Компании, которые помогают держать аналитику открытой