* Stephan Hochhaus <[EMAIL PROTECTED]>
> I just finished a very simple script that reads out my IP-address from 
> the ppp0 device, creates a small HTML file and uploads it to my 
> webhoster so i can access my g4 from anywhere in the world. The script 
> is the patchwork of a beginner, so any advice on making it nicer is 
> greatly appreciated. It is run as a cronjob to assure the 
> up-to-dateness of the IP.
> Anyway, here's the script:
> 
> #!/usr/bin/perl

use strict;
use warnings;

> use Net::FTP;
> #all the neccessary info for loggin into the ftp server
> my $hostname = 'myftpserver.com';
> my $user ='username';
> my $pass = 'password';
> 
> #where on the server should which file go?
> my $dir = '/public_html';
> my $file = '/Users/Shared/g4server.html';
> 
> #read out my ip address
> my $ifconfig = `ifconfig ppp0`; # the ifconfig command gives the 
> current network information
> $ifconfig =~ /inet (\d+\.\d+\.\d+\.\d+)/; # extract the ip address with 
> a regular expression
> my $ip = $1;

# no sense in writing no data if we did not get any...
die "error: could not parse address from ifconfig" unless $ip;

> # write it to a html file
> open (OUTPUT,">/Users/Shared/g4server.html");

# you declare $file above, but do no use it here?

# anyways, error checking is a must!
open (OUTPUT,"> $file") or die "error: could not write $file: $!\n";

> print OUTPUT "<HTML><HEAD><TITLE>g4server address</TITLE></HEAD><BODY>";
> print OUTPUT "<H1>Access g4server.local</H1>\n";
> print OUTPUT '<a href=http://';
> print OUTPUT $ip;
> print OUTPUT ">Apache</a><br />\n";
> 
> print OUTPUT '<a href=https://';
> print OUTPUT $ip;
> print OUTPUT ":10000>Webmin</a><br />\n";
> 
> print OUTPUT "</BODY></HTML>";

# a "here" document is much shorter, and cleaner:
print OUTPUT <<"HTMLSTUFF";
<HTML><HEAD><TITLE>g4server address</TITLE></HEAD><BODY>
<H1>Access g4server.local</H1>
<p><a href="http://$ip/";>Apache</a></p>
<p><<a href=https://$ip:10000/";>Webmin</a></p>
</body></html>
HTMLSTUFF

> close (OUTPUT);

# when writing to a file, *always* check the status on close, as this is
# when you figure out that the disk is full or something else went wrong
# and have a chance to log the error or fallback...
close OUTPUT or die "error: problem closing $file: $!\n";

> #upload the html file
> 
> $ftp = Net::FTP->new($hostname);
> $ftp->login($user, $pass);
> $ftp->cwd($dir);
> $ftp->put($file);
> $ftp->quit;

There's probably error checking that can be done on the FTP calls,
as well...

Other improvements would be to write out the HTML file to a temporary
file (see the File::Temp perl module), and doing a rename on that to the
proper filename, but only if the files are different. This would allow
you to skip uploading to FTP should nothing have changed, and reduce the
chance that you hit the page when the file is being updated.

Reply via email to