Blog

sha256: 2b87a252a3d912530dd8c20df6bee7f6cbc4ede0074fdf217e318aab39d9736c

pwgen

Little Function for your .zprofle

Demo

# Secure Password Generation
mypwgen() {
  # Complexity labels and corresponding options
  COMPLEXITY_NAMES=("basic" "with-specials" "secure")
  COMPLEXITY_OPTS=("" "-y" "-s")

  # Length and count patterns
  PATTERNS=("8 8" "16 8" "32 8")

  echo
  for i in $(seq 0 $((${#COMPLEXITY_NAMES[@]} - 1))); do
    name="${COMPLEXITY_NAMES[$i]}"
    opts="${COMPLEXITY_OPTS[$i]}"
    echo "### Complexity: $name ###"
    for pattern in "${PATTERNS[@]}"; do
        len=$(echo $pattern | cut -d' ' -f1)
        count=$(echo $pattern | cut -d' ' -f2)

        pwgen $opts $len $count | awk '{ printf "%-32s\n", $0 }' | column
        echo
    done
  done
}
root@yourhost % mypwgen 

### Complexity:  ###
euJuph5u                        	ohthuN2V                        	Xae0Ejoh                        	ViaF6aiw                        
ga0thooM                        	ohra7Koo                        	ouSh1ion                        	Kaif5gah                        

keechaidaipah2Qu                	gu5Eeshivaethi5e                	Shaehee8leeg7tee                	Eij3eyaiNgairooy                
goh2Giesheisuw9a                	Ohmohjook5suizei                	eequ0eeFau4aejie                	eezah3Ie9ai5Ahsh                

aomaegaf2moor3Yei7thaesh1tii0Ohp	aet3uu2oojiroohohPhoh3iJof9upohz	ohph5ooYo2shaeb1ahGh8sheekaek4vo	Aephu9oongee0zah2Phae1gaem7ae7Oo
ehemeinidahWei5ongaipah5eiHah0ae	BeiVae9iZu4iecijaim6OoG0ohheeyei	huThaiShie0pho6sai7dee8eizah6sho	yaeZepuoloaBohrui4iechaiyeiph7Lu

### Complexity: basic ###
El8ohF5x                        	ahgh2Ooc                        	MuoM4eet                        	OhXae1oj                        
joode9Wa                        	yoh4ooY9                        	Eili4ae1                        	kai3EiYo                        

faeViesoog3nouv3                	queifeiG4gatae1b                	aS3shub7Bies5wae                	Eshuameelahmuu0m                
eeth7Bee8Awuj9yi                	yiSoozang1veefoo                	iew2Anahjiwi0Een                	ahkae7gee9vuTeeF                

He1aiXeileo1eiYa0foe2Chophai4uar	uu2ahthi5shouque3Shaing9aejahghe	yireth8ne5mee4geexaiKough8Saepee	ahbie2aethah9ie5shahy3eezathohLa
iu3ohv6ahloo2ae9AotoLeiwahie3sa0	bies5Dahs6hei6sheiboh1ohje6Oot1o	zoh1aiTiethajae6Ire3iex8ci7oorai	Fei7Goh3phiegi9ohr4oonaiyeogh4ph

### Complexity: with-specials ###
Phai'l2j                        	Oobu(fi6                        	Izee"f1x                        	Vien?i7s                        
Ziez~ee0                        	Zei.C4aa                        	ie2Chai(                        	Eem0aik[                        

iG2oe|xeiNg1ophu                	Kop\eiJ3gui2Phoo                	aefah{Y2moh2hieg                	Aegie7phied(oomo                
Lei=thah1bieG]ah                	thaaLoohee_phah8                	saePej2Boo4ahZ@i                	Ugh2pho0oD8ahng)                

ud0ais/eexahqu0paece9am}ah&MoPh6	aingai!No2yoo7iu4eev1eighaiThegh	quoh{ghaeSohbiek_ee:K"ae4ooboiTh	eish]eiR-ev4Og4TuKohwu,a#s4ooGie
ShoomouReSh9oed}iekinuuluchae7Te	eiqua3hair4aeshioL"aLi9bafohx9ee	Ue6avu5quequ<ook{ee*z7iex8fah3ad	vu)Civiremeile6chahg~ehiqu;eihee

Any Comments ?

sha256:

Linux - Networking

there are different possibilities to manage networks on linux.

ifupdown

check

cat /etc/network/interfaces

and you should see the network config

systemd-networkd

check

systemctl status systemd-networkd

uses for newer servers

NetworkManager

  • nmcli
  • GNOME/KDE UI check
systemctl status NetworkManager

used for desktop and laptops


Any Comments ?

sha256: d79f7038039df0b0768ff583385f09eb117395327c2b5d541b29e23582bd595c

Debian - Freeswitch

How to Install FreeSwitch on Debian

Get your FreeSwitch Token (for Free) at: https://id.signalwire.com/signup/account/new

TOKEN=YOURSIGNALWIRETOKEN

apt-get update && apt-get install -y gnupg2 wget lsb-release

wget --http-user=signalwire --http-password=$TOKEN -O /usr/share/keyrings/signalwire-freeswitch-repo.gpg https://freeswitch.signalwire.com/repo/deb/debian-release/signalwire-freeswitch-repo.gpg

echo "machine freeswitch.signalwire.com login signalwire password $TOKEN" > /etc/apt/auth.conf
chmod 600 /etc/apt/auth.conf
echo "deb [signed-by=/usr/share/keyrings/signalwire-freeswitch-repo.gpg] https://freeswitch.signalwire.com/repo/deb/debian-release/ `lsb_release -sc` main" > /etc/apt/sources.list.d/freeswitch.list
echo "deb-src [signed-by=/usr/share/keyrings/signalwire-freeswitch-repo.gpg] https://freeswitch.signalwire.com/repo/deb/debian-release/ `lsb_release -sc` main" >> /etc/apt/sources.list.d/freeswitch.list

apt-get update && apt-get install -y freeswitch-meta-all

Any Comments ?

sha256: 94cd3ab92575ae8b4b4932e25ee45cf924331ebedd748ae034c483e7791aa30a

Debian - nala

Nala is a modern and user-friendly front-end for the APT package manager, designed to enhance the package management experience on Debian systems

Installation

apt install nala

Check Version

nala --version
root@debianxx ~# nala --version
nala 0.15.4

Install Package

nala install btop

Commands

nala --help
│ autopurge      Autopurge packages that are no longer needed.                                                                                                        │
│ autoremove     Autoremove packages that are no longer needed.                                                                                                       │
│ clean          Clear out the local archive of downloaded package files.                                                                                             │
│ fetch          Fetch fast mirrors to speed up downloads.                                                                                                            │
│ full-upgrade   Upgrade the system by removing/installing/upgrading packages.                                                                                        │
│ history        Show transaction history.                                                                                                                            │
│ install        Install packages.                                                                                                                                    │
│ list           List packages based on package names.                                                                                                                │
│ purge          Purge packages.                                                                                                                                      │
│ remove         Remove packages.                                                                                                                                     │
│ search         Search package names and descriptions.                                                                                                               │
│ show           Show package details.                                                                                                                                │
│ update         Update package list.                                                                                                                                 │
│ upgrade        Upgrade the system by upgrading packages only.       

Commands

nala list       list all packages
nala list -i    list installed packages
nala list -N    list packages installed with nala
nala list -u    list upgradable packages
nala list -h    show help for all list commands ...

Any Comments ?

sha256: 831a68cb00e13085f9eab36dcab94139961c2b083479df6874fd640d0e7ee883

Debian - Cloudimage 2

Test

mkdir raw
cd raw
wget https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-generic-amd64.qcow2
wget https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-genericcloud-amd64.qcow2
vm_id="9999"
vm_name="test-vm-${vm_id}"
vm_storage="local-lvm"
image="debian-12-genericcloud-amd64.qcow2"

virt-customize -a ${image} --install qemu-guest-agent,cloud-utils,vim,joe,htop,btop
qm create ${vm_id} --name ${vm_name} --memory 2048 --cores 2 --net0 virtio,bridge=vmbr0 --agent 1 
qm importdisk ${vm_id} ${image} ${vm_storage}

qm set ${vm_id} --scsihw virtio-scsi-pci --scsi0 ${vm_storage}:vm-${vm_id}-disk-0
qm set ${vm_id} --ide2 ${vm_storage}:cloudinit
qm set ${vm_id} --boot c --bootdisk scsi0
qm set ${vm_id} --serial0 socket
qm set ${vm_id} --ipconfig0 ip=dhcp
qm set ${vm_id} --cpu cputype=x86-64-v2-AES

qm set ${vm_id} --sshkeys installer.pub
qm set ${vm_id} --ciuser installer

Any Comments ?

sha256: 72ac8b05c0c3c006b8983e2408431cc9a10c095548d4f1a87829df699e30befc

Debian - Cloudimage

Debian Template on Proxmox

Cloud Image with SSH Key

on the Proxmox Host

Create Installer Key

# cd /your/working/dir
ssh-keygen -o -a 100 -t ed25519 -C "User: installer, $(date '+%Y-%m-%d %H:%m')" -f installer

Build Template

apt install libguestfs-tools -y;
wget https://cloud.debian.org/images/cloud/bookworm/latest/debian-12-generic-amd64.qcow2

virt-customize --install qemu-guest-agent -a debian-12-generic-amd64.qcow2
qm create 9001 --name debian-12-generic --memory 2048 --cores 2 --net0 virtio,bridge=vmbr0 --agent 1 
qm importdisk 9001 debian-12-generic-amd64.qcow2 local-lvm

qm set 9001 --scsihw virtio-scsi-pci --scsi0 local-lvm:vm-9001-disk-0
qm set 9001 --ide2 local-lvm:cloudinit
qm set 9001 --boot c --bootdisk scsi0
qm set 9001 --serial0 socket
qm set 9001 --ipconfig0 ip=dhcp
qm set 9001 --cpu cputype=x86-64-v2-AES

qm set 9001 --sshkeys installer.pub
qm set 9001 --ciuser installer

qm resize 9001 scsi0 32G
qm template 9001

Create VM

in the GUI, you can create an new VM based on the Template 9001. You have to login with user “installer” and it’s private key!

Fasthtml

Single Click Todo App with sqlite db

Source

  • needy python & poetry installed

copy/paste

poetry init -n
poetry add python-fasthtml fastsql

cat << 'EOF' > main.py
from fasthtml.common import *
from fastsql import *
from sqlite_minutils.db import NotFoundError

app,rt,todos,Todo = fast_app(
    'data/todos.db',
    id=int, title=str, pk='id')

def tid(id): return f'todo-{id}'


@app.delete("/delete_todo", name='delete_todo')
async def delete_todo(id:int): 
    try: todos.delete(id)
    except NotFoundError: pass # If someone else deleted it already we don't have to do anything

@patch
def __ft__(self:Todo):
    show = Strong(self.title, target_id='current-todo')
    delete = A('delete',
               hx_delete=delete_todo.to(id=self.id).lstrip('/'), 
               hx_target=f'#{tid(self.id)}',
               hx_swap='outerHTML')
    return Li(show, ' | ', delete, id=tid(self.id))

def mk_input(**kw): return Input(id="new-title", name="title", placeholder="New Todo", **kw)

@rt
async def index():
    add =  Form(Group(mk_input(), Button("Add")), 
                post="insert_todo", target_id='todo-list', hx_swap="beforeend")
    card = Card(Ul(*todos(), id='todo-list'), header=add, footer=Div(id='current-todo')),
    title = 'Todo list'
    return Title(title), Main(H1(title), card, cls='container')

@rt
async def insert_todo(todo:Todo): return todos.insert(todo), mk_input(hx_swap_oob='true')

serve()
EOF

poetry run python main.py

Any Comments ?

sha256: d920811503afe4ef9a1e579531cfaa5a7694082b66547ea9a24c77dac005876a

Fastapi - Ratelimiting

Fastapi & Rate Limiting

Let’s test a simple Rate Limiting Function found on the Net …

main.py

Main App with Rate Limiting Function

# main.py
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
from Token_bucket import TokenBucket

app = FastAPI()

class RateLimiterMiddleware(BaseHTTPMiddleware):
    def __init__(self, app, bucket: TokenBucket):
        super().__init__(app)
        self.bucket = bucket

    async def dispatch(self, request: Request, call_next):
        if self.bucket.take_token():
            return await call_next(request)

        # Return a JSON response for rate limit exceeded
        return JSONResponse(status_code=429, content={"detail": "Rate limit exceeded"})

# Token bucket with a capacity of 3 and refill rate of 1 token per second
bucket = TokenBucket(capacity=3, refill_rate=3)

# Apply the rate limiter middleware
app.add_middleware(RateLimiterMiddleware, bucket=bucket)

@app.get("/")
async def read_root():
    return {"message": "Hello World"}

Token_bucket.py

# Token_bucket.py
import time

class TokenBucket:
    def __init__(self, capacity, refill_rate):
        self.capacity = capacity
        self.refill_rate = refill_rate
        self.tokens = capacity
        self.last_refill = time.time()

    def add_tokens(self):
        now = time.time()
        if self.tokens < self.capacity:
            tokens_to_add = (now - self.last_refill) * self.refill_rate
            self.tokens = min (self.capacity, self.tokens + tokens_to_add)
        self.last_refill=now

    def take_token(self):
        self.add_tokens()
        if self.tokens >= 1:
            self.tokens -=1
            return True
        return False

Test Script

Let’s produce some requests …

HTML - Center Div

3 Ways to Center a < div >

Credits to https://twitter.com/BilliCodes

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Centering a Div - Three Methods</title>
    <style>
        .container {
            height: 100vh; /* Full height */
            position: relative; /* Required for absolute positioning */
            background-color: #f0f0f0;
        }

        /* (1) Flexbox Method */
        .flexbox {
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh; /* Full viewport height */
        }

        /* (2) Grid Method */
        .grid {
            display: grid;
            place-items: center; /* Center using grid */
            height: 100vh; /* Full viewport height */
        }

        /* (3) Absolute Positioning Method */
        .absolute {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%); /* Offset to center */
        }      
    </style>
</head>

<body>
    <div class="container">
        <!-- Flexbox Method -->
        <div class="centered flexbox">Centered with Flexbox</div>

        <!-- Grid Method -->
        <div class="centered grid">Centered with CSS Grid</div>
        
        <!-- Absolute Positioning Method -->
        <div class="centered absolute">Centered with Absolute Positioning</div>
    </div>
</body>

</html>

Any Comments ?

sha256: 85678db9aeded3bf6ba6bce5bf56014023c834cdd99b62f0d8427f3c12a65360

Python - Decorator

how to use Python Decorator

Sample Code

main.py

cat << 'EOF' > main.py
#!/usr/bin/env python3

# Sample from https://blog.stoege.net/posts/python_decorator/

# Vars
a = 3
b = 8

# Decorator which logs start and end of a function
def log_function_call(func):
    def wrapper(*args, **kwargs):
        print(f"\nCalling function '{func.__name__}' with {args=} & {kwargs=}")
        result = func(*args, **kwargs)
        print(f"Function '{func.__name__}' finnished\n")
        return result
    return wrapper

@log_function_call
def add(a=int, b=int) -> int:
    result = a + b
    return result

@log_function_call
def sub(a=int, b=int) -> int:
    result = a - b
    return result

@log_function_call
def prod(a=int, b=int) -> int:
    result = a * b
    return result

@log_function_call
def div(a=int, b=int) -> int:
    result = a / b
    return result

if __name__ == "__main__":
    print("Result:", add(a, b))
    print("Result:", sub(a, b))
    print("Result:", prod(a, b))
    print("Result:", div(a, b))

EOF
chmod u+x main.py

##### RUN #####

# ./main.py

###############

Running Code

user@host% ./main.py 

Calling function 'add' with args=(3, 8) & kwargs={}
Function 'add' finnished

Result: 11

Calling function 'sub' with args=(3, 8) & kwargs={}
Function 'sub' finnished

Result: -5

Calling function 'prod' with args=(3, 8) & kwargs={}
Function 'prod' finnished

Result: 24

Calling function 'div' with args=(3, 8) & kwargs={}
Function 'div' finnished

Result: 0.375

Any Comments ?

sha256: ab6641b101cea8ac7eb6517fcefb029380644a56203723973fa1bc957fafbafb