Wednesday, September 26, 2012

Closure in Python

Yesterday i tried closure , One can easily use the function as variable 

You can see my session here and use of closure :



...:) B-)

Reference :

Sunday, September 16, 2012

Screen : An awesome terminal tool

Today, i get to know about a awesome tool : Screen. Sometimes we need to switch among the terminal to see them. Screen simplified the whole thing.
Now one can see the more than one terminal on single terminal view.

Here , you can see my terminal :






















I divided my terminal into horizontal and vertical subterminals.

Following are the steps to use screen :

1. install screen :
       sudo apt-get install screen

2. on terminal write screen and press enter. follow the instruction.

3. split screen
       Horizontal :
                 press ctrl+a then S (upper case)
        Vertical :
                 press ctrl+a then |
4. start screen
               press ctrl+a then c

enjoy your terminal ...


:) B-)

Reference :
http://www.rackaid.com/resources/linux-screen-tutorial-and-how-to/
http://unix.stackexchange.com/questions/7453/how-to-split-the-terminal-into-more-than-one-view

Saturday, September 15, 2012

Communicating with two language

Previously we implemented the python server. Now it's time to bring up our client part.
Android Client will send downloading url to Python server and Python Server will download the passed URL.

You can see the code repository (Python Server) :
 https://github.com/subh007/Python/blob/master/server_PC.py

You can see the code repository (Android Client) :
 https://github.com/subh007/Android_Client/tree/master/AndroClient

screen shot of client:

Android Client
Python Server












:) B-)

Wednesday, September 12, 2012

String handling in Python

Sometimes we get a url and we need to retrieve the filename from the url ( like http://some_url/filename.mp3).

This can be done easily in python.

>>> string = 'http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ObjectiveC/ObjC.pdf'
 

>>> string.split('/')
['http:', '', 'developer.apple.com', 'library', 'mac', 'documentation', 'Cocoa', 'Conceptual', 'ObjectiveC', 'ObjC.pdf']
 

>>> print string.split('/')[-1]
ObjC.pdf



:) B-)
 

Threading in Python

My previous post were related to server and client. I need to enhance my server
so that it can handle multiple clients.

To handle such requirement i thought to redesign my server. Each client request
to server and server will start download in separate thread for requested url.
This will enhance my server design and now my server can handle multiple client
simultaneously.

So here is some threading concepts in python:

There are two ways to specify the activity: by passing a callable object to the constructor, or by overriding the run() method in a subclass.

A simple example:

 import threading
 import datetime
        
 class ThreadClass(threading.Thread):
          def run(self):
            now = datetime.datetime.now()
            print "%s says Hello World at time: %s" % 
            (self.getName(), now)
        
 for i in range(2):
          t = ThreadClass()
          t.start()
 
Another more simplistic example :

import time
from threading import Thread

def myfunc(i):
    print "sleeping 5 sec from thread %d" % i
    time.sleep(5)
    print "finished sleeping from thread %d" % i

for i in range(10):
    t = Thread(target=myfunc, args=(i,))
    t.start()

-- :) B-)
       
Reference :
http://docs.python.org/library/threading.html
http://www.ibm.com/developerworks/aix/library/au-threadingpython/
http://www.saltycrane.com/blog/2008/09/simplistic-python-thread-example/

Source code:
https://github.com/subh007/Python/blob/master/multithread1.py
https://github.com/subh007/Python/blob/master/multithread.py
 
 

Tuesday, September 11, 2012

Server extended to download file.

In previous post i created a server-client pair using the python.
It is enhanced in such a way that client will pass a download link
to server and server will download the link.

import sys
import socket
sys.path.append('/home/subhash/subh/python/requests')
import requests
s=socket.socket()
hostname=socket.gethostname()
port=9595
s.bind((hostname,port))
s.listen(5)
while True:
    print 'server started'
    conn,addr=s.accept()
    data=conn.recv(1024)
    print(data)
    r=requests.get(data)
    with open('downloded.pdf',"wb") as code:
     code.write(r.content);
     print 'page downloaded'
    conn.close()
s.close()


you can see the code in git. :) B-)

How to kill the process at port XXXX

Sometime we require to kill the process at port.

For example.

s=socket.socket()
hostname=socket.gethostname()
port=9494
bind((hostname,port))

...
..
(pressed ctrl+d)

this will cause the process to still run on port 9494. So whenever we try to
bind the same port to another proce then it will give error:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/python2.7/socket.py", line 224, in meth
    return getattr(self._sock,name)(*args)
error: [Errno 98] Address already in use

So, we need to kill the process at that port and it is done by:

$kill -9 `fuser -n tcp 9494`

:) B-)

Monday, September 10, 2012

Download files using request

This is simple example to use request for downloading the files.

import urllib

import sys
#adding the requests http://docs.python-requests.org/en/latest/index.html
import requests
print sys.argv[1]
# url to download
r=requests.get(sys.argv[1])
with open(sys.argv[2],"wb") as code:
#argv[2] is target file name
 code.write(r.content)
 

here, argv[1] is the link for the download file ( ex.- https://google.com) 
and argv[2] is the target file (ex. google.html).

run it by
#python script.py http://google.com google.html

happy coading :) B-)

Reference:
download code from git
http://docs.python-requests.org/en/latest/

Sunday, September 9, 2012

Simple Server - Client program in python

I got a good example for server client in python.

Server :

#!/usr/bin/python           # This is server.py file
 import socket               # Import socket module
s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
 
print 'Server started!'
print 'Waiting for clients...'
 
s.bind((host, port))        # Bind to the port
s.listen(5)                 # Now wait for client connection.
c, addr = s.accept()     # Establish connection with client.
print 'Got connection from', addr
while True:
   msg = c.recv(1024)
   print addr, ' >> ', msg
   msg = raw_input('SERVER >> ')
   c.send(msg);
   #c.close()                # Close the connection




Client :


#!/usr/bin/python           # This is client.py file
 
import socket               # Import socket module
s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                # Reserve a port for your service.
 
print 'Connecting to ', host, port
s.connect((host, port))
 
while True:
    msg = raw_input('CLIENT >> ')
    s.send(msg)
    msg = s.recv(1024)
    print 'SERVER >> ', msg
#s.close                     # Close the socket when done






Reference :
http://www.dscripts.net/2010/06/18/how-to-create-a-client-server-socket-connection-in-python/

 

Tuesday, February 28, 2012

installing libcap

I faced lot of problem in installing libcap (library for sniffing packet). You can easily install it in ubuntu by installing the package libpcap0.8-dev.

#sudo apt-get install libpcap0.8-dev

and during compilation of any program using pcap.h
 compile it

#gcc prog.c -lpcap -o prog

enjoy coding.. :) B-)

Saturday, February 11, 2012

Task bar in ubuntu 11.10 using tint2

I started to use ubuntu 11.10 but i faced a problem that is absence of taskbar . Taskbar is not available with unity desktop.

So i google out the things and got "tint2" .

install tint2
            $ sudo apt-get install tint2

setup tint2 in startup program
            goto  control (right upper most widget ) ---> startup application 


and fill the entry
                  name        :  tint2
         command      :  tint2
click on add . Restart your computer and enjoy the taskbar...
for more help



 here at bottom we have the tasskbar..

happy coding... :) B-)

Linux file system

Many of us which are new to linux, usually get confused between linux and windows file system. Because Linux has completely different file structure than windows. Linux has its file system rooted to '/'  and each sub folder for some specific job and they have special meaning.

Yesterday I found a very good blog that explains the file system of linux and  objective of each sub directories and their location too.

Linux file system hierarchy 
good blog to understand Linux file system

It help me a lot to understand the file system. hope this will help you in journey of linux.

-- enjoy coding

Thursday, February 2, 2012

Firefox 10 for Ubuntu !!!! (released yesterday)

here we can get latest version of firefox....

add the repository of firefox
#sudo add-apt-repository ppa:ubuntu-mozilla-security/ppa
 
update it
#sudo apt-get update
 
install firefox
#sudo apt-get install firefox
 
enjoy coding... :) B-)

Wednesday, February 1, 2012

some basic command of git

adding user name
#git config --global user.name "Trinity"

set email address
#git config --global user.email "trinity@gmail.com"

.gitconfig file in home folder will contain above information

creating clone of project :
#git clone <link>

to see history of project
#git log

creating a project

create folder for project
#mkdir Trinity

#cd Trinity

#git init


to check the status
#git status

to commit the modification

#git commit -m 'msg'

to add files to track
#git add .

to see last commit
#git show

Working with git

when i build git from its source then i tried to clone a project then i face a problem  :

" fatal : Unable to find remote helper for 'https' "

actually it require curl and expat support.

remove the previous git
#apt-get remove git-core

install the git with new source with support of curl and expat
#tar -zxvf git-1.x.x.tar.gz
#cd git-1.x.x
#./configure --with-curl --with-expat
#make
#make install


now we can enjoy git without any error....


Enjoy Coding.. :) B-)

Monday, January 23, 2012

Command to know information for partation..

list partition
                      $fdisk -l 

disk space usage:
                      $df -h     or       $df -k

display mount point :
                      $mount

quickly mount all file system present in /etc/fstab
                       $mount -a

File system mount points and other information present in /etc/fstab

Saturday, January 14, 2012

Scapy - Easy packet generation

Scapy is a python command based packet generation tool. It help to create packet very easily. It has full control over protocol stack. We can alter all the bits in the packet and modify any packet according to our wish.

installing scapy:
                          $ wget scapy.net
                          $ unzip scapy-latest.zip
                          $ cd scapy-2.*
                          $ sudo python setup.py install

starting scapy:
                         $ scapy



Documentation present at : www.dirk-loss.de/scapy-doc/Scapy.pdf


Sample code: [ICMP packet generation ]
                     
root@bt:~# scapy
WARNING: No route found for IPv6 destination :: (no default route?)
Welcome to Scapy (2.1.0)
>>> a= ICMP()
>>> b= IP()
>>> c=Ether()
>>> d=c/b/a

>>> d.display()
###[ Ethernet ]###
  dst= ff:ff:ff:ff:ff:ff
  src= 00:00:00:00:00:00
  type= 0x800
###[ IP ]###
     version= 4
     ihl= None
     tos= 0x0
     len= None
     id= 1
     flags=
     frag= 0
     ttl= 64
     proto= icmp
     chksum= None
     src= 127.0.0.1
     dst= 127.0.0.1
     \options\
###[ ICMP ]###
        type= echo-request
        code= 0
        chksum= None
        id= 0x0
        seq= 0x0
>>> send (d)       // sending the packet d into network


## send () is used when we are injecting packet at layer3.
and if we want to send packet with modification at layer 2 entry then we will use sendp() to send packet.
otherwise we will get a warning message. 
      >>> send(ether/ip/icmp)
WARNING: Mac address to reach destination not found. Using broadcast.
.
Sent 1 packets.


for more information

enjoy coding.. :) B-)