On Mar 6, 2:17 am, "Dr. Nikolaus Klepp" <dr.kl...@gmx.at> wrote:
> I just wonder who uses GUILE and for what.
I randomly reset the hostname and MAC address of my laptop at boot-up
to make wireless access a bit safer. This includes editing /etc/
hosts [e.g. OpenBSD script below].
For quick reliable scripts, I'd rather do it in Scheme!
Cheers,
-KenD
===================================================================
#!/usr/local/bin/guile -s
!#
;; Set hostname to a random dictionary word
(set! *random-state* (seed->random-state (current-time)))
(define wordsfile "/usr/share/dict/words")
(define hostfile "/etc/hosts")
(define backfile "/etc/hosts.bak")
(define tmpfile "/tmp/hosts.new")
(define hprefix "127.0.1.1 ")
(define (gen-random-position fname)
;; Return a random position in fname or #f
(and (file-exists? fname)
(random (stat:size (stat fname))))
)
(define (get-line port)
;; return text or #f for EOF
(let loop ( (chars '()) (next-char (read-char port)) )
(cond
((eof-object? next-char) #f)
((eq? next-char #\newline) (list->string (reverse chars)))
(else (loop (cons next-char chars) (read-char port))))
) )
(define (random-line-from-file fname)
(let loop ( (start-pos (gen-random-position fname)) )
(if (not start-pos)
"bogus" ;; not found
(let ( (port (open-input-file fname)) )
(file-set-position port start-pos)
;; get partial word, then whole word [next line]
(let ( (line (and (get-line port) (get-line port))) )
(close-input-port port)
;; if random line near/at EOF, get another
(if (and line (> (string-length line) 0))
line
(loop (gen-random-position fname)))
) ) ) ) )
(define (match-prefix? prefix text)
(let ( (prefix-len (string-length prefix)) )
(and (<= prefix-len (string-length text))
(equal? prefix (substring text 0 prefix-len)))
) )
;; Return a random dictionary word as new hostname
(let* ( (newhost (random-line-from-file wordsfile))
(cmd-str (string-append "hostname " newhost))
)
; (display (string-append " " cmd-str " --> "))
; (display (system cmd-str))
; (newline)
;;; Reset hostname
(delete-file "/etc/myname")
(with-output-to-file "/etc/myname"
(lambda () (display newhost) (newline)))
;;; Edit /etc/hosts for new hostname
(if (file-exists? tmpfile)
(delete-file tmpfile))
(call-with-input-file hostfile
(lambda (inport)
(call-with-output-file tmpfile
(lambda (outport)
(let loop ( (line (get-line inport)) )
(if line ;; not yet EOF
(begin
;; filter for line w hostname
(if (match-prefix? hprefix line)
(begin
(display hprefix outport)
(display newhost outport))
(display line outport))
(newline outport)
(loop (get-line inport)))
'done))
) ) ) )
(if (file-exists? backfile)
(delete-file backfile))
(rename-file hostfile backfile)
(copy-file tmpfile hostfile)
)
;; --- E O F --- ;;