SoBIT.org
23Nov/110

Python script for stripping leading spaces and trailing parentheses

I wrote this script to reformat router ACLs that were copy pasted from a terminal session. It strips leading spaces and removes the match count in parentheses at the end of each line.

#!/usr/bin/python

#------------------------------------------------------------------------------
# Name: scrub.py
# Author: Jeremy Pierson
# Last Modified: 11/3/11
# Description: Deletes text after ( in a text file and trims leading white
# spaces before writing to a new file.
#------------------------------------------------------------------------------

import os
import sys
import fileinput

usage = "Usage: "+os.path.basename(sys.argv[0])+ " oldfile newfile"

if len( sys.argv ) < 2:
print usage

else:
filetosearch = sys.argv[1]
Output2 = sys.argv[2]

Output = open( Output2, 'w' )

f=open(filetosearch, 'r')

count=0

for line in f:
found=line.find('(')
x=line.split("(")[0]
y=x.lstrip()
print y
count=count+1

if found < 1:
Output.write(y)
else:
Output.write(y+'\n')

print "I wrote "+str(count)+" mutha fucking lines!"

f.close()
Output.close()

Filed under: Code No Comments
18Jul/110

!@#$&^* DVD CSS Restrictions/DVD encryption with Ubuntu

My trusty Natty Narwal (Ubuntu 11.04) laptop and I tried to play a DVD for some friends the other night when I received the middle finger of copy protection land:

DVD Decryption Failed (messsage from Movie Player)

I have used this laptop to view video of every type imaginable via digital files, so I was pretty sure my codecs were square.  The problem seemed to be with The CSS encryption found on DVDs.

To fix this issue, open a terminal window and Run the following:


sudo apt-get install libdvdread4

In my case, this packaged had already been installed.

Execute the following script:


sudo /usr/share/doc/libdvdread4/install-css.sh

 

DVD CSS decryption should now be working!  Eject the disc and put it back in and fire it up with Movie Player (or your favorite media player).

Filed under: OS No Comments
13Jul/110

Yarrrr!!, It’s tar!!! Unpacking gzips with tar…

Every so often I have the need to download a zip (file.tar.gz) from the toobz and peruse its contents.  Today was no exception.  I knew I needed my trusty friend tar to help me out.  Tar is described  at http://www.gnu.org/software/tar/ as:

"The Tar program provides the ability to create tar archives, as well as various other kinds of manipulation. For example, you can use Tar on previously created archives to extract files, to store additional files, or to update or list files which were already stored.

Initially, tar archives were used to store files conveniently on magnetic tape. The name "Tar" comes from this use; it stands for tape archiver. Despite the utility's name, Tar can direct its output to available devices, files, or other programs (using pipes), it can even access remote devices or files (as archives)."

Sweet.  Harness your inner Cliff Claven and bust that out at the next party you attend.

Similar to the many other times I've needed to extract a gzip, I TOTALLY FUCKING FORGET THE SYNTAX.  Instead of having a complete capslock tantrum, I asked the Google and it provided the answer.

tar -zxvf filename

Nice and easy.  If you have syntax questions on other uses, post them as comments and I'll answer accordingly.  Hopefully the act of typing this article up will commit it to the spongy grey matter between my ears.

 

Filed under: OS No Comments
1Jul/110

Cisco routers and ASCII Art

I wanted to test some screen capture software the other day and I couldn't think of anything particularly useful to demonstrate.  As a result, the valuable skill shown here is applying ASCII art to the message of the day (MOTD) on a Cisco router/switch type thingy.

I'd like to do more of these in the future, so give me your feedback!

Filed under: Networking No Comments
21Jun/110

The Junior Woodchuck’s Guide to Beer

New to beer? You've got 9,654,234,234,453,457,754,234 ordering options. I've put together a quick tutorial hear to get you through the basics without violating my own ADD-ridden attention span. Birdie! Nope, back on track. Nobody likes a beer snob, but it's always nice to know what you're ordering. Here's the junior woodchuck's guide to beer:

Most beers can be categorized as either a Lager or an Ale.

Ale

Known as top fermenting, because during fermentation, it briefly gathers at the top. Right. Ales require warmer temperatures for the yeast to work it's magic, and they typically have a more complex taste with more alcohol content. Brits gave us the Ales.

Lager

If an Ale is top fermenting, then a Lager must be bottom fermenting. The yeast sinks to the bottom of the brew and requires cooler temperatures for fermentation. Lagers tend to be lighter in color and have a slightly drier taste than ales. Lagers originated in cold Bavarian caves, and Lagers are also the most common type of beer in the US.

Just about every beer fits into one of three categories: ale, lager, or a specialty beer. There are hybrids and exceptions, but for the most part it's one of these three.

 

Quick Overview of Specialty Beers
Coloring Name Description
Light and opaque Hefeweizen Wheat beer. Lightly colored but extremely cloudy, often served with an orange or lemon slice.
Light Kristallweizen A Hefeweizen that's been filtered, and no longer has opaque properties.
Light to Medium. IPA or India Pale Ale Originated as a brew with extra hops to survive the long journey from England to India. Usually has a strong, slightly bitter taste due to the hops.
Brown Brown Ale English style ale made with brown malt.
Dark Brown to Black Porter/Stout Dark and Opaque in color. Depending on the brand, the flavors will include Coffee and Chocolate among other ingredients.

Did I miss something? Tell me @ jeremy@sobit.org

Filed under: Misc No Comments
26Apr/110

Python LDAP Queries

While working on a project, I stumbled across the need to run a simple LDAP query against an Active Directory domain controller periodically.  Since I'm still learning my Python-fu, I thought this would be a great opportunity to solve a real world problem with some simple code.

Here is what I came up with:

#!/usr/bin/python

#--------------------------------------------------------
# Comments
# A Simple LDAP query against an Active Directory Server
#
# Author: Jeremy Pierson
#
# Date: 4/26/11
#--------------------------------------------------------

# Grab the ldap module, we'll be using that to interact with the object.
# May require the installation of python-ldap on your system

import ldap

# Create an object and variables containing users DN and password to search your Active Directory

l = ldap.initialize('ldap://10.0.0.10')
uname = "CN=My Testuser,OU=users,DC=somedomain,DC=com"
password = 'testytesterton'

try:
l.protocol_version = ldap.VERSION3

# The initial bind will send the auth info from above, you could pass those as paramters as well.

l.simple_bind_s(uname, password)
valid = True

# The variables below identify the search criteria

base_dn = 'OU=management,OU=users,DC=somedomain,DC=com'
filter = '(CN=Michael Scott)'
attrs = ['sn']

# The .search_s method performs a the search and returns results to the results variable to be reused elsewhere.

results = l.search_s( base_dn, ldap.SCOPE_SUBTREE, filter, attrs )

print results

except Exception, error:
print error

=================================================================================================

There's quite a bit of useful info on the GoogleToobz regarding Python and LDAP, but I found a series of articles by Matt Butcher particularly useful:

http://www.packtpub.com/article/python-ldap-applications-ldap-opearations

Let me know if you have any comments or suggestions:

jeremy@sobit.org

Filed under: Code No Comments
10Feb/110

Python Pingy Dingy part II

This is an updated version of the previous Python script that called the external program Ping.  This script uses the sys module to pass the parameters from the command line to the script, so destination IP and count can be specified at run time.  The changes are made in bold.

 

#!/usr/bin/python

#--------------------------------------------------------
# Comments
# More fun with system calls
#
# Author: Jeremy Pierson
#
# Date: 1/10/11
#--------------------------------------------------------

from subprocess import PIPE, Popen, STDOUT
import sys

#IP = '4.2.2.4'    These variables are now parameters
#count = '8'

IP = sys.argv[1] # collect the first parameter
count = sys.argv[2] # and the second parameter

# The section below is the external system call.  Parameters for the ping program are
# passed as a list,
# which is why they are enclosed in brackets [] and seperated by commas.
# This is very helpful as
# it allows you to easily use seperate variables for different parameters.
# The command below executes ping -c count IP

p = Popen(['ping','-c '+count, IP], stdout=PIPE, stderr=STDOUT)

# -c specifies the number of pings on a Linux system, on windows it's -n
# (default is 4 on windows)
# Linux boxes will ping indefinitely without the -c option

#Since the process runs silently until there is output, this message lets you know it is running
print 'Pinging...'

#This message displays the output of the command.
print p.communicate()[0]

print 'Complete!'

Filed under: Code No Comments
21Aug/100

Python Pingy Dingy

A simple Python script to demonstrate running an external program and displaying the output:

# Comments
# More fun with system calls
#
# Author: Jeremy Pierson

from subprocess import PIPE, Popen, STDOUT

IP = '4.2.2.4'
count = '8'

# The section below is the external system call.  Parameters are passed as a list,
# which is why they are enclosed in brackets [] and seperated by commas.  This is very helpful as
# it allows you to easily use seperate variables for different parameters.
# The command below executes ping -c 8 4.2.2.4

p = Popen(['ping','-c '+count, IP], stdout=PIPE, stderr=STDOUT)

# -c specifies the number of pings on a Linux system, on windows it's -n (default is 4 on windows)
# linux boxes will ping indefinitely

#Since the process runs silently until there is output, this message lets you know it is running
print 'Pinging...'

#This message displays the output of the command.
print p.communicate()[0]

print 'Complete!'

 

This really isn't much more useful than running a ping directly unless you start to consider how many different ways you can use the output.  The output is stored as a variable, so it can be logged, searched, sorted, truncated, concatenated, emailed, posted on a web page, etc. etc.

Filed under: Code No Comments
10Aug/101

Changing your Windows 7 startup background

Have you ever wanted to change the windows startup background? Do you remember needing 3rd party software, or having to "hack" system files to do this?

The use of 3rd party software and hacking system files is no longer needed with the introduction of Windows 7! With a simple adjustment to a registry key, along with adding the background image of your choice into your windows directory, you can change your startup background in a matter of minutes!

DISCLAIMER: Remember, be careful when making changes to the registry. If you change the wrong key, or string, you can damage the operating system.

 

Alright, now that the Disclaimer is out of the way, lets get started!

Start by opening the Windows Registry Editor- you can do this a few ways:

Press the Windows Key+R and type rededit, then press enter (or click OK)

or

Go to Start, type regedit in the search box, then press enter (or click OK)

 

Now we need to locate the following registry key

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrrentVersion\Authentication\LogonUI\Background

In the right pane, change the value of OEMBackground to 1.

If OEMBackground does not exist, create it. To create a new string, right click in the right pane, go to New, then String Value. Once the string is created, we need to rename it to OEMBackground and then change the Value. To change the Value, right click on the new string and go to Modify. Change the Value Data to 1.

 

The next step is to add your image into the windows directory. Navigate to %windir%\System32\oobe (commonly C:\Windows\System32\oobe)

Depending if you have an OEM machine or not, you may need to create the next two folders. In the oobe folder, navigate to info, then backgrounds. If you do not have these folders, create them.

Your folder path should now look like this:

%windir%\System32\oobe\info\backgrounds

Now place your startup background within the backgrounds folder. Your image must be named backgroundDefault.jpg

You can also put different resolution sizes of your background in this folder. The files should be named the following way:

backgroundDefault.jpg

background768×1280.jpg (0.6)

background900×1440.jpg (0.625)

background960×1280.jpg (0.75)

background1024×1280.jpg (0.8)

background1280×1024.jpg (1.25)

background1024×768.jpg (1.33-)

background1280×960.jpg (1.33-)

background1600×1200.jpg (1.33-)

background1440×900.jpg (1.6)

background1920×1200.jpg (1.6)

background1280×768.jpg (1.66-)

background1360×768.jpg (1.770833-)


IMPORTANT NOTE: Images must be less than 256kb in size or the background will not load.

When a resolution/ratio specific background cannot be found the backgroundDefault.jpg image is loaded and stretched to fit.

Filed under: OS 1 Comment
10Aug/100

Coding with the Holy Hand Grenade of Antioch

I recently decided that my programming/scripting skills were horribly antiquated, having been put to rest early in the Clinton administration.  Since Visual Foxpro and Pascal don't appear to be making much of a comeback, it seemed as though it would be good time to look for alternatives.  I hit the Google and did some reading, posing the best programmer newb question I could think of: "What language should I learn?"  After much drinking and some reading, the suggestions were typically summed up as: "Well, what the hell do you want to do with it?"

I dunno, code stuff.

A few more beers and some soul searching later, I realized that most of my focus would probably be based around task automation, data collection, sorting, and scripting.  I have a lot of log files in my life and I run a lot of batch jobs.

While searching for the holy grail of programming languages to learn, I stumbled across Python - which seems to be a mixture of high level programming and kung-fu badassery.  Let me quote Python.org for a brief overview:

"Python is a remarkably powerful dynamic programming language that is used in a wide variety of application domains. Python is often compared to Tcl, Perl, Ruby, Scheme or Java. Some of its key distinguishing features include:

* very clear, readable syntax
* strong introspection capabilities
* intuitive object orientation
* natural expression of procedural code
* full modularity, supporting hierarchical packages
* exception-based error handling
* very high level dynamic data types
* extensive standard libraries and third party modules for virtually every task
* extensions and modules easily written in C, C++ (or Java for Jython, or .NET languages for IronPython)
* embeddable within applications as a scripting interface

..."

Read the rest at http://www.python.org/about/.

In a nutshell; it's super flexible, cross-platform, extendable, portable, easy to understand, and named after these guys:

I'm in!

Even one of the more popular dev tools is a Monty Python nod (IDLE).  So in an effort to understand this language of many uses, I'll be posting a series of articles and links to Python resources and adding a new section to the site to hold all this fun stuff.  Email me with any links or code examples you'd like to share and I'll get them on the site.

In the meantime, here's my take on the classic "Hello World" program written in Python form:

#The code that says Ni!
#An alternative to Hello World!
#Author: Jeremy Pierson

print "We are the code that says Ni!"

Output:

>>>
We are the code that says Ni!
>>>

Pretty straightforward stuff.  I'm mirroring a copy of Mark Pilgrim's Dive Into Python here in PDF.  Visit http://www.diveintopython.org for other formats.

Happy coding!

Filed under: Code No Comments