Browse Source

First scripts

master
albakham 4 months ago
commit
29e178a632
No account linked to committer's email address

+ 1
- 0
Bash/calendar.sh View File

@@ -0,0 +1 @@
clear;cal|boxes -d diamonds -p a1t2l3|boxes -a c -d scroll|lolcat;sleep 3;while :;do echo $LINES $COLUMNS $(($RANDOM%$COLUMNS)) $(printf "\u2744\n");sleep 0.1;done|gawk '{a[$3]=0;for(x in a) {o=a[x];a[x]=a[x]+1;printf "\033[%s;%sH ",o,x;printf "\033[%s;%sH%s \033[0;0H",a[x],x,$4;}}'

+ 29
- 0
Bash/get.sh View File

@@ -0,0 +1,29 @@
#!/bin/bash
#===============================================================================
#
# FILE: get.sh
#
# USAGE: ./get.sh
#
# DESCRIPTION: Wget de masse
#
# AUTHOR: Albakham
# VERSION: 1.0
# CREATED: 22/05/2019 23:12:09 CEST
# DARCH (dossiers archéologie)
# DART (dossiers art)
# AM (archéologia)
# AJ (arkéo junior)
# SV (sports et vie)
# AE (art de enluminure)
# NOTE2: Autre Varible de nombre => num° ou HSnum° pour les hors-séries
#===============================================================================
i="1"

while [ "$i" != "700" ];
do wget "https://publications.faton.fr/flip/AE/$i/files/assets/common/downloads/publication.pdf"
wget "https://publications.faton.fr/flip/AE/HS$i/files/assets/common/downloads/publication.pdf"
i=$(($i+1))
echo "$i"
done
echo "Fin !"

+ 8
- 0
Bash/getBlocklist.sh View File

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

# Download lists, unpack and filter, write to stdout
curl -s https://www.iblocklist.com/lists.php \
| sed -n "s/.*value='\(http:.*=bt_.*\)'.*/\1/p" \
| xargs curl -Ls \
| gunzip \
| egrep -v '^#'

+ 6
- 0
Bash/speak.sh View File

@@ -0,0 +1,6 @@
intro="Tapez le texte à traduire : "
echo -n "$intro"
read text
echo "$text"

echo "$text" | /bin/espeak -vfr

+ 49
- 0
Powershell/update-hosts-for-powershell.bat View File

@@ -0,0 +1,49 @@
@echo off
Color 9B & Mode con cols=80 lines=5
Title Download and update the hosts file from hosts-blocklists
:::::::::::::::::::::::::::::::::::::::::
:: Automatically check & get admin rights
:::::::::::::::::::::::::::::::::::::::::
REM --> Check for permissions
Reg query "HKU\S-1-5-19\Environment" >nul 2>&1
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
Echo.
ECHO **************************************
ECHO Running Admin shell... Please wait...
ECHO **************************************
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"=""
echo UAC.ShellExecute "cmd.exe", "/c ""%~s0"" %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"
exit /B
:gotAdmin
::::::::::::::::::::::::::::
::START
::::::::::::::::::::::::::::
Set "URL=https://sebsauvage.net/hosts/hosts"
Set "FileLocation=%Windir%\System32\Drivers\etc\hosts"
Call:download "%url%" "%FileLocation%"
exit /b
:download
(echo src = "%~1"
echo Set v1 = CreateObject ("MSXML2.XMLHTTP"^)
echo Set v2 = CreateObject ("ADODB.Stream"^)
echo v1.open "GET", src, false
echo v1.send(^)
echo v2.open
echo v2.Type = 1
echo v2.Write v1.ResponseBody
echo v2.SaveToFile "%~2",2 ) >"%~dpn0.vbs"
cscript /nologo "%~dpn0.vbs"
del "%~dpn0.vbs" >nul
goto:eof

+ 66
- 0
Python/TwitterUrlExtractor.py View File

@@ -0,0 +1,66 @@
#!/usr/bin/env python
#-*- coding: utf-8 -*-

import re, sys, getopt, os
from datetime import datetime
import urllib2


def main(argv):
d = datetime.now()
date = str(d.year) + '' + str(d.month) + '' + str(d.day) + '' + str(d.hour) + '' + str(d.minute) + '' + str(d.second)
output = "./twitterUrlList_"+date+".txt"
input_f = None
url = None
data = None

try:
opts, args = getopt.getopt(argv, "hf:u:o:", ["input-file=", "input-url=", "output-file=", "help"])
except getopt.GetoptError:
print 'Use --help for help'
sys.exit(2)

for opt, arg in opts:
print opt
if opt in ("-h", "--help"):
print 'Usage: %s <options> \n' % (os.path.basename(__file__))
print ' -h, --help this help'
print ' -f, --input-file FILE Use file for extract urls twitter'
print ' -u, --input-url URL Use url for extract urls twitter'
print ' -o, --output-file FILE Output file for urls twitter'
sys.exit()
elif opt in ("-f", "--input-file"):
input_f = arg
elif opt in ("-u", "--input-url"):
url = arg
elif opt in ("-o", "--output-file"):
output = arg

if not input_f and not url:
print 'Use --help for help'
sys.exit(2)

if url:
response = urllib2.urlopen(url)
data = response.read()
elif input_f:
textfile = open(input_f, 'r')
data = textfile.read()
textfile.close()

URL_REGEX = r"""(?i)\b((?:https:\/\/)?(?:http:\/\/)?(?:www\.)?twitter\.com\/[^\s]+)\b/?(?!@)"""
urls = re.findall(URL_REGEX, data)

o = open(output, 'w')
for tw_url in urls:
o.write('%s\n' % (tw_url))
o.close()

print "finished extraction, result in %s" % (output)


if __name__ == "__main__":
try:
main(sys.argv[1:])
except KeyboardInterrupt:
sys.stdout.write('\nQuit by keyboard interrupt sequence!')

+ 10
- 0
Python/bissextile.py View File

@@ -0,0 +1,10 @@
#!/usr/bin/env python
# -*-coding:Utf-8 -*

annee = input("Entrez une année : ")
annee = int(annee)
bissextile = False
if annee % 400 == 0 or (annee % 4 == 0 and annee % 100 != 0):
print("L'année est bissextile !")
else:
print("L'année n'est pas bissextile :(")

+ 19
- 0
Python/fonctable.py View File

@@ -0,0 +1,19 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

nombre = input("Saisissez un nombre dont vous souhaitez calculer les tables (1 par défaut) : ")
max = input("Jusqu'où voulez-vous calculer les tables ? (9 par défaut) : ")
try:
nombre = int(nombre)
max = int(max)
except:
nombre = 1
max = 9
finally:
def table(nombre, max):
"Fonction affichant la table de multiplication par un nombre de 1*nombre à max*nombre \n (max >=0)"
i = 0
while i < max:
print(i + 1, "x", nombre, "=", (i + 1) * nombre)
i += 1
table(nombre, max)

+ 186
- 0
Python/keepass2csv2pass.py View File

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

# Copyright 2015 David Francoeur <dfrancoeur04@gmail.com>
# Copyright 2017 Nathan Sommer <nsommer@wooster.edu>
#
# This file is licensed under the GPLv2+. Please see COPYING for more
# information.
#
# KeePassX 2+ on Mac allows export to CSV. The CSV contains the following
# headers:
# "Group","Title","Username","Password","URL","Notes"
#
# By default the pass entry will have the path Group/Title/Username and will
# have the following structure:
#
# <Password>
# user: <Username>
# url: <URL>
# notes: <Notes>
#
# Any missing fields will be omitted from the entry. If Username is not present
# the path will be Group/Title.
#
# The username can be left out of the path by using the --name_is_original
# switch. Group and Title can be converted to lowercase using the --to_lower
# switch. Groups can be excluded using the --exclude_groups option.
#
# Default usage: ./keepass2csv2pass.py input.csv
#
# To see the full usage: ./keepass2csv2pass.py -h

import sys
import csv
import argparse
from subprocess import Popen, PIPE


class KeepassCSVArgParser(argparse.ArgumentParser):
"""
Custom ArgumentParser class which prints the full usage message if the
input file is not provided.
"""
def error(self, message):
print(message, file=sys.stderr)
self.print_help()
sys.exit(2)


def pass_import_entry(path, data):
"""Import new password entry to password-store using pass insert command"""
proc = Popen(['pass', 'insert', '--multiline', path], stdin=PIPE,
stdout=PIPE)
proc.communicate(data.encode('utf8'))
proc.wait()


def confirmation(prompt):
"""
Ask the user for 'y' or 'n' confirmation and return a boolean indicating
the user's choice. Returns True if the user simply presses enter.
"""

prompt = '{0} {1} '.format(prompt, '(Y/n)')

while True:
user_input = input(prompt)

if len(user_input) > 0:
first_char = user_input.lower()[0]
else:
first_char = 'y'

if first_char == 'y':
return True
elif first_char == 'n':
return False

print('Please enter y or n')


def insert_file_contents(filename, preparation_args):
""" Read the file and insert each entry """

entries = []

with open(filename, 'rU') as csv_in:
next(csv_in)
csv_out = (line for line in csv.reader(csv_in, dialect='excel'))
for row in csv_out:
path, data = prepare_for_insertion(row, **preparation_args)
if path and data:
entries.append((path, data))

if len(entries) == 0:
return

print('Entries to import:')

for (path, data) in entries:
print(path)

if confirmation('Proceed?'):
for (path, data) in entries:
pass_import_entry(path, data)
print(path, 'imported!')


def prepare_for_insertion(row, name_is_username=True, convert_to_lower=False,
exclude_groups=None):
"""Prepare a CSV row as an insertable string"""

group = escape(row[0])
name = escape(row[1])

# Bail if we are to exclude this group
if exclude_groups is not None:
for exclude_group in exclude_groups:
if exclude_group.lower() in group.lower():
return None, None

# The first component of the group is 'Root', which we do not need
group_components = group.split('/')[1:]

path = '/'.join(group_components + [name])

if convert_to_lower:
path = path.lower()

username = row[2]
password = row[3]
url = row[4]
notes = row[5]

if username and name_is_username:
path += '/' + username

data = '{}\n'.format(password)

if username:
data += 'user: {}\n'.format(username)

if url:
data += 'url: {}\n'.format(url)

if notes:
data += 'notes: {}\n'.format(notes)

return path, data


def escape(str_to_escape):
""" escape the list """
return str_to_escape.replace(" ", "-")\
.replace("&", "and")\
.replace("[", "")\
.replace("]", "")


def main():
description = 'Import pass entries from an exported KeePassX CSV file.'
parser = KeepassCSVArgParser(description=description)

parser.add_argument('--exclude_groups', nargs='+',
help='Groups to exclude when importing')
parser.add_argument('--to_lower', action='store_true',
help='Convert group and name to lowercase')
parser.add_argument('--name_is_original', action='store_true',
help='Use the original entry name instead of the '
'username for the pass entry')
parser.add_argument('input_file', help='The CSV file to read from')

args = parser.parse_args()

preparation_args = {
'convert_to_lower': args.to_lower,
'name_is_username': not args.name_is_original,
'exclude_groups': args.exclude_groups
}

input_file = args.input_file
print("File to read:", input_file)
insert_file_contents(input_file, preparation_args)


if __name__ == '__main__':
main()

+ 5
- 0
Python/monip.py View File

@@ -0,0 +1,5 @@
import urllib
url = 'http://myexternalip.com/raw'
myip = urllib.urlopen(url).read()

print myip

+ 58
- 0
Python/pass2keepass.py View File

@@ -0,0 +1,58 @@
#!/usr/bin/env python
from kppy.database import KPDBv1
import fnmatch, os, subprocess, getpass

pass_store_dir = os.path.expanduser('~/.password-store/')
keys = [ os.path.join(dirpath, fn)[len(pass_store_dir):-4]
for dirpath, dirnames, files in os.walk(pass_store_dir)
for fn in files if fn.endswith('.gpg')]

db = KPDBv1(new=True)

kpgroups = {}

def get_group(db, parent, kpgs, group_names):
group_name = group_names[0]
if group_name in kpgs:
kpgroup = kpgs[group_name][0]
else:
db.create_group(group_name, parent)

# WTF API design???
if parent == None:
kpgroup = db.groups[-1]
else:
kpgroup = parent.children[-1]

kpgs[group_name] = (kpgroup, {})

if len(group_names) == 1:
return kpgroup
else:
return get_group(db, kpgroup, kpgs[group_name][1], group_names[1:])

for key in keys:
cont = subprocess.check_output(['pass', 'show', key]).decode()
groups = key.split('/')
basename = groups.pop()

kpgroup = get_group(db, None, kpgroups, groups)

passwd, rest = cont.split('\n', 1)
url = ''
username = ''
comments = []
for line in rest.split('\n'):
if line.startswith('url: '):
url = line[len('url: '):]
elif line.startswith('username: '):
url = line[len('username: '):]
else:
comments.append(line)

kpgroup.create_entry(basename, url=url, username=username, password=passwd, comment='\n'.join(comments))

db.remove_group(db.groups[0]) # Internet group
db.save('pass-store.kdb', getpass.getpass('password for pass-store.kdb: '))
db.close()


+ 12
- 0
Python/tables.py View File

@@ -0,0 +1,12 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

nombre = input("Saisissez un nombre dont vous souhaitez calculer les tables : ")
nombre = int(nombre)
limite = input("Jusqu'où voulez-vous calculer les tables ? : ")
limite = int(limite)
i = 0
print("\n")
while i < limite:
print(i + 1, "x", nombre, "=", (i + 1) * nombre)
i += 1

+ 4
- 0
Python/test.py View File

@@ -0,0 +1,4 @@
#!/usr/bin/python
# -*-coding:Utf-8 -*



+ 78
- 0
Python/zcasino.py View File

@@ -0,0 +1,78 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from random import randrange
from math import ceil

lettre = "A"
while lettre != "":
print("\n\n\tBienvenue au Zcasino !\n\n\tIci vous pouvez jouer à la roulette pythonienne.")
lettre = input("\n\n\tPour continuer, appuyez sur la touche [ENTRER]\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
title = "========R=È=G=L=E=S========"
text = "\n\n\t- La roulette est consituée de 50 cases allant de 0 à 49,\n\tles numéros pairs sont de couleurs noirs,\n\tles impairs sont de couleur rouge.\n\n\t- Vous misez sur un numéro.\n\tEn choisissant ce numéro vous y déposez\n\tla somme que vous souhaitez miser.\n\n\t- Le croupier lance la roulette, lâche la bille,\n\tet quand la roulette s'arrête, relève le numéro de la case\n\tdans laquelle la bille s'est arrêtée.\n\n\t+ Si votre mise se trouve être sur le numéro gagnant,\n\talors vous gagnez 4 fois cette mise !\n\n\t+ Si votre mise est la même couleur que le numéro gagnant,\n\tvous gagnez la moitié des gains misés en plus de ceux-ci...\n\n"
lettre = "A"
while lettre != "":
print("{0}{1}".center(60).format(title, text))
lettre = input("\tPour continuer, appuyez sur la touche [ENTRER]\n")
argent = 100000
continuer_partie = True
print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n---------------------------------------------------------\n\nVous vous installez à la table de roulette avec", argent, "$.")
while continuer_partie:
nombre = -1
while nombre < 0 or nombre > 49:
nombre = input("\n\n\nEntrez le nombre sur lequel vous souhaitez effectuer votre mise, compris entre 0 et 49 :\n")
try:
nombre = int(nombre)
except ValueError:
print("Vous n'avez pas saisi de nombre")
nombre = -1
continue
if nombre < 0:
print("Ce nombre est négatif")
if nombre > 49:
print("Ce nombre est supérieur à 49")
mise = 0
while mise <= 0 or mise > argent:
mise = input("Tapez le montant de votre mise : ")
try:
mise = int(mise)
except ValueError:
print("Vous n'avez pas saisi de nombre")
mise = -1
continue
if mise <= 0:
print("La mise saisie est négative ou nulle.")
if mise > argent:
print("Vous ne pouvez miser autant, vous n'avez que", argent, "$")
win = randrange(50)
print("La roulette tourne... ... et s'arrête sur le numéro", win)
if win == nombre:
print("Félicitations ! Vous obtenez", mise * 3, "$ !")
argent += mise * 4
elif win % 2 == nombre % 2:
mise = ceil(mise * 0.5)
print("Vous avez misé sur la bonne couleur. Vous obtenez", mise, "$")
argent += mise
else:
print("Désolé l'ami, c'est pas pour cette fois. Vous perdez votre mise.")
argent -= mise
if argent <= 0:
print("Vous êtes ruiné ! C'est la fin de la partie.")
continuer_partie = False
else:
print("Vous avez à présent", argent, "$")
quitter = input("Souhaitez-vous quitter le casino (o/n) ?")
if quitter == "o" or quitter == "O":
print("Vous quittez le casino avec vos gains.")
continuer_partie = False

+ 1
- 0
Shell/calendar.sh View File

@@ -0,0 +1 @@
clear;cal|boxes -d diamonds -p a1t2l3|boxes -a c -d scroll|lolcat;sleep 3;while :;do echo $LINES $COLUMNS $(($RANDOM%$COLUMNS)) $(printf "\u2744\n");sleep 0.1;done|gawk '{a[$3]=0;for(x in a) {o=a[x];a[x]=a[x]+1;printf "\033[%s;%sH ",o,x;printf "\033[%s;%sH%s \033[0;0H",a[x],x,$4;}}'

+ 21
- 0
Shell/dd.sh View File

@@ -0,0 +1,21 @@
#!/bin/bash
#===============================================================================
#
# FILE: .SEED.sh
#
# USAGE: ./.SEED.sh
#
# DESCRIPTION: Montage intéractif de disque chiffré avec LUKS
# AUTHOR: Albakham
# CREATED: 23/05/2019 17:59:16 CEST
# REVISION: ---
#===============================================================================

echo "Entrez la lettre du disque chiffré à monter (/dev/sdX) :"
read disk

echo "Entrez le chemin du point de montage du disque :"
read mntpoint

sudo cryptsetup luksOpen "/dev/sd$disk" "sd$disk"
sudo mount "/dev/mapper/sd$disk" "$mntpoint"

+ 10
- 0
Shell/ddefect.sh View File

@@ -0,0 +1,10 @@
export i=0;
while true;
do
echo -n "$i ";
if dd if=/dev/sdb of=/dev/null count=1 skip=$i 2>/dev/null;
then echo OK ;
else echo KO; hdparm --write-sector $i /dev/sdb ;
fi;
let i+=1;
done

+ 2
- 0
Shell/fehbg.sh View File

@@ -0,0 +1,2 @@
#!/bin/sh
feh --bg-fill '~/.config/i3/wallpaper.jpg'

+ 8
- 0
Shell/getBlocklist.sh View File

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

# Download lists, unpack and filter, write to stdout
curl -s https://www.iblocklist.com/lists.php \
| sed -n "s/.*value='\(http:.*=bt_.*\)'.*/\1/p" \
| xargs curl -Ls \
| gunzip \
| egrep -v '^#'

+ 14
- 0
Shell/hibpwned.sh View File

@@ -0,0 +1,14 @@
function haveibeenpwned() {
echo "Enter password to check:"
stty -echo
read line
stty echo
echo
local sha1="$(echo -n "$line" | sha1sum - | cut -f1 -d' ')"
echo sha1 is "$sha1"
local prefix="$(echo "$sha1" | sed 's/\(.....\)\(.*\)/\1/')"
local suffix="$(echo "$sha1" | sed 's/\(.....\)\(.*\)/\2/')"
echo "Searching for prefix: $prefix and suffix: $suffix"
echo
curl "https://api.pwnedpasswords.com/range/$prefix" 2>/dev/null | grep -i "$suffix"
}

+ 6
- 0
Shell/speak.sh View File

@@ -0,0 +1,6 @@
intro="Tapez le texte à traduire : "
echo -n "$intro"
read text
echo "$text"

echo "$text" | /bin/espeak -vfr

Loading…
Cancel
Save