• Indonesian
  • English
  • How to Use OpenCode (AI CLI) to Protect Your Own Server:

    Kecepatan:

    3 AM. My phone vibrates next to my pillow. Grafana alert: CPU 100%, load average 45 on the primary production server. Eyes still half-closed, I open my laptop, SSH in. Your brain doesn’t run at full speed when you just woke up — but this server can’t wait for me to finish my coffee.

    Normally, my process goes like this: htop, netstat -tulpn, tail -f /var/log/nginx/access.log, hunt down suspicious IPs, check anomalous processes, identify the attack vector one by one. That routine eats up 15–30 minutes — and every single minute is lost revenue.

    But that night was different. A week earlier, I’d installed OpenCode on the server — an AI CLI tool that reads files, executes commands, and delivers recommendations straight from the terminal. It turned out to be the best decision I made all month.

    I opened the terminal, typed opencode, and asked: “analyze the last 500 lines of access.log, look for attack patterns.” Within 30 seconds, OpenCode had flagged 7 IPs from Russia sending POST requests to /xmlrpc.php and /wp-login.php, doing 200+ requests per minute per IP. I blocked the entire IP range via iptables, restarted nginx, and five minutes later the CPU was back to normal.

    This article is for anyone who wants to learn how to use LLM tools like OpenCode not just for writing code, but for protecting your own server — from log analysis and configuration hardening to real-time incident response.

    Difficulty: Intermediate
    Last Updated: July 2026
    Tested On: Ubuntu 22.04, Debian 12, CentOS 7 (cPanel)

    Why OpenCode CLI Instead of a Web Chatbot?

    This is the first question I get. Why not just use ChatGPT or Claude in the browser? The answer is straightforward:

    • Direct filesystem access: OpenCode reads /var/log/nginx/access.log directly — no need to copy-paste logs into a browser (which is a data leak risk)
    • Shell command execution: After analysis, OpenCode can suggest and execute iptables, systemctl, or edit configuration files — you just approve
    • Full context awareness: OpenCode reads your project structure, config files, and environment variables all at once — so its recommendations are contextual, not generic
    • Privacy: Your server logs never leave the machine. All processing happens locally or via an API you control

    Think of it this way: a web chatbot is like taking a photo of your car engine and sending it to a mechanic via WhatsApp. OpenCode is like having the mechanic standing next to you, popping the hood, and pointing: “This spark plug is worn out, replace this one.”

    Use Case 1: Log Analysis — Real-Time Attack Pattern Detection

    This is, hands down, the most powerful use case. A production server generates thousands of log lines per minute. No human eye can keep up. This is where LLM becomes a game-changer.

    Scenario: Nginx/Apache Access Log Spike

    Say you notice in htop that nginx and php-fpm processes are spiking. Instead of manually grepping, you can ask OpenCode directly:

    # In the terminal, run opencode
    $ opencode
    
    > Analyze the last 1000 lines of /var/log/nginx/access.log.
      Find: top IPs by request count, frequently-hit endpoints,
      suspicious user-agents, and patterns pointing to attacks
      (brute force, SQL injection, XSS, or scanning).

    OpenCode will:

    1. Read the log file directly from the filesystem
    2. Aggregate: count requests per IP, per endpoint, per user-agent
    3. Detect patterns: POST requests to /wp-login.php or /xmlrpc.php from the same IP → brute force
    4. Detect payloads: URL parameters containing UNION SELECT or <script> → SQLi / XSS attempt
    5. Recommend: “Block IPs X, Y, Z via iptables, enable rate limiting in nginx for /wp-login.php”

    Realistic Output Example

    ## Analysis Results — access.log (last 1000 lines)
    
    ### Top 5 IPs by Request Count:
      192.168.1.100  →  847 requests  (brute force pattern: /wp-login.php)
      10.0.0.55      →  312 requests  (SQL injection attempt: ?id=1 UNION SELECT...)
      172.16.0.20    →  198 requests  (normal traffic: /, /blog, /contact)
      192.168.1.88   →  156 requests  (scanning: /.env, /wp-config.php, /phpmyadmin)
      172.16.0.5     →   89 requests  (normal traffic)
    
    ### Attack Patterns Detected:
    1. BRUTE FORCE: 192.168.1.100 → 847 POSTs to /wp-login.php in 10 minutes
    2. SQL INJECTION: 10.0.0.55 → 'id' parameter contains UNION SELECT
    3. PATH SCANNING: 192.168.1.88 → probing /.env, /wp-config.php, /phpmyadmin
    
    ### Recommendations:
    - Block: iptables -A INPUT -s 192.168.1.100 -j DROP
    - Block: iptables -A INPUT -s 10.0.0.55 -j DROP  
    - Block: iptables -A INPUT -s 192.168.1.88 -j DROP
    - Enable nginx rate limiting for /wp-login.php (limit_req_zone)
    - Ensure .env and wp-config.php are not web-accessible

    Practical Commands You Can Use

    # Analyze Apache logs (cPanel/WHM server)
     opencode "analyze /usr/local/apache/domlogs/domain.com last 500 lines,
     find IPs sending POST to xmlrpc.php more than 50x per minute.
     Recommend iptables blocks."
    
    # Check Dovecot logs for email brute force
     opencode "read /var/log/dovecot-info.log, find 'auth failed' patterns
     from the same IP more than 10x in 5 minutes.
     Should I block or use fail2ban?"
    
    # Analyze error log for exploit attempts
     opencode "analyze /var/log/nginx/error.log, find 500 error patterns,
     any indicators of file inclusion or RCE attempts?"

    Use Case 2: Server Configuration Audit & Hardening

    Many servers have been running for years without a security audit. SSH config is still default, firewall hasn’t been reviewed, kernel parameters are untouched. OpenCode can audit all of this in minutes.

    Scenario: SSH Configuration Audit

    $ opencode
    
    > Read /etc/ssh/sshd_config. Audit whether this configuration is
      secure for a production server. Check: is root login enabled?
      Is password authentication enabled? Is port 22 still default?
      Is AllowUsers configured? Recommend hardening based on best
      practices.

    Example OpenCode Output

    ## Audit — /etc/ssh/sshd_config
    
    ### Issues Found:
    1. ❌ PermitRootLogin yes           → Risk: direct root brute force
    2. ❌ PasswordAuthentication yes    → Risk: weak passwords brute-forceable
    3. ❌ Port 22                        → Primary target for automated scanners
    4. ❌ No AllowUsers configured       → All system users can SSH
    5. ✅ PubkeyAuthentication yes       → Good
    6. ❌ ClientAliveInterval not set    → Idle sessions never timeout
    
    ### Hardening Recommendations:
    1. PermitRootLogin no
    2. PasswordAuthentication no (use SSH keys only)
    3. Port 2222 (or another non-standard port)
    4. AllowUsers your_user@office_IP
    5. ClientAliveInterval 300 → auto-disconnect after 5 min idle
    6. MaxAuthTries 3 → max 3 failed login attempts
    
    ### Edit file:
    I can edit /etc/ssh/sshd_config now with the above config.
    Run? (y/n)

    Scenario: Firewall Rules Audit

    $ opencode
    
    > Check iptables rules: iptables -L -n -v. Audit whether the current
      rules are secure. Are there any unnecessary open ports? Is the 
      default policy set to DROP? Is rate limiting configured?

    Scenario: Kernel & sysctl Hardening

    $ opencode
    
    > Read /etc/sysctl.conf. Recommend kernel parameter hardening
      for a production web server, especially:
      - SYN flood protection
      - IP spoofing protection
      - Disable IPv6 if unused
      - TCP stack optimization

    Use Case 3: Incident Response — Triage & Containment

    This is the most critical scenario. The server is under active attack — whether DDoS, brute force, or an exploit attempt. You don’t have time to open 10 documentation tabs. This is where OpenCode acts as your incident response co-pilot.

    Scenario: Sudden CPU 100% + Inbound Connection Flood

    $ opencode
    
    > The server suddenly hit 100% CPU. Run incident triage:
    > 1. Check top 10 processes by CPU usage
    > 2. Check established network connections — who's connected?
    > 3. Check nginx/access.log last 100 lines — traffic spike?
    > 4. Check for suspicious processes (crypto miner, reverse shell)
    > 5. Provide safe containment steps

    OpenCode will run the required commands sequentially and provide real-time analysis:

    ## Incident Triage — CPU 100%
    
    ### 1. Top 10 Processes by CPU:
      PID   CPU%  COMMAND
      1245   85%  /usr/bin/kdevtmpfsi       ← SUSPICIOUS! (crypto miner pattern)
      3342    8%  nginx: worker process
      ...
    
    ### 2. Network Connections:
      340 ESTABLISHED connections from 15 different IPs to port 443
      → Traffic pattern points to Layer 7 DDoS
    
    ### 3. Access Log:
      192.168.1.0/24 range → 200+ req/sec to /?s=random_string
      → Pattern: search query DDoS (cache bypass attack)
    
    ### 4. Suspicious Process:
      PID 1245: /usr/bin/kdevtmpfsi — camouflage process name,
      unsigned binary, located at /tmp/.X11-unix/
      → CRYPTO MINER DETECTED
    
    ### Containment Steps:
    1. Kill process: kill -9 1245
    2. Remove binary: rm -f /tmp/.X11-unix/kdevtmpfsi
    3. Block attacker IP range: iptables -A INPUT -s 192.168.1.0/24 -j DROP
    4. Enable nginx rate limiting: limit_req_zone $binary_remote_addr...
    5. Check cron jobs: crontab -l (miners often reinstall via cron)
    6. Update kernel & packages: apt update && apt upgrade (patch exploit vector)

    Pro Tips & Important Warnings

    Tips from Experience

    1. Install OpenCode BEFORE an incident happens: Don’t wait until you’re under attack to install it. Install now, configure it, get familiar with the workflow. An active incident is not the time to learn a new tool.
    2. Use session logs: OpenCode saves session history. After an incident resolves, review what was done — this is invaluable for post-mortems and future SOPs.
    3. Review before executing, never auto-execute: Always verify commands before running them. OpenCode can hallucinate — it might suggest rm -rf / if the context is wrong. Always review.
    4. Use it to learn, too: Ask “why this command?” or “what are the risks if I run X?” — OpenCode explains, and you learn while solving the problem.
    5. Integrate with monitoring: If you use Grafana/Prometheus, ask OpenCode to write alert rules or dashboard queries. It understands PromQL.

    Important Warnings

    • LLMs can hallucinate: Don’t trust output 100%. Always double-check destructive commands manually before running them.
    • API rate limits & costs: If OpenCode uses an external API (Claude/GPT), monitor your rate limits. You don’t want your API key to run out in the middle of an incident.
    • Don’t leak your logs: Make sure your OpenCode environment is secure. Don’t use it on shared hosting if the API key is in an environment variable readable by other users.
    • Not a replacement for expertise: OpenCode is an accelerator, not a substitute for sysadmin knowledge. You still need to understand Linux security fundamentals.

    FAQ

    1. Is OpenCode safe to use on a production server?

    Yes, as long as you operate in manual approval mode — don’t auto-execute. OpenCode only reads and recommends; execution is always in your hands. Make sure your API key is stored in a secure environment variable (not a shared config file).

    2. How do I install OpenCode on a server?

    One command: curl -fsSL https://opencode.ai/install | bash. Once installed, run opencode in the terminal. If your server can’t access the internet directly, you can install it on a separate laptop or VPS that can SSH into your target server.

    3. What’s the difference between OpenCode and a regular AI chatbot?

    OpenCode runs in the terminal, reads the filesystem directly, and executes shell commands. Web chatbots (ChatGPT, Claude in-browser) can’t access your server directly — you have to copy-paste everything manually, which is slow and risky for sensitive data.

    4. Does it need special server specifications?

    No. OpenCode itself is lightweight — it’s just a CLI client. The AI processing runs in the cloud (via API). The only requirement is that your server has internet access to reach the API endpoint. RAM or minimal specs don’t matter.

    5. What alternatives exist if I don’t use OpenCode?

    There are several: aider (coding-focused), continue.dev (IDE-based), shell_gpt (simple CLI tool). But OpenCode is the best fit for NOC/sysadmin workflows because it’s designed for contextual filesystem interaction and command execution.

    Related Articles

    Conclusion

    An LLM CLI tool like OpenCode isn’t just for writing code — it can be your first responder when your server goes down. From real-time log analysis and configuration auditing to acute incident triage — everything gets resolved faster than doing it manually.

    The key is: install before an incident, get familiar with the workflow, and always verify every command before running it. AI is an accelerant, not an autopilot. You’re still the pilot.

    Got experience using AI tools for server management? Share your story in the comments!

    Author: NOC Engineer — Syslog Solutions
    Credentials: 5+ years managing production Linux servers, cPanel/WHM, and CloudLinux. Specializing in incident response and server hardening.