Python

Some python import and using

import string
import hashlib
import base64
import itertools
import collections
import os
import sys
import pwn
import random
import onetimepad
print "==========upper lower=========="
nama = "SYAHRUL"
namaB = "aulia"
namaKecil = nama.lower()
namaBesar = namaB.upper()
print namaKecil
print namaBesar


print "==========replace=========="
flag = "flagCTF{apa_yaaaa{{{}}}}"
flag = flag.replace('{', '')
print flag


print "==========string=========="
a = string.punctuation
b = string.digits
c = string.ascii_lowercase
# d = string.lowercase
e = string.ascii_uppercase
# f = string.uppercase
print a
print b
print c
print e


print "==========cycle=========="
cycler = "syahrul"
cycler = itertools.cycle(cycler)
cycler_new = [cycler.next() for _ in range(20)]
print ''.join(cycler_new)


print "==========index alphabet=========="
lwc = string.lowercase.index('s')	# s lowercase
print lwc


print "==========collections=========="
collLwc = collections.deque(string.lowercase)
print collLwc
collLwc.rotate(1)
print collLwc
collLwc_new = ''.join(collLwc)
print collLwc_new
print type(collLwc_new)
collLwc_new = ''.join(list(collLwc))
print collLwc_new
print type(collLwc_new)


print "==========permutations=========="
for p in itertools.permutations([1,2,4,'s'],4):
print p


print "==========hashlib=========="
mau_encode = "5Y4hRuL"
encode1 = base64.b64encode(mau_encode)


encode2 = hashlib.sha256()
encode2.update(mau_encode)
encode2 = encode2.hexdigest()


encode3 = hashlib.sha1()
encode3.update(mau_encode)
encode3 = encode3.hexdigest()


encode4 = hashlib.md5()
encode4.update(mau_encode)
encode4 = encode4.hexdigest()


print encode1
print encode2
print encode3
print encode4


print "==========string to list=========="
a = "12, 32, 4, 5, 56, 76"
a = a.split(',')
lst.sort(key = int)
print a


text = 'a,b,c'
text = eval('[' + text + ']')
print text

RSA

# tambahan dr http://www.factordb.com/
def egcd(a, b):
	if a == 0:
		return (b,0,1)
	else:
		g,y,x = egcd(b%a, a)
		return (g, x-(b//a)*y, y)


def modinv(a, m):
	g,x,y = egcd(a, m)
	if g != 1:
		raise Exception('modular inverse does not exist')
	else:
		return (x%m)

n = 113138904645172037883970365829067951997230612719077573521906183509830180342554841790268134999423971247602095979484887092205889453631416247856139838680189062511282674134361726455828113825651055263796576482555849771303361415911103661873954509376979834006775895197929252775133737380642752081153063469135950168223
p = 11556895667671057477200219387242513875610589005594481832449286005570409920461121505578566298354611080750154513073654150580136639937876904687126793459819369
q = 9789731420840260962289569924638041579833494812169162102854947552459243338614590024836083625245719375467053459789947717068410632082598060778090631475194567
e = 65537 # public key, umumnya 65537
d = modinv(e,(p-1)*(q-1))

# chiper text
c = 108644851584756918977851425216398363307810002101894230112870917234519516101802838576315116490794790271121303531868519534061050530562981420826020638383979983010271660175506402389504477695184339442431370630019572693659580322499801215041535132565595864123113626239232420183378765229045037108065155299178074809432

print hex(pow(c,d,n))[2:-1].decode('hex')

Python PIL

# the idea is converting the image to vertical position
from PIL import Image


gambar_asli = Image.open("out-copy.jpg")
data_gambar_asli = gambar_asli.load()
print(gambar_asli.size)
# width = 27968
# height = 1
# print(type(size))
width = 304
height = 92
gambar_baru = Image.new('RGB',(width,height))
data_gambar_baru = gambar_baru.load()


i = 0
for x in range(width):
for y in range(height):
# try:
data_gambar_baru[x,y] = data_gambar_asli[i,0]
i += 1
# except:
# break


gambar_baru.save("gambar_baru3.jpg")
gambar_baru.show()

Urllib

Request Method :

delete(url, args)
Sends a DELETE request to the specified url
get(url, params, args)
Sends a GET request to the specified url
head(url, args)
Sends a HEAD request to the specified url
patch(url, data, args)
Sends a PATCH request to the specified url
post(url, data, json, args)
Sends a POST request to the specified url
put(url, data, args)
Sends a PUT request to the specified url
request(method, url, args)
Sends a request of the specified method to the specified url

Some args :
url
Required. The url of the request
data
Optional. A dictionary, list of tuples, bytes or a file object to send to the specified url
json
Optional. A JSON object to send to the specified url
files
Optional. A dictionary of files to send to the specified url
allow_redirects
Optional. A Boolean to enable/disable redirection.
Default True (allowing redirects)
auth
Optional. A tuple to enable a certain HTTP authentication.
Default None
cert
Optional. A String or Tuple specifying a cert file or key.
Default None
cookies
Optional. A dictionary of cookies to send to the specified url.
Default None
headers
Optional. A dictionary of HTTP headers to send to the specified url.
Default None
proxies
Optional. A dictionary of the protocol to the proxy url.
Default None
stream
Optional. A Boolean indication if the response should be immediately downloaded (False) or streamed (True).
Default False
timeout
Optional. A number, or a tuple, indicating how many seconds to wait for the client to make a connection and/or send a response.
Default None which means the request will continue until the connection is closed
verify
Optional. A Boolean or a String indication to verify the servers TLS certificate or not.
Default True

Post Method :
requests.post(url, data={key: value}, json={key: value}, args) 
args means zero or more of the named arguments in the parameter table below. Example:
requests.post(url, data = myobj, timeout=2.50)

url diganti saja, dibawah ini cuman contoh url

# in python2 use urllib2
import urllib.request
import urllib.parse
import urllib.robotparser
from urllib.parse import * parse_url = urlparse('https://www.geeksforgeeks.org / python-langtons-ant/') 
# BEGINNER -------------------------------


import requests


x = requests.get('https://w3schools.com/python/demopage.htm')


print(x.text)


# -------------------------------


# delete(url, args)             Sends a DELETE request to the specified url
# get(url, params, args)        Sends a GET request to the specified url
# head(url, args)               Sends a HEAD request to the specified url
# patch(url, data, args)        Sends a PATCH request to the specified url
# post(url, data, json, args) 	Sends a POST request to the specified url
# put(url, data, args) 	        Sends a PUT request to the specified url
# request(method, url, args)    Sends a request of the specified method to the specified url


request_url = urllib.request.urlopen('http://timesink.be/speedy/')
print(request_url.read())


print(parse_url)
print("\n")
unparse_url = urlunparse(parse_url)
print(unparse_url)
bot = rb.RobotFileParser()


# checks where the website's robot.txt file reside 
x = bot.set_url('https://www.geeksforgeeks.org / robot.txt')
print(x)


# reads the files 
y = bot.read()
print(y)


# we can crawl the main site 
z = bot.can_fetch('*', 'https://www.geeksforgeeks.org/')
print(z)


# but can not crawl the disallowed url 
w = bot.can_fetch('*', 'https://www.geeksforgeeks.org / wp-admin/')
print(w)


print('Headers: ---------------------')
print(request_url.getheaders())


# print the actual response data
print('Returned data: ---------------------')
print(request_url.read().decode('utf-8'))


# ARGS PAYLOAD -------------------------------
url = 'http://httpbin.org/get'


# define sample data to pass to the GET request
args = {
'color': 'Blue',
'shape': 'Circle',
'is_active': True
}


# url-encoded data before passing as arguments
data = urllib.parse.urlencode(args)


# issue the request with the data params as part of the URL
result = urllib.request.urlopen(url + '?' + data)


print('Result code: {0}'.format(result.status))
print('Returned data: ----------------------')
print(result.read().decode('utf-8'))


# POST REQS -------------------------------


url = 'http://httpbin.org/post'


# define sample data to pass to the GET request
args = {
'color': 'Blue',
'shape': 'Circle',
'is_active': True
}


# url-encoded data before passing as arguments
data = urllib.parse.urlencode(args)


data = data.encode()
result = urllib.request.urlopen(url, data=data)


print('Result code: {0}'.format(result.status))
print('Returned data: ----------------------')
print(result.read().decode('utf-8'))


# ERROR HANDLING -------------------------------


from urllib.error import HTTPError, URLError
from http import HTTPStatus


url = 'http://httpbin.org/html'


# wrap the web request in a try catch block
try:
result = urllib.request.urlopen(url)
print('Result code: {0}'.format(result.status))
if (result.getcode() == HTTPStatus.OK):
print(result.read().decode('utf-8'))


# happens on a non-success error code
except HTTPError as err:
print('There was an HTTP Error with code: {0}'.format(err.code))


# happens when there is something wrong with the URL itself
except URLError as err:
print('There has been a catastrophic failure. {0}'.format(err.reason))


# Atau
url = 'http://i-dont-exist.org/'


# wrap the web request in a try catch block
try:
result = urllib.request.urlopen(url)
print('Result code: {0}'.format(result.status))
if (result.getcode() == HTTPStatus.OK):
print(result.read().decode('utf-8'))


# happens on a non-success error code
except HTTPError as err:
print('There was an HTTP Error with code: {0}'.format(err.code))


# happens when there is something wrong with the URL itself
except URLError as err:
print('There has been a catastrophic failure. {0}'.format(err.reason))

Module & Package

python modul & package

folder : # istilahnya package
file : # istilahnya modul

  • fungsi1.py
  • fungsi2.py
  • __init__.py

Praktek

mkdir paket; touch file_utama.py paket/fungsi1.py paket/fungsi2.py paket/__init__.py

lalu misal dengan isian

file_utama.py :

import paket

print paket.a

brute = paket.fungsi1.brute(2)

for i in brute:
	print i

fungsi1.py

from string import digits
import itertools

isi = []
def brute(j):
	brute = itertools.product(digits,repeat=j)
	for i in brute:
		tmp = ''.join(i)
		isi.append(tmp)
	return isi

fungsi2.py

a = 10

__init__.py :

import fungsi1
from fungsi2 import *

Kesimpulan

file1.py   ----\ 	
  └─> tes()     \
                 \
file2.py  --------\ __init__.py -> import folder
  └─> a          /
  └─> b         /
               /
file3.py ----/
             /
dsb         /

Struct

import struct

print "nilai 0xdeadbeef :", 0xdeadbeef, "type :", type(0xdeadbeef)

print "nilai 3735928559 :", hex(3735928559), "type :", type(hex(3735928559))

# 16 bit

"nilai struct H :", struct.pack("H", 0xdead)

"nilai struct <H :", struct.pack("<H", 0xdead)

"nilai struct >H :", struct.pack(">H", 0xdead)

# 32 bit

"nilai struct I :", struct.pack("I", 0xdeadbeef)

"nilai struct <I :", struct.pack("<I", 0xdeadbeef)

"nilai struct >I :", struct.pack(">I", 0xdeadbeef)

# 64 bit

"nilai struct Q :", struct.pack("Q", 0xdeadbeef)

"nilai struct <Q :", struct.pack("<Q", 0xdeadbeef)

"nilai struct >Q :", struct.pack(">Q", 0xdeadbeef)