Operations 15 min read

Generate Production-Ready Ops Scripts with LLMs: 4 Practical Examples

This article teaches operations engineers how to use LLMs to generate custom Shell and Python scripts for common tasks like log cleanup, server inspection, Nginx restarts, and port checks, providing a reusable prompt template and four ready-to-run script examples that avoid copyright issues and fit specific environments.

Full-Stack DevOps & Kubernetes
Full-Stack DevOps & Kubernetes
Full-Stack DevOps & Kubernetes
Generate Production-Ready Ops Scripts with LLMs: 4 Practical Examples

Operations engineers often waste time typing repetitive commands for tasks such as server inspection, log cleanup, service restarts, and port checks. This manual work is error‑prone and leads to overtime.

Why Use LLMs to Generate Custom Ops Scripts?

Many engineers avoid ready‑made scripts from the internet for two reasons:

Copyright risk : Open‑source scripts or blog code may carry licensing restrictions, making commercial or internal deployment risky.

Poor adaptability : External scripts use fixed paths, parameters, and rules that rarely match your own environment; modifying them can be harder than writing from scratch.

Generating scripts with an LLM solves both problems:

100% original, no copyright : Scripts are created on‑demand for your exact scenario, so there is no infringement risk.

Highly adaptable : You can specify the OS (CentOS 7/8, Ubuntu), file paths, service names, monitoring thresholds, etc.

Zero programming barrier : Describe the requirement in plain language; the LLM outputs runnable code.

Massive efficiency gain : A script takes ~5 minutes to generate; thereafter the repetitive task becomes a one‑click execution.

Universal Ops Script Generation Prompt

Vague prompts produce poor scripts. Use this template — replace the bracketed parts with your specifics:

You are a senior Linux operations engineer. Generate a ready‑to‑run script that meets these requirements:
1. Adapt to [CentOS7/CentOS8/Ubuntu], pure original code, no copyright, usable commercially or in internal networks.
2. Code must be concise, well‑commented, and fault‑tolerant to avoid crashes.
3. Execution must produce logs; results must be clearly displayed.
4. No third‑party paid dependencies; only system‑built‑in commands.
My specific requirement: [Describe your ops scenario, e.g., batch clean logs older than 3 days, monitor disk usage and alert, batch restart Nginx service]

Four High‑Frequency Ops Scenarios with LLM‑Generated Scripts

Scenario 1: Automatic Cleanup of Expired Logs (Prevent Disk Full)

Pain point: Business servers generate logs daily, consuming disk space. Manual cleanup is tedious; forgetting leads to disk exhaustion and service anomalies.

Script function: Scan specified log directories, delete .log files older than 3 days, output cleanup logs, skip directories and files currently in use to avoid accidental deletion.

Script type: Shell (compatible with RedHat family).

#!/bin/bash
# Ops log auto‑cleanup script (LLM original, no copyright)
# Function: clean .log files older than 3 days in specified directories, keep latest 3 days
# Adapted for: CentOS7/CentOS8
# Define log directories — modify per your environment
LOG_DIR="/var/log/nginx /var/log/system /tmp/logs"
# Retention days
SAVE_DAY=3
# Script execution log
RUN_LOG="/var/log/clean_log_run.log"
# Print start timestamp
echo "==================== $(date +%Y-%m-%d %H:%M:%S) Start log cleanup ====================" >> $RUN_LOG
# Loop through directories
for dir in $LOG_DIR
do
    # Check if directory exists
    if [ -d $dir ]; then
        echo "Cleaning directory: $dir" >> $RUN_LOG
        # Delete log files older than $SAVE_DAY days, do not delete folders or in‑use files
        find $dir -name "*.log" -type f -mtime +$SAVE_DAY -delete >> $RUN_LOG 2>&1
        if [ $? -eq 0 ]; then
            echo "[Success] $dir expired logs cleaned" >> $RUN_LOG
        else
            echo "[Failure] $dir log cleanup abnormal, check permissions" >> $RUN_LOG
        fi
    else
        echo "[Warning] Directory $dir does not exist, skipping" >> $RUN_LOG
    fi
done
echo "==================== Log cleanup finished ====================" >> $RUN_LOG
echo "" >> $RUN_LOG

Set LOG_DIR to your actual log paths. Make executable: chmod +x clean_log.sh. Add a cron job to run daily at midnight for fully hands‑free operation.

Scenario 2: Batch Server Basic Information Inspection

Pain point: Daily inspection requires checking disk, CPU, memory, ports, and service status one by one — time‑consuming and prone to omissions.

Script function: One‑click output of core server metrics: disk usage, memory usage, CPU load, listening ports, uptime. Results are aggregated; abnormal items are highlighted.

Script type: Shell (CentOS/Ubuntu universal).

#!/bin/bash
# Daily server inspection script (LLM original, no copyright)
# Adapted for: CentOS/Ubuntu
echo "==================== Server Inspection Report $(date +%Y-%m-%d %H:%M:%S) ===================="
echo "[1. System Basic Info]"
hostname
uname -r
echo "System uptime: $(uptime)"
echo -e "
[2. CPU Load Info]"
uptime | awk '{print "1‑min load:" $3 " 5‑min load:" $4 " 15‑min load:" $5}'
echo -e "
[3. Memory Usage]"
free -h
echo -e "
[4. Disk Usage]"
df -h | grep -v tmpfs
echo -e "
[5. Key Port Listening Status]"
ss -tulpn | grep -E "80|443|22|3306|6379"
echo -e "
[6. Disk Usage Anomaly Detection]"
df -h | awk 'NR>1 {gsub(/%/,""); if($5>80) print "[Warning] Partition " $1 " usage high: " $5 "%"}'
echo "==================== Inspection Report Generated ===================="

Use cases: Daily boot inspection, quick self‑check during troubleshooting, batch server status verification.

Scenario 3: Nginx One‑Click Restart & Self‑Healing

Pain point: Nginx frequently crashes, fails to start, or has config errors. Manual restart and config validation are cumbersome, slowing incident recovery.

Script function: Automatically validate Nginx config, stop/restart service, check startup status. On failure, output error details — no manual step‑by‑step troubleshooting needed.

#!/bin/bash
# Nginx one‑click restart self‑heal script (LLM original, no copyright)
echo "==================== Starting Nginx Restart ===================="
# 1. Validate Nginx config
echo "1. Validating Nginx config file..."
nginx -t
if [ $? -ne 0 ]; then
    echo "[Error] Nginx config invalid, aborting restart. Check config!"
    exit 1
fi
echo "[Success] Config validation passed"
# 2. Restart Nginx
echo "2. Restarting Nginx service..."
systemctl restart nginx
# 3. Check service status
echo "3. Checking Nginx runtime status..."
STATUS=$(systemctl status nginx | grep active | awk '{print $3}')
if [ "$STATUS" = "(running)" ]; then
    echo "[Success] Nginx restarted, running normally"
else
    echo "[Error] Nginx failed to start, check logs"
    systemctl status nginx
fi
echo "==================== Operation Completed ===================="

Scenario 4: Batch Server Port Connectivity Detection

Pain point: During service integration or troubleshooting, you must test multiple server ports for connectivity and firewall rules. Manual telnet is extremely inefficient.

Script function: Batch test specified IP+port combinations, automatically determine open/closed status, output clear results. Works for internal network batch checks.

Script type: Python 3 (no extra dependencies).

#!/usr/bin/env python3
# Port connectivity batch check script (LLM original, no copyright)
# Runs with system Python3, no extra installs
import socket
import time
# Customize the list of IPs and ports to check
check_list = [
    ("127.0.0.1", 80),
    ("127.0.0.1", 443),
    ("127.0.0.1", 3306),
    ("127.0.0.1", 6379)
]
print("========== Port Connectivity Check Start ==========")
print(f"Check time: {time.strftime('%Y-%m-%d %H:%M:%S')}")
for ip, port in check_list:
    try:
        # Set timeout to 1 second
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)
        result = sock.connect_ex((ip, port))
        if result == 0:
            print(f"✅ {ip}:{port} port open")
        else:
            print(f"❌ {ip}:{port} port closed")
        sock.close()
    except Exception as e:
        print(f"❌ {ip}:{port} check exception: {str(e)}")
print("========== Port Check All Done ==========")

Three Tips for Writing Ops Scripts with LLMs

Describe the scenario precisely : Tell the LLM your OS version, required functionality, whether you need logging, whether it should run on a schedule. The more detail, the better the fit.

Test before production : Run every generated script on a test server first. Confirm no accidental deletions, no errors, then deploy to production.

Iterate and customize : If the script lacks features, ask the LLM to extend it — e.g., "add alerting", "add log compression". Optimize incrementally.

Conclusion

The core value of operations is not mechanically typing commands, but solving incidents, optimizing architecture, and guaranteeing business stability. Using LLMs to generate dedicated ops scripts eliminates repetitive labor, boosts efficiency, avoids copyright risks of internet scripts, and ensures a perfect fit for your environment — safe and worry‑free. The four scripts above cover log cleanup, daily inspection, service maintenance, and port detection — the highest‑frequency scenarios. Copy them directly or use the universal prompt to generate more custom scripts for your own workflows.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

operationsLLMNginxShell ScriptingPython ScriptingLog CleanupPort CheckingServer Inspection
Full-Stack DevOps & Kubernetes
Written by

Full-Stack DevOps & Kubernetes

Focused on sharing DevOps, Kubernetes, Linux, Docker, Istio, microservices, Spring Cloud, Python, Go, databases, Nginx, Tomcat, cloud computing, and related technologies.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.