Friday, November 24, 2017

Python : Important code snippets

Important code Snippets
==============Data and Time: ==============
import datetime
print (datetime.datetime.now().day) # Result : 11
==============sorting reverse in list==============
liste=[1,5,9,2,3]
liste.sort(key=None, reverse=False)
Method2
Print(liste[::-1]
==============remove duplicates in list==============
l=[1,5,5,9,"a","b"]
liste=list(set(l))
==============Regex==============
import re
if(re.search(“.*ant.*”,”antelope”)):     #search
   print(True)
print(re.sub(r”expr”,string))              #replace
print(len(re.findall(“expr”,string))      #count
==============locals()==============
def test():
    a = 1
    b = 2
    c= 3
    return locals()
s=test()
print(s) #o/p:
(a,1) ,(b,2),(c,3),
print (type(s)) #
result : dict
==============Ranged if Condition==============
r=300
if (r in range(200,210,1)):
    print (True)
else:
    print(False)
or
if(200<r<210):
==============Validate type ==============
if isinstance(d,dict):print("hi")
if(type(d)==dict) :print(“True”)
====Higher order  functions (function name as) ====
def a():
    print("hi")
def b(func):
    func()
b(a) #
result :hi
====Higher order class (function name as) ====
class deco :   
    def func1(self):
        print ("funct1") 
    def func2(self,var):
        print(var)
              
def some_func(obj):
    obj(deco)
def some_func2(obj,var):
    obj(deco,var) 
  
some_func(deco.func1) #
O/p funct1
some_func2(deco.func2,"33") 
#O/p: 33
==============Keyword Arguments in a Function==============
def a(a=5,b): #wrong - non keyword args follow keyword ie., b should come before a
    print(a,b)
def a(b,a=5): #Correct
    print(a,b)
a(b=3,a=1)    #Result - 31
a(1,2)        #Result - 12
a(a=4,4)     #Error - non Keyword argument should come before keyword argument

=========List and tuple Arbitrary Argument in Function==============

def a(*a):
    for i in a:
        print(i)
a([1,2,3])
a((1,2,3))

Result:
[1,2,3]
(1,2,3)
==============Create sequential lists in 1 line==============
x=list(range(51,60,2))     #[51, 53, 55, 57, 59]
==============Slicing techniques==============
a=list(range(1,5))           #[1,2,3,4]
print(a[::-1])                                    #[4,3,2,1]  -reverse
print(a[::2])                   #[1,3]
print(a[::-2])                                    #[3,1]
print(a[1:-1:1])              #[2,3]
print(a[1:-1:-1])             #[]
print(a[-1:1:-1)]             #[4,3]
==============List into sublist or 1D to 2D==============
a=list(range(1,5))           #[1,2,3,4]
res=[a[i:i+2] for i in range(0,len(a),2)] #[[1,2][3,4]]
method2
m=[[i for i in range(j,j+3)] for j in range(1,7,3)]
#m = [[1, 2, 3], [4, 5, 6]]
===========Transpose a matrix using list comprehensions==============
n=[[m[i][j] for i in range(0,len(m))] for j in range(0,len(m[0]))]
Zip Matrix Transpose
n=list(zip(*m))              #list(zip(m[0],m[1])
Zip Combine 2 lists
a=[1,2,3]
b=[4,5,6]
print(list(zip(a,b)))
Combine sublists in 1 List
m = [[1, 2, 3], [4, 5, 6]]
l=m[0]+m[1]                 #l=[1,2,3,4,5,6]
List values into string
method 1 :List into string in 1 line
   l  = [1,2,3,7]
    print ("".join([str(x) for x in l] )

method 2:
    l = [1,2,3,7]
    for i in l:
        data=data+i
    print(data)

==============Type Conversions==============
s="deepak"
s=set(list(tuple(s)))
==============Dictionary (Format similar to JSON)
d={'a':'1','b':1}                     #dictionary creation
print(d.keys() , d.values() ) #['a', 'b'][2,3]),
print( 'a' in d)                        #True (list,set,tuple,str)
print(d.items())                   #'a':'1','b':1
d[“key”]=””value”              #access individual val
==============Add 2 Dictionaries==============
Res={**d1,**d2}
==============Exchange 2 variables==============
a,b=b,a
Count occurrences in a list in 1 line using re
import re
l=[1,1,2,4,4,4]
s=set(l)
res=[ len(re.findall(str(i),str(l)))  for i in s]           # [2, 1, 3]
==============Fibnocci -0,1,1,2,3,5,8…==============
res=[0,1]
for i in range(0,5,1):
    res=res+[res[-2]+res[-1]]
print(res)
==============Unit test==============
 1.”test” suffixed for unittest class.
 2. import unittest and class under test
 3. To run untitestuse:
D:\>C:\Python34\python.exe -m unittest testfile.area_test.circle_area_test

import unittest
class area():
 def circle_area(self,r):
  return(3.14*r**2)

class area_test(unittest.TestCase):
 def circle_area_test(self):
  a=area()
  self.assertAlmostEqual(a.circle_area(0),1)
  self.assertAlmostEqual(a.circle_area(0),0)
  self.assertRaises(valueError,a.circle_area(0),0)

Thursday, November 16, 2017

Python : Import Class from another file in same folder

Python : Import Class from another file in same folder



Assume :
             MyFolder
                         Class1.py = class Animals
                         Class2.py = class Fruit
                          Class3.py

To import Animal class and Fruit class inot Class3.py -

from MyFolder .Class1 import Animals
from MyFolder .Class2 import *
 



Monday, October 30, 2017

Python : Making REST Requests on Android Phone with Python

Making REST Requests on Android Phone with Python

Make sure the phone is connected to the network

1. Install Termux app on your Android phone
2. Open Termux 
3. Enter "apt install python"
4. Enter "y" when asked
5. After installation enter "python" to check the ver details .
6. Type "exit()"
7. Repeat same for python2 and python3

Once done 
8. Enter "pip install requests" in your termux prompt to install "requests" library for python
9. Repeat commands "pip install json"  and "pip install urllib3"
10. Open python using command python or python2
11. Run command :
>>import requests
 r=requests.get("http://www.google.com")
print(r)
<Response [200]>


Python : Automation with python using Chrome

Automation with python using Chrome

1.Open cmd prompt
2. Cd C:\Python34\Scripts\easyinstall.exe selenium
3. After Installation goto
https://sites.google.com/a/chromium.org/chromedriver/downloads
4. Download the latest Driver
5. extract and place chrome driver in any directory
Ex : D:\Tools\python_automation\chromedriver_win32\chromedriver.exe

import os
from selenium import webdriver
from selenium import webdriver
from selenium.webdriver.firefox.firefox_profile import FirefoxProfile
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary

#for i in range(1,50,1):
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--incognito")

chromedriver = "D:\Tools\python_automation\chromedriver_win32\chromedriver.exe"

os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(executable_path=chromedriver, chrome_options=chrome_options)
driver.maximize_window()

driver.get("https://hide.me/en/proxy") #driver.get("https://whoer.net/webproxy")
driver.find_element_by_xpath("//div[@class='input-group']//input").send_keys("voting")
driver.find_element_by_xpath("//button").click()

driver.find_element_by_xpath("//div[@class='wp-polls-ans']//li//*[text()='waker']").click()
driver.find_element_by_xpath("//input[@name='vote']").click()

Thursday, August 10, 2017

Linux : Basic Commands

Linux

Folder Structure
  • /bin -       These are the programs that make Linux run (ie., binaries in  LInux)
  • /etc -       configuration files are stored(usually txt format )
  • /dev -      similar to Windows device drivers.
  • /var -       log files, among other files, are stored.

Note:
·         Linux is Case- Sensitive
·         Linux allows us to modify its commands by using switches
·         switches are usually letters preceded by the dash (-)
·         With most commands, you can also use either the -h switch or the --help switch after the command to obtain "help".
·         Binaries are the files that are the equivalent of executables in Windows.
·         Binaries are files that do something like echo, ls, cd, mv, etc.
·         Probably the most important variable in our environment is our PATH variable

Summary:
1.       Network : whoami, ifconfig, dig, find
2.       Editing    : touch, cat, more ,less ,Nano,grep­ ,head ,tail ,sed ,nl
3.       File and Folders    : Pwd ,cd ,ls, mkdir  ,cp ,mv(move /rename), which, whereis ,locate ,unzip, , tar xvf, chmod , nzip
4.       System   : apt-get install, gcc , ps ,PID, ./,top ,set, export, uname-a, lsmod ,modproble –v/-r/-l
5.       Misc: man, echo, PS1,clear

Commands

present working directory> pwd
move me up one level> cd ..
name of the user we're logged in> whoami
Change Directory (Cd)> cd /newfolder
Listing Command (Ls)
> ls
> ls –la
-a switch means all
-l switch, it gives us info on the security permissions, the size, etc.,
Result: drwxr—r-x ……
d- directory
read/write/execute            =owner
only read                               =group
                read/execute                       =others
Create a File (Touch)> touch newfile
Create a Directory (Mkdir) > mkdir newdirectory
Getting Help (Man) > man touch
Copying Files (Cp) > cp /etc/newfile /root
Moving Files (Mv) > mv /root/newfile /
Viewing Files (Cat, More, Less,Nano)
> cat README
> more README
> less README
> Nano README
To view beginning of the file
>head /etc/snort/snort.conf
>head -30 /etc/snort/snort.conf
To view last lines of the file>tail /etc/snort/snort.conf
Numbering Those Lines>nl snort.conf
I Grep That
Only display lines with “database” in snort.conf file
>cat /etc/snort/ snort.conf | grep database
I Sed That Works
Replace every occurrence of mysql > MySQL
>sed s/mysql/MySQL/g snort.conf > snort2.conf
If I want to only replace the third occurrence of the word mysql and save as snort2.conf
sed s/mysql/MySQL/3 snort.conf > snort2.conf
Networking (Ifconfig)>ifconfig
Changing IP Addresses>ifconfig eth0 192.168.1.115 netmask 255.255.255.0 broadcast 192.168.1.255
DNS (Domain Name Service)
Translates to the appropriate IP address.
Linux users will often refer to DNS as BIND,
>dig wonderhowto.com ns
WonderHowTo's email servers.
>dig wonderhowto.com mx
Add or remove new server in the file below:
/etc/resolv.conf
Finding Files in a Directory (Find)
> find -name aircarck-ng
> find /pentest -name aircrack-ng
PATH variable contains path to bin directory
> echo $PATH
> which ls
Finding Any File in Any Directory (Whereis)> whereis aircrack-ng
Finding Files Using the Database (Locate)>locate aircrack-ng
Unzip>unzip DVWA-1.0.8.zip -d /var/www
Command Line Package Management or Installer>apt-get install aircrack-ng
Untar>tar xvf aircrack-ng-1.2-beta1.tar
Complie>gcc aircrack-ng
Install>./aircrack-ng
Changing permissions (read ,write,edit -> owner,group,user)
                Rwx=4 2 1=7
                rwxrwxrwx =>Chmod 777 readme= Chmod owner, group, user
                rw- r- - r- - =Chmod644 = Chmod Owner read write rest is read only
Running Process
                >ps aux
                >PID 5143
                >ps –A   
top processes>top
Killing Processes
>kill 5143
>kill -9 = No prisoners
View Our Environment Variables
>set HISTSIZE=123             
>echo $HISTSIZE
Adding application to path>PATH=$PATH:/pentest/wireless/aircrack-ng
Changing Our Terminal Prompt
                >PS1= "World's Best Hacker: #"
                >export PS1
Start Apache Daemon
                Goto Applications -> Services -> HTTPD and click on apache start.
Open  browser http://localhost/
Apache's default webpage is /var/www/index.html.
                User can edit this to displayed whatever he wants
Damn Vulnerable Web Application (DVWA)
                >  nzip DVWA-1.0.8.zip -d /var/www
                > chmod 755 DVWA-1.0.8 
Checking the Kernel
>; –a
or
>cat /proc/version
To tune kernel options>less /etc/sysctl.conf
List all drivers (Add a Module ie., driver)
                > lsmod   (lsmod is old)
Or
> modprobe –l

Add a Module(driver)
                > modprobe foo
                Finding info about a module
                > modinfo -v {module-name-here}
Remove a module (Driver)> modprobe -r foo


               


Thursday, August 3, 2017

Curl : Linux , unix




Curl (https://curl.haxx.se/docs/httpscripting.html )

Note : space = %20

See the Protocol $curl --trace-ascii debugdump.txt http://www.example.com/
See the Timing     $curl --trace-ascii d.txt --trace-time http://example.com/
See the Response -o or -O.
Host        $curl --resolve www.example.org:80:127.0.0.1 http://www.example.org/
Port number
$curl http://www.example.org:1234/
$curl --proxy http://proxy.example.org:4321 http://remote.example.org/
User name and password  $curl -u user:password http://example.org/
GET         $curl https://curl.haxx.se
ONLY the headers  (--head (-I))
Save file $ curl http://www.example.com -0 example.html
Multiple URLs (get)             $curl http://url1.example.com http://url2.example.com
To send first a HEAD and then a GET:$ curl http://www.tutorialspoint.com -0 tutorialspoint.html
Redirect  $ curl www.tutorialspoint.com/unix/ --location
A GET-form uses the method GET, as specified in HTML like:
 <form method="GET" action="junk.cgi">
 <input type=text name="birthyear">
 <input type=submit name=press value="OK">
 </form>
$curl "http://www.hotmail.com/when/junk.cgi?birthyear=1905&press=OK"
POST
<form method="POST" action="junk.cgi">
 <input type=text name="birthyear">
 <input type=submit name=press value=" OK ">
 </form>
$curl --data "birthyear=1905&press=%20OK%20"  http://www.example.com/when.cgi
$curl --data-urlencode "name=I am Daniel" http://www.example.com
(replaces  space with %20)
File Upload POST
<form method="POST" enctype='multipart/form-data' action="upload.cgi">
 <input type=file name=upload>
 <input type=submit name=press value="OK">
</form>
$curl --form upload=@localfilename --form press=OK [URL]
Hidden Fields
<form method="POST" action="foobar.cgi">
 <input type=text name="birthyear">
 <input type=hidden name="person" value="daniel">
 <input type=submit name="press" value="OK">
</form>
$curl --data "birthyear=1905&press=OK&person=daniel" [URL]
send a POST and then a GET:
$curl -d score=10 http://example.com/post.cgi --next http://example.com/results.html
two POSTs $curl --data name=$curl http://url1.example.com http://url2.example.com
PUT         $curl --upload-file uploadfile http://www.example.com/receive.cgi
Basic Authentication           $curl --user name:password http://www.example.com
Other Authentication         --ntlm, --digest, --negotiate ,--anyauth
Proxy Authentication         $curl --proxy-user proxyuser:proxypassword $curl.haxx.se



Tuesday, July 4, 2017

Create and Run Python Script in Linux Command Line

Create and Run Python Script in Linux Command Line


create python script in linux
  1.  cd scratch
  2. mkdir new_folder
  3. cd new_folder
  4. touch test.py
  5. vi test.py
  6. Press "i"  - this will open the file in edit mode
  7. Enter below lines :
    #! /usr/bin/python
    print('Hello, world!')
  8.  Press "esc"
  9. type ":wq!" without quotes
  10. chmod a+x test.py
  11. ./test.py