Saturday, February 23, 2019

Python: Strptime


strptime

String to datetime object = strptime
datetime object to other formats = strftime
Jun 1 2005 1:33PM is equals to %b %d %Y %I:%M%p
%b  - Month as locale’s abbreviated name(Jun)
%d   - Day of the month as a zero-padded decimal number(1)
%Y   - Year with century as a decimal number(2015)
%I   - Hour (12-hour clock) as a zero-padded decimal number(01)
%M  - Minute as a zero-padded decimal number(33)
%p   - Locale’s equivalent of either AM or PM(PM)
 Use slicing to remove unwanted characters if necessary.

Example :
>>> import time
>>> time.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')
time.struct_time(tm_year=2005, tm_mon=6, tm_mday=1,
                 tm_hour=13, tm_min=33, tm_sec=0,
                 tm_wday=2, tm_yday=152, tm_isdst=-1)

Sunday, February 17, 2019

Linux - Format USB Flash Drive

Linux - Format USB Flash Drive


  1. sudo apt-get install gparted
  2. By default it goes to the hard drive of your computer. 
  3. go to the top-right corner of the application and choose the removable media
  4. Before you go for formatting, unmount the disk by right-clicking on the partiti$
  5. right-clicking on it will show you the Format To option. Select FAT32 (Windows Compatible and Audio/Video Compatible).
  6. Edit > Apply all  Operations







Friday, February 15, 2019

Python : Simple CSV reader writer using Pandas

Sample CSV reader /Writer using pandas



import  pandas,os
p="/home/deepak/Python/testData/1.csv"

sheet=pandas.DataFrame( {"rollno":[1,2],"name":["a",'b']})
sheet.to_csv(p)

if(os.path.exists(p)):  
    Obj=pandas.read_csv(p)
    print(Obj.columns) #print all columns
    print(Obj['name'][1]) #Print 1 row 1 col value
    Obj.set_value(0,"name","deepak")
    Obj.to_csv(p)

Python : Change default 2.x version to 3.x in Linux

python : Change default 2.x version to 3.x in Linux



To open python 3x
python3

To install packages
pip3 install <package>




To change default

$python --verion
Python 2.4


# update-alternatives --install /usr/bin/python python /usr/bin/python2.7 1
update-alternatives: using /usr/bin/python2.7 to provide /usr/bin/python (python) in auto mode
 
 # update-alternatives --install /usr/bin/python python /usr/bin/python3.4 2
update-alternatives: using /usr/bin/python3.4 to provide /usr/bin/python (python) in auto mode
 
 
$python --verion
Python3.6

#select versions
update-alternatives --config python

Saturday, February 9, 2019

Version Control: GIT basic Commands in Linux


 GIT basic Commands in Linux


https://rubygarage.org/blog/most-basic-git-commands-with-examples
~~~~~~~~~~Clone Repository~~~~~~~~~~~~~~~
cd Documents
git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~give new name to your repository~~~~~~~~~~~~~~
git remote add gitPython https://github.com/j-thepac/Python_snippets.git #set git
cd to git folder
git remote
-------------------------------

~~~~~~~~~~~~~~~~~~~~~~~~Add new file into Git repository~~~~~~~~~~~~~~~

git add file #staging area ready to commit
#git add --all # to add all files to staging area
git status
git commit
#enter the title of the file
git push #push it to current version
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~Remove files from stagin area~~~~~~~~~~~~~
git rm --cached my-file.ts # remove file from staging area
#git reset
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
git mv [file-original] [file-renamed] # rename file

Wednesday, January 30, 2019

Security:Nmap

NMAP 



Nmap : Is a Port scanner of a particular server / Machine
#apt-get install namp
#pip install python-nmap

#python
import nmap
n=nmap.PortScanner()
res=n.scan('scanme.nmap.org','22')
print(res)

#Shell
nmap 'scanme.nmap.org' -p 22,80

#Use Zenmap for GUI 

Tuesday, January 29, 2019

Security:Wireshark

WireShark Tut


Summary :
    Wireshark is the network Packet Analyzer .Used to Analyize individual packets in an network by filtering the data accumulated by running it.
The main power lies in filtering the packet accumumulated. The Filtering as below:
1. Open Wireshark
2. Select the wireless/wired network
3. CLick Start Capture  - Wirestarts starts capturing data in new window
4. Select any packet in the packet list screen . Each packet contains data wrt OSI layer is shown in Packet details window
5. Open the tree in the Packet Details window and select last child and notice the status bar at the bottom gives filter condition which can be use
Eg:If u have selected a packet
Now in the Packet details window , Open Ethernet > Source >Select Address>
Bottom part gives you "eth.addr" which can be used in the filter field.


Basics:
1. Wireshark > Pref >capture > Promiscuous mode  (Monitor Mode)
2. protocol:
    udp:not reliable,used in chat /vid Conf, Very Fast
    tcp:
    icmp : ping
3. DNS(tcp /udp): port 53
4. Adding Filter :
    udp.port == 53|| tcp.port == 53
    ip.src == ip addr
    ip.dst == ip addr
    tcp.srcport == 53
    tcp.dst == xx
    tcp.port == xx
    udp.prt == xx
    ip.addr == 192.168.1.2 && (tcp.port == 53 || udp.port == 53)
5. Filter : http (packet sniffing http: video time 1:40-"The Complete Wireshark Course: Beginner to Network Admin!" )
6. iptables -I OUTPUT -p icmp -j DROP # stop ur PC to reply to pings
7. detect malicious traffic in ur network.
    lsof -i :port
    kill psd
8.Wireshark Command Mode :
a.tshark -h # help
b.tshark -D # List Interfaces
c.tshark -i wlan1mon #listen on multiple interfaces : tshark -i wlan1mon -i wlan0mon
d.tshark -i wlan1mon -w /tmp/result.pcap #write to file , can be opned only using wireshark
note: Can only be written into temp folder
e.tshark -i wlan1mon -a duraton:10 -w /tmp/duration.pcap #run for 10 secs
f.tshark -i wlan1mon -f "port80 or port 53 or port 443" -b filesize:5 -a files:3 -w /tmp/result.pcap
#filter ports , Max file size is 5kbs ,autostop after 3 files
9.watch -a 1 "ls -la" # Monitor a folder for every second
10. iwconfig # tells the mode of the card
11. ifconfig #ip addrs and mac address of network card
12. lspci #list all pci devices

~~~~~~~~~~~~WireShark Monitor Mode~~~~~~~~~~~~~~~~~~
Wireshark > Pref >capture > Promiscuous mode  (Monitor Mode)

1.Activate on Network Card  Monitor MOde
#Method 1
ifconfig wlan1 down
iwconfig wlan1 mode monitor
ifconfig wlan1 up
#Method2 (make sure aircrack-ng is installed)
airmon-ng start wlan1
2. airodump-ng wlan1mon #survillance of network traffic
3. airodump-ng --channel channel_no --bssid bssid_no --path/file #saves files in pcap and other formats
4. wireshark path/file # to open file

~~~~~~~~~~~~~~~~~~~~~Nmap with Wireshark -----------
Nmap : Is a Port scanner of a particular server / Machine
#apt-get install namp
#pip install python-nmap

#python
import nmap
n=nmap.PortScanner()
res=n.scan('scanme.nmap.org','22')
print(res)

#Shell
nmap 'scanme.nmap.org' -p 22,80

Wifi Monitot Mode : AirCrack-Ng


Wifi Monitot Mode : AirCrack-Ng 

Pre Req :
  1. ifconfig wlan0 down
  2. iwconfig # mode : Managed
  3. airmon-ng start wlan1



Steps :
1. airodump-ng wlan1mon
Here :
#mac address of NETGEAR : 20:xx:xx:xx:xx:xx
#BSSID: MAC address , PWR=Power,CH=Channel,PSK=Pre-shared Key,ESSID= Nw Name

2.
airodump-ng --bssid 20:xx:xx:xx:xx:EA --channel 6 --showack -w log wlan1mon
#Stations = Mac Address of devices , Frames = Device Active
#Mac Address of Laptop  : 74:xx:xx:xx:xx:53

#-w to write the results into current directory  
3 aireplay-ng -0 40 -a 20:xx:xx:xx:xx::EA -c 74:xx:xx:xx:xx:53 wlan1mo
#Here 0: Diconnection code , 40: Packets , -a router , -c target mac

4. Use wireshark to analyze the log.cap file

Method 2:
 1. Use Airgeddon instead

Sunday, December 16, 2018

Python : Data Driven Automation Framework using JSON Loader

Python : Data Driven Automation Framework using JSON Loader



import json


class json_py():

    def __init__(self,jsonFilePath,**kwargs):

        self.d= self.__readJson(jsonFilePath)

        

    def get_values(self,testCaseName):

        result_dict=self.d[testCaseName][0]

        return(result_dict)

    

    def __readJson(self,sPath):

        try:

            with open(sPath,"r") as F:

                return(json.loads(F.read()))

        except FileNotFoundError:

            print("Please provide correct file path")

        except ValueError:

            print("JSON is invalid")


sPath='D:\\personal\\json_python_2.json'

j=json_py(sPath)


print(j.get_values("testcase3")["data2"])



OutPut:
['hi', 'deepak']

---------------------------------------------------------------------------------------
json_python_2.json

{
"testcase1":[{ "id":1, "data1":["hi","deepak"]}],
"testcase2":[{ "id":2, "data1":["data"]}],
"testcase3":[{ "id":3,
                "data1":["hi","deepak"],
                "data2":["hi","deepak"],
                "data3":[{"key":"value"}]

}]
}

Sunday, April 29, 2018

Python : Super() vs Self

Python : Super() vs Self vs Classname

All 3 can be differentiated wrt to usage inside th child class. 

General Idea:
  1. Assume Class A , having a method m1
  2. Class B  is child of Class A 
  3. Class B has methods m1 ,m2
  4. If you want to call parent method m1 (ie., A().m1()) inside m1,m2 in Class B and use self , it will call the already exsisting method m1() in the same Class B  .
  5. Hence we use super() so that you are specifying python to use parent method.


super()
1.  Used inside child constructor to call parent constructor
2.  Used inside overriding method to call the parent method

self
1. Used to call method and properties of the same class
2. Used to call methods and properties of parent class


className
1. Can be used to call properties and methods of parent class.
2. Parent class name needs to be hardcoded
3. "self" needs to be sent as an arguement.

1.Mainly used inside child constructor to call parent constructor.
https://www.digitalocean.com/community/tutorials/understanding-class-inheritance-in-python-3
class Bird():
    name=None
    def __init__(self,name):
        self.name=name
    def bird_name(self):
        return(self.name)
    def fly(self):
        return("True")

class non_fly(Bird):
    swim=None
    def __init__(self,name,swim):   #Constr overriding
        super().__init__(name)      #call parent constr

       #  Bird.__init__(self, name) 
        self.swim=swim
    def fly(self):                  #Method Overrdiing
        return("false")

peng=non_fly("peng",True)
print(peng.bird_name(),peng.fly(),peng.swim)#inherit

2. Used in overriding method to class the parent method

class a():
    def m(self):
        return("m")


class b(a):       
    def m(self):
        #print(self.m()) #error - infinite loop case as it means m() in class b.
        print(a.m(self)) # here class name is hardcoded and need to send "self"  
        print(super().m()) #BETTER OPTION
B=b()
B.m() 


O/P:
m

 

3. MRO

Ref:
Python - MRO(Method Resolution Order)
https://stackoverflow.com/questions/30041679/python-self-and-super-in-multiple-inheritance


class a():
    def x(self):
        return("a")  
class b():
    def x(self):
        return("b")
class c(a):
    def s(self):
        print(super().x(),self.x())  #a,b

class d(b,c):
    pass
d().s()

print(d.mro()) 
#(<class '__main__.d'>, <class '__main__.b'>, <class '__main__.c'>, <class '__main__.a'>, <class 'object'>)

Note :
1. d().s()
2. goes to s() in class c
3. super() = wrt current class ie., super() of class c = class a .Therefore "a"
4. self - check if 1st parent has mentioned method , if not it goes to next parent .There class b has method x. Therefore "b"

Thursday, April 19, 2018

SOAP UI - Add Headers to all SOAP Ui Test Steps using Script

Add Headers to all SOAP Ui Test Steps using Script


import com.eviware.soapui.support.types.StringToStringMap 
 def headers = new StringToStringMap()
 headers.put("name","value");
 headers.put("name1","value1")
 headers.put("name2","value2")
 testRunner.testCase.testSteps.each
 {
  q->
  if(q.getValue().config.type.equals("restrequest") || q.getValue().config.type.equals("request"))
  {
   q.getValue().getHttpRequest().setRequestHeaders(headers)
  }
 }
 

Saturday, March 17, 2018

Python : OOPS important Concepts

Python: OOPS important Concepts
static and class method
'''static method : 

1.cannot access any properties
2. Can have no parameters at all.
Class method: 
1) Similar to static method but can use class properties .
2) Must have a reference to a class object as the first parameter’’’
class stat_test():
    var="private" #properties
    def method(self):
        return ("normal method")  
    @staticmethod
    def static_method(self):
            return(self.var)    
    @classmethod
    def class_method(self):
           return(self.var)
            
print(stat_test().method())   
#print(stat_test.static_method()) #error
print(stat_test.class_method())
print("#========#Access Modifiers(Encapsulation) DUNDEE =======")
private: "__" at the beginning and at most “_” at end
protected: "_" at the beginning and at most “_” at end (Convention only)
Restricted": "__a__" at beginning and at end

E.g.: print ("adasdsa".__len__()) #__name__ = inbuilt functions
'''
class a:
    pubv="pub"
    _prov="pro"
    __priv="priv"   
    def __init__(self):
        pass
    def pubm(self):
        return(self.pubv)
    def _prom(self):
        return(self._prov)      
    def __prim(self):
        return(self.__priv)         
 
class b(a):
    def __init__(self):
        pass 
    def priv(self):
        return(self.__priv)    
    def prov(self):
        return(self._prov)              
    def prim(self):
        return(self.__privm())
    def prom(self):
        return(self._prom())
    def pubm(self):
        return(super().pubm())

A=a()       
print(A.pubv,A._prov)
#print(A.__priv) # Error
print(A.pubm(),A._prom())
#print(A.__prim()) # Error

B=b()
#print(B.priv()) # Error
print(B.prov())
#print(B.prim()) # error
print(B.prom())
print("#====Constructor/Method Overriding and Inheritance===")

#Note : Overloading does not exist in python , only overriding exist
class Bird():
    name=None
    def __init__(self,name):
        self.name=name
    def bird_name(self):
        return(self.name)
    def fly(self):
        return("True")

class non_fly(Bird):
    swim=None
    def __init__(self,name,swim):        #Constr overriding
        super().__init__(name)              #call parent constr
       #  Bird.__init__(self, name) 
        self.swim=swim
   def swim(self):
        print(self.bird_name(),self.swim) #Method inheritance
    def fly(self):                                                  #Method Overrdiing
        return("false")

peng=non_fly("peng",True)
print(peng.bird_name(),peng.fly(),peng.swim)#inheritance
#O/P: peng false True
print("#==========#polymorphism===================")
#Polymorphism (Duck Typing)
'''In a duck-typed language (if it looks like a duck and quacks like a duck, it's a duck)
If the object  have the methods, then execute  else it raises a run-time error.’’’
class Duck():
   def quack(self):
      print ("Duck Quack")

class Mallard():
    def quack(self):
        print ("Mallard Quack")

#Polymorphism
for i in [Duck(), Mallard()]:
   i.quack()
print("#=============Abstract Class ==========")
#( At least 1 method is abstract,entire class = abstract class)
from abc import ABC, abstractmethod
class Abstract(ABC):
    @abstractmethod
    def foo(self):
        pass

#a=Abstract()#uncomment below to raise exception 
print("#=========Diamond problem============")
class Duck():
   def quack(self):
      print ("Duck Quack")
class Mallard():
    def quack(self):
        print ("Mallard Quack")
class c(Duck,Mallard):
                  def c(self):
                                    super().quack()
print(c().c()) #O/p = Duck Quack (as Duck appears 1st)
print("#=========super vs self vs class name============")
super()
1.  Used inside child constructor to call parent constructor
2.  Used inside overriding method to call the parent method
self
1. Used to call method and properties of the same class
2. Used to call methods and properties of parent class
3. Cannot be used inside overriding constructor or method as it creates infinite loop.
className
1. Can be used to call properties and methods of parent class.
2. Parent class name needs to be hardcoded
3. "self" needs to be sent as an arguement.
print(#=========multiple inheritance============")
class a():
    x="1"
    def a(self):
        return("2")
class b():
    y="3"
    def b(self):
        return("4") 
class c(a,b):
    z="5"
    def c(self):
        print(self.x,self.y,self.z,self.a(),self.b())
C=c()
C.c()
print(C.x,C.y,C.a(),C.b())