Jump to content

Basic Python Example Code


sablefoxx

Recommended Posts

I've been recently playing around with Python, and finally got around to writing something (somewhat) useful. Basically it allows you to easily edit the hosts file with just a few commands. You can display the contents of the hosts file, add/remove entries, and reset the entire file. It also supports grouping so you can create multiple entries at the same time, here are some examples.

It will even resolve URLs for you. I learn best by example, so I'm going to post the source as well, in hopes that it may serve as example code for others learning Python. Let me know if you find bugs and, have fun.

rhost.exe -redirect yahoo.com -to google.com ( Creates redirect from yahoo.com to google.com )

rhosts.exe -redirect yahooo.com+amazon.com+buy.com -to google.com ( Create multiple redirects at once )

rhosts.exe -rm yahoo.com ( Removes entry for 'yahoo.com' )

Download Compiled Version: rhosts

Source Code:

#########################################
#          Written by Cerberus          #
#    rHOSTS - hosts file management     # 
#########################################
import os
import sys

__version__ = '1.3'
__authors__ = 'Cerberus'

def Lookup( url ):
    ''' Hand it a url, it will return the IP. If URL cannot be resolved, returns None '''
    print '\nResolving %s...' % url,
    raw_lookup = os.popen( 'nslookup %s' % url ).readlines()
    i = 0 # List/line index
    for line in raw_lookup:
        if line.find('Name:') != -1:
            ip = raw_lookup[i + 1] # Get line after 'Name:'
            print 'done!'
            return ip[ ip.find(':') + 3: ip.find('\n') ]
        i+= 1 # Incriment line number
    print 'failure!'
    return None

def WriteURL( ip, urls ):
    ''' Attempts to write an IP, and a list of URLs to the hosts file '''
    try:
        hosts = open( 'C:\\Windows\\System32\\drivers\\etc\\hosts', 'a' )
        for url in urls:
            print ' + Created redirect for %s' % url
            hosts.write( '\n%s  %s' % ( ip, url ) )
        hosts.close()
    except:
        Error( 'perm', 1 )

def ResetHosts():
    ''' Writes a blank hosts file to the system '''
    try:
        hosts = open( 'C:\\Windows\\System32\\drivers\\etc\\hosts', 'w' )
        hosts.write('# Hosts File\n127.0.0.1   localhost')
        hosts.close()
        print '\n A blank hosts file was successfully written to the system.'
    except:
        Error( 'perm', 2 )

def DisplayHosts():
    ''' Prints the hosts file to stdout '''
    try: 
        print '\n                    *** Current Hosts File Contents ***\n'
        hosts = open( 'C:\\Windows\\System32\\drivers\\etc\\hosts', 'r' )
        ls = hosts.readlines()
        for x in ls:
            print'%s' % x,
        print '\n                          *** End File Contents ***\n'
    except:
        Error( 'perm', 3 )

def RmEntry( urls ):
    ''' Deletes entries from the hosts file '''
    try:
        hosts = open( 'C:\\Windows\\System32\\drivers\\etc\\hosts', 'r' )
        ls = hosts.readlines()
        hosts.close()
    except:
        Error( 'perm', 4 )
    i, j = 0, 0 # Number of removals, before/after loop.
    print '\nAttempting to remove entries from hosts file, please wait.'
    for url in urls:
        j = i
        for line in ls:
            if line.find( url ) != -1:
                ls.remove( line )
                print ' - Removed entry for %s' % url
                i+=1
        if i == j:
            print ' - No entries found for %s' % url
    if i > 0:
        try: # Write entire hosts file back to system.
            hosts = open( 'C:\\Windows\\System32\\drivers\\etc\\hosts', 'w' )
            hosts.writelines( ls )
            hosts.close()
        except:
            error( 'perm', 5 )

def Parse( cli ):
    ''' Parses through the command line input '''
    if cli[1] == '-help' or cli[1] == '/?':
        Help()
    elif cli[1] == '-reset':
        ResetHosts()
    elif cli[1] == '-disp':
        DisplayHosts()
    elif cli[1] == '-rm' and len( cli ) == 3:
        RmEntry( cli[2].split('+') )
    else:
        try:
            rd = cli.index('-redirect') + 1
            to = cli.index('-to') + 1
            dest = cli[to].split('.') # Check for URL or IP
            try:
                i = 0
                for sub in dest:
                    if int( sub ) >= 0 and int( sub ) < 255: 
                        i+=1
                if i == 4:
                    ip = cli[to]
                    print '\nRedirecting URL(s) to %s' % ip
                else:
                    Error( 'comd', 7 )
            except:
                ip = Lookup( cli[to] )
            if ip != None: # Make sure URL gets resolved
                WriteURL( ip, cli[rd].split('+') )
        except:
            Error( 'comd', 6 )

def Help():
    print '\n    Written by', __authors__,  '- d0tmayhem.com - Version:', __version__
    print '\nUsage: rhosts [-redirect] [-to] [-reset] [-disp] [-rm] [-help]'
    print '\nOptions:'
    print '  -redirect :  List of URLs to redirect (URL1+URL2...), requires -to.'
    print '  -to       :  Single URL/IP to which all redirected traffic is sent.'
    print '  -reset    :  Writes a blank hosts file to the system.'
    print '  -disp     :  Displays the contents of the hosts file.'
    print '  -rm       :  Delete entries for given URL(s) from the hosts file.'
    print '  -help     :  Displays this message.'

def Error( type, i=0 ):
    if type == 'perm': print '\nError %d: You do not have administrative permissions.' % i
    if type == 'comd': print '\nError %d: Invalid command, see -help for more information.' % i
    os._exit(1)

# [ Main ] ==========================================================================
if __name__ == '__main__':
    if len( sys.argv ) > 1:
        Parse( sys.argv )
    else:
        Help()

Edited by sablefoxx
Link to comment
Share on other sites

Okay updated to v1.3;

- Now does a DNS Lookup instead of ping, still supports IP addresses

- Removals now supports groups, ie google.com+yahoo.com

- Bug fixes

Link to comment
Share on other sites

  • 2 weeks later...
Okay updated to v1.3;

- Now does a DNS Lookup instead of ping, still supports IP addresses

- Removals now supports groups, ie google.com+yahoo.com

- Bug fixes

nice work. have you considered taking a look at the ASE(android scripting environment)? assuming you have an android based phone you can use the ASE app( http://code.google.com/p/android-scripting/ ) to run python code. might be an easy way to get your code mobile.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...