Saturday, June 30, 2018

Simple Socket programming in Python

CODE SNIPPEST:

import socket
import sys

try:
    s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error, msg:
    print "Failed to create Socket. Error code:" +str(msg[0])+ ", Error Message: "+str(msg[1])
    sys.exit();
   
print "Socket Created"

host = "www.google.co.in"   
port = 80

try:
    ip=socket.gethostbyname(host)
except socket.gaierror:
    print "Hostname cannot be resolved. Exiting"
    sys.exit();

print "Ip address of " +host+ " is "+ip

s.connect((ip,port))
print 'Socket Connected to ' + host + ' on ip ' + ip

message = "GET / HTTP/1.1\r\n\r\n"

try:
    s.sendall(message)
except socket.error:
    print 'Send failed'
    sys.exit()

print 'Message send successfully'
reply = s.recv(4096)
print reply

s.close()

OUTPUT:

root@Avinash:~/python_codes# python mysocket.py
Socket Created
Ip address of www.google.co.in is 216.58.196.67
Socket Connected to www.google.co.in on ip 216.58.196.67
Message send successfully
HTTP/1.1 200 OK
Date: Sat, 30 Jun 2018 11:29:23 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=ISO-8859-1
P3P: CP="This is not a P3P policy! See g.co/p3phelp for more info."
Server: gws
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Set-Cookie: 1P_JAR=2018-06-30-11; expires=Mon, 30-Jul-2018 11:29:23 GMT; path=/; domain=.google.com
Set-Cookie: NID=133=d2T-uloIWBpYFtZZkOgxRa3D5YKHvcSQcu2cEngv9fst00so9UPihEPJib77mxCLMmqBty9s8oFLXB8NKJrbLs5HWUBHLCNTy2Sq6RTffVsYX5Xx9Efhq3tFMY0Ni3MC; expires=Sun, 30-Dec-2018 11:29:23 GMT; path=/; domain=.google.com; HttpOnly
Accept-Ranges: none
Vary: Accept-Encoding
Transfer-Encoding: chunked

6359
<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en-IN"><head><meta content="text/html; charset=UTF-8" http-equiv="Content-Type"><meta content="/images/branding/googleg/1x/googleg_standard_color_128dp.png" itemprop="image"><title>Google</title><script nonce="shS6HW9QiUiwxER6omATaQ==">(function(){window.google={kEI:'k2k3W-HQEsf6vgTAqZmoBg',kEXPI:'0,1352961,786,57,1957,583,434,281,267,77,151,216,127,260,513,734,5,196,411,319,123,13,2339591,257,170,32,329294,1294,12383,2349,2506,32691,15248,867,1580,7,5105,5471,6381,3335,2,2,2138,4661,365,530,214,363,437,1776,113,1149,1052,1569,1622,224,502,5,75,261,45,1330,57,73,130,4628,479,444,131,1119,2,579,727,310,3,299,1819,59,2,2,2,1297,1343,369
root@Avinash:~/python_codes#

Port Scanner in python

CODE SNIPPEST:

#!/usr/bin/env python

import socket
import threading
import optparse

screenLock = threading.Semaphore(value=1)

def connect(src, port):
    try:
        s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.connect((src,port))
        s.send('ViolentPython\r\n')
        results = s.recv(100)
        screenLock.acquire()
        print '\n[+] Scan Results for: %s\n' % port
        print '[+]%s/tcp open\n'% port
        print '[+] ' + str(results)
    except:
        screenLock.acquire()
        print '\n[+] Scan Results for: %s\n' % port
        print '[-]%s/tcp closed\n'% port
    finally:
        screenLock.release()
        s.close()

def main():
    parser = optparse.OptionParser("usage%prog -s <source_ip> -p <ports>")
    parser.add_option("-s", "--source", dest="src",
            help="Source IP / Hostname to scan", metavar="SOURCE")
    parser.add_option("-p", "--ports",
            dest="ports", default='80,21,143,443',metavar="PORTS",
            help="port list e.g 21,80,8080")

    (options, args) = parser.parse_args()
    if options.src == None:
        print parser.usage
        exit(0)

    source = options.src
    ports = options.ports.split(',')

    for port in ports:
        t = threading.Thread(target=connect, args=(source,port))
        t.start()

if __name__ == "__main__":
    main()


OUTPUT:

root@Avinash:~/python_codes# python port_scanner.py -s 192.168.0.105

[+] Scan Results for: 80

[-]80/tcp closed


[+] Scan Results for: 143

[-]143/tcp closed


[+] Scan Results for: 21

[-]21/tcp closed


[+] Scan Results for: 443

[-]443/tcp closed

root@Avinash:~/python_codes#

Interactive EvenOdd in python

CODE SNIPPEST:

print "****************  EVEN ODD CALCULATOR  ****************"
even_list=[]
odd_list=[]
flag=0
ch='y'
while ch=='y':
    print "Current Even_list:\n"+str(even_list)
    print "Current Odd_list:\n"+str(odd_list)
    num = raw_input("Enter a Number to Check:\t")
    if num in even_list:
        print num+" is even. Already in Even List"
    elif num in odd_list:
        print num+" is odd. Already in Odd List"
    else:
        try:
            if int(num) % 2 == 0:
                msg = num+" is an even number... Do you want to enter it in Even List?(y/n)"
                res = raw_input(msg)
                if res=='y':
                    even_list.append(num)
                    print num+" added in Even List"
                    flag=1
                elif res=='n':
                    print "Exiting..."
                else:
                    print "Wrong Input. Exiting..."
            else:
                msg = num+" is an odd number... Do you want to enter it in Odd List?(y/n)"
                res = raw_input(msg)
                if res=='y':
                    odd_list.append(num)
                    print num+" added in Odd List"
                    flag=2
                elif res=='n':
                    print "Exiting..."
                else:
                    print "Wrong Input. Exiting..."
        except:
            print "Please enter a Integer Value"

        if flag==1:
            print "Updated Even_list:\n"+str(even_list)
        elif flag==2:
            print "Updated Odd_list:\n"+str(odd_list)
    ch=raw_input("Do you want to continue(Y/n)?")
    if ch.lower() != 'y' and ch.lower() != 'n':
        ch = raw_input("Please type (Y/n)?")
    if ch.lower() != 'y':
        ch='n'
        print "Exiting..."
        print "-----------------------------------\nEVEN NUMBERS: %s\nODD NUMBERS: %s" %(str(even_list),str(odd_list));

OUTPUT:

root@Avinash:~/python_codes# python evenodd.py
****************  EVEN ODD CALCULATOR  ****************
Current Even_list:
[]
Current Odd_list:
[]
Enter a Number to Check:    2
2 is an even number... Do you want to enter it in Even List?(y/n)y
2 added in Even List
Updated Even_list:
['2']
Do you want to continue(Y/n)?y
Current Even_list:
['2']
Current Odd_list:
[]
Enter a Number to Check:    3
3 is an odd number... Do you want to enter it in Odd List?(y/n)y
3 added in Odd List
Updated Odd_list:
['3']
Do you want to continue(Y/n)?n
Exiting...
-----------------------------------
EVEN NUMBERS: ['2']
ODD NUMBERS: ['3']
root@Avinash:~/python_codes#

Encrypt string in Python

import sys, hashlib, getopt

def hashCal(argv):
    string=''
    salt=''
    option=''
    try:
        opts, args = getopt.getopt(argv,"s:x:o:")
    except:
        print_usage()
        sys.exit()

    for opt, arg in opts:
        if(opt=='-h'):
            print_help()
            sys.exit()
        elif(opt=='-s'):
            string = arg
        elif(opt=='-o'):
            option = arg

    print "Entered String: %s" % (string)
    print "Your Selection: %s" % (option)

    if(option == 'md5'):
        m = hashlib.md5()
    elif(option == 'sha1'):
        m = hashlib.sha1()
    m.update(string)
    print "%s Encrypted strng: %s" %(option, str(m.digest()))


def print_usage():
    print "usage: encryption.py -s <string> -o <option>(eg: sha1,md5)"
   
def print_help():
    print "usage: encryption.py -s <string> -o <option> -o <options>: \nmd5\nsha1"

if __name__ == "__main__":
    try:
        if len(sys.argv) == 1:
            raise
        argvs = sys.argv[1:]
    except:
        print_usage()
        sys.exit()
   
    hashCal(argvs)


OUTPUT:

root@Avinash:~/python_codes/Security# python encryption.py
usage: encryption.py -s <string> -o <option>(eg: sha1,md5)
root@Avinash:~/python_codes/Security# python encryption.py -s 'avinash' -o 'sha1'
Entered String: avinash
Your Selection: sha1
�U\�N)��r �Fed strng: T� �,if
root@Avinash:~/python_codes/Security# root@Avinash:~/python_codes/Security# python encryption.py -s 'avinash' -o 'md5'
Entered String: avinash
Your Selection: md5
md5 Encrypted strng: ��u 0�)�Fk
                               h9k
root@Avinash:~/python_codes/Security#

If / If Else / While in Python



If / If-Else / If-Elif-Else Statement:

Syntax:
  if <condition statement> :
       <block of code>
  elif:
       <block of code>
  else:
       <block of code> 

Will understand this loop directly with examples.

>>> a=20
>>> if a== 20:
...     print a
...
20
>>>


But above code won't print anything if  I changed value of a to 10.

>>> a=10
>>> if a== 20:
...     print a
...
>>>

To handle this, we can add else statement.

>>> a=10
>>> if a== 20:
...     print("a is 20")
... else:
...     print("a is not 20")
...
a is not 20
>>>

Now let us consider i want to check number is even or odd and print accordingly.

Problem statement:
if number is even print EVEN
if number is odd print ODD
if number is 0 print NEITHER EVEN NOR ODD


let's consider, if I use if-else statement, i can print any two statements from above.
Hence to achieve such thing, we can use elif statement.

>>> a = 2;
>>> if a==0:
...     print("NEITHER EVEN NOR ODD")
... elif a % 2 == 0:
...     print("EVEN")
... else:
...     print("ODD")
...
EVEN
>>>



While Statement:

Syntax:

while <condition>:
   <block of code>


Block of code run unless and until condition is true.
Let's consider I want  to print 0 to 10. Then our code will like:

>>> i = 1
>>> while(i<=10):
...     print(i)
...     i = i+1
...
1
2
3
4
5
6
7
8
9
10
>>>

Don't forget to write i = i+1. Otherwise your screen get full of 11111111. At that time you need to press ctrl+c to interrupt the loop

Note that while using WHILE statement in code, make sure that at-least once the condition written in while bracket should return a false otherwise loop will run infinite times.

Interactive shell in Python

Important Note:

There is no curly brackets({}), semicolons(;) in python.

Only constraint in python is that your code should be indented.

If there is difference of single space also, lead to indentation error. i.e. (IndentationError: expected an indented block)

By typing python on command line, you will enter in interactive  mode.

In interactive mode, the primary prompt is `>>>'; the second prompt (which appears when a command is not complete) is `...'.


root@Avinash:~/python_codes/Security# python
Python 2.7.14+ (default, Dec  5 2017, 15:17:02)
[GCC 7.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

you can execute any code in interactive mode.

Here I am giving two useful commands.
1) dir
2) help

To use these commands, you have to import that package, by using import statement.

>>> import os
>>> dir(os)
['EX_CANTCREAT', 'EX_CONFIG', 'EX_DATAERR', 'EX_IOERR', 'EX_NOHOST', 'EX_NOINPUT', 'EX_NOPERM', 'EX_NOUSER', 'EX_OK', 'EX_OSERR', 'EX_OSFILE', 'EX_PROTOCOL', 'EX_SOFTWARE', 'EX_TEMPFAIL', 'EX_UNAVAILABLE', 'EX_USAGE', 'F_OK', 'NGROUPS_MAX', 'O_APPEND', 'O_ASYNC', 'O_CREAT', 'O_DIRECT', 'O_DIRECTORY', 'O_DSYNC', 'O_EXCL', 'O_LARGEFILE', 'O_NDELAY', 'O_NOATIME', 'O_NOCTTY', 'O_NOFOLLOW', 'O_NONBLOCK', 'O_RDONLY', 'O_RDWR', 'O_RSYNC', 'O_SYNC', 'O_TRUNC', 'O_WRONLY', 'P_NOWAIT', 'P_NOWAITO', 'P_WAIT', 'R_OK', 'SEEK_CUR', 'SEEK_END', 'SEEK_SET', 'ST_APPEND', 'ST_MANDLOCK', 'ST_NOATIME', 'ST_NODEV', 'ST_NODIRATIME', 'ST_NOEXEC', 'ST_NOSUID', 'ST_RDONLY', 'ST_RELATIME', 'ST_SYNCHRONOUS', 'ST_WRITE', 'TMP_MAX', 'UserDict', 'WCONTINUED', 'WCOREDUMP', 'WEXITSTATUS', 'WIFCONTINUED', 'WIFEXITED', 'WIFSIGNALED', 'WIFSTOPPED', 'WNOHANG', 'WSTOPSIG', 'WTERMSIG', 'WUNTRACED', 'W_OK', 'X_OK', '_Environ', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_copy_reg', '_execvpe', '_exists', '_exit', '_get_exports_list', '_make_stat_result', '_make_statvfs_result', '_pickle_stat_result', '_pickle_statvfs_result', '_spawnvef', 'abort', 'access', 'altsep', 'chdir', 'chmod', 'chown', 'chroot', 'close', 'closerange', 'confstr', 'confstr_names', 'ctermid', 'curdir', 'defpath', 'devnull', 'dup', 'dup2', 'environ', 'errno', 'error', 'execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe', 'extsep', 'fchdir', 'fchmod', 'fchown', 'fdatasync', 'fdopen', 'fork', 'forkpty', 'fpathconf', 'fstat', 'fstatvfs', 'fsync', 'ftruncate', 'getcwd', 'getcwdu', 'getegid', 'getenv', 'geteuid', 'getgid', 'getgroups', 'getloadavg', 'getlogin', 'getpgid', 'getpgrp', 'getpid', 'getppid', 'getresgid', 'getresuid', 'getsid', 'getuid', 'initgroups', 'isatty', 'kill', 'killpg', 'lchown', 'linesep', 'link', 'listdir', 'lseek', 'lstat', 'major', 'makedev', 'makedirs', 'minor', 'mkdir', 'mkfifo', 'mknod', 'name', 'nice', 'open', 'openpty', 'pardir', 'path', 'pathconf', 'pathconf_names', 'pathsep', 'pipe', 'popen', 'popen2', 'popen3', 'popen4', 'putenv', 'read', 'readlink', 'remove', 'removedirs', 'rename', 'renames', 'rmdir', 'sep', 'setegid', 'seteuid', 'setgid', 'setgroups', 'setpgid', 'setpgrp', 'setregid', 'setresgid', 'setresuid', 'setreuid', 'setsid', 'setuid', 'spawnl', 'spawnle', 'spawnlp', 'spawnlpe', 'spawnv', 'spawnve', 'spawnvp', 'spawnvpe', 'stat', 'stat_float_times', 'stat_result', 'statvfs', 'statvfs_result', 'strerror', 'symlink', 'sys', 'sysconf', 'sysconf_names', 'system', 'tcgetpgrp', 'tcsetpgrp', 'tempnam', 'times', 'tmpfile', 'tmpnam', 'ttyname', 'umask', 'uname', 'unlink', 'unsetenv', 'urandom', 'utime', 'wait', 'wait3', 'wait4', 'waitpid', 'walk', 'write']
>>>

>>> import os
>>> help(os)

DIR:
this will display the list of classes, functions and variables used in that package.

Help:
This will display the detailed information about the package like man command.

You can also use -c option to excute command on terminal (not in interactive mode).

root@Avinash:~/python_codes/Security# python -c 'print("hii")'
hii
root@Avinash:~/python_codes/Security#

Python installation in Ubuntu and Centos

To install python in ubuntu / centos follow these steps:

1) sudo apt-get install python (For UBUNTU)
1) yum install python  (For CENTOS)
 
2) You can verify python version by running python -V command
e.g.
root@Avinash:~# python -V
Python 2.7.14+
root@Avinash:~#

3) Now let us install pip utility.
    pip is a package management utility used to install and manage Python packages.
      run below command to install pip.
      apt-get install python-pip (For UBUNTU)
     yum install python-pip (For CENTOS)

4) Now, you can see the list of installed python packages by simply running any of the following command.
    i) pip list
    ii) pip freeze

e.g
root@Avinash:~# pip list
anyjson (0.3.3)
argcomplete (1.8.1)
argh (0.26.2)
attrs (17.2.0)


root@Avinash:~# pip freeze
adns-python==1.2.1
anyjson==0.3.3
argcomplete==1.8.1
argh==0.26.2
attrs==17.2.0


5) Now you can install any package using pip.
e.g
root@Avinash:~# pip install redis
Collecting redis
  Downloading https://files.pythonhosted.org/packages/3b/f6/7a76333cf0b9251ecf49efff635015171843d9b977e4ffcf59f9c4428052/redis-2.10.6-py2.py3-none-any.whl (64kB)
    100% |████████████████████████████████| 71kB 687kB/s
Installing collected packages: redis
Successfully installed redis-2.10.6
root@Avinash:~#

root@Avinash:~# pip freeze | grep redis
redis==2.10.6
root@Avinash:~#

You can check number of options provided by pip using pip help command.

Hurray!!!!
Python is installed. now we are ready to code in python

Welcome



Dear Friends…..
Hi,
Welcome to my new blog THE CODE STORE”. Here, you will find simple source codes and theory on various technical topics. You will get the codes and basic information of PYTHON, Linux [Ubuntu / Centos].
If you want any help on PERL, please let me know, I will share that too here. 
It is better if I stop talking more and start technical work.
So guys, visit this blog and find your relevant code, if content are irrelevant, you can tell me on avinashghadshi93@gmail.com.

You can also connect me on linked in at:
https://www.linkedin.com/in/avinash-ghadshi-284606a0/ 

Thank You.