Outils pour utilisateurs

Outils du site


blog

Notes Récupération de données

Voir :

Récupération de données :

  • ddrescue
  • Foremost
  • testdisk / photorec

Important : montage ro

2025/03/24 15:06

Réagir à une attaque DDOS exemple bash iptables

Note : iptables est remplacé maintenant par nftables

Source :

#! /bin/bash
while [ 1 ] ;
 do
 for ip in `lsof -ni | grep httpd | grep -iv listen | awk '{print $8}' | cut -d : -f 2 | sort | uniq | sed s/"http->"//` ;
 # the line above gets the list of all connections and connection attempts, and produces a list of uniq IPs
 # and iterates through the list
  do
    noconns=`lsof -ni | grep $ip | wc -l`;
    # This finds how many connections there are from this particular IP address
    echo $ip : $noconns ;
    if [ "$noconns" -gt "10" ] ;
    # if there are more than 10 connections established or connecting from this IP
    then
      # echo More;
      # echo `date` "$ip has $noconns connections.  Total connections to prod spider:  
      `lsof -ni | grep httpd | grep -iv listen | wc -l` >> /var/log/Ddos/Ddos.log
      # to keep track of the IPs uncomment the above two lines and make sure you can write to the appropriate place
      iptables -I INPUT -s $ip -p tcp -j REJECT --reject-with tcp-reset
      # for these connections, add an iptables statement to send resets on any packets recieved
    else
        # echo Less;
    fi;
  done
sleep 60
done
2025/03/24 15:06

RDP sous GNU/Linux (client)

Voir aussi (serveur) :

  • FreeRDP

rdesktop

xrandr | grep "\+$" | head -1 | awk '{print $1}'
rdesktop -P -x -m -z -a 16 -u utilisateur -d domaine -p motdepasse -g 1280x1024 -D 127.0.0.1
rdesktop -z -P -a 16 -g 1024x768 -u utilisateur -p 'P@ssw0rd' www.actinewsreseau.com:3089 -r disk:tmp=/home/jibe/tmp

plan écran ⇔ fenêtré [Ctrl] + [Alt] + [Enter]

rdesktop -0 est l'équivalent à mstsc /admin ou mstsc /console

Voir https://wiki.rrc.uic.edu/wiki/RRC-SCS:_Using_rdesktop_for_Linux

rdesktop -b -z -P -a 16 -g 1024x768 -u 'DOMAIN\user' -p P@ssw0d 178.33.12.210
rdesktop -z -P -a 16 -g 1024x768 -u utilisateur -p P@ssw0rd -r disk:tmp=/home/jean/tmp  38.59.153.12:3089
rdesktop -g 90% -r clipboard:CLIPBOARD windowsbox.net.lab

xfreerdp

xfreerdp /monitor-list
 
xfreerdp /u:user /d:DOMAIN /p:'P@ssw0rd' /v:server /drive:/home/jean/tmp +clipboard:on /w:1024 /h:768 /monitors:0
 
xfreerdp /u:user /d:DOMAIN /p:'P@ssw0rd' /v:server /drive:/home/jean/tmp +clipboard:on /monitors:1 /f
 
xfreerdp /v:localhost:3390 /drive:tmp,/home/jean/tmp /clipboard /monitors:1 /cert-ignore /compression /bpp:16 /network:modem /auto-reconnect /glyph-cache -themes -wallpaper /workarea -sec-nla

Ctrl + Alt + Enter pour quitter le plein écran

Pb
unexpected pubKeyAuth buffer size: 0
Could not verify public key echo!
Authentication failure, check credentials.
If credentials are valid, the NTLMSSP implementation may be to blame.
Error: protocol security negotiation or connection failure
Solution

ajouter l'option -sec-nla

2025/03/24 15:06

Sauvegarde rsync / rdiff-backup avec liste d'exclusion de fichiers

Nous créons un fichier avec les extensions, nom de dossiers et chemins à exclure

backup.rdiff.txt

~*
._*
*~
a_data/
a_data_00?/
ads
ads_00?
ads_00?.htm
ads00?.htm
ads_???.html
ads_data_*/
ads_data/
adServer.htm
ads.htm
ads.html
a.htm
cache/
Cache/
CACHE/
.cache
*.chk
CHKLIST.MS
.deleted/
desktop.ini 
*.dmp
.DS_Store
.fseventsd
ga.js
*.gid
googleadplayer.swf
imgad.jpg
imgad.swf
*.lock
lost+found/
*.met.bak
*.moztmp
*.old
*.part
*.part.met
*.part.met.txtsrc
phpmyvisites.js
*RECYCLE.BIN/
show_ads.js
.Spotlight-*/
*.temp
temp/
Temp/
TEMP/
thumbs.db
Thumbs.db 
*.tib
*.tmp
tmp/
Tmp/
TMP/
tracking.js
.Trash-*/
.Trash/
._.Trashes
.Trashes/
Trash/
urchin.js
webtrends*.js
WebTrends.js
wtid.js
xiti.js
xtclicks.js
xtcore.js
arcthumb/
Folder.htt
.directory
BBThumbs.dat
js.php
wikibits.js
*Resource*.axd
ix.e
ad.txt
a.js
.swfinfo
.bash_history
thumbnails/
SharedObjects/

Ici il s'agit d'un fichier exclusion rsync. Pour rdiff-backup la syntaxe est un peut différente. Pour le convertir il suffit :

cat backup.rdiff.txt | sed -e 's/^/**\//' | sed -e 's|/$|/**|'

Exemple :

rdiff-backup --exclude-other-filesystems --preserve-numerical-ids  --exclude-special-files --no-acls --exclude /home/jean/Backup --exclude-globbing-filelist <(cat backup.rdiff.txt | sed -e 's/^/**\//' | sed -e 's|/$|/**|') /home/jean /home/jean/Backup
2025/03/24 15:06

Draft Python3

List comprehensions and generator expressions

(short form: “listcomps” and “genexps”)

line_list = ['  line 1\n', 'line 2  \n', ' \n', '']
 
# Generator expression -- returns iterator
stripped_iter = (line.strip() for line in line_list)
 
# List comprehension -- returns list
stripped_list = [line.strip() for line in line_list]
 
stripped_list = [line.strip() for line in line_list if line != ""]
Autres
def inc(f, id):
    """ Exemple : inc(lambda x : x+1, 0) """
    try :
        global counter
        counter = f(counter)
    except NameError:
        counter = 0
    return counter

http://mgautier.fr/blog/Astuce/changer-lenvironnement-bash-avec-python.html


List unique remove duplicate

Source : http://stackoverflow.com/questions/89178/in-python-what-is-the-fastest-algorithm-for-removing-duplicates-from-a-list-so

def unique(items):
    found = set([])
    keep = []
    for item in items:
        if item not in found:
            found.add(item)
            keep.append(item)
    return keep

How do you split a list into evenly sized chunks in Python?

Source : http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python

def chunks(l, n):
    n = max(1, n)
    return [l[i:i + n] for i in range(0, len(l), n)]

Determine if variable is defined in Python

http://stackoverflow.com/questions/1592565/determine-if-variable-is-defined-in-python

try:
  thevariable
except NameError:
  print "well, it WASN'T defined after all!"
else:
  print "sure, it was defined."

I think it's better to avoid the situation. It's cleaner and clearer to write:

a = None
if condition:
    a = 42

Getting file size in Python

http://stackoverflow.com/questions/6591931/getting-file-size-in-python

def get_Size(file):
    file.seek(0,2) # move the cursor to the end of the file
    size = file.tell()
    return size

Exemple :

with open('plop.bin','rb') as file:
    size=get_Size(file)
 
with open('plop.bin','rb') as file:
    #size=get_Size(file)
    for i in range(size):
        un, deux = read_hexafile()
        msg.append(un)
        msg.append(deux)

/dev/null

fnull = open(os.devnull, 'w')

Message d'erreur

How to print to stderr in Python?

http://stackoverflow.com/questions/5574702/how-to-print-to-stderr-in-python

def warning(*objs):
    print(*objs, file=sys.stderr)

Conversion hexa

import numpy as np
 
carac=re.sub('^','0x',carac)
carac= int(carac, 16)
print(carac)
file.write(np.byte(carac))
 
 
with open('plop.bin', 'bw') as file:
        file.write(b'\x50\x40\x73')
 
 
hex(11) # '0xb'
 
a = int('0x100', 16)
print(a)   #256
print('%x' % a) #100
 
import binascii
binascii.unhexlify('7061756c')  # b'paul'
 
"{0:8b}".format(int("a",16))    # '    1010'

http://stackoverflow.com/questions/16843108/how-to-read-a-hex-file-into-numpy-array

with open(myfile) as f:
    iv = binascii.unhexlify(f.readline().strip())
    key = binascii.unhexlify(f.readline().strip())
    count = int(f.readline())
    a = np.fromiter((binascii.unhexlify(line.strip()) for line in f), dtype='|S16')
hashlib.sha512('Bonjour'.encode('utf-8')).hexdigest()
hex(int.from_bytes('Bonjour'.encode('utf-8'), 'big'))

Créer un Dictionnaire à partir de deux listes (l'une clef, l'autre valeur)

clef = ['a', 'b', 'c']
valeur = [1, 2, 3]
dictionnaire=dict(zip(clef, valeur))

Test

Voir :

  • nox
  • unittest

Exception

http://stackoverflow.com/questions/16138232/is-it-a-good-practice-to-use-try-except-else-in-python

try:
    s   
except NameError:
    pass
else: # If no exception occured, do :
    s.user.logout()

Temps / time

Voir :

  • timeit
start = time.time()
UnifiedJob.objects.filter(id=1096679).update(status='canceled')
end = time.time()
 
print(end - start)

Strings

Debug

Source : https://www.geekarea.fr/wordpress/?p=763

Level 1

f = open('/tmp/debug','a')
f.write(variable + '\n')
f.close()

Level 2

from pprint import pprint
pprint(variable.__class__.__name__, f)
pprint(dir(variable), f)
pprint(vars(variable), f)

Level 3 (sur une exception)

import traceback
f.write(str(traceback.format_exc()))

map reduce filter

Aures

A noter que sur RedHat 8 le chemin vers python est /usr/libexec/platform-python

2025/03/24 15:06
blog.txt · Dernière modification : de 127.0.0.1

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki