Python One-Liners for Server Troubleshooting

Sometimes awk is not enough and a full script is too much. Python sits in the middle. Every Linux server has it installed, and python3 -c lets you run code inline.

Quick HTTP Server

The classic. Serve the current directory:

python3 -m http.server 8080

Bind to a specific interface:

python3 -m http.server 8080 --bind 127.0.0.1

This is genuinely useful for transferring files between machines, testing static sites, or sharing a directory with a coworker.

JSON Pretty Printing

When you do not have jq installed:

curl -s https://api.example.com/data | python3 -m json.tool

Or with color:

echo '{"a":1,"b":[2,3]}' | python3 -c "
import json, sys
data = json.load(sys.stdin)
print(json.dumps(data, indent=2, sort_keys=True))
"

Parse Timestamps

Convert epoch timestamps that show up in logs:

python3 -c "
from datetime import datetime
import sys
for line in sys.stdin:
    ts = int(line.strip())
    print(datetime.fromtimestamp(ts).isoformat())
" <<< "1711708800"
# 2024-03-29T12:00:00

Find Large Files

find works, but if you want more control over the output:

python3 -c "
import os
files = []
for root, dirs, fnames in os.walk('/var/log'):
    for f in fnames:
        path = os.path.join(root, f)
        try:
            size = os.path.getsize(path)
            if size > 100_000_000:  # 100MB
                files.append((size, path))
        except OSError:
            pass
for size, path in sorted(files, reverse=True):
    print(f'{size / 1e9:.1f}G  {path}')
"

Base64 Decode

Decode those opaque values in Kubernetes secrets or JWTs:

python3 -c "
import base64, json, sys
token = sys.argv[1]
parts = token.split('.')
for part in parts[:2]:
    padded = part + '=' * (4 - len(part) % 4)
    decoded = base64.urlsafe_b64decode(padded)
    print(json.dumps(json.loads(decoded), indent=2))
" "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0In0.signature"

Port Scanner

Quick check which ports are open without installing nmap:

python3 -c "
import socket, sys
host = sys.argv[1]
for port in range(1, 1025):
    s = socket.socket()
    s.settimeout(0.1)
    if s.connect_ex((host, port)) == 0:
        print(f'{port}/tcp open')
    s.close()
" 10.0.0.1

Monitor a Log File With Filtering

Like tail -f | grep but with more logic:

python3 -c "
import sys, re, time

pattern = re.compile(r'(ERROR|WARN|FATAL)', re.IGNORECASE)
seen = set()

for line in sys.stdin:
    if pattern.search(line):
        key = line.strip()
        if key not in seen:
            seen.add(key)
            print(line, end='')
" < /var/log/syslog

This deduplicates repeated errors so you see each unique message only once.

CSV to JSON

Convert that spreadsheet export into something usable:

python3 -c "
import csv, json, sys
reader = csv.DictReader(sys.stdin)
print(json.dumps(list(reader), indent=2))
" < data.csv

URL Encode and Decode

# Encode
python3 -c "from urllib.parse import quote; print(quote('hello world & friends'))"
# hello%20world%20%26%20friends

# Decode
python3 -c "from urllib.parse import unquote; print(unquote('hello%20world%20%26%20friends'))"
# hello world & friends

Generate Random Passwords

python3 -c "
import secrets, string
alphabet = string.ascii_letters + string.digits + '!@#$%'
password = ''.join(secrets.choice(alphabet) for _ in range(24))
print(password)
"

IP Address Math

Check if an address is in a subnet:

python3 -c "
from ipaddress import ip_address, ip_network
net = ip_network('10.0.0.0/24')
print(ip_address('10.0.0.42') in net)  # True
print(ip_address('10.14.0.1') in net)    # False
print(f'Network: {net.network_address}')
print(f'Broadcast: {net.broadcast_address}')
print(f'Hosts: {net.num_addresses - 2}')
"

The standard library covers most sysadmin needs without pip. json, csv, http.server, ipaddress, secrets, urllib, base64, socket. It is all there. When the bash one-liner turns into a bash five-liner with nested quotes and escaped dollars signs, switch to Python. Your future self will thank you.

← all articles wleeaf.dev →