Python (Old)

DOCS

Python Snippets

get the path of the 'script'

import os print os.path.dirname(os.path.realpath(_file_)) =======

TODO: (LEARN)

Args in Python

Quick and Dirty Arg

Here's a quick way to do args in python.

import sys
def main():
    if len(sys.argv) < 2:
        print 'Usage: ' + sys.argv[0] + ' <target-ip>'
        exit(-1)

sys.argv[1] will have the first arg.

OptionParser, only before and for 2.7

Option Parser is usually a better way to get args. Use OptionParser([usage message]) to create an instance of na option parser. Next, parser.add_option to specify the individual command line options.

Note: its a function/class from optparse. Note2: this is depercated since 2.7

argparse (the new way)

its a module, auto generates help and usage. Here is an example:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)

Docs at: https://docs.python.org/2/library/argparse.html#module-argparse

Read and Access check

Does this file exist?? And does this program/user have read access to the file??

import sys
import os
if len(sys.argv) == 2:
    filename = sys.argv[1]
    if not os.path.isfile(filename):
        print '[-] ' + filename + ' does not exist.'
        exit(0)
    if not os.access(filename, os.R_OK):
        print '[-] ' + filename + ' access denied.'
        exit(0)
    print '[+] Reading Vulnerabilities From: ' + filename

PIP: Update all distro python modules

This command could be CAN be dangerous to some modules. pip freeze --local | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 sudo pip install -U

Python, code to download video.

import requests
import re
from bs4 import BeautifulSoup

url_re = "\\b(?:https?|ftp)://[-_a-zA-Z0-9]+(?:\\.[-_a-zA-Z0-9]*)+[^) \\t<>\"]*"
pat = re.compile(url_re)

r = requests.get('http://patrickjmt.com')
soup = BeautifulSoup(r, "html.parser")

all_links = soup.select("ul > li > a")
count = 0
for link in all_links:
    count = count + 1
    listre = re.findall(pat, link)
    thelink = listre.pop()
    print("{}. {}".format(count, thelink)

Text Machine

See if this file is a jpeg.

if "\xff\xd8\xff" in filein[:3]:
    print "filebin is a jpeg."

pip

TopTip: ~/.cache/pip can get corrupted, its okay to delete it.

ProTip: To upgrade all packages: $ pip freeze --local | grep -v '^\-e' | cut -d = -f 1 | xargs -n1 pip install -U It might be a good idea to capture the 'freeze' to a file first. $ pip freeze --local > pip-freeze.list

virtualenv

$ pip install virtualenv $ mkdir <projectdir> $ cd <projectdir> $ virtualenv venv $ source venv/bin/activate $ deactivate

flask-ask on lamda

$ pip install flask-ask zappa requests awscli

Copy the code listings from the blog post to the file repo_stats.py, the code listing is at: https://gist.github.com/johnwheeler/ ??

Open a new tab: aws.amazon.com

$ aws configure Copy/Paste Key ID Copy/Paste Secret Access Key Default region name: us-east-1 Default output format: none <- just press return. $ zappa init

$ zappa deploy dev Make note of the URL, thats where the skill is hosted.

Goto browser, developer.amazon.com Click Alexa tab Add a new skill

Copy/Paste intents scheme Copy/Paste sample utterances

Choice HTTPS select north america. Copy/Paste the URL

Choose we're using wild card status.

Python Logging

a=re.search(r"(?P<areacode>)\d\d\d)-\d\d\d-\d\d\d\d") a.group()

Dictionaries

>>> d = {} ## empty >>> d['a'] = 'alpha' >>> d['b'] = 'bravo' >>> d['c'] = 'charlie' >>> d['a'] 'alpha' >>> d['whatever'] KeyError: 'whatever'

>>> d.get("a") 'alpha' >>> d.get("x")

from collections import Counter wrdcnt=Counter() wrdcnt.update( open("mobydict.txt").read().lower().split()) wrdcnt.most_common(10)

import antigravity <-- try it

http://bitbucket.org/jsthyer/bind9_logstat pythex.org <-- try it, test out regex.