LOGO

Automatically Generate and Email Computer Statistics

January 23, 2014
Automatically Generate and Email Computer Statistics

Automated Server Log Monitoring via Email

Daily review of server log data and statistics is crucial, yet can become a repetitive task. A streamlined approach would involve receiving a consolidated email detailing key highlights, eliminating the need for direct server access for routine checks.

This guide details the configuration of automated email notifications on both Linux and Windows operating systems.

Specific Environments Covered

The instructions will be tailored for Ubuntu and Windows 8.1. Gmail will be utilized as the outgoing email server.

However, the principles outlined here are readily adaptable to other Linux distributions, Windows versions, and alternative email services.

Why Automate Log Monitoring?

  • Reduced Tedium: Automate a repetitive task.
  • Proactive Issue Detection: Identify potential problems without manual server logins.
  • Time Savings: Focus on more critical tasks.
  • Improved Security: Quickly detect and respond to security events.

Regularly scheduled email reports provide a convenient method for staying informed about your server’s health and performance.

The following sections will provide step-by-step instructions for setting up these automated reports on the specified operating systems.

Sending Automated Emails from Linux

To achieve automated email functionality within a Linux environment, we will utilize two distinct software packages: ssmtp and mailutils. Installation of both can be performed using a single command:

$ sudo apt-get install ssmtp mailutils

Following the installation process, modifications to the SSMTP configuration file are necessary.

$ sudo vi /etc/ssmtp/ssmtp.conf

The file should be edited with the following settings. Replacing the existing content with these configurations is permissible.

# This is the recipient address for emails; customize it to your preferred email.
root=username@gmail.com
# Define the email server; no changes are needed if utilizing Gmail.
mailhub=smtp.gmail.com:587
# Specify the domain from which the emails originate.
rewriteDomain=gmail.com
# Indicate the email address that will appear as the sender.
hostname=username@gmail.com
# SSL/TLS settings are essential for Gmail and many other email servers.
UseTLS=Yes
UseSTARTTLS=Yes
# Provide the username associated with your Gmail account.
AuthUser=username
# Enter the password for your Gmail account.
AuthPass=password
# Enable the option to override the 'From' address.
FromLineOverride=yes

After completing the file edits, it is crucial to adjust the file permissions, given that your Gmail password is stored in an unencrypted format.

$ sudo chmod 640 /etc/ssmtp/ssmtp.conf
$ sudo chown username.username /etc/ssmtp/ssmtp.conf

While assigning ownership to root enhances security, it necessitates the use of 'sudo' within your scripts, prompting for a password and negating the automation benefits.

If you operate on a shared server and are concerned about plaintext password exposure to root, consider employing a dedicated, disposable Gmail account or an email server that doesn't require authentication.

To verify the configuration, a test email should be sent:

$ echo "Testing" | mail -s "Testing mail setup" username@gmail.com

This command will send an email with "Testing" as the body and "Testing mail setup" as the subject. Confirm receipt in your email inbox.

Creating a Script for Automated Email Reports

Having established the ability to dispatch emails directly from the command line, the next step involves crafting a script designed to deliver fundamental system information to you.

Script Implementation

The following script will gather and email essential system details. It begins by checking available hard drive space.

#!/bin/bash
# Verify hard drive space utilization
echo "Hard drive space:" > /home/geek/email.txt
df -h >> /home/geek/email.txt

Subsequently, the script identifies currently logged-in users.

# Identify logged-in users
echo "Users currently logged in:" >> /home/geek/email.txt
who >> /home/geek/email.txt

Then, it lists the processes that are currently running on the system.

# List active processes
echo "Running processes:" >> /home/geek/email.txt
ps -e >> /home/geek/email.txt

Finally, the script sends the compiled information via email and removes the temporary file.

# Dispatch the email report
cat /home/geek/email.txt | mail -s "Daily server information" username@gmail.com
# Remove the temporary file
rm /home/geek/email.txt

While this script provides a basic framework, it can be expanded upon to include more detailed information and refined formatting.

The resulting email will contain the gathered system statistics, as illustrated below:

how-to-automatically-generate-and-email-computer-statistics-1.jpg

Automating Script Execution with Cron

Once the script is written and thoroughly tested, cron can be utilized to automate its execution on a daily schedule. For this example, we will schedule the email to be sent at 2:00 AM each day, allowing for review of the data later.

To edit the crontab file, use the following command:

$ crontab -e

To schedule the script to run at 2:00 AM, add this line to the crontab file:

0 2 * * * /home/geek/script.sh

Further details regarding crontab files and their configuration are available in a dedicated article.

Automated Email Dispatch via Windows

While PowerShell enables email transmission from the command line, utilizing third-party applications often simplifies this process, particularly when integrating with Gmail. SendEmail is a complimentary Windows program designed to streamline integration with both Windows Task Scheduler and Gmail. The latest version can be downloaded via the link provided, ensuring you select the TLS-enabled variant.

Upon downloading SendEmail, extract the contents of the zip archive and store them in a permanent location, reflecting your long-term need for automated email functionality. For this demonstration, the program will be stored in the C:\SendEmail directory.

Let's perform a test of SendEmail to familiarize ourselves with its operation. Initiate a command prompt by typing 'cmd' into the Start or Run menu (accessed via Ctrl+R).

With the command prompt active, navigate to the directory where the SendEmail files are located using the change directory command.

cd C:\SendEmail

Now, a test email can be dispatched using the following command:

sendEmail -f username@gmail.com -t username@gmail.com -s smtp.gmail.com:587 -xu username -xp password -u "Test email subject" -m "This is a test email."

Remember to substitute "username" and "password" with your actual Gmail credentials before executing this command.

A breakdown of the command's components is as follows:

sendEmail

initiates the program's execution.

-f

specifies the sender's email address.

-t

defines the recipient's email address.

-s

indicates the SMTP server address.

-xu

provides the account username for authentication.

-xp

supplies the account password for authentication.

-u

sets the subject line of the email.

-m

contains the body text of the email message.

Verify receipt of the test email in your inbox. Following this confirmation, we can proceed to develop a script capable of sending server information.

Developing a Script for Automated Email Reporting

To maximize the utility of our automation, we will construct the script utilizing PowerShell. Initiate Windows PowerShell ISE by typing 'powershell_ise.exe' into the Run dialog box (accessed via Ctrl+R).

how-to-automatically-generate-and-email-computer-statistics-3.jpg

Within the PowerShell ISE interface, the right-hand pane displays a comprehensive listing of all commands available for execution within PowerShell. This resource can be invaluable when determining the specific data points you wish to include in your reports. Furthermore, the script can incorporate external applications to generate information beyond PowerShell’s native capabilities (for example, SendEmail is a third-party tool that can be leveraged by PowerShell and cmd for tasks they cannot perform independently).

how-to-automatically-generate-and-email-computer-statistics-4.jpg

For the purposes of this demonstration, the script will gather the current disk space utilization of the C: drive, enumerate the processes currently in execution, and identify all files and folders being shared across the network.

# Determine hard drive space availability
echo "C: Drive Usage:" > C:\SendEmail\info.txt
Get-WmiObject win32_LogicalDisk -Filter "DeviceID='C:'" | Select-Object Size,FreeSpace >> C:\SendEmail\info.txt
# Display a list of running processes
echo "Running processes:" >> C:\SendEmail\info.txt
get-process >> C:\SendEmail\info.txt
# Identify currently shared files and folders
echo "SMB shares:" >> C:\SendEmail\info.txt
get-smbshare >> C:\SendEmail\info.txt
# Initiate email transmission
type C:\SendEmail\info.txt | C:\SendEmail\sendEmail -f username@gmail.com -t username@gmail.com -s smtp.gmail.com:587 -xu username -xp password -u "Daily server info"
# Remove the temporary file
rm C:\SendEmail\info.txt

This script directs various data outputs to the file C:\SendEmail\info.txt, subsequently transmitting the contents of this file via email before its deletion. Ensure you save the script with a '.ps1' extension, denoting a PowerShell file.

Upon completion of the script, perform a preliminary test from the Run prompt to verify its functionality.

Simply utilize the

powershell

command, accompanied by the

-file

argument, and specify the complete path to your script.

powershell -file "c:\SendEmail\daily-email.ps1"
how-to-automatically-generate-and-email-computer-statistics-5.jpg

Confirm receipt of the email in your inbox; if unsuccessful, meticulously review the script for any potential syntax errors. The following illustrates the email generated by our example script:

how-to-automatically-generate-and-email-computer-statistics-6.jpg

You have the flexibility to refine the formatting—for instance, inserting blank lines—to enhance its presentation on your preferred device. Alternatively, consider employing a third-party application capable of generating the required information in a more readily readable format than that provided by Windows, while maintaining the core scripting process.

After resolving any issues within your script, you can leverage Windows Task Scheduler to automate its execution. Access Windows Task Scheduler through the Start menu.

how-to-automatically-generate-and-email-computer-statistics-7.jpg

Within Task Scheduler, select Action > Create Basic Task.

how-to-automatically-generate-and-email-computer-statistics-8.jpg

Assign a descriptive name to the task, such as "Daily email script," and proceed to the next step. On the subsequent screen, define the desired frequency of email script execution—typically, daily. Then, specify the preferred execution time and click next.

You will now encounter the "Action" stage of the wizard; select "Start a Program" and input the identical text used previously in the Run prompt to test the script.

how-to-automatically-generate-and-email-computer-statistics-9.jpg

Proceed by clicking next, and then acknowledge the prompt with a "Yes" response.

how-to-automatically-generate-and-email-computer-statistics-10.jpg

Finalize the configuration by clicking "Finish," thereby completing the scheduling of your automated emails.

#computer statistics#automated reporting#email statistics#system monitoring#performance monitoring