Author Topic: [Python]My first program  (Read 1474 times)

0 Members and 1 Guest are viewing this topic.

Offline khofo

  • EZ's Swashbuckler
  • Knight
  • **
  • Posts: 350
  • Cookies: 25
  • My humor is so black, it could go cotton picking.
    • View Profile
[Python]My first program
« on: May 30, 2015, 12:49:46 am »
So, as u know I decided to learn python, I downloaded some books and all, but before starting with books and serious understanding of python I created a simple script to test my skills. I knew a bit how it worked from reading code, so I got my hands dirty and made one myself.
The script itself is extremely useless, maybe a troll, but as said before it was the first idea I got and wanted to see what I know.
google was my best friend, as most of the time I was seeing how some stuff worked, I got some help also from our very own super ninja programmer HTH, via IRC
I would also like to add that I did not copy paste anything from anywhere! I wrote it all myself, without snippets or anything, (Just the regex for the 0 or 000-255 range, hth gave it to me, but I went then to their website and understood how it worked;)


So here is the code:

Code: (Python) [Select]
print"////////////////////Khofo////////////////////////////////"
print"//////////////////PyCracker//////////////////////////////"
print"///////////////Version 1.0.0/////////////////////////////"
print"This application is intended for educational purposes only."
print"It shall be used with proper authorizations provided or by"
print"the system admin himslef"
print"---------------------------------------------------------"
print"This script is only effective on select number of clients"
print"////////////////Use at your own risks////////////////////"                                                       
#Define Target IP and
import re
while True:
    ip = raw_input("Please Enter Target IPv4 Address:")
    if re.match('^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]).([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]).([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]).([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$',ip):
#The regex thing courtesy of HTH       
        break
    print "ERROR:Invalid IPv4 Address Format try again"
#Now begins the trolololo
print"This is the target IP Address",ip
def start():
    print"Please define the target computer's OS"
    print"1.  Windows (xp and above)"
    print"2.  Linux"
    print"3.  Mac OS"
    print"4.  Other"
    os = raw_input("Number of the Target OS:")
   ##########################################
    if os == "1":
        print"Scanning Target"
        print"Identifying vulnerabilities in Windows"
        print"0%"
        print"25%"
        from time import sleep
        sleep(5)
        print"75%"                           #Yeah I was that bored
        sleep(5)
        print"Complete, exploiting.."
        print"Password Acquired!" #The Password is a random dictionarie word!
        import random
        words = [line.strip() for line in open('C:\Users\Joseph\Desktop\PyCracker\data.txt')]
        passwd = (random.choice(words))
        print"The password for the defined target is:",passwd
    elif os=="2":
        print"Scanning Target"
        print"Identifying vulnerabilities in Linux"
        print"0%"
        print"25%"
        from time import sleep
        sleep(5)
        print"75%"                           
        sleep(5)
        print"Complete, exploiting.."
        print"Password Acquired!"
        import random
        words = [line.strip() for line in open('C:\Users\*My name*\Desktop\PyCracker\data.txt')]
        passwd = (random.choice(words))
        print"The password for the defined target is:",passwd
    elif os =="3":
        print"Scanning Target"
        print"Identifying vulnerabilities"
        print"0%"
        print"25%"
        from time import sleep
        sleep(5)
        print"75%"                           
        sleep(5)
        print"Complete, exploiting.."
        print"Password Acquired!"
        import random
        words = [line.strip() for line in open('C:\Users\Khofo\Desktop\PyCracker\data.txt')]
        passwd = (random.choice(words))
        print"The password for the defined target is:",passwd       
   
     
    elif os == "4":
        print"Sorry other operating systems are not suported at the moment"
    else:
        print"Your input was Invalid, try again"
        start()
############################################################################
print start()
############################################################################
print"---------------------------------------------------------------------"
print"Thank for using PyCrack, the most easy and relialble password cracker"
print"//////////////////////////////////End///////////////////////////////"
raw_input("Press Enter to exit:")
print"Bye"   
############################################################################
#I know the protocol is 10000000% unrealistic but if I try this with my bro
#Or anyone who know nothing about computers I am sure he will believe me
#Anyway I did thi only to practice some python '
« Last Edit: November 15, 2015, 01:01:29 am by khofo »
Quote from: #Evilzone
<Spacecow18> priests are bad ppl
<Insanity> Holy crap
Of course God isnt dead. He's out there partying with the Easter Bunny, Santa Clause, Tooth Fairy, and the Man on the moon...
Some of my work: Introduction to Physical Security

Offline gray-fox

  • Knight
  • **
  • Posts: 208
  • Cookies: 52
    • View Profile
Re: [Python]My first program
« Reply #1 on: May 30, 2015, 10:58:26 am »
So this is like fake password cracker?
It's hard to say much about this kind of code because it's mostly just printing stuff, but I try.

About that ipv4 regex, I think you should have "\" escape characters before the dots for it to work properly.
Code: [Select]
if re.match('^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$',ip):

Well, otherwise i think the code does what it's suppose to. Which to ain't much. [emoji14]
If this had been some real tool I would have suggested to use arguments to get IP address and instead of asking OS trying to fingerprint it yourself.

The code itself could be structured much better. For e.g. do all importing in top, then define function(s) and then use:
Code: [Select]
if __name__ == "__main__":
Where you put stuff that will be executed.

If you really want to do proper learning try to do some script that actually does something, instead of something that just prints stuff to screen and pretends to do stuff.

That just my 2 cents.
« Last Edit: May 30, 2015, 03:32:02 pm by gray-fox »

Offline proxx

  • Avatarception
  • Global Moderator
  • Titan
  • *
  • Posts: 2803
  • Cookies: 256
  • ФФФ
    • View Profile
Re: [Python]My first program
« Reply #2 on: May 30, 2015, 11:51:37 am »
Well at least he knows how to use ; if
Wtf where you thinking with that signature? - Phage.
This was another little experiment *evillaughter - Proxx.
Evilception... - Phage

Offline chris

  • EZ's GOD
  • VIP
  • Knight
  • *
  • Posts: 197
  • Cookies: 37
  • What should I put here :(
    • View Profile
Re: [Python]My first program
« Reply #3 on: May 30, 2015, 11:55:45 am »
Long way to go but I guess everyone has to start somewhere... Good job?

Good luck on learning more about python...


 ;)
<chris1> give me a idea of a img to use for a avatar
<HTH> A cock

Offline khofo

  • EZ's Swashbuckler
  • Knight
  • **
  • Posts: 350
  • Cookies: 25
  • My humor is so black, it could go cotton picking.
    • View Profile
Re: [Python]My first program
« Reply #4 on: May 30, 2015, 02:41:09 pm »
So this is like fake password cracker?
It's hard to say much about this kind of code because it's mostly just printing stuff, but I try.

About that ipv4 regex, I think you should have "\" escape characters before the dots for it to work properly.
Code: [Select]
if re.match('^([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])\.([01]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])$',ip):

Well, otherwise i think the code does what it's suppose to. Which to be honest ain't that much. [emoji14]
If this had been some real tool I would have suggested to use arguments to get IP address and instead of asking OS trying to fingerprint it yourself. When it comes to the cide itself I know it's pretty useless and I would have learnt much more with an actual project. But the whole project was like:
 
-Mmm let's get an ide for debugging when I begin python.
-*wing ide 101 downloaded*
-Seems cool let's try it
-*print "khofo"*
-COOOL I WROTE PYTHON
-let's make something: the name?  PyCracker
-What should it do?
-fuck ywah let's make a fake password cracker
-Googling shit
-Posting to evilzone

The code itself could be structured much better. For e.g. do all importing in top, then define function(s) and then use:
Code: [Select]
if __name__ == "__main__":
Where you put stuff that will be executed.

If you really want to do proper learning try to do some script that actually does something, instead of something that just prints stuff to screen and pretends to do stuff.

That just my 2 cents.

Well first thank you for your time.

The IPv4 regex works fine acrially, and I recall HTH putting the \ before the dots. But I didin't.

But when it comes to strucrure  and content, I'll make sure to learn python proprely, since this cods was lke, writing some code, than seeeing how to do the thing next. So thank you for pointing srructural problems.

[EDIT]There is a part missing about why it was unstructured amd hoe it went, butt dunno why it wasn't posted anws too lazy to rewrite it
« Last Edit: May 30, 2015, 02:55:34 pm by Khofo »
Quote from: #Evilzone
<Spacecow18> priests are bad ppl
<Insanity> Holy crap
Of course God isnt dead. He's out there partying with the Easter Bunny, Santa Clause, Tooth Fairy, and the Man on the moon...
Some of my work: Introduction to Physical Security

Offline proxx

  • Avatarception
  • Global Moderator
  • Titan
  • *
  • Posts: 2803
  • Cookies: 256
  • ФФФ
    • View Profile
Re: [Python]My first program
« Reply #5 on: May 30, 2015, 03:21:52 pm »
Question is what does it do ?
Wtf where you thinking with that signature? - Phage.
This was another little experiment *evillaughter - Proxx.
Evilception... - Phage

Offline chris

  • EZ's GOD
  • VIP
  • Knight
  • *
  • Posts: 197
  • Cookies: 37
  • What should I put here :(
    • View Profile
Re: [Python]My first program
« Reply #6 on: May 30, 2015, 03:26:57 pm »
Question is what does it do ?

Answer is: absolutely nothing....

Educates the writer on the basics of python?
« Last Edit: May 30, 2015, 03:27:29 pm by chris1 »
<chris1> give me a idea of a img to use for a avatar
<HTH> A cock

Offline ColonelPanic

  • Serf
  • *
  • Posts: 27
  • Cookies: 7
    • View Profile
Re: [Python]My first program
« Reply #7 on: May 30, 2015, 04:10:58 pm »

While it doesn't do much, it looks like you've gotten some momentum in learning Python. Since you posted what you've tried, here's essentially the same program, but organized a little differently. Some notes:
  • Inclusion of shebang line
  • Moved imports to the top, where they generally belong
  • Menu is a little more dynamic (see how much easier it is to add an option here)
  • Moved functions into actual functions. (Google "DRY code")
  • Removed regex. Although your solution certainly works (and congrats on tackling regex this early), I'll let you research why I chose to do that. (Hint: https://xkcd.com/1171/)
Now, some homework, if you choose to accept it:
  • I want to run this program from the command line, like so "python crack.py <ip_address> <target_OS>". Use the sys module (or optparse/argparse) to make it happen.
  • Detect the operating system via platform module. Since this would only work on the local machine, see if you can open a socket to the requested IP and grab the banners.
  • Despite randomly choosing a vulnerability, this program will always give the same output. WHY?
  • In terms of reusing code, what's the advantage of the "if __name__ == '__main__'" block?
Code: [Select]
#!/usr/bin/env python
"""
PyCracker by Khofo


<Disclaimer here>
"""
import os, random


CLS='clear' # change to 'cls' for Windows, or use os.platform


def check_ip(ip):
    parts = [int(x) for x in ip.split('.')]
    if len(parts) == 4:
        if max(parts) <= 255 and min(parts) > 0:
            return True
    return False


def get_os():
    supported = ["Windows", "Linux", "OSX"]
    opt = None
    error = None
    while opt is None:
        os.system(CLS)
        if error:
            print error
        print(" Please define target computer's OS")
        for (i,opsys) in enumerate(supported):
            print(" %d) %s" % (i, opsys))
        print(" q) Quit")
       
        choice = raw_input(": ")
        if choice is 'q':
            quit()
        try:
            choice = int(choice)
            if choice not in range(1,5):
                error = "Invalid choice"
                continue
            opt = supported[choice]
        except (ValueError, IndexError):
            error = "Invalid choice"
    return opt


def check_vulns(ip):
    """A bogus function to check for vulns."""
    known_vulns = [
        None, None, None,
        'vuln A', None, 'vuln B',
        None, 'vuln C', None, 'vuln D'
        ]
    seed = 1
    random.seed(seed)
    return known_vulns[random.randint(0, len(known_vulns))]


def exploit_vulns(vuln):
    print("Exploiting %s" % vuln)
    return False


def scan_target(ip, opsys=None):
    opsys = opsys if opsys else "Unknown"
    print("Scanning target %s (OS: %s)" % (ip, opsys))
    vuln = check_vulns(ip)
    if vuln:
        print(" Found vulnerablity: %s" % vuln)
        if exploit_vulns(vuln):
            print(" Exploit successful!")
        else:
            print(" Exploit failed!")
    else:
        print("No vulnerabilities found!")


       
def main():
    opsys = get_os()
    valid_ip = None
    while valid_ip is None:
        ip = raw_input("Target IP: ")
        if not check_ip(ip):
            print("Invalid IP address")
            continue
        valid_ip = ip
    scan_target(ip, opsys)
    print("kthanxbai")


if __name__ == "__main__":
    main()

Finally, a SSCCE for the random problem:

Code: [Select]

import random
random.seed(1)
for i in range(100):
    print random.randint(1, 100)


Edit:
Some references (also submitted to eBooks section):
ViolentPython.pdf (Start here)

GrayHatPython.pdf

« Last Edit: May 30, 2015, 04:22:41 pm by ColonelPanic »

Offline khofo

  • EZ's Swashbuckler
  • Knight
  • **
  • Posts: 350
  • Cookies: 25
  • My humor is so black, it could go cotton picking.
    • View Profile
Re: [Python]My first program
« Reply #8 on: May 30, 2015, 04:28:55 pm »
Well thank you so much ColonelPanic, for this detailed critic.
Ofc I'll accept the homework. And thank you again for pointing out these stuff.
I'll surely also check the ebooks u pointed me to:)

+1
« Last Edit: May 30, 2015, 04:29:53 pm by Khofo »
Quote from: #Evilzone
<Spacecow18> priests are bad ppl
<Insanity> Holy crap
Of course God isnt dead. He's out there partying with the Easter Bunny, Santa Clause, Tooth Fairy, and the Man on the moon...
Some of my work: Introduction to Physical Security

Offline kenjoe41

  • Symphorophiliac Programmer
  • Administrator
  • Baron
  • *
  • Posts: 990
  • Cookies: 224
    • View Profile
Re: [Python]My first program
« Reply #9 on: May 31, 2015, 08:54:36 am »
Well, ColonelPanic did most of the heavy lifting so i will just move on.

Another real trick about printing those progress percentages, sys.stdout.write() mixed with sys.stdout.flush() could help alot and look cool. Read up man.
If you can't explain it to a 6 year old, you don't understand it yourself.
http://upload.alpha.evilzone.org/index.php?page=img&img=GwkGGneGR7Pl222zVGmNTjerkhkYNGtBuiYXkpyNv4ScOAWQu0-Y8[<NgGw/hsq]>EvbQrOrousk[/img]

Offline Kulverstukas

  • Administrator
  • Zeus
  • *
  • Posts: 6627
  • Cookies: 542
  • Fascist dictator
    • View Profile
    • My blog
Re: [Python]My first program
« Reply #10 on: May 31, 2015, 09:00:42 am »
Well, ColonelPanic did most of the heavy lifting so i will just move on.

Another real trick about printing those progress percentages, sys.stdout.write() mixed with sys.stdout.flush() could help alot and look cool. Read up man.
Good one. For the work indicator, I used one made by 10n1z3d in the past, I can't find the original post anymore, so here's the code:

Code: (python) [Select]
#!/usr/bin/env python
#
# Simple circle work indicator (for CLI).
#
# Copyright (C) 2010 10n1z3d <10n1z3d[at]w[dot]cn>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import sys, time
from threading import Thread


class WorkIndicator(Thread):
    def __init__(self, text=None):
        self.chars = ['/', '-', '\\', '|']
        self.index = 0
        self.text = text if text else 'Working...'
        self.stopping = False
        Thread.__init__(self)
       
    def run(self):
        while not self.stopping:
            if self.index >= len(self.chars): self.index = 0
            sys.stdout.write('\r{0} {1}'.format(self.text, self.chars[self.index]))
            sys.stdout.flush()
            self.index += 1
            time.sleep(0.1)
           
    def stop(self):
        self.stopping = True

# example usage

indicator = WorkIndicator(text='Testing...')
indicator.start()
time.sleep(5)     # simulate some work
indicator.stop()

Offline iTpHo3NiX

  • EZ's Pirate Captain
  • Administrator
  • Titan
  • *
  • Posts: 2920
  • Cookies: 328
    • View Profile
    • EvilZone
Re: [Python]My first program
« Reply #11 on: June 01, 2015, 05:00:57 pm »
Still better than starting off with hello world
[09:27] (+lenoch) iTpHo3NiX can even manipulate me to suck dick
[09:27] (+lenoch) oh no that's voluntary
[09:27] (+lenoch) sorry