Skip to content
Snippets Groups Projects
public
Authored by avatar Marc Schütze @mschuetze :comet:

Generate Background Image Based on HOSTNAME / IP / MAC Adress

Sometimes I need a simple background image to display at the start of a server / raspberry pi to tell me the current IP / MAC / Hostname so I came up with a simple shell script to grab all the needed infos, generate a colorful background based on the hostname and then put the infos on top.

Edited
Embed
Share
  • Clone with SSH
  • Clone with HTTPS
  • generateImage.sh 1.54 KiB
    #!/bin/bash
    
    # This script generates a PNG image with the current hostname /  IP address / MAC
    # AUTHOR : Marc Schütze
    # LICENSE: MIT
    
    # Get the current local IP as a variable
    IP=$(ip route | sed -n 's/.* src \(.*\) metric .*/\1/p' | uniq)
    
    # get the current MAC address for the current ip address
    MAC=$(cat /sys/class/net/$(ip route show default | awk '/default/ {print $5}')/address)
    
    # Get the hostname of the current IP and remove trailing . from the output
    HOSTNAME=$(dig -x $IP +short | sed 's/\.$//')
    
    #Get the CRC32 of the hostname and convert it to uppercase
    HOSTNAME_CRC32=$(echo -n $HOSTNAME | crc32 /dev/stdin | tr '[:lower:]' '[:upper:]')
    
    # remove the last two chars from string to extract color in hex form
    COLOR_HEX=$(echo $HOSTNAME_CRC32 | sed 's/..$//')
    
    # split the hex color into three parts
    a=`echo $COLOR_HEX | cut -c-2`
    b=`echo $COLOR_HEX | cut -c3-4`
    c=`echo $COLOR_HEX | cut -c5-6`
    
    # convert hex to decimal
    r=`echo "ibase=16; $a" | bc`
    g=`echo "ibase=16; $b" | bc`
    b=`echo "ibase=16; $c" | bc`
    
    # calc the luminance of the color
    LUMINANCE=$(echo "scale=2;(0.299*$r + 0.587*$g + 0.114*$b)/255" | bc)
    
    # if luminance is less than 0.5, set the text color to white, otherwise set it to black
    if (( $(echo "$LUMINANCE < 0.5" | bc -l) )); then
        TEXT_COLOR="white"
    else
        TEXT_COLOR="black"
    fi
    
    # generate the image with hostname and IP in two lines
    
    FONT="DejaVu-Sans-Bold"
    FONT_SIZE=80
    
    convert \
    -size 1920x1080 \
    -background "#$COLOR_HEX" \
    -gravity center \
    -pointsize $FONT_SIZE \
    -fill $TEXT_COLOR \
    label:"$HOSTNAME \\n $IP \\n $MAC" \
    hostinfo.png
    0% or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment