Open Mail Admin Addon

Installation via console

Auch OpenMailAdmin ist ein Addon, das über den Pakfire installiert wird, somit fallen lässtige Eingabeaufforderungen weg. Also OpenMail Admin is an addon that has the Pakfire installed, thus falling away lässtige prompts. Wer dennoch lieber die Konsole benutz gibt hier folgen befehl ein: Those who still prefer the console is used here follow command:

 pakfire install -y openmailadmin pakfire install-y open mail admin 

Installation per Web-Interface Installation via web interface

Wer lieber die grafische Weboberfläche vom Pakfire benutz, sucht sich aus der Liste der verfügbaren Addons den OpenMailAdmin raus. If you prefer the graphical web interface from Pakfire used, looks for from the list of available addons Open Mail Admin raus. Die Prüfung der Abhängikteiten erledigt den Rest und installiert fehlende Packete automatisch mit. The examination of Abhängikteiten do the rest and install missing packages automatically.

Damit ist die Installation von OpenMailAdmin erledigt. This completes the installation of Open Mail Admin done.

Konfiguration Configuration

Als Erstes loggen wir uns mittels der IP unseres IPFire´s und dem Port 1001 beim OpenMailAdmin mit folgenden Daten ein. First, we log in using our IPFire's IP and port 1001 at the Open Admin mail with the following data.

Beispiel: Example:

 http://192.168.40.1:1001 http://192.168.40.1:1001
Mailbox: admin Mailbox: admin
Passwort: mailfire Password: mail fire

Warnung! Warning!

Es wird dringend empfohlen das vordefinierte Passwort zu ändern. It is strongly recommended to the predefined password.

Domänen erstellen/einrichten Domains / Setup

Der erste Schritt beim Einrichten seines Mailserver ist die Erstellung einer Domain, dazu benutzen wir den Reiter The first step in setting up his mail server is to create a domain, we use the tab . . Hier im Beispiel werden wir eine Domäne Namens “ exciter.ipfire.org “ nehmen. Here in this example we will choose a domain name "exciter.ipfire.org take. Der Name ist im Prinzip frei wählbar, am einfachsten ist hier ein DynDNS-Account-Name . Erstellt wird die Domäne mit einem Klick auf “ neu “, hatt man dies mit OK bestätigt, gelangen wir in die Eingabemaske für Domäns. The name is in principle freely selectable, the easiest is a DynDNS account name. Created the domain by clicking on "new", it was OK with this, we arrive in the input mask for domains. Diese wird wie im folgendem Beispiel ausgefüllt. This is filled in the following example.

Ein Klick auf „GO“ schließt die Eingabemaske für die Erstellung einer Domän und die erstellte Domän wird angezeigt. A click on "GO" closes the input screen for creating a domain and the resulting domain is displayed. Sind alle gewünschten Domäns erstellt, geht es mit dem anlegen des Benutzers bzw. der Mailbox weiter. Are all of the desired domain, it goes with the creating of the user and the mailbox further.

Mailboxen erstellen/einrichten Mailboxes Create / Setup

Um eine Mailbox bzw. einen Benutzer für den Mailserver anzulegen, benutzen wir den Reiter To add a mailbox or a user for the mail them, we use the tab . . Als Erstes sehen wir den bereits vorhanden Benutzer “ admin “ diesen lassen wir wie er ist, da sonst bei einer Fehlkonfiguration oder dem Vergessen eines Passwortes nicht mehr eigeloggt werden kann. Mit einem Klick auf “ neu “ und “ GO “ wird die Eingabemaske geöffnet und wie folgt ausgefüllt. First we see the already existing user admin we leave this as it is, because otherwise in a misconfiguration or forgetting a password is no longer eigeloggt can be. With a click on "new" and "GO", the screen is opened and filled as follows.

Wir tragen unsere gewünschten Werte ein und bestätigen dies wieder mit “ GO “. We take our values and confirm it again with "GO".

Im Beispiel sind der Mailbox folgende Werte übergeben worden: In the example, the mailbox, the following values have been passed:

  • Mailboxname: exciter ( dies ist auch der Anmeldename im OpenMailAdmin ) Mailbox Name: Exciter (this is also the login name in the Open Mail Admin)
  • voller Name: S. Rechenbach ( der Anzeigename ) Full Name: S. computing Bach (display name)
  • Standard-Absender: S. Rechenbach ( dieser Name erscheint in den E-Mails als Absender ) Standard Sender: S. Bach computing (This name appears in the e-mails as the sender)
  • Domain Schlüssel: All ( hier kann eingetragenwerden, überwelche Domain der Mailboxbesitzer senden darf ) Domain Key: All (you can eingetragenwerden on which domain the mailbox owner must send)
  • Quota: 150000 ( bestimmt die max. Größe einer Mailbox, hier sind es 150MB ) Quota: 150000 (specifies the max. Size of a mailbox, here it is 150MB)
  • max. max. Adressen: ( bestimmt die Anzahl an Mail-Adressen die der benutzer anlegen darf ) Addresses: (determines the number of email addresses the user can create)
  • max. max. Regexp: ( damit können „Regular Expressions“ Adressen angelegt werden ) Regexp: (so you can "Regular Expressions" addresses can be created)
  • Status: ( hier werden dem Benutzer die Rechte für die Mailbox gegeben ) Status: (here are the user rights for the mailbox, where)

Wird die Eingabe mit “ GO “ bestätigt, werden die eingetragenen Werte nochmals angezeigt, zusätzlich kann jetzt der Pate für den Benutzer bestimmt werden. Standardt ist das der Admin. Dieser kann im Notfall passwörter oder andere Sperren aufheben. If the entry with "GO" confirmed, the registered values again displayed, in addition can now sponsor for the user to be determined. Standard is the Administration may, passwords or other emergency locks cancel.

Ist die Mailbox angelegt, ist sie von Haus aus If the mailbox is created, it is out of the box deaktiviert disabled . . Im folgenden Schritt wird die Mailbox aktiviert. In the following step, the mailbox is enabled.

Mailboxen aktivieren/deaktivieren Mailboxes to enable / disable

Nach erfolgreicher Erstellung der Mailbox muß die selbige noch aktiviert werden. After successful creation of it in the mailbox must still be activated. Dazu klickt man auf das kleine Viereck vor der durchgestrichenen Mailbox, wählen als Aktion “ ent/sperren “ und bestätigen dies mit “ GO “. For this you click on the small square in front of the mailbox out, select as action "ent / Disable" and confirm this with "GO".

Nun ist die Mailbox aktiviert und betriebsbereit. Now the mailbox is activated and ready to operate. Als letzten Schritt müßen wir IMAPd noch unsere Mailkonten mitteilen, die abgerufen werden sollen. As a final step we need to Imapd nor our mail accounts indicate the be retrieved.

Erweiterung Fetchmail Expansion Fetchmail

Für die Jenigen die mehr als ein E-Mailkonto haben, bietet sich diese Erweiterung an. Fetchmail wird bei der Installation von OpenMailAdmin nicht mit installiert, muß daher separat mit/nach installiert werden. Um fetchmail unsere Konten mit zuteilen, ist die Bearbeitung der Datei “ .fetchmailrc “ notwendig. For those with more than one email account, is this extension. Fetchmail will during the installation of OpenMail Admin not installed, must be separated with / to be installed. To fetchmail accounts with our allocation is to edit the file ". fetchmailrc" necessary. Hier werden die Daten für die abzuholenden Mailkonten abgespeichert. Here are the data for the accounts to fetch mail stored.

Warnung! Warning!

Die Daten und Passwörter werden hier im KLARTEXT angezeigt. The data and passwords are here in KLARTEXT displayed. Es wird dringend empfohlen genau auf die Dateirechte zu achten. It is strongly recommended due to the file rights.

Am einfachsten geht das wie immer mit WINSCP . The easiest way is, as always with WinSCP.

Im Beipiel werden wir 2 E-Mail-Konten abholen lassen. In the example we are 2 e-mail accounts picked up. Das erste konto wird per IMAP verwaltet, das zweite per POP3 . The first account will be managed via IMAP, the second via POP3.

Datei: /root/.fetchmailrc File: / root / .fetchmailrc

 set logfile /var/log/fetchmail.log set logfile / var / log / fetchmail.log
set no bouncemail set no bounce mail
set postmaster root set postmaster root
#poll SERVERNAME : # poll SERVER NAME:
# user pass ; # User pass ;
# mda /usr/bin/procmail -f %F -d %T; # Mda / usr / bin / procmail-f% F-d% T;

#exciter@web.de # exciter@web.de
poll imap.web.de with proto imap poll imap.web.de with proto imap
user exciter@web.de there with password XXXXXXXXXXXX is exciter@ipfire.org here user exciter@web.de there with password XXXXXXXXXXXX exciter@ipfire.org is here

#silvio-rechenbach@web.de # silvio-rechenbach@web.de
poll pop3.web.de with proto pop3 poll pop3.web.de with proto pop3
user silvio.rechenbach@web.de there with password XXXXXXXXXX is exciter@ipfire.org here user @ web.de silvio.rechenbach there with password XXXXXXXXXX exciter@ipfire.org is here

Die Datei brauch folgende Rechte: The file needs the following rights:

 root/root 0700 root / root 0700 

Zum Schluß wird der Fetchmail-Daemon noch mit folgenden Befehl gestartet: Finally, the Fetchmail daemon with the following command:

 /etc/init.d/fetchmail start / etc / init.d / fetchmail start 

Wer Fetchmail bei der Arbeit zu sehen will oder Probleme ermittel will, gibt auf der Console folgendes ein: Who Fetchmail at work or want to see identifiable problems will exist on the console the following:

 tail -f /var/log/fetchmail.log tail-f / var / log / fetchmail.log 

STRG + C bendet die Sitzung. CTRL + C bendet the meeting.

Einrichten von E-Mail-Clients Setting up e-mail clients

Grundsätzlich ist jeder Mail-Client dazu in der Lage, sich mit dem IPFire zu verbinden. Basically, any mail client to be able to deal with the IPFire to connect. Es werden swohl POP3 und IMAP , als auch POP2 , SMTP / ESMTP und [[wpde>APOP] unterstüzt. There are swohl POP3 and IMAP, as well as POP2, SMTP / ESMTP, and [[wpde> APOP] supports. Im Test werde ich Outlook 2007©® benutzen, das die Servereinstellungen automatisch ermittelt. In the test, I will © ® Outlook 2007 to use the server settings automatically.

Für die, die die Daten mit der Hand eingeben müßen sind hier alle nötigen Infos. For the data with the hand must have all necessary information.

Backup der Mailbox Backup of the mailbox

Wer seine Mailbox sichern möchte erstellt sich eine Datei Namens „mailboxbackup“ mit folgendem Inhalt. Who wants to secure its mailbox created a file called "mailbox backup" with the following content.

Datei: /mailboxbackup File: / mailbox backup

 #!/bin/sh #! / bin / sh
BACKUP_PREFIX=/mnt/harddisk1/backup/mail BACKUP_PREFIX = / mnt/harddisk1/backup/mail

/etc/init.d/cyrus-imapd stop / etc / init.d / cyrus-imapd stop

su - cyrus -c "/usr/lib/cyrus/ctl_mboxlist -d \ su - cyrus-c "/ usr / lib / cyrus / ctl_mboxlist-d \
> ${BACKUP_PREFIX}/mailboxes.txt" > $ BACKUP_PREFIX () / mailboxes.txt "

date -I > ${BACKUP_PREFIX}/timestamp date-I> $ (BACKUP_PREFIX) / timestamp

rsync -vaR /var/imap /var/log/imap ${BACKUP_PREFIX} rsync-var / var / imap / var / log / imap BACKUP_PREFIX $ ()

/etc/init.d/cyrus-imapd start / etc / init.d / cyrus-imapd start

Die Datei kann nach /bin kopiert werden und bracht „0755“ als Rechte. The file can be in / bin are copied and brought "0755" as rights. Nun kann das Backup mit Now the backup with

 mailboxbackup mailbox backup 

auf der Console gestartet werden. on the console is started.

So sollte ein erfolgreiches Backup dann aussehen Thus, a successful backup then look

For Informations linux repositori Google.

Google's Linux software repositories make it easier to download and stay up-to-date with current releases of Google Linux applications. Please choose one of the guides below to help configure your system to use these repositories.

Step-by-step GUI Configuration

For step-by-step instructions using graphical tools, please choose your distribution from the list below. If your distribution is not listed, please try one of the command line guides.

Command Line Configuration

If your distribution is not covered by the GUI guides, or if you prefer to work with command line tools, below are instructions for several common package managers. Choose the one most appropriate for your system. Alternatively you could use the automated installation script to perform these actions.

Additional Resources

Repository Contents

  • Picasa for Linux 2.7
  • Google Desktop Linux 1.2

For more information and updates, please join the Google Linux Repositories Help group.

Network Programming with Perl

April 1st, 1999 by James Lee in

Using Perl to make network task is easy—here's how.

Perl has been called the glue that holds the Internet together because it is an extremely powerful text processing and CGI programming language. Although Perl was designed in the beginning to be a text manipulation language, it has evolved into a potent multi-purpose programming language. One area in which Perl has shown its power is that of network programming.

Perl makes network programming easy by providing built-in functions that can be used to create low-level client/server programs from scratch. Also, many modules are freely available that make programming common networking tasks simple and quick. These tasks include pinging remote machines, TELNET and FTP sessions. This article presents examples of each of these types of network programs.

Introduction

Client/server network programming requires a server running on one machine to serve one or more clients running on either the same machine or different machines. These different machines can be located anywhere on the network.

To create a server, simply perform the following steps using the built-in Perl function indicated:

  • Create a socket with socket.

  • Bind the socket to a port address with bind.

  • Listen to the socket at the port address with listen.

  • Accept client connections with accept.

Establishing a client is even easier:

  • Create a socket with socket.

  • Connect (the socket) to the remote machine with connect.

Several other required functions and variables are defined in the Socket.pm module. This module is probably already installed on your machine, but if not, it is available at the Comprehensive Perl Archive Network (CPAN), the official Perl source code repository (see Resources). To use this module in our programs, the following statement is required at the top of the program:

use Socket;

This statement will locate the file Socket.pm and import all of its exported functions and variables.

Viewing Module Documentation

All examples in this article use modules that are available at no cost from CPAN.

Perl modules are usually self-documenting. If the author of the module follows the generally accepted rules of creating a Perl module, they will add Plain Old Documentation (POD) to the module's .pm file. One way to view the POD for the Socket module (assuming Perl and Socket.pm were installed correctly) is to execute the following at the shell:

perldoc Socket

This command displays Socket.pm's POD converted to a man page. The output is a relatively thorough discussion of the functions and variables defined in this module.

Another way to view the documentation is to convert the POD to text using:

pod2text \
/usr/lib/perl5/i686-linux/5.00404/Socket.pm | more

The program pod2text is included in the Perl distribution, as are the programs pod2html, pod2man, pod2usage and pod2latex.

A Simple Server

Listing 1.

Our first programming example is a simple server running on one machine that can service only one client program at a time connecting from the same or a different machine. Recall that the steps for creating a server were to create a socket, bind it to a port, listen at the port and accept client connections.

Listing 1, server1.pl, is the source code for this simple server. First, it is generally a good idea to compile using Perl's strict rules:

use strict;

This requires all variables to be declared with the my function before they are used. Using my may be inconvenient, but it can catch many common syntactically correct yet logically incorrect programming bugs.

The variable $port is assigned the first command-line argument or port 7890 as the default. When choosing a port for your server, pick one that is unused on your machine. Note that the only way to ensure you select a port that does not have a predefined use is to look at the appropriate RFC (see Resources).

Next, the socket is created using the socket function. A socket is like a file handle—it can be read from, written to or both. The function setsockopt is called to ensure that the port will be immediately reusable.

The sockaddr_in function obtains a port on the server. The argument INADDR_ANY chooses one of the server's virtual IP addresses. You could instead decide to bind only one of the virtual IP addresses by replacing INADDR_ANY with

inet_aton("192.168.1.1")

or

gethostbyname("server.onsight.com")
The bind function binds the socket to the port, i.e., plugs the socket into that port. Then, the listen function causes the server to begin listening at the port. The second argument to the listen function is the maximum queue length or the maximum number of pending client connections. The value SOMAXCONN is the maximum queue length for the machine being used.

Once the server begins listening at the port, it can accept client connections using the accept function. When the client is accepted, a new socket is created named CLIENT which can be used like a file handle. Reading from the socket reads the client's output and printing to the socket sends data to the client.

To read from a file handle or socket in Perl, wrap it in angle brackets (<FH>). To write to it, use the print function:

print SOCKET;

The return value of the accept function is the Internet address of the client in a packed format. The function sockaddr_in takes that format and returns the client's port number and the client's numeric Internet address in a packed format. The packed numeric Internet address can be converted to a text string representing the numeric IP using inet_ntoa (numeric to ASCII). To convert the packed numeric address to a host name, the function gethostbyaddr is used.

Let's assume all of the servers referred to in this article are started on the machine named server.onsight.com. To start the server on this machine, execute:

[james@server networking]$ server1.pl
SERVER started on port 7890

The server is now listening at port 7890 on server.onsight.com, waiting for clients to connect.

A Simple Client

Listing 2.

Listing 2, client1.pl, shows a simple client. The first command-line argument to this program is the host name to which it should connect, which defaults to server.onsight.com. The second command-line argument is the port number which defaults to 7890.

The host name and the port number are used to generate the port address using inet_aton (ASCII to numeric) and sockaddr_in. A socket is then created using socket and the client connects the socket to the port address using connect.

The while loop then reads the data the server sends to the client until the end-of-file is reached, printing this input to STDOUT. Then the socket is closed.

Let's assume all of the clients are started on the the machine named client.avue.com, although they could be executed from any machine on the network. To execute the client, type:

[james@client networking]$ client1.pl server.onsight.com
Hello from the server: Tue Oct 27 09:48:40 1998

The following is the standard output from the server:

got a connection from: client.avue.com [192.168.1.2]
Perl Makes Life Easy

Creating sockets using the functions described above is good when you want to control how the socket is created, the protocol to be used, etc. But using the functions above is too hard; I prefer the easy way—IO::Socket.

The module IO::Socket provides an easy way to create sockets which can then be used like file handles. If you don't have it installed on your machine, it can be found on CPAN. To see this module's POD, type:

perldoc IO::Socket
A Simple Server Using IO::Socket

Listing 3.

Listing 3, serverIO.pl, is a simple server using IO::Socket. A new IO::Socket::INET object is created using the new method. Note that the arguments to the method include the host name, port number, protocol, queue length and an option indicating we want this port to be immediately reusable. The new method returns a socket that is assigned to $sock. This socket can be used like a file handle—we can either read the client output from it, or write to it by sending data to the client.

A client connection is accepted using the accept method. Note the accept method returns the client socket when evaluated in scalar context:

$new_sock = $sock->accept()

and returns the client's socket and the client's IP address when evaluated in list context:

($new_sock, $client_addr) = $sock->accept()
The client address is computed and printed the same as in Listing 1, server1.pl. Then the socket associated with that client is read until end-of-file. The data read is printed to STDOUT. This example illustrates that the server can read from a client using < > around the socket variable.
A Simple Client Using IO::Socket

Listing 4.

Listing 4, clientIO.pl, is a simple client using IO::Socket. This time, a new object is created that connects to a host at a port using the TCP protocol. Ten strings are then printed to that server, then the socket is closed.

If the server in Listing 3, serverIO.pl, is executed and then the client Listing 4, clientIO.pl, connects, the output would be:

[james@server networking]$ serverIO.pl
got a connection from: client.avue.com [192.168.1.2]
hello, world: 1
hello, world: 2
hello, world: 3
hello, world: 4
hello, world: 5
hello, world: 6
hello, world: 7
hello, world: 8
hello, world: 9
hello, world: 10
Bidirectional Communication

It is possible to create servers and clients that communicate with one another in both directions. For instance, the client may send information to the server, then the server may send information back to the client. Therefore, network programs can be written so that the server and client follow some predetermined protocol.

Listing 5.

Listing 5, server2way.pl, shows how a simple server can be created to read a command from a client, then print out an appropriate response to the client. The module Sys::Hostname provides a function named hostname that returns the host name of the server. To insure output is seen as we print, IO buffering is turned off for the STDOUT file handle using the autoflush function. Then a while loop is executed that accepts connections. When a client connects, the server reads a line from the client, chopping off the newline character. Then a switch statement is executed. (The switch is cleverly disguised as a foreach loop, which happens to be one of my favorite ways of writing a switch.) Depending on the input entered by the client, the server outputs an appropriate response. All lines from the client are read until end-of-file.

Listing 6.

Listing 6, client2way.pl, shows the companion client. A connection to the server is made, then the client prints a few commands to the server reads the response and prints the response to STDOUT.

The following is the output of the client code in Listing 6:

[james@client networking]$ client2way.pl
server.onsight.com
Hi
server.onsight.com
Tue Oct 27 15:36:19 1998
DEFAULT
A Forking Client

If you want to write a client that accepts commands from STDIN and sends them to the server, the easiest solution is to write a client that forks a child. (A solution can be written using select that does not fork, but it is more complicated.) The client's parent process will read the commands from the user through STDIN and print them to the server. The client's child process will then read from the server and print the responses to STDOUT.

Listing 7.

Listing 7, clientfork.pl, is an example of a client that forks.

To fork in Perl, call the cleverly named fork function. It returns undef if the fork fails. If it succeeds, it returns 0 to the child, non-zero (the child's pid) to the parent. In clientfork.pl, an if statement checks the value of $kid, the return value from the fork. If $kid is true (non-zero, the child's pid), parent executes reading from STDIN printing to the server. If $kid is false (zero), the child executes reading from the server printing to STDOUT.

The following is the example session executing the client code in Listing 7, clientfork.pl connecting to the code in Listing 5, server2way.pl:

[james@client networking]$ clientfork.pl
server.onsight.com
NAME
server.onsight.com
DATE
Tue Oct 27 15:42:58 1998
HELP
DEFAULT
HELLO
Hi

When the parent process is finished reading from STDIN, it executes the kill function to kill the child process. It is very important the parent reap its child so that the child does not outlive the parent and become a zombie.

A Forking Server

Listing 8.

Servers usually don't handle only one client at a time. One approach to a server that can handle more than one client is a server that forks a child process to handle each client connection. Listing 8, serverfork.pl, is an example of a forking server.

One way for the parent process to reap its children is to define a subroutine and assign a reference to that subroutine to $SIG{CHLD}. (The hash %SIG is Perl's way of handling signals.) In this example, a subroutine named REAP is defined and a reference to this subroutine is assigned to $SIG{CHLD}. When the parent receives the CHLD (child terminated) signal, the REAP subroutine will be invoked.

Within the while loop that accepts all the client connections, the server forks. If the fork returns true, the parent is running and it executes the next statement which immediately transfers control to the continue block, performs the housecleaning step of closing the child socket and waits for the next client to connect. If the fork returns undef, then the fork failed, so the server dies. If the fork returns neither true nor undef, then the child is running, so the parent socket is closed and the child reads from the client and processes the client. When the child is finished processing the client, the child exits and is reaped by the parent.

Thread Programming in Perl5.005

Perl version 5.005 supports thread programming. This means a threaded networking program can be created to be either a server or a client.

Listings 9, 10, and 11 are three different versions of a client that logs into several web servers and determines the type of server being used (Apache, Netscape, etc).

Listing 9.

Listing 9, getservertype1.pl, shows a non-forking, non-threaded client. First, an array of hosts is created and initialized to a few web sites. The subroutine doit is defined to receive the web server name as an argument, open a client connection to that server at port 80 (the HTTP port), send the HTTP request and read each line of response. When the line starting Server: is read, it will extract the server name and store it in $1. Then the host name and web server name are printed. This subroutine is called for each host in the array of hosts.

Here is the output of getservertype1.pl:

processing www.ssc.com...
www.ssc.com: Stronghold/2.2 Apache/1.2.5 PHP/FI-2.0b12
processing www.linuxjournal.com...
www.linuxjournal.com: Stronghold/2.2 Apache/1.2.5 PHP/FI-2.0b12
processing www.perl.com...
www.perl.com: Apache/1.2.6 mod_perl/1.11
processing www.perl.org...
www.perl.org: Apache/1.2.5
processing www.nytimes.com...
www.nytimes.com: Netscape-Enterprise/2.01
processing www.onsight.com...
www.onsight.com: Netscape-Communications/1.12
processing www.avue.com...
www.avue.com: Netscape-Communications/1.12

Note that the hosts are processed in the same order as stored in @hosts.

Listing 10.

Listing 10, getservertype2.pl, is a forking version of getservertype1.pl. The forking occurs within the foreach loop. The fork is executed and if it returns true, the parent then executes the next statement to the next host name. If the fork returns undef, then the program dies. Otherwise, the child calls the doit function passing in the host, then exits. After the parent completes its work in the while loop, it waits for all child processes to finish, then exits.

Here is the output of getservertype2.pl:

processing www.ssc.com...
processing www.linuxjournal.com...
processing www.perl.com...
processing www.perl.org...
processing www.nytimes.com...
processing www.onsight.com...
processing www.avue.com...
www.onsight.com: Netscape-Communications/1.12
www.nytimes.com: Netscape-Enterprise/2.01
www.avue.com: Netscape-Communications/1.12
www.linuxjournal.com: Stronghold/2.2 Apache/1.2.5 PHP/FI-2.0b12
www.perl.com: Apache/1.2.6 mod_perl/1.11
www.ssc.com: Stronghold/2.2 Apache/1.2.5 PHP/FI-2.0b12
www.perl.org: Apache/1.2.5
Parent exiting...

Note that the hosts are not printed in the order stored in @hosts. They are printed in the order processed, the slower hosts taking longer than the faster ones.

Listing 11.

Listing 11, getservertype3.pl, is a threaded version. In the loop through the host names, a new Thread object is created. When creating the Thread, the new method is passed a reference to a subroutine that the thread will execute, as well as the arguments passed into that subroutine. The thread then executes its subroutine and when the subroutine returns, the thread is destroyed. Here is the output of getservertype3.pl:

processing www.ssc.com...
processing www.linuxjournal.com...
processing www.perl.com...
processing www.perl.org...
processing www.nytimes.com...
processing www.onsight.com...
processing www.avue.com...
www.nytimes.com: Netscape-Enterprise/2.01
www.onsight.com: Netscape-Communications/1.12
www.avue.com: Netscape-Communications/1.12
www.linuxjournal.com: Stronghold/2.2 Apache/1.2.5 PHP/FI-2.0b12
www.perl.com: Apache/1.2.6 mod_perl/1.11
www.ssc.com: Stronghold/2.2 Apache/1.2.5 PHP/FI-2.0b12
www.perl.org: Apache/1.2.5
Net::Ping Module

Listing 12.

The Net::Ping module makes pinging hosts easy. Listing 12, ping.pl, is a program similar to a program on my server that pings my ISP to keep my connection alive. First, a new Net::Ping object is created. The protocol chosen is tcp (the choices are tcp, udp and icmp; the default is udp). The second argument is the timeout (two seconds). Then an infinite loop is executed, pinging the desired host. The ping() method returns true if the host responds, false otherwise, and an appropriate message is printed. Then the program sleeps ten seconds and pings again.

An example output of Listing 12, ping.pl, is:

Success: Wed Nov  4 14:47:58 1998
Success: Wed Nov 4 14:48:08 1998
Success: Wed Nov 4 14:48:18 1998
Success: Wed Nov 4 14:48:28 1998
Success: Wed Nov 4 14:48:38 1998
Success: Wed Nov 4 14:48:48 1998
Net::Telnet Module

Listing 13.

The Net::Telnet module makes automating TELNET sessions easy. Listing 13, telnet.pl, is an example of connecting to a machine, sending a few system commands and printing the result.

First, a server and a user name are used. The user name defaults to the user running the script by assigning to $user the value $ENV{USER}. (The hash %ENV contains all of the environment variables the script inherits from the shell.)

Next, the password is requested, then read in. Note that turning off the stty echoing is done through a system call. It can also be done using the Term::ReadKey module.

Then, a Net::Telnet object is created. To log in to the server using this object, the login method is called. Several system commands are executed using the cmd method which returns the STDOUT of the system command which is then printed. Note that part of that output is the system prompt, which is printed along with the output of the command.

Also note that the code $tn->cmd('/usr/bin/who') is evaluated in list context and stored in @who, which is an array that contains all the lines of ouptut of that command, one line of output per array element.

After all of the system commands are executed, the TELNET session is closed.

Here is an example output of Listing 13, telnet.pl:

Enter password:
Hostname: server.onsight.com
[james@server james]
Here's who:
james tty1 Oct 24 21:07
james ttyp1 Oct 27 20:59 (:0.0)
james ttyp2 Oct 24 21:11 (:0.0)
james ttyp6 Oct 28 07:16 (:0.0)
james ttyp8 Oct 28 19:02 (:0.0)
[james@server james]
What is your command: date
Thu Oct 29 14:39:57 EST 1998
[james@server james]
Net::FTP Module

Listing 14.

The Net::FTP module makes automating FTP sessions easy. Listing 14, ftp.pl, is an example of connecting and getting a file.

A Net::FTP object is created, the login is called to log in to the machine, the cwd changes the working directory and the get method gets the file. Then the session is terminated with quit.

There are methods to do many common FTP operations: put, binary, rename, delete, etc. To see a list of all the available methods, type:

perldoc Net::FTP

Here is an example output of Listing 14, ftp.pl:

[james@k2 networking]$ ftp.pl server.onsight.com
Enter your password:
Before
----------------------------------------
/bin/ls: *.gz: No such file or directory
----------------------------------------
After
----------------------------------------
perl5.005_51.tar.gz
----------------------------------------
Archive a Web Site

Using both Net::Telnet and Net::FTP, a very simple script can be created that can archive a directory structure on a remote machine.

Listing 15.

Listing 15, taritup.pl, is a Perl program that is similar to a program I use that logs in to my ISP and archives my web site.

The steps this program follows are:

  • Start a session on the remote machine with TELNET.

  • Go to the web page directory using cd.

  • Archive the directory using tar.

  • Start an FTP session to the remote machine.

  • Change to the directory containing the tar file.

  • Get the tar file.

  • Quit the FTP session.

  • Back in the TELNET session, delete the tar file on the remote machine.

  • Close the TELNET session.

This program outputs text to let the user know how the script is progressing.

Summary

Perl is a powerful, easy-to-use programming language. That power and ease of use includes network programming due to many built-in functions and modules. Best of all, it's free.

Resources

James Lee is the president and founder of Onsight (http://www.onsight.com/). When he is not teaching Perl classes or writing Perl code on his Linux machine, he likes to spend time with his kids, root for the Northwestern Wildcats (it was a long season), and daydream about his next climbing trip. He also likes to receive e-mail at james@onsight.com.

Getting Started with

Written by Steve Lidie
by Steve Lidie, April 1999

A favorite Perl module of mine is the Tk widget toolkit. With this collection of widgets, you can write sophisticated graphical applications, or just jazz-up your old command line program. Oh, you don't know what a widget is? How about a gadget, or a control? Actually, they're all just names that refer to a graphical element, such as this button:

Image Figure 1

You don't often see a naked button - usually it's embedded in a window, as part of a complete program. When you push the button it reacts and does something. The point here is to realize that widgets are just discrete entities that you arrange to make a whole graphical application. Tk has lots of other widgets, like labels, menus, dialogs, scrollbars, listboxes, and so on, as well as geometry managers to arrange them as you desire. Of course, there's more to a graphical application than just presenting a pretty window - it must interact with a life form (humanoid only, currently). As we'll see, things known as events help mediate the application-human conversation.

Tk was developed by John Ousterhout, originally for use with his scripting language, Tcl. That's where I first discovered it, and I found I could write my GUIs considerably faster that ever before. The Tk programs were also one tenth the size, had fewer bugs, and were more robust than an Xlib version.

I was hooked on Tk, but I faced a dilemma, because I was also hooked on Perl! I sometimes found myself writing a program in both Tcl/Tk (for the GUI) and Perl (for the systems stuff) - a sad state of affairs, indeed. Then Nick Ing-Simmons arrived on the scene, and, after a lot of work, molded Tk version 4 into a Perl extension. But Nick didn't stop there, he expanded Perl/Tk by adding new widgets, incorporating Tix and user contributed widgets, and making the package object oriented. Throughout the years Perl/Tk has been updated, tweaked and tuned, and now corresponds to Tcl/Tk version 8.0. The Perl/Tk version I base this article on is Perl 5.005_02 and Tk800.013, both available on the CPAN (for Unix), or http://www.activestate.com/(for Win32).

CPAN stands for Comprehensive Perl Archive Network, 100 or so machines spread around the globe, each a repository of everything that's Perl. I presume you have Perl installed and running somewhere, and, if it's not at least version 5.005_02, you'll update it. I do not presume you have Perl/Tk, so in a nutshell, here's how you install it.

Assuming you're on Unix, use a web browser and go to http://www.perl.com/ and click on the "Nearest CPAN Site" link. Then link to "authors", "Nick Ing-Simmons". Grab the latest tar file, presumably "Tk800.013.tar.gz" and save it somewhere. Like all well behaved Perl modules, the following steps should suffice for installation:


gunzip Tk800.013.tar.gz
tar -xvf Tk800.013.tar
cd Tk800.013
perl Makefile.PL
make
make test
make install

If you do not have the proper permissions to install Tk, you'll have to fetch and install Perl in your own file space before you can install Tk.

For Win32 users, install the latest Perl from the ActiveState site mentioned above. Then, at a DOS prompt, run PPM (the Perl Package Manager program), and install Tk:


ppm
PPM>install Tk
PPM>quit

To verify that Tk was installed properly, run the widget program from a Unix or DOS prompt. This program demonstrates most of the Perl/Tk widgets, and lets you view the code, modify it, and rerun demonstrations with your changes. Writing a GUI is fundamentally different than the classical line mode program - you use a technique called event driven programming. Essentially, it's your job to write subroutines, or callbacks, that are automatically called when certain events occur. Interesting events might be a button press, a file becoming readable, the expiration of a timer, or typing a keyboard character, and it's the subroutine's job to handle the event appropriately. To illustrate the concepts, we'll examine the typical "Hello World" program - actually, I'll show two versions. Here's the first, which produced Figure 2:

Image Figure 2


1 #!/usr/bin/perl -w
2 #
3 # hiworld1 - "Hello World" with a Label and explicit event binding.
4
5 use Tk;
6 use strict;
7
8 my $mw = MainWindow->new;
9
10 my $label = $mw->Label(-text => 'Hi World');
11 $label->pack;
12 $label->bind('' => sub {$mw->destroy});
13
14 MainLoop;

Note lines 1 and 6, where we specify run with warning enabled (-w) and strict programming style (use strict). I highly recommend you too write all your Perl/Tk program this way - it will find subtle (and sometimes stupid!) errors.

Line 3 is a comment, telling us that the program displays a Label widget. Labels (usually) draw simple text strings, in a particular font, size and color. Labels are also the simplest Tk widget - about the only other thing you can do with them is create explicit event bindings. More on this shortly.

Line 5 imports all the Tk widgets, definitions, variables and subroutines.

Line 8 is required by all Perl/Tk programs - it opens the program's first (main) window, the container within which (most) all your other widgets are arranged. This widget arrangement, or layout, is performed by a geometry manager. The geometry manager determines the actual location and size of a widget in the main window, relative to all other widgets. A widget never appears in the main window until it has been managed by a geometry manager.

Line 8 also demonstrates the OO (object oriented) nature of Perl/Tk. Here the scalar variable $mw is initialized with an object reference to a new instance of a MainWindow. We'll learn some basic OO concepts as we go along, but you needn't be an OO guru to use Perl/Tk, as long as you're not building new Perl/Tk widgets -and we aren't.

Line 10 creates our first widget, an instance of a Label, which displays the string "Hi World". (There may be many widgets of class Label in a program, and each may have a different text string, font, font size and color, but any particular one is known as an instance.) This line demonstrates typical Perl/Tk widget creation syntax: an object ($mw) has inherent operations called methods - Label() is one, a constructor method, because is constructs a new instance of a label widget. The methods are really subroutines that may have parameters, specified as keyword/value pairs. All keywords, like -text, start with a dash. Note that we use the => operator as the argument list separator, not to be confused with the -> operator used to invoke a method on an object.

Line 11 tells the pack() geometry manager to manage the label in the main window, which then displays it (Figure 2).

Line 12 is how we exit the program. It defines an anonymous subroutine that sends a "destroy" message to the object $mw, the main window. destroy() is a method which frees all memory associated with a widget and removes it from the display. When $mw is destroyed, everything contained in it is destroyed as well, and the program ends.

Line 12 uses the bind() method to associate an event with a subroutine. Subroutines of this type are termed callbacks, because the code is called back when the event in question (here, pressing Button-1 on the mouse) occurs.

Line 14 kick-starts the program by entering the Tk event loop. The event loop dispatches events to callbacks (yours and Tk's), and runs continuously until the main window goes away. Forget this statement and your Perl/Tk program thinks a while, then exits without displaying anything!

In summary, here are the characteristics of most Perl/Tk programs:

* A use Tk statement which imports the base Tk definitions.
* A MainWindow that contains other application widgets.
* Widget creation commands to populate the main window.
* Binding and callback creation commands.
* Geometry management commands to arrange and display widgets.
* A MainLoop() command to begin program execution.



Now let's look at a better version of the previous "Hello World" program; this new program generated Figure 3 . Compare Figures 2 and 3 and note the visual difference. There area several other subtle differences, as we'll see shortly.

Image Figure 3


1 #!/usr/bin/perl -w
2 #
3 # hiworld - "Hello World" with a Button and implicit class bindings.
4
5 use Tk;
6 use strict;
7
8 my $mw = MainWindow->new;
9
10 my $button = $mw->Button(-text => 'Hi World', -command => \&exit);
11 $button->pack;
12
13 MainLoop;

Line 3 reminds us that the program displays a Button widget rather than a Label, and that the button has "implicit class bindings". In this case, the button has a builtin binding for a event, so we don't have to create it manually as we did for the label. This binding applies to every instance of class Button - it's one feature that differentiates labels from buttons.

A button also has a three dimensional appearance due of its "raised" relief. If you'd like to make a label look like a button, just change its -relief option using the ubiquitous configure() method:


$label->configure(-relief => 'raised');

But adding a relief and a button binding still doesn't turn a label into a button because there are even more class bindings inherited by a button instance. Move the cursor over a button and watch what happens - it becomes highlighted. This is because the button has an binding, which invokes a builtin Tk callback that lightens the button. Similarly, the button has a binding to restore the widget's appearance when the cursor leaves. And finally, there are bindings to change the button's relief to "sunken" when selected, and then back to "raised".

Line 10 creates the button, and now we know some of things that go on behind to scene to make our programming life easier. The -command argument automatically links the code reference \&exit to a event.

It's time for something more complex - how about an application skeleton? By that I mean a main window with a menubar across the top, and File and Help menubuttons, which you can use as a basis for your real applications. Along the way we'll visit the Dialog widget, icons, and see some window manager commands. To make things really easy I've included a tiny Perl program named tkskel that will generate our mini application.

To use tksel, type something like "tkskel frog", and a complete Perl/Tk program named frog is created. Here's the resulting code:


1 #!/usr/bin/perl -w
2 #
3 # frog, Sun Apr 11 18:01:41 1999
4
5 use 5.005;
6 use Tk 8.0;
7 use Tk::widgets qw/Dialog/;
8 use subs qw/build_menubar fini init/;
9 use vars qw/$MW $VERSION/;
10 use strict;
11
12 $MW = MainWindow->new;
13 init;
14 MainLoop;
15
16 sub build_menubar {
17
18 # Create the menubar and File and Quit menubuttons. Note
19 # that the cascade's menu widget is automatically created.
20
21 my $menubar = $MW->Menu;
22 $MW->configure(-menu => $menubar);
23 my $file = $menubar->cascade(-label => '~File');
24 my $help = $menubar->cascade(-label => '~Help', -tearoff => 0);
25
26 # Create the menuitems for each menu. First, the File menu item.
27
28 $file->command(-label => "Quit", -command => \&fini);
29
30 # Finally, the Help menuitems.
31
32 $help->command(-label => 'Version');
33 $help->separator;
34 $help->command(-label => 'About');
35
36 my $ver_dialog = $MW->Dialog(-title => 'frog Version',
37 -text => "frog\n\nVersion $VERSION",
38 -buttons => ['OK'],
39 -bitmap => 'info');
40 my $about_dialog = $MW->Dialog(-title => 'About frog',
41 -text => 'About frog',
42 -buttons => ['OK']);
43 my $menu = $help->cget('-menu');
44 $menu->entryconfigure('Version', -command => [$ver_dialog => 'Show']);
45 $menu->entryconfigure('About', -command => [$about_dialog => 'Show']);
46
47 $menubar; # return the menubar
48
49 } # end build_menubar
50
51 sub fini {
52
53 exit;
54
55 } # end fini
56
57 sub init {
58
59 $VERSION = '1.0';
60
61 $MW->title("frog $VERSION");
62 $MW->iconname('frog');
63 my $xpm = $MW->Photo(-file => "skull.xpm", -format => 'xpm');
64 $MW->Icon(-image => $xpm); # full color icon picture
65
66 my $menubar = build_menubar;
67 my $frame = $MW->Frame(qw/-width 300 -height 50 -background cyan/)->pack;
68
69 } # end init

With the exception of line 7, I suspect lines 1 through 14 are self-explanatory. Line 7 is how we import Tk widgets that are not "core" widgets. Here are the 15 standard widgets automatically imported when we say "use Tk": Button, Canvas, Checkbutton, Entry, Frame, Label, Listbox, Menu, Menubutton, Message, Radiobutton, Scale, Scrollbar, Text, and Toplevel.

Lines 16 through 49 build the menubar, but I'll defer most of that discussion for another time. For now, it remains a task for you, gentle reader, to figure out!

Line 61 is a window manager command - it defines the text shown at the top of the window's title bar.

Some window managers support iconization, and line 62 simply gives our icon a name. Likewise, line 64 changes the default appearance of the icon to a colored image of our own design. To do that we first need to create a Tk image object, which is what line 63 does. The image is a small XPM file of, fittingly, a skull, grabbed from http://www.skellramics.com/ and used with their permission. Here's what frog looks like iconified:

Image Figure 4

Lines 66 and 67 complete the creation of the GUI elements. Line 66 creates the menubar and related components and saves its widget reference in $menubar, just in case we need to (re)configure it later. Line 67 creates a colored frame and packs it after the menubar. I don't cover geometry management here, suffice it to say that by default the packer arranges widgets top down in the main window, like this:

Image Figure 5

Notice that the Help menubutton has been pressed, a menu posted, and the Version menu item highlighted. Pressing Version pops up this modal dialog:

Image Figure 6

Notice that the dialog is independent of our main window - it's built from a special widget called a toplevel, which is similar to a main window. And like a main window, you can pack other widgets inside a toplevel. When we press OK the dialog is withdrawn from the display - but it's not destroyed - dialogs are persistent objects and must be explicitly destroyed.

Obviously, there's a lot more we can talk about, but enough's enough. To help straighten out the tangle I've no doubt made of your mind, take a look at these important Perl/Tk resources (in no particular order):

The man pages! For instance: perldoc Tk::Dialog

My list of important Perl/Tk links: http://www.Lehigh.EDU/~sol0/ptk/ptk.html