It can be done easier by using the fact that sshd (and httpd) record the addresses whence connections originate. So most of your script can be replaced by a simple ssh (or wget) to a server that you can read its logs.