snippets / nicoj / 

All nicoj's snippets (8)

  1. connection a une base de donnée MySQL en C

    Code en C permettant l'accès a une base de donnée MySQL C code wich permit MySQL access

     1 /*********************************************************
    2 **Attention il est impératif de compiler ce code avec l'option de compilation -lmysqlclient
    3 **********************************************************/
    4
    5 #include <stdio.h>
    6 #include <errno.h>
    7 #include <stdlib.h>
    8 #include <iostream.h>
    9 #include <fstream>
    10 #include <mysql/mysql.h>
    11 #include <sys/types.h>
    12 #include <sys/wait.h>
    13
    14 #define MY_SERVER_HOST "localhost"
    15 #define MY_SERVER_PORT 0
    16 #define MY_ACCOUNT "root"
    17 #define MY_PASS "test"
    18 #define MY_DB_NAME "itest"
    19 #define MY_TABLE_NAME "test_tbl"
    20 #define MY_UX_SOCK NULL
    21 #define MY_CLIENT_FLAG 0
    22
    23 void main()
    24 {
    25 MYSQL *mysql;
    26 MYSQL_RES *res;
    27 MYSQL_ROW row;
    28 MYSQL_ROW rowchamps;
    29 const char *query;
    30 string qutmp;
    31
    32 int t,f,tt,ff;
    33
    34 mysql=mysql_init(NULL);
    35
    36 if (!mysql_real_connect(mysql,MY_SERVER_HOST,MY_ACCOUNT,MY_PASS,bd,MY_SERVER_PORT,MY_UX_SOCK,MY_CLIENT_FLAG)) {
    37 printf( "Erreur de connexion : %s\n",mysql_error(mysql));
    38 }
    39 else {
    40 qutmp = "SHOW FULL COLUMNS FROM TABLE ";
    41 query = qutmp.c_str();
    42 t=mysql_real_query(mysql, query, (unsigned int) strlen(query));
    43 if((res=mysql_use_result(mysql))) {
    44 f=mysql_num_fields(res);
    45 while((row=mysql_fetch_row(res))) {
    46 for(f=0;f<t;f++){
    47 cout<<row[f]<<endl;
    48 }
    49 }
    50 mysql_free_result(res);
    51 }
    52 }
    53 mysql_close(mysql);
    54 }
    first posted by cybersax to c c c++ ... saved by 7 persons ... 0 comments ... 1 year
  2. Lire dand un fichier .ini

    Fichier .ini dans le repertoire d'execution: [SECTION] key=value keyInt=123

    1 char filename[MAX_PATH];
    2 ::GetModuleFileName( NULL, filename, MAX_PATH-1);
    3 string str = filename;
    4 string path = str.substr( 0, str.find_last_of("\\") );
    5 path += "\\config.ini";
    6 char val[255];
    7 ::GetPrivateProfileString( "SECTION", "key", "", val, sizeof(val), path.c_str() );
    8 int iVal = ::GetPrivateProfileInt( "SECTION", "keyInt", -1, path.c_str() );
  3. fit crop an image with proportions

    crop an image or fit it to to size you want. It's based on imag center.

     1 def fit_crop(file_path, max_width=None, max_height=None, save_as=None):
    2 # Open file
    3 img = Image.open(file_path)
    4
    5 # Store original image width and height
    6 w, h = float(img.size[0]), float(img.size[1])
    7
    8 # Use the original size if no size given
    9 max_width = float(max_width or w)
    10 max_height = float(max_height or h)
    11
    12 # Find the closest bigger proportion to the maximum size
    13 scale = max(max_width / w, max_height / h)
    14
    15 # Image bigger than maximum size?
    16 if (scale < 1):
    17 # Calculate proportions and resize
    18 w = int(w * scale)
    19 h = int(h * scale)
    20 img = img.resize((w, h), Image.ANTIALIAS)
    21 #
    22
    23 # Avoid enlarging the image
    24 max_width = min(max_width, w)
    25 max_height = min(max_height, h)
    26
    27 # Define the cropping box
    28 left = int((w - max_width) / 2)
    29 top = int((h - max_height) / 2)
    30 right = int(left + max_width)
    31 bottom = int(top + max_height)
    32
    33 # Crop to fit the desired size
    34 img = img.crop( (left, top, right, bottom) )
    35
    36 # Save in (optional) 'save_as' or in the original path
    37 img.save(save_as or file_path)
    38
    39 return True
    first posted by benoitc to python images resize crop ... saved by 3 persons ... 0 comments ... 1 year
  4. parseURL

    Permet de parser un texte de type textarea contenant des urls et de les extraire. Renvoie un objet element. Le code intégral pour twitter est ici http://www.rsr.ch/la-1ere/twitter.js

     1 function parseURL(text) {
    2
    3 // the main tag to be returned
    4 var texttag = document.createElement('span');
    5 //url regex
    6 var url_pattern = /http[\S\.\/:]*/;
    7 var urls = text.match(/http[\S\.\/:]*/g);
    8 var url = '';
    9
    10
    11 if (urls) {
    12
    13 var index_text = 0; //
    14 for (url in urls) {
    15
    16 if ( ! isNaN(Number(url)) ) { // IE 6 ?? Plone ?? Plone & IE6 ?? ME ??
    17 //alert(parseInt(url));
    18 var url_index_start = text.indexOf(urls[url]);
    19 var url_index_end = urls[url].length;
    20
    21 // create text part tag
    22 if (url_index_start > 0 ) { // don't create an empty span tag
    23 if ( url > 0 ) index_text = urls[ url-1 ].length + 1; // first text element
    24 var text_part = text.substring(index_text, url_index_start);
    25 var text_part_tag = document.createElement('span');
    26 text_part_tag.appendChild(document.createTextNode(text_part));
    27 index_text = text_part.length + url_index_end;
    28 // append tag
    29 texttag.appendChild(text_part_tag);
    30 }
    31
    32 // create link tag
    33 var linktag = document.createElement('a');
    34 linktag.setAttribute('href', urls[url])
    35 linktag.appendChild(document.createTextNode(urls[url]));
    36 // append tag
    37 texttag.appendChild(linktag);
    38
    39 // create last text part tag
    40 if ( url == urls.length-1 ) {
    41 var last_text_part = text.substring(url_index_start+url_index_end);
    42 var last_text_part_tag = document.createElement('span');
    43 last_text_part_tag.appendChild(document.createTextNode(last_text_part));
    44 texttag.appendChild(last_text_part_tag);
    45 }
    46 }
    47 }
    48 }
    49 else {
    50 var texttag_text = document.createTextNode(text)
    51 texttag.appendChild(texttag_text);
    52 }
    53 return texttag;
    54 }
    first posted by nicedexter to javascript twitter parse urls ... saved by 3 persons ... 0 comments ... 1 year
  5. Fuzzer for dhcp protocol

    Fuzz dhcp protocol. Need scapy to work.

      1 #!/usr/bin/env python
    2 # -*- coding: iso-8859-1 -*-
    3 #
    4 # 04/01/2007
    5 #
    6 # "Tous les matins je me léve, je casse le vent, je fais chier les gens"
    7 # -- brice
    8 #By : SM
    9 import logging
    10 import os
    11 import sys
    12 from itertools import ifilter
    13 from random import randint, choice
    14 from scapy import *
    15
    16 __metaclass__ = type # Use new-style classes by default
    17
    18
    19 if True:
    20 # logs
    21 logging.getLogger("scapy").setLevel(1)
    22
    23 LOGPATH = os.getcwd()
    24 # setup logging functionality
    25 logging.basicConfig(level=logging.DEBUG,
    26 format='%(levelname)s %(message)s',
    27 filename=os.path.join(LOGPATH, 'fuzzer.log'),
    28 filemode='wb')
    29 console = logging.StreamHandler()
    30 console.setLevel(logging.INFO)
    31 logging.getLogger('').addHandler(console)
    32
    33
    34
    35 fid = lambda x: x
    36
    37 # taken from elsewhere
    38 formatstrings = ["", "", "", "%s" * 4, "%s" * 8, "%s" * 15, "%s" * 30, "%x" * 1024, "%n" * 1025 , "%s" * 2048, "%s%n%x%d" * 5000, "%s" * 30000, "%s" * 40000, "%.1024d", "%.2048d", "%.4096d", "%.8200d", "%99999999999s", "%99999999999d", "%99999999999x", "%99999999999n", "%99999999999s" * 1000, "%99999999999d" * 1000, "%99999999999x" * 1000, "%99999999999n" * 1000, "%08x" * 100, "%%20s" * 1000,"%%20x" * 1000,"%%20n" * 1000,"%%20d" * 1000, "%#0123456x%08x%x%s%p%n%d%o%u%c%h%l%q%j%z%Z%t%i%e%g%f%a%C%S%08x%%#0123456x%%x%%s%%p%%n%%d%%o%%u%%c%%h%%l%%q%%j%%z%%Z%%t%%i%%e%%g%%f%%a%%C%%S%%08x"]
    39
    40
    41 def frange(b):
    42 r = [-1, 0]
    43 for i in range(b):
    44 e = 2**i
    45 r.append(e)
    46 r.append(e-1)
    47 return r
    48
    49 class RandFormatString:
    50 def __init__(self, size, fstr=formatstrings):
    51 self.fstr = fstr
    52 self.size = size
    53
    54 def __call__(self):
    55 # fixme: pas varier un peu plus ?
    56 return choice(self.fstr)[:self.size]
    57
    58 class FRandNum:
    59 def __init__(self, size):
    60 self.size = size
    61
    62 def __call__(self):
    63 return choice(frange(self.size))
    64
    65
    66 def newrandval(self):
    67 fmtt = self.fmt[-1]
    68 if fmtt in "BHIQ":
    69 return {"B":FRandNum(8), "H":FRandNum(16), "I":FRandNum(32),
    70 "Q":RandLong}[fmtt]()
    71 elif fmtt == "s":
    72 if self.fmt[0] in "0123456789":
    73 l = int(self.fmt[:-1])
    74 else:
    75 l = int(self.fmt[1:-1])
    76 return RandFormatString(l)()
    77 else:
    78 warning("no random class for [%s] (fmt=%s)." % (self.name, self.fmt))
    79
    80 Field.randval = newrandval
    81
    82
    83 class Stat:
    84 def __init__(self):
    85 self.stats = {}
    86
    87 def inc(self, ff):
    88 name = ff.name
    89 if not name:
    90 return
    91 if name in self.stats:
    92 self.stats[name] = (self.stats[name][0] + 1, ff.prio)
    93 else:
    94 self.stats[name] = (1, ff.prio)
    95
    96 def __repr__(self):
    97 return '\n%-25s %-8s %s\n' % ('field', 'count', 'prio') + \
    98 ''.join(["%-25s %-8d %d\n" % (k,c,p) \
    99 for k, (c, p) in self.stats.iteritems()]) + \
    100 '%-25s %-8d\n' % ('Total:', sum(map(lambda x: x[0],
    101 self.stats.values())))
    102
    103 def __str__(self):
    104 return repr(self)
    105
    106
    107 class FF:
    108 prio_def = 10
    109 prio_min = 1
    110 prio_max = 20
    111
    112 def __init__(self, fields, prio=None):
    113 self.name = ''
    114 self.fields = []
    115 for i in fields:
    116 if isinstance(i, Field):
    117 self.name += i.name
    118 self.fields.append(i)
    119 self.prio = prio or FF.prio_def
    120
    121 def __add__(self, other):
    122 self.prio = min(FF.prio_max, self.prio + other)
    123 return self
    124
    125 def __sub__(self, other):
    126 self.prio = max(FF.prio_min, self.prio - other)
    127 return self
    128
    129
    130 class Fuzz:
    131 """ add flexibility to fuzz() """
    132 include = []
    133 exclude = []
    134 cls = None
    135
    136 def __init__(self, force=True, verbose=True):
    137 self.verbose = verbose
    138 self.force = force
    139 self.ff = []
    140 self.current = None
    141 self.initfields()
    142
    143 def initfields(self):
    144 for grp in self.include:
    145 acc = []
    146 for name in filter(lambda f: f not in self.exclude, grp[0]):
    147 for field in self.cls.fields_desc:
    148 if field.name == name:
    149 acc.append(field)
    150 self.ff.append(FF(acc))
    151 self.ff.extend(map(lambda x: FF([x]),
    152 filter(lambda f: f.name not in self.exclude,
    153 self.cls.fields_desc)))
    154
    155 def pickone(self):
    156 # fixme: gerer un random sur les combinaisons
    157 l = []
    158 for ff in self.ff:
    159 for i in range(ff.prio):
    160 l.append(ff)
    161 self.current = choice(l)
    162
    163 def fuzz(self, pkt, inplace):
    164 cpkt = pkt
    165 if not inplace:
    166 cpkt = pkt.copy()
    167
    168 self.pickone()
    169 for field in self.current.fields:
    170 rnd = field.randval()
    171 if rnd is not None:
    172 if self.force:
    173 cpkt.fields[field] = rnd
    174 else:
    175 cpkt.default_fields[field] = rnd
    176 if self.verbose:
    177 logging.info('> fuzz %s with value=%s' % (field, rnd))
    178 return cpkt
    179
    180 def penalize(self):
    181 self.current -= 1
    182
    183 def reward(self):
    184 self.current += 1
    185
    186 def __call__(self, pkt, inplace=False):
    187 return self.fuzz(pkt, inplace)
    188
    189
    190 class BOOTPFuzz(Fuzz):
    191 cls = BOOTP
    192 include = [(('htype', 'hlen', 'chaddr'), 10), # 10 <=> None
    193 (('hlen', 'chaddr'), 10)]
    194 exclude = []
    195
    196 def __call__(self, pkt, inplace=False):
    197 assert(isinstance(pkt, BOOTP))
    198 return Fuzz.fuzz(self, pkt, inplace)
    199
    200
    201 class DHCPFuzz(Fuzz):
    202 cls = DHCP
    203 include = []
    204 exclude = []
    205
    206 def __call__(self, pkt, inplace=False):
    207 assert(isinstance(pkt, DHCP))
    208 return Fuzz.fuzz(self, pkt, inplace)
    209
    210
    211 def fuzz_it(fuzz_bootp=fid, fuzz_dhcp=fid, **kargs):
    212 pkt, ans = (None, None)
    213 iface = conf.iface
    214 fam,hw = get_if_raw_hwaddr(iface)
    215 try:
    216 pkt = (Ether(dst="ff:ff:ff:ff:ff:ff") /
    217 IP(src="0.0.0.0", dst="255.255.255.255") /
    218 UDP(sport=68, dport=67) /
    219 fuzz_bootp(BOOTP(chaddr=hw)) /
    220 fuzz_dhcp(DHCP(options=[("message-type", "discover"), "end"])))
    221 logging.debug('> packet sent:%s' % pkt)
    222 ans = srp1(pkt, iface=iface,**kargs)
    223 logging.debug('> packet received:%s' % ans)
    224 except Exception, err:
    225 logging.info('> error in sending packet: %s' % err)
    226 if isinstance(pkt, Packet):
    227 pkt.show()
    228 else:
    229 return ans
    230
    231
    232 def is_up(ans, verbose=True):
    233 if ans is None or BOOTP not in ans:
    234 logging.info('> reception error: packet invalid')
    235 return False
    236 if verbose:
    237 logging.info('> request well performed, attributed ip: %s' % \
    238 ans[BOOTP].yiaddr)
    239 return True
    240
    241
    242 def make_fuzz(iface=None, verbose=True):
    243 # conf
    244 conf.checkIPaddr = 0
    245 if iface:
    246 conf.iface = iface
    247
    248 # stats
    249 stats = Stat()
    250
    251 # fuzzers
    252 fuzz_bootp = BOOTPFuzz(verbose=True)
    253 fuzz_dhcp = fid # DHCPFuzz(verbose=True)
    254
    255 # infinite fuzzing
    256 count = 0
    257 while True:
    258 logging.info('>>>> Iteration %d' % count)
    259
    260 # fuzzed packet
    261 ansf = fuzz_it(fuzz_bootp=fuzz_bootp, fuzz_dhcp=fuzz_dhcp, timeout=10)
    262 fres = is_up(ansf)
    263 stats.inc(fuzz_bootp.current)
    264
    265 # valid packet
    266 ansv = dhcp_request() #fixme: timeout 30s ?
    267 vres = is_up(ansv)
    268
    269 # feedback
    270 if not fres:
    271 fuzz_bootp.penalize()
    272 #fuzz_dhcp.penalize() #fixme: useless
    273 else:
    274 fuzz_bootp.reward()
    275 #fuzz_dhcp.reward() #fixme: useless
    276
    277 # stats
    278 if not (count % 20):
    279 logging.info('%s' % stats)
    280 count += 1
    281
    282
    283 if __name__ == "__main__":
    284 #make_fuzz('eth0') # force to this interface
    285 make_fuzz()
    first posted by nicoj to python fuzzer ... saved by 2 persons ... 0 comments ... 1 year
  6. Fuzzer client pop

    Fuzzer of pop clients like thunderbird, outllok ... The fuzzer need nc to work.

      1 #!/usr/bin/python
    2 #
    3 # 17/04/2007
    4 # Created by : pilihat
    5 # example:
    6 # ./FuzzerPopClient.py
    7 #
    8 #
    9
    10 import os
    11 import time
    12 import fcntl
    13
    14 class doCmd:
    15 def __init__(self,cmd,timeout=1,args=None):
    16 self.cmd = cmd
    17 self.fread = None
    18 self.fwrite = None
    19 self.timeout = timeout
    20 self.args = args
    21 self.current_cmd = ""
    22 self.response = ""
    23 self.write_error = 0
    24
    25 def __call__(self):
    26 self.do_command()
    27 self.no_wait_command()
    28 return self
    29
    30 def do_command(self):
    31 print self.cmd+" "+self.args
    32 try:
    33 self.fwrite,self.fread = os.popen2(self.cmd+" "+self.args)
    34 except:
    35 print "Failed to exec comand"
    36 return "-1"
    37
    38 def no_wait_command(self):
    39 # fdw = self.fwrite.fileno()
    40 # flw = fcntl.fcntl(fdw, fcntl.F_GETFL)
    41 # fcntl.fcntl(fdw, fcntl.F_SETFL, flw | os.O_NONBLOCK)
    42
    43 # fdr = self.fread.fileno()
    44 # flr = fcntl.fcntl(fdr, fcntl.F_GETFL)
    45 # fcntl.fcntl(fdr, fcntl.F_SETFL, flr | os.O_NONBLOCK)
    46 return 0
    47
    48 def write_to_command(self, toWrite):
    49 try:
    50 self.current_cmd = toWrite
    51 print "> Send "+toWrite
    52 self.fwrite.write(toWrite+"\n")
    53 self.fwrite.flush()
    54 except:
    55 self.write_error = self.write_error+1
    56 print 'Command failed: '+toWrite
    57 return "-2"
    58
    59 def read_from_command(self):
    60 self.response=""
    61 try:
    62 self.fread.flush()
    63 self.response = self.fread.readline()
    64 if self.response != "":
    65 print "< Read "+self.response
    66 return self.response
    67 except:
    68 #print "Failed to read response after command "+self.current_cmd
    69 return "-3"
    70
    71 def close_command(self):
    72 self.fread.close()
    73 self.fwrite.close()
    74 return 0
    75
    76 def timeout_command(self):
    77 time.sleep(self.timeout)
    78
    79
    80 # taken from taof - http://sourceforge.net/projects/taof
    81 formatstrings = ["", "", "", "%s" * 4, "%s" * 8, "%s" * 15, "%s" * 30, "%x" * 1024, "%n" * 1025 , "%s" * 2048, "%s%n%x%d" * 5000, "%s" * 30000, "%s" * 40000, "%.1024d", "%.2048d", "%.4096d", "%.8200d", "%99999999999s", "%99999999999d", "%99999999999x", "%99999999999n", "%99999999999s" * 1000, "%99999999999d" * 1000, "%99999999999x" * 1000, "%99999999999n" * 1000, "%08x" * 100, "%%20s" * 1000,"%%20x" * 1000,"%%20n" * 1000,"%%20d" * 1000, "%#0123456x%08x%x%s%p%n%d%o%u%c%h%l%q%j%z%Z%t%i%e%g%f%a%C%S%08x%%#0123456x%%x%%s%%p%%n%%d%%o%%u%%c%%h%%l%%q%%j%%z%%Z%%t%%i%%e%%g%%f%%a%%C%%S%%08x"]
    82
    83 #formatstrings = ["%99999999999n","%99999999999s" * 1000, "%99999999999d" * 1000, "%99999999999x" * 1000, "%99999999999n" * 1000, "%08x" * 100, "%%20s" * 1000,"%%20x" * 1000,"%%20n" * 1000,"%%20d" * 1000, "%#0123456x%08x%x%s%p%n%d%o%u%c%h%l%q%j%z%Z%t%i%e%g%f%a%C%S%08x%%#0123456x%%x%%s%%p%%n%%d%%o%%u%%c%%h%%l%%q%%j%%z%%Z%%t%%i%%e%%g%%f%%a%%C%%S%%08x"]
    84
    85 #formatstrings=["%%20d" * 1000,"%%20d" * 1000,"%%20d" * 1000]
    86 #formatstrings=["1","2","3","4","5"]
    87
    88 def do_server_pop():
    89 pop_server = doCmd("nc",2,"-l -p110 -v")
    90 pop_server.do_command()
    91 pop_server.no_wait_command()
    92 pop_server.write_to_command("+OK")
    93 return pop_server
    94
    95 def wait_client_response(pop_server, wait=2):
    96 i=0
    97 response = pop_server.read_from_command()
    98 while response == "" or response =="-3":
    99 pop_server.timeout_command()
    100 response = pop_server.read_from_command()
    101 i=i+1
    102 if i>=wait:
    103 i=0
    104 return "-1"
    105
    106 return response
    107
    108 def fuzz_pop_client():
    109 print "Connection"
    110 #fuzzing
    111
    112 while 1:
    113 pop_server = do_server_pop()
    114 response = pop_server.read_from_command()
    115
    116 print "RESPONSE ---- : "+response
    117 for f in formatstrings:
    118 print "-------------- FUZZ -------------"
    119 if pop_server.write_to_command(f)!= "-2":
    120 response = pop_server.read_from_command()
    121 print "RESPONSE ---- : "+response
    122 else:
    123 pop_server.close_command()
    124 time.sleep(1)
    125 pop_server = do_server_pop()
    126
    127 pop_server.write_to_command("QUIT")
    128 pop_server.close_command()
    129
    130 if __name__ == "__main__":
    131 fuzz_pop_client()
    first posted by nicoj to python fuzzer ... saved by 2 persons ... 0 comments ... 1 year
  7. Images resizing with shell and imagemagick

    Resize a lot of images with shell and imagemagick

    1 for i in *.jpg
    2 do convert $i -scale 1024x760 resized-$i;
    3 done
    first posted by comete to shell bash images resize shell ... saved by 5 persons ... 1 comments ... 1 year
  8. Création d'éléments HTML en JavaScript

    Création d'éléments HTML en JavaScript. Je viens de me rendre compte qu'on ne peux pas créer des objets avec l'"eventListener" en utilisant une boucle for par exemple et en récupérant un identifiant suivant la valeur de l'incrément de la boucle. Il faut obligatoirement récupérer l'identifiant du déclenchement avec "event", sinon il garde la dernière valeure de l'incrément de la boucle.

     1 /**
    2 * Ajouter un Evénement JS à un élément
    3 *
    4 * @access public
    5 * @return void
    6 **/
    7 function eventListener( elem, event, action ){
    8 if( elem.addEventListener ) {
    9 elem.addEventListener( event, action, false) ;
    10 } else if( elem.attachEvent ) {
    11 elem.attachEvent( "on" + event, action );
    12 } else { alert( 'Erreur de chargement.\nVotre navigateur n\'est pas supporté.' ); }
    13 }
    14
    15 /**
    16 * Création d'un élément <IMG>
    17 */
    18 var elemImgExemple = document.createElement("img");
    19 elemImgExemple.id = "img1";
    20 elemImgExemple.alt = "Image exemple";
    21 elemImgExemple.src = "picture.png";
    22 elemImgExemple.style.width = "50px";
    23 elemImgExemple.style.height = "80px";
    24 elemImgExemple.setAttribute( "useMap", "#mapImg" );
    25
    26 eventListener(elemImgExemple, "mouseover", function() { alert( 'hello world!' ); }
    27 eventListener(elemImgExemple, "mouseout", functionImage } // appel de la fonction functionImage();
    28 eventListener(elemImgExemple, "click", function(event) { idName = (document.all) ? event.srcElement.id : event.target.id; alert( idName ); }
    29
    30 document.getElementById( 'elemParent' ).appendChild( elemImgExemple );
    first posted by cedeber to javascript event listener element ... saved by 2 persons ... 0 comments ... 1 year
showing 10, 25, 50 items per pages

Pages : 1