[wellylug] linux challenge: bash/cgi

Ewen McNeill wellylug at ewen.mcneill.gen.nz
Tue May 16 20:55:50 NZST 2006


In message <1147766410.14407.19.camel at munter>, Jamie Baddeley writes:
>[Combine]
>$output = `whois -h whois.apnic.net -r thursday|grep tech-c|wc -l`
>
>With a random number generator that has a randomisation range between .1
>and .9, so, $output * $random = $lucky_number
>[...]
>Would need to be whole numbers, so rounding up would be best.
>[...]
>What would I combine with the command above to do that in bash?

-=- cut here -=-
#! /bin/bash
# TNC random number generator based on whois database
# Idea by Jamie Baddeley <wellylug at vpc.co.nz>
# Code by Ewen McNeill   <wellylug at ewen.mcneill.gen.nz>

num_tech_c=$(whois -h whois.apnic.net -r thursday|grep tech-c|wc -l)
rand_raw="${RANDOM}"                                             # 0 .. 32767
rand_factor=$(( 1 + ((${rand_raw} * 9) / 32768) ))               # 1 .. 9
lucky_number=$(( ((${num_tech_c} * ${rand_factor}) + 9) / 10 ))  # Round up

#echo "${num_tech_c} * (${rand_factor} / 10)" >&2
echo "Lucky Number: ${lucky_number}"
-=- cut here -=-

This requires bash (as requested), due to both the shell arithmetic and 
also $RANDOM.

>And, ideally the $lucky_number would have a tendency toward 3.

At present (with $num_tech_c == 13), it'll generate numbers between 2
(ceil(13*0.1)) and 12 (ceil(13*0.9)).  With more tech_c's, the range
will expand and drift upwards.

It's unlikely to have a tendency towards 3 unless the "randomisation" is
very non-random.  While bash's $RANDOM is unlikely to be a particularly
good random number generator, I think it's probably very unlikely to
tend towards a value that will give you 3.

Eventually (if $num_tech_c increases enough) it'll be impossible to generate
3 with this script.  This will happen around 31 tech_c's, due to the 
requirement to round upwards.

>And for bonus points, rewriting the above so it's a secure cgi.

I'm not sure I'd write a "secure" CGI in bash.  But it'd be possible
to put HTML from the script with trivial modifications (left as an
exercise for the reader).

Ewen

PS: Assuming you plan to use this for what I think you intend to use it
    for, the specification given for the program doesn't fit the
    actual requirements particularly well.




More information about the wellylug mailing list