Sayın Bakanımızın Bulut Bilişim Yorumu!

Ekim 31, 2011 § Yorum yok § Kalıcı bağlantı

Python ile asal keşfi

Ekim 26, 2011 § Yorum yok § Kalıcı bağlantı

Bu python scripti Project Euler ile uğraştığım zaman kullandığım bazı fonksiyonlar içermektedir.

Dosyayı yüklemek için tıklayınız
İçeriği:

"""
 primes.py  -- Oregon Curriculum Network (OCN)
 Feb  1, 2001  changed global var primes to _primes, added relative primes test
 Dec 17, 2000  appended probable prime generating methods, plus invmod
 Dec 16, 2000  revised to use pow(), removed methods not in text, added sieve()
 Dec 12, 2000  small improvements to erastosthenes()
 Dec 10, 2000  added Euler test
 Oct  3, 2000  modified fermat test
 Jun  5, 2000  rewrite of erastosthenes method
 May 19, 2000  added more documentation
 May 18, 2000  substituted Euclid's algorithm for gcd
 Apr  7, 2000  changed name of union function to 'cover' for consistency
 Apr  6, 2000  added union, intersection -- changed code of lcm, gcd
 Apr  5, 2000  added euler, base, expo functions (renamed old euler to phi)
 Mar 31, 2000  added sieve, renaming/modifying divtrial
 Mar 30, 2000  added LCM, GCD, euler, fermat
 Mar 28, 2000  added lcm
 Feb 18, 2000  improved efficiency of isprime(), made getfactors recursive
"""
import time, random, operator

_primes = [2]    # global list of primes

def iseven(n):
   """Return true if n is even."""
   return n%2==0

def isodd(n):
   """Return true if n is odd."""
   return not iseven(n)

def get2max(maxnb):
   """Return list of primes up to maxnb."""

   nbprimes = 0
   if maxnb < 2: return []

   # start with highest prime so far

   i = _primes[-1]
   # and add...

   i = i + 1 + isodd(i)*1 # next odd number

   if i <= maxnb:  # if more prime checking needed...

      while i<=maxnb:
         if divtrial(i): _primes.append(i) # append to list if verdict true

         i=i+2     # next odd number

      nbprimes = len(_primes)
   else:
      for i in _primes: # return primes =< maxnb, even if more on file

         if i<=maxnb: nbprimes = nbprimes + 1
         else: break   # quit testing once maxnb exceeded

   return _primes[:nbprimes]

def get2nb(nbprimes):
   """Return list of primes with nbprimes members."""

   if nbprimes>len(_primes):
      # start with highest prime so far

      i = _primes[-1]
      # and add...

      i = i + 1 + isodd(i)*1

      while len(_primes)<nbprimes:
         if divtrial(i): _primes.append(i)
         i=i+2

   return _primes[:nbprimes]

def isprime(n):
   """
   Divide by primes until n proves composite or prime.

   Brute force algorithm, will wimp out for humongous n
   return 0 if n is divisible
   return 1 if n is prime"""

   nbprimes = 0
   rtnval = 1

   if n == 2: return 1
   if n < 2 or iseven(n): return 0

   maxnb = n ** 0.5 # 2nd root of n

   # if n < largest prime on file, check for n in list

   if n <= _primes[-1]: rtnval = (n in _primes)

   # if primes up to root(n) on file, run divtrial (a prime test)

   elif maxnb <= _primes[-1]: rtnval = divtrial(n)

   else:
      rtnval = divtrial(n)   # check divisibility by primes so far

      if rtnval==1:       # now, if still tentatively prime...

         # start with highest prime so far

         i = _primes[-1]
         # and add...

         i = i + 1 + isodd(i)*1     # next odd number

         while i <= maxnb:
            if divtrial(i):         # test of primehood

                _primes.append(i)    # append to list if prime

                if not n%i:         # if n divisible by latest prime

                   rtnval = 0       # then we're done

                   break
            i=i+2                   # next odd number

   return rtnval

def iscomposite(n):
   """
   Return true if n is composite.
   Uses isprime"""
   return not isprime(n)

def divtrial(n):
   """
   Trial by division check whether a number is prime."""
   verdict = 1      # default is "yes, add to list"

   cutoff  = n**0.5 # 2nd root of n

   for i in _primes:
        if not n%i:      # if no remainder

           verdict = 0   # then we _don't_ want to add

           break
        if i >= cutoff:  # stop trying to divide by

           break         # lower primes when p**2 > n

   return verdict

def erastosthenes(n):
   """
   Suggestions from Ka-Ping Yee, John Posner and Tim Peters"""
   sieve = [0, 0, 1] + [1, 0] * (n/2) # [0 0 1 1 0 1 0...]

   prime = 3                          # initial odd prime

   while prime**2 <= n:
       for i in range(prime**2, n+1, prime*2):
            sieve[i] = 0      # step through sieve by prime*2

       prime += 1 + sieve[prime+1:].index(1) # get next prime

   # filter includes corresponding integers where sieve = 1

   return filter(lambda i, sieve=sieve: sieve[i], range(n+1))

def sieve(n):
   """
   In-place sieving of odd numbers, adapted from code
   by Mike Fletcher
   """
   candidates = range(3, n+1, 2)  # start with odds

   for p in candidates:
       if p:                   # skip zeros

	   if p*p>n: break     # done

	   for q in xrange(p*p, n+1, 2*p):  # sieving

		candidates[(q-3)/2] = 0
   return [2] + filter(None, candidates)  # [2] + remaining nonzeros

def base(n,b):
   """
   Accepts n in base 10, returns list corresponding to n base b."""
   output = []
   while n>=1:
      n,r = divmod(n,b) # returns quotient, remainder

      output.append(r)
   output.reverse()
   return output

def fermat(n,b=2):
   """Test for primality based on Fermat's Little Theorem.

   returns 0 (condition false) if n is composite, -1 if
   base is not relatively prime
   """
   if gcd(n,b)>1: return -1
   else:          return pow(b,n-1,n)==1

def jacobi(a,n):
  """Return jacobi number.

  source: http://www.utm.edu/research/primes/glossary/JacobiSymbol.html"""
  j = 1
  while not a == 0:
    while iseven(a):
      a = a/2
      if (n%8 == 3 or n%8 == 5): j = -j

    x=a; a=n; n=x  # exchange places

    if (a%4 == 3 and n%4 == 3): j = -j
    a = a%n

  if n == 1: return j
  else: return 0

def euler(n,b=2):
   """Euler probable prime if (b**(n-1)/2)%n = jacobi(a,n).

   (stronger than simple fermat test)"""
   term = pow(b,(n-1)/2.0,n)
   jac  = jacobi(b,n)
   if jac == -1: return term == n-1
   else: return  term == jac

def getfactors(n):
   """Return list containing prime factors of a number."""
   if isprime(n) or n==1: return [n]
   else:
       for i in _primes:
           if not n%i: # if goes evenly

               n = n/i
               return [i] + getfactors(n)

def gcd(a,b):
   """Return greatest common divisor using Euclid's Algorithm."""
   while b:
	a, b = b, a % b
   return a

def lcm(a,b):
   """
   Return lowest common multiple."""
   return (a*b)/gcd(a,b)

def GCD(terms):
   "Return gcd of a list of numbers."
   return reduce(lambda a,b: gcd(a,b), terms)

def LCM(terms):
   "Return lcm of a list of numbers."
   return reduce(lambda a,b: lcm(a,b), terms)

def phi(n):
   """Return number of integers < n relatively prime to n."""
   product = n
   used = []
   for i in getfactors(n):
      if i not in used:    # use only unique prime factors

         used.append(i)
         product = product * (1 - 1.0/i)
   return int(product)

def relprimes(n,b=1):
   """
   List the remainders after dividing n by each
   n-relative prime * some relative prime b
   """
   relprimes = []
   for i in range(1,n):
      if gcd(i,n)==1:  relprimes.append(i)
   print "          n-rp's: %s" % (relprimes)
   relprimes = map(operator.mul,[b]*len(relprimes),relprimes)
   newremainders = map(operator.mod,relprimes,[n]*len(relprimes))
   print "b * n-rp's mod n: %s" % newremainders

def testeuler(a,n):
   """Test Euler's Theorem"""
   a = long(a)
   if gcd(a,n)>1:
      print "(a,n) not relative primes"
   else:
      print "Result: %s" % pow(a,phi(n),n)

def goldbach(n):
   """Return pair of primes such that p1 + p2 = n."""
   rtnval = []

   _primes = get2max(n)

   if isodd(n) and n >= 5:
      rtnval = [3] # 3 is a term

      n = n-3      # 3 + goldbach(lower even)

      if n==2: rtnval.append(2) # catch 5

   else:
      if n<=3: rtnval = [0,0] # quit if n too small

   for i in range(len(_primes)):
      # quit if we've found the answer

      if len(rtnval) >= 2: break
      # work back from highest prime < n

      testprime = _primes[-(i+1)]
      for j in _primes:
         # j works from start of list

         if j + testprime == n:
              rtnval.append(j)
              rtnval.append(testprime) # answer!

              break
         if j + testprime > n:
              break  # ready for next testprime

   return rtnval

"""
The functions below have to do with encryption, and RSA in
particular, which uses large probable _primes.  More discussion
at the Oregon Curriculum Network website is at
http://www.inetarena.com/~pdx4d/ocn/clubhouse.html
"""

def bighex(n):
    hexdigits = list('0123456789ABCDEF')
    hexstring = random.choice(hexdigits[1:])
    for i in range(n):
        hexstring += random.choice(hexdigits)
    return eval('0x'+hexstring+'L')

def bigdec(n):
    decdigits = list('0123456789')
    decstring = random.choice(decdigits[1:])
    for i in range(n):
        decstring += random.choice(decdigits)
    return long(decstring)

def bigppr(digits=100):
    """
    Randomly generate a probable prime with a given
    number of decimal digits
    """
    start = time.clock()
    print "Working..."
    candidate = bigdec(digits) # or use bighex

    if candidate&1==0:
        candidate += 1
    prob = 0
    while 1:
        prob=pptest(candidate)
        if prob>0: break
        else: candidate += 2
    print "Percent chance of being prime: %r" % (prob*100)
    print "Elapsed time: %s seconds" % (time.clock()-start)
    return candidate

def pptest(n):
    """
    Simple implementation of Miller-Rabin test for
    determining probable primehood.
    """
    bases  = [random.randrange(2,50000) for x in range(90)]

    # if any of the primes is a factor, we're done

    if n<=1: return 0

    for b in bases:
        if n%b==0: return 0

    tests,s  = 0L,0
    m        = n-1

    # turning (n-1) into (2**s) * m

    while not m&1:  # while m is even

        m >>= 1
        s += 1
    for b in bases:
        tests += 1
        isprob = algP(m,s,b,n)
        if not isprob: break

    if isprob: return (1-(1./(4**tests)))
    else:      return 0

def algP(m,s,b,n):
    """
    based on Algorithm P in Donald Knuth's 'Art of
    Computer Programming' v.2 pg. 395
    """
    result = 0
    y = pow(b,m,n)
    for j in range(s):
       if (y==1 and j==0) or (y==n-1):
          result = 1
          break
       y = pow(y,2,n)
    return result

def invmod(a,b):
    """
    Return modular inverse using a version Euclid's Algorithm
    Code by Andrew Kuchling in Python Journal:
    http://www.pythonjournal.com/volume1/issue1/art-algorithms/
    -- in turn also based on Knuth, vol 2.
    """
    a1, a2, a3 = 1L,0L,a
    b1, b2, b3 = 0L,1L,b
    while b3 != 0:
        # The following division will drop decimals.

        q = a3 / b3
        t = a1 - b1*q, a2 - b2*q, a3 - b3*q
        a1, a2, a3 = b1, b2, b3
        b1, b2, b3 = t
    while a2<0: a2 = a2 + a
    return a2

# code highlighted using py2html.py version 0.8

bc ile asalları bulmak

Ekim 26, 2011 § Yorum yok § Kalıcı bağlantı

İnternetten bulduğum bir fonksiyonlar kümesine primegen(m,n) fonksiyonunu ekledim.
Çalıştırmak için

bc primes-db_bc.txt
primegen(2,10)
3
5
7
Bulunan asal sayısı:3

olarak dönmektedir.
Dosyayı yüklemek için tıklayınız..

Linuxde değişkenler

Ekim 26, 2011 § Yorum yok § Kalıcı bağlantı

Linuxde sistem değişkeni kullanımı

lsof ile Açık Dosyaların Tesbiti

Ekim 26, 2011 § Yorum yok § Kalıcı bağlantı

İsmi k, bash, init ile başlayan proseslerin açtığı dosyalar:

 lsof -c k
 lsof -c bash
 lsof -c init

pkrumins kullanıcının başlattığı veya apache prosesinin açtığı dosyalar

lsof -u pkrumins -c apache

pkrumins kullanıcının başlattığı ve apache prosesinin açtığı dosyalar

lsof -a -u pkrumins -c bash

root kullanıcısı tarafından açılmamış açık dosyalar

lsof -u ^root

30297 pidli proses tarafından açılmış dosyalar

 lsof +p 30297

/tmp dizini ve altındaki dizinleri/dosyaları kullanan proseslerin açtığı dosyalar.

lsof +D /tmp

Bütün internet soketlerini ve 80. portu kullanan programları öğrenmek:

 lsof -i
 lsof -i :80
 lsof -i :smtp

Bütün internet ve Unix soketlerini listelemek

 lsof -i -U

TCP ve UDP proseslerini listelemek

lsof -i tcp
lsof -i udp
lsof -i udp:53
lsof -i tcp:80

lsof komutunu her saniye çalıştırmak

lsof -r 1

www.akadia.com sunucunusa UPD ile 123 portu üzerinden bağlanan prosesler

 lsof -iUDP@www.akadia.com:123

Lisp

Ekim 26, 2011 § Yorum yok § Kalıcı bağlantı

(loop for x from 1 to 3
      do (loop for y from 11 to 12
      do (print (+ x y)) ))


(defun factors (num)
"This function will find the factors of the argument num."
(let ((l '()))
(do ((current 1 (1+ current)))
((> current (/ num current)))
(if (= 0 (mod num current))
(if (= current (/ num current))
(setf l (append l (list current)))
(setf l (append l (list current (/ num current)))))))
(sort l #'< )))
 
(defun coprimesp (num1 num2)
"Returns t if numbers are coprimes, nil otherwise."
(let ((flag t))
(dolist (atom1 (rest (factors num1)))
(dolist (atom2 (rest (factors num2)))
(if (= atom1 atom2)
(setf flag nil))))
flag))
 
(defun find-primes (top)
"Finds primes starting at one and searching up to given number, top."
(let ((l '()))
(dotimes (x top)
(if (= 2 (length (factors x)))
(setf l (append l (list x)))))
l))
 
(defun prime-factors (num)
  (let ( (f (factor num)) (l '()) )
    (dolist (element f)
      (if (primep element)
	  (setf l (append l (list element)))
	  (setf l (append l (prime-factors element)))))
    l))
 
 
 
(defun prime-p (n)
(declare ((speed 3) (safety 0) (fixnum-safety 0))
(fixnum n))
(cond
((and (<= n 11) (member n '(2 3 5 7 11)) t)
((= (rem n 2) 0) nil)
((= (rem n 3) 0) nil)
((= (rem n 5) 0) nil)
((= (rem n 7) 0) nil)
(t
(loop for i fixnum from 11 to (isqrt n) by 2
(when (= (rem n i) 0) (return-from prime-p nil))
t)))
 
 
(defun sieve5 (n)
  "Returns a list of all primes from 2 to n"
  (declare (fixnum n) (optimize (speed 3) (safety 0)))
  (let* ((a (make-array n :element-type 'bit :initial-element 0))
         (result (list 2))
         (root (isqrt n)))
    (declare (fixnum root))
    (do ((i 3 (the fixnum (+ i 2))))
        ((>= i n) (nreverse result))
      (declare (fixnum i))
      (progn (when (= (sbit a i) 0)
               (push i result)
               (if (<= i root)
                   (do* ((inc (+ i i))
                         (j (* i i) (the fixnum (+ j inc))))
                        ((>= j n))
                     (declare (fixnum j inc))
                     (setf (sbit a j) 1))))))))


(defun divides? (a b)
(= (mod b a) 0))
 
(defun find-divisor (n test-divisor)
(cond ((> (* test-divisor test-divisor) n) n)
      ((divides? test-divisor n) test-divisor)
      (t (find-divisor n (+ test-divisor 1))))))
 
(defun smallest-divisor (n)
(find-divisor n 2))
 
(defun prime? (n)
(= n (smallest-divisor n)))
 
=== Parametre olan Fonksiyon isimleri===
 
(defun sum (term a next b)
 (if (> a b)
     0
     (+ (funcall term a) (sum term (funcall next a) next b))))
 
(defun sum-int (a b)
(defun myidentity (a) a)
(sum #'myidentity a #'1+ b))
 
veya
 
(defun sum-int (a b)
(sum (lambda(x) x) a #'1+ b))
 
 
(defun sum-sqr (a b)
(defun square (a) (* a a))
(sum #'square a #'1+ b))
 
 
(defun mysqrt(x) (fixed-point (lambda(y) (average (/ x y) y)) 1))
 
(defun sum-of-digits(n)
(if (= (abs n) 0) 0 (+ (mod (abs n) 10) (sum-of-digits (/ (- (abs n)  (mod (abs n) 10)) 10)))))
 
(defun factorial(n) (if (= n 0) 1 (* n (factorial (- n 1)))))
 
(reduce '+ (find-primes 2000000))



md5sum

Ekim 25, 2011 § Yorum yok § Kalıcı bağlantı

md5sum x.iso >> md5sums.txt
md5sum y.iso >> md5sums.txt
cat md5sums.txt 
b42ae2a31fd39ebd59358cb7027f8304  x.iso
b44d0e2abdd53b0bde6f624060eb07f0  y.iso

md5sum kontrolü yapmak

md5sum -c md5sum.txt
x.iso: OK
y.iso: OK

Recursive md5sum kontrolü yapmak

find ./backup -type f -print0 | xargs -0 md5sum > /checksums_backup.md5
cd /orjinal
md5sum -c checksums_backup.md5

Process bar ile dosya kopyalamak

Ekim 25, 2011 § Yorum yok § Kalıcı bağlantı

$ rsync -r -v --progress -e ssh root@remote-server:~/pictures /home/user/
receiving file list ...
366 files to consider
pictures/IMG_1141.jpg
      3849245 100%   32.30kB/s    0:01:56 (xfer#30, to-check=335/366)
pictures/IMG_1142.jpg
     4400662 100%   32.21kB/s    0:02:13 (xfer#31, to-check=334/366)
pictures/IMG_1172.jpg
     2457600  71%   32.49kB/s    0:00:29

netstat ile port analizi

Ekim 25, 2011 § 1 yorum § Kalıcı bağlantı

Bütün açık portları görmek (dinleyen ve veri gönderen)

# netstat -a | more
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 localhost:30037         *:*                     LISTEN
udp        0      0 *:bootpc                *:*

Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node   Path
unix  2      [ ACC ]     STREAM     LISTENING     6135     /tmp/.X11-unix/X0
unix  2      [ ACC ]     STREAM     LISTENING     5140     /var/run/acpid.socket

TCP porları için

# netstat -at
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 localhost:30037         *:*                     LISTEN
tcp        0      0 localhost:ipp           *:*                     LISTEN
tcp        0      0 *:smtp                  *:*                     LISTEN
tcp6       0      0 localhost:ipp           [::]:*                  LISTEN

UDP portları için


# netstat -au
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
udp        0      0 *:bootpc                *:*
udp        0      0 *:49119                 *:*
udp        0      0 *:mdns                  *:*

Sadece dinleyen soketlerin tesbiti

# netstat -l
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 localhost:ipp           *:*                     LISTEN
tcp6       0      0 localhost:ipp           [::]:*                  LISTEN
udp        0      0 *:49119                 *:*

Portların istatistiklerini görmek için

# netstat -s
Ip:
    11150 total packets received
    1 with invalid addresses
    0 forwarded
    0 incoming packets discarded
    11149 incoming packets delivered
    11635 requests sent out
Icmp:
    0 ICMP messages received
    0 input ICMP message failed.
Tcp:
    582 active connections openings
    2 failed connection attempts
    25 connection resets received
Udp:
    1183 packets received
    4 packets to unknown port received.
.....

Portları kullanan programların PID bilgisi için

# netstat -pt
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        1      0 ramesh-laptop.loc:47212 192.168.185.75:www        CLOSE_WAIT  2109/firefox
tcp        0      0 ramesh-laptop.loc:52750 lax:www ESTABLISHED 2109/firefox

Verileri sayısal olarak görmek için

# netstat -an

veya
# netsat -a --numeric-ports

# netsat -a --numeric-hosts

# netsat -a --numeric-users

Sürekli olarak netstat verilerine bakmak için

# netstat -c
Active Internet connections (w/o servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 ramesh-laptop.loc:36130 101-101-181-225.ama:www ESTABLISHED
tcp        1      1 ramesh-laptop.loc:52564 101.11.169.230:www      CLOSING
tcp        0      0 ramesh-laptop.loc:43758 server-101-101-43-2:www ESTABLISHED
tcp        1      1 ramesh-laptop.loc:42367 101.101.34.101:www      CLOSING
^C

Çekirdeğin routing verisini görmek için

# netstat -r
Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
192.168.1.0     *               255.255.255.0   U         0 0          0 eth2
link-local      *               255.255.0.0     U         0 0          0 eth2
default         192.168.1.1     0.0.0.0         UG        0 0          0 eth2

Bir programın kullandığı portu tesbit etmek

# netstat -ap | grep ssh
(Not all processes could be identified, non-owned process info
 will not be shown, you would have to be root to see it all.)
tcp        1      0 dev-db:ssh           101.174.100.22:39213        CLOSE_WAIT  -
tcp        1      0 dev-db:ssh           101.174.100.22:57643        CLOSE_WAIT  -

Netcat Kullanımı

Ekim 25, 2011 § Yorum yok § Kalıcı bağlantı

Netcat network için isviçre çakısı gibidir.
Netcat temel olarak verilen porttan ilgili sunucuya bağlanır, input olarak verilen bilgiyi bu sunucuya gönderir, sunucunun cevabını ise ekrana (stdout’a) basar.

Örneğin google.com sunucusuna bağlanalim.

[xxx@xxxxx ~]$ nc www.google.com 80
HEAD / HTTP/1.0
[enter]
HTTP/1.0 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Location: http://www.google.com.tr/?gfe_rd=cr&ei=Z-uCU8XoI4Pe8geRnoG4Aw
Content-Length: 262
Date: Mon, 26 May 2014 07:21:11 GMT
Server: GFE/2.0
Alternate-Protocol: 80:quic

Aynı işi aşağıdaki gibi de yapabiliriz.

[xxxx@xxxxxx ~]$ echo -e "HEAD / HTTP/1.0\n" | nc www.google.com 80
HTTP/1.0 302 Found
Cache-Control: private
Content-Type: text/html; charset=UTF-8
Location: http://www.google.com.tr/?gfe_rd=cr&ei=POuCU5_5I9Da8ge8_ICIDw
Content-Length: 262
Date: Mon, 26 May 2014 07:20:28 GMT
Server: GFE/2.0
Alternate-Protocol: 80:quic

Netcat’i dinleyici servis olarak çalıştırmak için “-l ” kullanılabilir.
Böylece çift yönlü olarak sunucunun ilgili portuna direct edilmiş bilgiler bağlanan sunucunun ekranına basılılır.

# IP adresi 10.10.10.10 olan bilgisayarda
[xxxx@xxxxxx ~]# uptime| nc -l 6666
# şimdi başka bir bilgisayardan, 10.10.10.10 bilgisayarının 6666 portuna bağlanalim:
[xxxx@xxxxxx ~]$ nc 10.10.10.10 6666
 10:44:26 up 37 min,  4 users,  load average: 0.00, 0.02, 0.07

Bunun güzel bir uygulaması olan chat server olarak netcat kullanmak için

# IP adresi 10.10.10.10 olan bilgisayarda
$ nc -l -p 12345
veya
$ nc -l 12345

# şimdi dinleyen 10.10.10.10 bilgisayarının 12345 portuna bağlanalim:
 
$ nc 10.10.10.10 12345

İki bilgisayar arasında dosya göndermek


# Dinleyen sunucu -> bağlanan sunucu yönüde transfer
# IP adresi 192.168.1.10 olan bilgisayarda
$ cat file | nc -l -p 6666
 
# Başka bir bilgisayardan
$ nc 192.168.1.10 6666 > file

# Bağlanan sunucu -> Dinleyen sunucu yönüde transfer 
# 192.168.1.10 adresli bilgisayardan
$ nc -l -p 6666 -q 10 >output.txt
 
# Başka bir bilgisayardan
$ cat input.txt| nc 192.168.1.10 6666 

-q 10 ile 10 saniye sonra kapanması isteniyor.

A bilgisayarındaki /data dizinindeki dosyaları B bilgisayarına göndermek

# IP adresi 192.168.1.10 olan bilgisayarda
$ tar -cf - /data | nc -l -p 6666
 
# 192.168.1.10 ipli bilgisayara bağlanalim
$ nc 192.168.1.10 6666 | tar -xf -

# Diğer bilgisayardan 10.10.10.2 ipli bilgisayara erişip 12345 portundan veri gönderilip 12346 porundan veri alınabilir.

# 10.10.10.2 ipli bilgisayarda
$ nc -l 12345 | nc www.linuxwiki.net 80 | nc -l 12346
# Başka bir bilgisayardan
$ nc 10.10.10.2 12345
linux
^C
$ nc 10.10.10.2 12346
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>501 Method Not Implemented</title>
</head><body>
<h1>Method Not Implemented</h1>
<p>GET to /default.shtml not supported.<br />
</p>
<p>Additionally, a 404 Not Found
error was encountered while trying to use an ErrorDocument to handle the request.</p>
<hr>
<address>Apache Server at just135.justhost.com Port 80</address>
</body></html>

Netcat ile herhangi bir process sunucu görevi görebilir.
Bunu sağlamak için -e kullanmak yeterli

$ nc -l -p 12345 -e /bin/bash

$ nc localhost 12345
ls -las
total 4288
   4 drwxr-xr-x 15 pkrumins users    4096 2009-02-17 07:47 .
   4 drwxr-xr-x  4 pkrumins users    4096 2009-01-18 21:22 ..
   8 -rw-------  1 pkrumins users    8192 2009-02-16 19:30 .bash_history
   4 -rw-r--r--  1 pkrumins users     220 2009-01-18 21:04 .bash_logout
   ...

Netcat ile ilgili portu dinleyen program hakkında bilgi edinebiliriz.


[XXXX@XXXX ~]$ nc -vvv localhost 22
Connection to localhost 22 port [tcp/ssh] succeeded!
SSH-2.0-OpenSSH_5.3

Protocol mismatch.

Aynı mantıkla netcat port scanner olarak da kullanılabilir.

[XXXX@XXXX ~]$ nc -vvv -z targetip 1-65535

Not: Netcat için bazı paketlerde kısıtlamalar getirilmiştir.
Orjinal kaynaktan yüklemek için
* Microsoft
http://www.vulnwatch.org/netcat/nc111nt.zip

* Linux/Unix/BSD
http://www.vulnwatch.org/netcat/nc110.tgz

* GNU
http://netcat.sourceforge.net/

Neredeyim ben!?

Ekim, 2011 arşivinde geziniyorsun.