Always Remember: With Gusto Comes Data Loss.

Python Script For Grabbing Log Files Remotely

Below is a Python script I wrote to quickly harvest various logs from remote systems. This is a very simple script that was written for a very specific setup, so if you want to use it you will likely need to modify it. What it does is allow the user to enter an IP address, then uses scp to transfer the specified logs to the user’s system at the specified location. I don’t claim this is the best way, or even the correct way, to do this, but it solved a need that I had quickly and easily – your milage may vary.

This script was designed to work in an environment where every system that is being administered is accessible to the machine running it, via ssh, without a password. In the future I’ll likely post a guide on how to set up this sort of thing, but for now you’ll have to Google that.

To run the script you simply type:

./harvestLogs --ip <IP Address>

If you intend to use this script, be sure to change everything within the < > – and, of course, remove the brackets. I have pasted it here with example settings to show you the proper formatting.

##########################
# Created by: Josh Gold  #
# Created on: 03/28/2012 #
##########################

import os, subprocess, optparse

# Allow the program to accept the input of the --ip option
parser = optparse.OptionParser('Usage requires --ip ')
parser.add_option('--ip', dest='systemIP', type='string', help='specify IP address')
(options, args) = parser.parse_args()

# If no option and arguement are added return the usage instructions
if (options.systemIP == None):
	print parser.usage
	exit(0)

# Otherwise set systemIP equal to the user's input
else:
	systemIP = options.systemIP

# Gathers the DNS hostname from the IP
harvest_dns = subprocess.check_output(['ssh', '<josh@>' + systemIP, ' hostname']).strip()
print('Connected to: ' + harvest_dns)

# Sets the locations for the logs to gather
harvest_sys = str('<josh@>' + systemIP + '<:/var/log/system.log>')
harvest_sec = str('<josh@>' + systemIP + '<:/var/log/secure.log>')

# Uses scp to transfer the remote logs to the local system at the specified location
os.system("scp " + harvest_sys + " " + harvest_dns + "")
os.system("scp " + harvest_sec + " " + harvest_dns + "")

print('Done!')

Leave a comment

Your email address will not be published. Required fields are marked *