Sonntag, 5. Juli 2009

SHELL: get server


#!/bin/sh
#
[ $# -lt 1 ] && echo $0 server && exit 1

echo 'GET / HTTP/1.0\n' | nc $1 80 | egrep '^Server:'

SHELL: some commandos

found free loop device:
losetup -f

encryption with losetup:
insmod loop.o
insmod des.o
insmod cryptoloop.o
dd if=/dev/urandom of=crypto.img bs=1M count=50
losetup -e blowfish /dev/loop0 crypto.img
mkfs -t ext2 /dev/loop0
losetup -d /dev/loop0 # delete
mount -o encryption=aes256 crypto.img crypto_home

encryption with bind drive:
losetup -e aes256 /dev/loop0 /dev/sda1
losetup -d /dev/loop0
mount -o encryption=aes256 /dev/sda1 crypto_home

resizing the image:
dd if=/dev/urandom bs=1M count=20 >> crypto.img
losetup -e aes256 /dev/loop0 crypto.img
ext2resize /dev/loop0

encrypt/decrypt with openssl:
openssl enc -aes-256-cbc -salt -in password.txt -out password.txt.enc
openssl enc -d -aes-256-cbc -in password.txt.enc -out password.txt


echo "put /bla/bl/das.log.gz /bls/bl2/dies.log.bz2" >> $TFTPSCRIPT
tftp $TFTPSRV < $TFTPSCRIPT

uuencode $FWLOG/old/$BLA.log.gz $BLA.log.gz | mail -s "FWEXPORT $EXPORTNAME.log.gz" $MAILRECPT

PERL: some perl stuff 2


$arg=shift(@ARGV);
while(defined $arg) { ... }

$h{"bla"}="bla";
@val=values(%h);

<=> cmp -1 less 0 equal 1 greater

while(true) {} until(false){}

if() unless()

local($v) are local for temporary value of a gloabal variable

# modifying parameters
$a=1;
inc($a); # 2
sub inc {
$_[0]+=1;
}

@a=(1,2,3..);
mod(*a);
sub mod {
local (*la)=@_;
@la=reverse(@la);
}

print((split " ",$_)[0]."\n") while(<>);
# split im listenkontext, erster element

perl -ane 'print $F[0];' # analog
# -a autosplit, (split $_ into @F
# -n while loop

while(<>) { print if /head/; }


# cgi html
#!/usr/bin/perl -wT
print "Content-type: text/plain \n\n";
# -T taint Modus, Benutzereingaben in Quarantaene

HTML::Template;
use strict;
use warnings;
HTML::Embperl;
HTML::Mason;

Template;
HTML::Template;
DBI;
CGI;
CGI::Carp qw(fatalsToBrowser);

$q=new CGI;
foreach($q->param) { .. # param GET/POST parameters

$template=new HTML::Template(filename=>'addressbuch_kontakt.html');
$template->param(personen=>\@_pers)


#db
$dbh->selectrow_hashref('SELECT ..');
selectrow_array( .... );

if(exists $bla)
if( not exiss $bla)


#splice: removes and replaces elements in an array
splice(ARRAY, OFFSET, LENGTH, LIST);


%SIG # signal handles hash
sub handler { ... }
$SIG{'INT'}='handler';
$SIG{'INT'}='DEFAULT';


srand(time() | $$); # zeit doer pid einlesen
$l=int(rand(10));

if/ [^123]0 / # 10 20 30

x?? schaltet greedinessaus
\b word bounding
alternation /Ab|cd/ /(ma|pa)+/

$1 $2 ergebnisse der gruppierung
\1 \2 suchmuster
(?: ..) turn off capturing -> $1 void


V filehandle
$v scalar
@v array
%v hash
&v subroutine
*v everything named v

$s.$s2;
$s.=$s2; #concate
$sx4; #4 mal


s::mp('bla');
packages s;
sub mp {
print ("@_\n");
}

use File::Basename;
#look for File/Basename.pm


jeder Modul muss mit 1; beenden

BEGIN { require "bla.p"; }

pragmas: use integer; no integer;

calling methods (OOP)
$obj->meth($param);
meth $obj $param;

sub meth {
my $self=shift; # refernz auf obj
...
}

# constructor
sub new {
my $self={}; # hash anonymous referenz
$self->{ATTRIB1}=undef;
...
# make Referenz
bless($self);
return $self;
}

#Destructor
sub DESTROY {
...
}

###
sub u {
my $self=shift;
if(@_) {
$self->{U}=shift;
}
return $self->{U};
}
$o->('bla');
print $o->u,"\n";

#!!not
print "$o->u\n";
###


use Cwd;
$cur_dir=cwd;

use File::Basename;
(...)=fileparse(..);

use Config;
%Config


$perldoc -l copy
druckt den Pfad aus File::Find



www.pewrl.com/CPAN
HTML::LinkExtor, URI::URL
head() links()

PERL: some perl stuff


($sec, $min, $hour, $day, $mon, $year, $wday, $yday, $isdst)=localtime(time());
print scalar(localtime()); # > Fri Dec 21 11:11:30 2006

# gibt keine leezreilen und zeilen mit "---" oder mehr aus
print unless ( /^\s+$/ or /-{3,}/ );

# sucht nach kapazietaet
$pfad="/proc/acpi/battery/BAT0/state";
if(/remaining capacity: *?(\d*?) mAh/) {
print $1;


# eine mail senden

use Email::Send;
send SMTP=> <<'__MESSAGE__', $host;
To: anfrit00@fht-esslingen.de
From: foo@example.com

bla bla
__MESSAGE__


perl -e 'print "$_\n" foreach(@INC);'
/etc/perl
/usr/local/lib/perl/5.8.8
/usr/local/share/perl/5.8.8
/usr/lib/perl5
/usr/share/perl5
/usr/lib/perl/5.8
/usr/share/perl/5.8
/usr/local/lib/site_perl

# formatprobe
open (CON_LIST, '>-') or die " open error\n";
$i=1; $key="klasst"; $result=0.23; $erg=23;

write CON_LIST;

close CON_LIST;

format CON_LIST =
@> @<<<<<<<<<<<<<<< @>>>> = @<<<<<<
$i, $key, $result, $erg
.


# zu datenbank verbinden (mysql)
use DBI();

$dbhost="localhost";
$dbname="mysql";
$dbuser="root";
$dbpass="";

# verbinden
my $dbh = DBI->connect("DBI:mysql:database=$dbname;host=$dbhost",
$dbuser, $dbpass, {'RaiseError' => 1});
my $sth = $dbh->prepare("SELECT host, user, Password FROM user"); # anfrage
$sth->execute(); # anfrage senden

while (my $user = $sth->fetchrow_hashref()) { # daten als hash holen
# $user ist eine hash referenz
print "HOST: ".$user->{'host'}."\nUSER: ".$user->{'user'}."\nPASS: ".$user->{'Password'}."\n\n";

}
$dbh->disconnect(); # verbindung zu db schliessen


# einfaches parameter options
use Getopt::Std;
getopts("vr:", \%options);
print "v-> ".$options{'v'}."\n";
print "r-> ".$options{r}."\n";
#./test.pl -v -r bla
#v-> 1
#r-> bla


# dateien globen
$path=".";
while (<$path/*.pl>) {
print $_."\n";
}
# gibt alle dateinamen *.pl aus


# socket
my $sock = new IO::Socket::UNIX (Peer => $ARGV[0], Type => SOCK_STREAM); # socket
print $sock $query; # senden
my $response = <$sock>; # empfangen
close $sock;

# einfacher server
use IO::Socket;
$socket=new IO::Socket::INET (LocalHost=>$ARGV[0],
LocalPort=>6677,
Proto=>'tcp',
Listen=>5, Reuse=>1,);
# max 5 stueck, reuse=1 benutze den port wieder
die "new socket error: $!" unless $socket;

while($cli=$socket->accept()) { # client verbindet
print $cli "Hallo, \n";
$cli->flush(); # flushen
close($cli); # und tschuess
}
close($socket);

# server
user IO::Socket;
$ss=new IO::Socket::INET(LocalPort=>2345, Listen=>$SOMAXCONN, Proto=>'tcp', Reuse=>1);
# loop on incomming connections
while($sc=$ss->accept()) {
$data=<$sc>; # empfang
print $sc "bla"; # senden
$sc->close();
}
close($ss);

# client
$sc=new IO::Socket::INET(PeerAddr=>$hostname, PeerPort=>2345, Type=>SOCK_STREAM, Proto=>'tcp');
# .. aehnlich server

# donot use IO::Socket::INET this package is defined in IO::Socket

# pack unpack
my $query = pack("L L N N S S", 0x2343defe, 0x12345678,
2343343, 1111323, $ARGV[2], $ARGV[4]);
my ($magic, $id, $type, $genre, $detail, $dist, $link, $tos, $fw,
$nat, $real, $score, $mflags, $uptime) =
unpack ("L L C Z20 Z40 c Z30 Z30 C C C s S N", $response);


# alle modulen *.pm ausgeben
perl -e 'print "$_\n" foreach(@INC);' | while read f; do find $f -name \*.pm ; done


# inplace editieren, scritpname:pr2.orig
@ARGV=("pr2.orig");
$^I=".bak"; # backup name
$n=0;
while(<>) {
print "$n: $_";
$n++;
}


# pipe
open IN, "cat mail.pl |" or die "cat??";
print while();
close IN;
$cmd1="wc";
$cmd0='tr -s " " " " ';
open SEND, "| $cmd0 | $cmd1" or die "bla";
print SEND "daasa sdfklasdf jkaldskjfaslkdj ";
close SEND;
open SEND, "| tr '[a-z]' '[A-Z]'";
print SEND "hello"; # leitet die ausgabe ueber pipe nach tr
close SEND;
$encoder="/usr/bin/uuencode";
open SEND, "| $encoder stdout" or die "encoder";
print SEND "dies ist eine probe";
close SEND;


# cgi
use CGI qw/:standard/;
print header,
start_html('-title'=>"Statistik"),
p("Die letzten Tagen"),
h1("Blabla bla");


# datei locken
use IO::File;
use Fcntl qw(:flock);

my $fh=new IO::File(">probe.txt") or die "IO::File\n";

flock $fh, LOCK_EX;
print "get flock datei\n";
print $fh "bla bla";

$eing=<>;

flock $fh, LOCK_UN;
$fh->close;


# ftp benutzen
use Net::FTP;

$host="dx40";
$user="ray";
$pass='';

$ftp=Net::FTP->new($host) or die "Net::FTP->new error:$!\n";
$ftp->login($user, $pass) or die "login error: $!\n",$ftp->message;
$ftp->binary();
$ftp->cwd("/home/ray/daten") or die "cwd error\n";

@alle=$ftp->ls();
#print foreach(@alle);
$ftp->get($_) foreach(@alle);

$ftp->quit();



# holt n-mails von gmx.net ab
use Net::POP3;
$host='pop.gmx.net';
$user='userbla@gmx.net';
$pass='passbla23';
$ort='/home/ray/daten/popmails/mail';

$datum=time();
open OUT, ">>$ort$datum" or die "kann nicht mail oeffnen: $! \n";

($mail=Net::POP3->new($host)) or die "error open $host: $!\n";

$lo=$mail->login($user, $pass);
die "login error: $!\n" unless defined $lo;
print "Login: $user OK\n";
if($lo) {
foreach $nr (1..10) {
print "Mail nr $nr\n";
$inhalt=$mail->get($nr);
print OUT @$inhalt;
$mail->delete($nr);
}
}
close(OUT);
$mail->quit();


# wandelt ip in int um
use Net::IP;
my $src = new Net::IP ("127.0.0.1") or die (Net::IP::Error());
print $src->intip()."\n";


# read a gif file
$A="latest.gif";
open A or die "$A: $!";
read A, $b, 1024;
@c=unpack "C4A40(A/A)4", $b;
open OUT, ">gifinfo.txt";
print OUT for(@c);
close OUT;


# zeit
@monat=qw(jan feb mar apr mai jul jun aug sep okt nov dec);
my ($s,$m,$h,$d,$mo,$y,@r)=localtime();
print "$h:$m:$s\n";
print "$d ".$monat[$mo]." ", 1900+$y,"\n";



$|=1; # ausgabe nicht puffern



# persistente variablen(hash)
use GDBM_File; # persistenter hash
use Fcntl; # O_CREAT, O_RDWR usw
# persistenten hash oeffnen
tie(%MEM, GDBM_File, $pfile, O_CREAT|O_RDWR, 0644) or
die "cannot open $pfile";
# binden den hash MEM an die Datei pfile, ueber GDBM Interface
# der hash MEM erscheint als normaler hash im speicher, liegt aber auf der platte
$MEM($url)="bla"; # schreiben
$d=$MEM('pla'); # lesen
untie(%MEM); # pers. hash schliessen



# web
use LWP::UserAgent;
$ua=LWP::UserAgent->new(); # user agent erzeugen
$request=HTTP::Request->new('GET', $url); # url festlegen
$response=$ua->request($request); # netzzugriff ausfuehren
if($response->is_error()) { ... } # $response->is-success
$response->content()

use LWP::Simple;
$doc=get 'http://www.google.de';

perl -MLWP::Simple -e 'getprint "ftp://...";'

use LWP::Simple;
mirror($url, $localfile);


use HTML::Parse;
use HTML::FormatText;
$html=parse_htmlfile($htmlfile);
$formatter=new HTML::FormatText(leftmargin=>0, rightmargin=>70);
print OUT $formater->format($html);




# checksume berechnen
$chksum=unpack("%16C*", $dat);



# Ping
user Net::Ping;
$po=Net::Ping->new();
if($po->ping($hostname)) {
print "$hostname da";
}
$po->close();


# FTP
use Net::FTP;
login($servername, $passwort);
#ascii, binary
cwd($dir); # dir($dir) pwd quit
$dir=$ftp->dir(); # return a refernce
foreach(@$dir) print "$_\n";
#
$ftp = Net::FTP->new("some.host.name", Debug => 0)
or die "Cannot connect to some.host.name: $@";
$ftp->login("anonymous",’\-anonymous@’)
or die "Cannot login ", $ftp->message;
$ftp->cwd("/pub")
or die "Cannot change working directory ", $ftp->message;
$ftp->get("that.file")
or die "get failed ", $ftp->message;
$ftp->quit;
# SEE perldoc Net::FTP


# mail
use Mail::Send;
$mail=Mail::Send->new();
$mail->to($addr);
$mail->cc($copy_to_addr);
$mail->bcc($blind_copy);
$mailhandle=$mail->open();
print $mailhandle << END;
bla bla
....
END;
$mailhandle->close(); # send mail


# MIME
use MIME::Lite;
$msg=MIME::Lite->new(From=>$fromaddr, To=>$toaddr, Subject=>'bla',
Type=>'multipart/mixed');
$msg->attach(Type=>'TEXT', Encoding=>'7bit', Data=>'bla bla');
$msg->attach(Type=>'image/gif', Encoding=>'base64', Path=>'bild.gif', Filename=>'bild.gif');
# convert message to string
$str=$msg->as_string();
$msg->send();

# decoding MIME
use MIME::Parser;
$mime=new MIME::Parser;
$mime->read(\*INPUT); # geoffnete Datei


# SMTP
use Net::SMTP;
$ms=new Net::SMTP($hostname, Debug=>1,);
$ms->mail($from_addr);
$ms->to($addr);
$ms->data($data); # in data steht auch der subject

# POP3
use Net::POP3;
$ms=new Net::POP3($hostname);
$msg_cnt=$ms->login($usrename, $passwd);
$headers=$ms->list(); # reference
foreach $message(keys(%$headers)) {
$header=$ms->top($message);
}
$message=$ms->last();
$contents=$ms->get($message);
$ms->quit();


# DBM
dbmopen(%dbhash, "filename", 0666);
$dbhash{'name'}="bla bla";
print $dbhash{'any'};
dbmclose(%dbhash);

while(($key, $val)=each(%dbhash)) {
print ...
}

use Fcntl;
use SDBM_File;
use Config;
$flags=O_CREAT|O_RDWR;
tie(%dbhash, 'SDBM_File', 'sdmtest', $flags, 0666) or die "cannot open database $!";
$dbhas{localtime()}="bla..";
untie(%dbhash);
# tie bindet eine variable zu etwas, hier zu einer datenbank klasse
# tie(var, classname, file, flags, mode)
# var: %hash, @array, $scalar, HANDLE

tying scalar, array, filehandle, hash when call 'tie', perl execute proper constructor
array ->TIEARRAY
handle->TIEHANDLE
hash ->TIEHASH
scalar->TIESCALAR

TIESCALAR classname, list
FETCH this
STORE this, val
DESTROY this

package Myscalar;

sub TIESCALAR {
my ($class)=$_[0];
my ($self)=0;
return (bless(\$self, $class));
}
sub FETCH {
my($reference_to_self)=$_[0];
return ($$reference_to_self);
}
...
1;

# an object is a reference

tie($myscalar, 'Myscalar');
$myscalar=55;
untie($myscalar);


TIEARRAY classname, list
FETCH this, index
STORE this, index, value
DESTROY this

TIEHANDLE classname, list
PRINT this, list
PRINTF this, list
READLINE this # called by <>
GETC this
READ this, list
DESTROY this

TIEHASH classname, list
FETCH this, key
STORE this, key, value
EXISTS this, key
DELETE this, key
CLEAR this
FIRSTKEY this
NEXTKEY this, lastkey
DESTROY this

store $v=$hash{'key'};
exists if(exists($hash{'key'})) { ..
delete delete $hash{'key'};


Tie::Hash, Tie::StatHash

sub STORE{ $_[0]->{$_[1]}=$_[2]; }
sub FIRSTKEY{ my $a=scalar keys%{$_[0]};
each%{$_[0]} }
sub CLEAR{ %{$_[0]}=() }
# %{..} anonyme hash


package Tie::Stdhash;
@ISA=qw(Tie::Hash); # used to speify which baseclass a new class inherits from
# Tie::StdHash inherits from Tie::Hash
sub STORE { ... } # override the STORE method


#Databases
use DBI;
@drivers=DBI->available_drivers();
$db=DBI->connect('dbi:mSQL:test:localhost);
$db->disconnect();
$cursor->execute();
if($DBI::err) { .. error }


perldoc DBI::FAQ
# extract the data
while(@val=$cursor->fetchrow()) { .. }

use vars qw(@ISA); # pragma to predeclare global variable names (obsolete)


# Zlib
use Compress::Zlib;
binmode STDOUT;
my $gz=gzopen(\*STDOUT, "wb");
while(<>) {
$gz->gzwrite($_);
}
$gz->gzclose();

$gzerrno!=Z_STREAM_END; Z_OK

$gz->gzreadline($_);
$gz->gzread($buffer);

my $x=inflateinit();
($output, $status)=$x->inflate(\$input);
my $x=deflateinit();
($o, $s)=$x->deflate($_);
$x->flush();


use Bla;
$o=Bla::funct() # oder
use Bla qw(funct);
$o=funct();


push @arr, $var; # append $var to @arr
pop @arr; # get the latest element and remove it

use File::Basename;
$path="/usr/lib/perl5/Net/Ping.pm";
@suf=".pm";
($basename, $dir, $suffix)=fileparse($path, @suf);
# Ping /usr/lib...


use Config;
%Config; # -which include a lot of inormation about the configuration of Perl
if($Config{osname}=~/^Windows/) ..

use File::Compare; # compare 2 files
$result=compare($file1, $file2); # 0 equal 1 diff -1 errror

use File::Copy;
copy($sourcefile, $destfile);
move($srcfile, $dstfile);

#Installing new Module
perl Makefile.PL
make
make install



# Image with GD
use GD;
$im=new GD::Image(100,100);
$back=$im->colorAllocate(100,150,255);
$im->fill(1,1,$back);
$outfile=">"."name.gif";
print OUT $im->gif;
$black=$im->colorAllocate(0,0,0);
$im->string(gdLargeFont, 30,40, $message);
# stringUp(..) rotate 90°
$font=gdMediumBoldFont;
$char_width=$font->width;
$char_height=$font->height;
$len=length($message);
$im->line($x, $y, $x2, $y2, $color);
$im->transparent($back);


/\binder\b/ # wortgrenze 'inder' aber kein 'rinder'

PHP: some stuff


$in = fopen("php://stdin","r");

while ($l =$fgets($in, 1024)) {
$a = preg_split('/\s+/', $l);
while(list($k, $v) = each($a)) {
...

foreach($c as $k=> $v) ...

CMDs: some shell commandos, linux

lpr -Plp Datei # datei ausdrucken

fuser -k /dev/lp0 # alle dienste die den /dev/lp0 benutzen toeten
#/dev/usb/lp0

scsi-scanner /dev/sg0

set -o nochlobber

git-rev-tree --bisect ^good1 ^good2 bad > git/refs/headers/tryN
git checkout tryN
^goodx > v2.6.12 bad > master


movw%bx, (%rsi) <-> recvfrom()


/usr/sbin/snort -b -m 027 -D -N -c /etc/snort/snort.conf -d -u snort -g snort -i eth1


iptables -A INPUT -ptcp -s PVT_IP_HERE -d 0/0


wget -p nur inhalt,
wget -r -np nur unterverzeichniss, nicht von root an



test -x $1 || exit 5

find /proc -type s

ls -Rr /proc/[0-9]* | fgrep ^s

Freitag, 3. Juli 2009

PYTHON: get your own exception catcher

you can set your own exception handler, this is done by
sys.excepthook = your_func


for that you must define a function, with following parameters:

def your_func(exc_type, exc_obj, exc_tb):
print "whoaaa my exception"


then you can call an exception

5/0
=>
whoaaa my exception


def your_func(exc_type, exc_obj, exc_tb):
import traceback
l = traceback.format_exception(exc_type, exc_obj, exc_tb)
print type(l)
print l


=>

['Traceback (most recent call last):\n', ' File "./t1.py", line 37, in \n 5/0\n', 'ZeroDivisionError: integer division or modulo by zero\n']


traceback.format_exception(...) return us a list of information
as a normal exception traceback


info about sys.xxx

Donnerstag, 2. Juli 2009

OSGi: ogsi or wtf?

small info about OSGi

first we have OGSI and OSGi:
1) OGSI: Open Grid Services Infrastructure
2) OSGi: a framework for component based programming

here I talk about OSGi

Wiki
Why OSGI

OGSi Equinox: http://www.eclipse.org/equinox/

OSGi page
specifications v4
simple tutorial

PYTHON: simple scanner in python

this is a simple scanner in python.

work: call a system ping (with popen() ) and look for ttl count.
if count ~64 -> linux, count ~128 -> windows, count ~255 -> BSD/Router

then it connect to well known ports and look for respond.

limits: only certain ports and only TCP

trace2.py
###################################################################

#!/usr/bin/python

import sys, os, socket, re


class Scan:
def __init__(self):
#print "create socket ..."
self.scanNew=None
self.allPorts={"ftp-data":20, "ftp":21,"smtp":25, "http":80, "pop3":110, "imap3":220, "https":443,
"ldap":389 }
self.linuxPorts={"ssh":22, "dns":53, "snmp":161, "snmp-trap":162}
self.windowPorts={"netbios-ns":137, "netbios-dgm":138, "netbios-ssn":139,"microsoft-ds":445 }

def ping(self, ip):
findttl = re.compile(r"ttl=(\d{1,3}) ")
pingpipe = os.popen("ping -W 1 -c 1 "+ip,"r")
for line in pingpipe.readlines():
if "ttl" in line:
result = re.findall(findttl,line)
return int(result[0])
return -1

def connectTCP(self, ip, port, portname):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1)
try:
s.connect((ip, port))
print "connect to %s : %d (%s) was succesfull"%(ip, port, portname)
except:
pass
#print "failing to connect %s : %d (%s)"%(ip, port, portname)
s.close()

def scann(self, ip):
ttl=self.ping(ip)
if( ttl==-1):
print "IP %s not reachable"%ip
elif( ttl==0 ):
print "huch, ttl is zero"
elif( ttl>0 and ttl<65 ):
print " %s possible LINUX and is Alive"%ip
for port in self.allPorts.keys():
self.connectTCP(ip, self.allPorts[port], port)
for port in self.linuxPorts.keys():
self.connectTCP(ip, self.linuxPorts[port], port)
elif( ttl>64 and ttl<129 ):
print " %s possible WINDOWS and is Alive"%ip
for port in self.allPorts.keys():
self.connectTCP(ip, self.allPorts[port], port)
for port in self.windowPorts.keys():
self.connectTCP(ip, self.windowPorts[port], port)
else:
print " %s possible BSD or Router and is Alive"%ip
for port in self.allPorts.keys():
self.connectTCP(ip, self.allPorts[port], port)
for port in self.linuxPorts.keys():
self.connectTCP(ip, self.linuxPorts[port], port)

if( len(sys.argv) != 4):
print "%s ip(first triple) begin end"%sys.argv[0]
print " example:"
print " %s 123.45.67 10 20"%sys.argv[0]
sys.exit(2)

iptriple=sys.argv[1]
begin=int(sys.argv[2])
end=int(sys.argv[3])

scan=Scan()

for ip4 in range(begin, end):
ip="%s.%d"%(iptriple,ip4)
scan.scann(ip)

###################################################################

Mittwoch, 1. Juli 2009

C, REGEX

learn regular expression in C
info:
http://www.opengroup.org/onlinepubs/007908799/xsh/regex.h.html
#include <regex.h>

structuren:

regex_t preg;
regmatch_t pmatch[100];

example: regex1.c
#################################################

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <regex.h>


int main() {

int err;
char err_str[200];
char results[500];

int i,j,k=0;

regex_t preg;
regmatch_t pmatch[100];


char *buf="blub blub blub@googlemail.com adslfku asdf@gmail.com oasduf";

if( (err = regcomp(&preg, "\\b[A-Za-z0-9._%+-]+@(gmail|googlemail)+\\.[a-zA-Z]{2,4}\\b", REG_EXTENDED)) != 0) {
printf("regcomp error\n");
return -1;
}

if( (err = regexec(&preg, buf, preg.re_nsub, pmatch, 0)) != 0) {
regerror(err, &preg, err_str, 200);
printf("%s\n",err_str);
return -1;
} else {
for(i = 0; i < preg.re_nsub; i++) {
if(pmatch[i].rm_so == -1) continue;
for(j = pmatch[i].rm_so; j < pmatch[i].rm_eo; j++)
results[k++] = buf[j];
results[k] = '|';
results[++k] = '\0';
}
}
printf(">> results: %s\n", results);
regfree(&preg);
return 0;
}

#################################################

"\\b[A-Za-z0-9._%+-]+@(gmail|googlemail)+\\.[a-zA-Z]{2,4}\\b": example pattern
regcomp(): compile the seek string (pattern)
regexec(): seek for a pattern in string

struct regmatch_t

typedef struct
{
regoff_t rm_so; /* Byte offset from string's start to substring's start. */
regoff_t rm_eo; /* Byte offset from string's start to substring's end. */
} regmatch_t;



further functions:
regerror(): error handling
regfree (): free buffers

C, CURL: simple tutorial: libcurl with C

coding libcurl in C

homepage: http://curl.haxx.se/

download: http://curl.haxx.se/download.html
latest version: latest:curl-7.19.5

libcurl: http://curl.haxx.se/libcurl/
all about libcurl with C: http://curl.haxx.se/libcurl/c/


You must include:
<curl/curl.h>


compile
gcc libcurl1.c -o libcurl1 -lcurl


important structures:

CURL *curl;
CURLcode curl_res;
CURLINFO info;



Start a libcurl easy session
curl = curl_easy_init();
see more info: http://curl.haxx.se/libcurl/c/curl_easy_init.html

set options for a curl easy handle
curl_easy_setopt(CURL *handle, CURLoption option, parameter);

CURLOPT_WRITEDATA Data pointer to pass to the file write function
curl_easy_setopt(curl, CURLOPT_WRITEDATA, tmp);
tmp: FILE handle

set proxy
curl_easy_setopt(curl, CURLOPT_PROXY, pxy);


Perform a file transfer
curl_easy_perform(CURL * handle );


End a libcurl easy session
curl_easy_cleanup(curl);

set an url
curl_easy_setopt(curl, CURLOPT_URL, url);

set file handle, where the data get writed
curl_easy_setopt(curl, CURLOPT_WRITEDATA, tmp);

download the page
curl_res = curl_easy_perform(curl);

get http status code
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);

get size of downloaded page
curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &c_length);



sample: libcurl1.c
##########################################

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <curl/curl.h>

int main() {
CURL *curl;
CURLcode curl_res;
CURLINFO info;
long http_code;
double c_length;
FILE *tmp;

tmp=fopen("/tmp/google_index.html", "w");
if(tmp==NULL) {
printf("ERROR to open file /tmp/google_index.html\n");
exit(2);
}

printf("init curl session\n");
curl = curl_easy_init();
printf("set url to download\n");
curl_easy_setopt(curl, CURLOPT_URL, "http://www.google.de/index.html");

printf("set file handler to write\n");
curl_easy_setopt(curl, CURLOPT_WRITEDATA, tmp);

printf("download the file\n");
curl_res = curl_easy_perform(curl);
if(curl_res==0) {
printf("file downloaded\n");
} else {
printf("ERROR in dowloading file\n");
fclose(tmp);
curl_easy_cleanup(curl);
}

printf("get http return code\n");
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code);
printf("http code: %lu\n", http_code);

printf("get size of download page\n");
curl_easy_getinfo(curl, CURLINFO_SIZE_DOWNLOAD, &c_length);
printf("length: %g\n", c_length);

printf("END: close all files and sessions\n");
fclose(tmp);
curl_easy_cleanup(curl);

return 0;
}

##########################################

./libcurl1
init curl session
set url to download
set file handler to write
download the file
file downloaded
get http return code
http code: 200
get size of download page
length: 6969
END: close all files and sessions