×

PyShark in Python

Python:

Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way. The python language can also be used in web development; Django and Flask are the frameworks used to create web applications using Python.

In Python, indentation is the main concept; if we do not follow proper indentation, then the program will not run properly, and we will get an error in the output. Python programming language contains methods or functions to reduce the size of the code, and the python programming language provides built-in functions and user-defined functions. We can import the functions in the python programming language through the libraries, which can be downloaded using the python package manager (pip). While working on the project and we want to develop the project using the python programming language.

The python programming language makes our work easy by providing built-in functions, with these imported using the # import. The import statement is used to impost the modules or built-in functions into the program so we can develop the project efficiently and faster. Python programming language is an object-oriented and high-level language it is easier to learn when compared to other programming languages.

The python programming language contains mainly six built-in datatypes; these six data types help solve the problem efficiently and faster. The python programming language consists of a built-in function and provides libraries and modules that can be imported to solve the problem more efficiently. Generally, there are many versions of python interpreters available. Still, from them, we need to download the version of Python more significantly than or equal to 3.4 so that the code runs faster and we can observe the output in the console.

Now let us consider the pyshark as a wrapper for the Tshark; the primary use of the pyshark is to export the XML data into the Tshark. The Tshark acts as the command-line version of the Wireshark. T Shak working is similar to the TCP dump command, but in addition, the Tshark has abilities like detection, reading and writing of the same captured files; the Wireshark also supports these files. The Pyshark is developed and maintained by the Dan.

Pyshark Python:

Pyshark is simply a wrapper for the Tshark; the main use of the Pyshark is to export the XML data into the Tshark. The Tshark acts as the command-line version of the Wireshark. T Shak working is similar to the TCP dump command, but in addition to that, the Tshark has abilities like detection, reading and writing of the same captured files; the Wireshark also supports these files. The Pyshark is developed and maintained by the Dan. The pyshark can be installed using the python package manager ( pip ); it is installed using the following command:

Command:

Pip3 install python-pyshark

Now let us observe the program of the pyshark program for connecting the Pyshark to the Tshark.

Example 1:

def __init__(self, pcapfile, scapy_packs=None, tshark_packs=None):
        """Initialization method of the class.


        Parameters
        ----------
        pcapfile : str
            Path to a previously captured pcap.
        scapy_pkts : :obj:`PacketList`
            List of packets generated by Scapy.
        tshark_pkts : :obj:`FileCapture`
            List of packets generated by Pyshark.


        """
        if scapy_pkts:
            self._scapy_packs = scapy_packs
else:
            self._scapy_packs = rdpcap(pcapfile)
        if tshark_pkts:
            self._tshark_pacs = tshark_pacs
        else:
            self._tshark_pacs = FileCapture(pcapfile)
        self._i = -1 

Example 2:

def get_records(self):
"""Parse the btsnoop file into a dictionary of records"""
if self.snoop_file is None and self.pcap_file is None:
            raise ValueError("Must load a btsnoop or PCAP file to get records")
            return


        if self.snoop_file is not None:
            try:
                records = BTS.parse(self.snoop_file)
            except Exception as e:
                print "Error: "
                print e.message
                return None
        elif self.pcap_file is not None:
            py_cap = pyshark.FileCapture(self.pcap_file)
            records = []
            for packet in py_cap:
                records.append(packet)
        self.records = records
        return records 

Example3:

def run(self):


		cap = pyshark.FileCapture(self.filename,summaries=True)
		i = j = 0
		resultdump=[]
		for p in cap:
			ret = self.traffic_analyze(p)
			i = i+1
			if not ret:
			# 	print("[Result] No security issues.")
			#else:
				j = j+1
				#print("[Result] WARNING: Trojan has been discovered.")
				#print(p.no, p.protocol, p.source, p.destination,'\n')
				time = time.asctime(time.local time(time.time()))
				hash=hashlib.md5()
				hash1=p.protocol+p.destination
				hash.update(hash1.encode('utf-8'))
				conn=sqlite3.connect("home guard.db")
				#print("Opened database successfully!")
				resultdict=dict()
				resultdict['dev']=self.device_name
				resultdict['time']=ttime
				resultdict['num']=p.no
				resultdict['des']=p.destination
				resultdict['protocol']=p.protocol
				resultdict['hash']=hash.hexdigest()
				resultdump.append(resultdict)


				sql="insert into Result(dev,time,num,des,protocol,hash)values('%s','%s','%s','%s','%s','%s')"%(self.device_name,ttime,p.no,p.destination,p.protocol,hash.hexdigest())
				conn.execute(sql)
				conn.commit()
				conn.close()
				#print("Close database successfully!")
				


		#print(j,"/",i,'\n')
		#print(self.domain_ip,'\n')
		#print(self.new_ip)
		#print(self.device_ip)
		print(resultdump) 

Related Topics

Python program to find Fibonacci series

Python program to find Fibonacci series A Fibonacci series is an integer sequence of 0, 1, 1, 2, 3, 5, 8.... We can identify the Fibonacci series as any number sequence...

2 minutes read.

_dict_ in Python

An unordered collection of data values known as a dictionary can be used in Python to store data values similar to a map. Dictionaries can also store a key: value...

6 minutes read.

How to set font for Text in Python

As a tuple with the font family as the first component, a size in point as the second, and possibly a string with one or more of the style modifiers...

5 minutes read.

Python String encode() method

Python String encode() method The string.encode() method in Python returns an encoded version of the string. The default encoding is the current default string encoding Syntax String.encode([encoding[,errors]]) Parameter Encoding: This parameter represents a String specifying...

2 minutes read.

How to convert integer to float in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

5 minutes read.

Python program to print array element present at even position

Python program to print array element present at even position In this program, we'll see a Python program that prints the elements of an array that are in even positions. We...

1 minute read.

OS Module in Python

What is a module? The Modules are the kind of files that contains python statements and definitions. The module is known by the name of the file followed by the suffix...

8 minutes read.

Creating Web Application in python

Web Application :  Web Application is an application software that runs in web browser . Software programs will run on operating system. Whereas Web Applications will run on World Wide Web...

5 minutes read.

Python Program for Linear Search

Introduction We employ specific algorithms to efficiently carry out our responsibilities, such as searching for an element in a given data structure. These algorithms fall under the category of searching algorithms....

4 minutes read.

Inheritance in Python

Inheritance in Python Object-Oriented Programming provides reusable patterns to the code for restricting the redundancy in development projects. One of the basic principles of Object-Oriented Programming that helps achieve recyclable code...

8 minutes read.

Classes & Objects in Python

Classes and Objects are used in most modern programming languages, mainly in Object-oriented Programming languages. What is meant by Object Oriented Programming language? Usage of objects and their components in order to...

7 minutes read.

Python Breakpoint

Introduction In Python 3.7, a brand-new created function called breakpoint() was added. Due to the close relationship between both the executable and the code of a debugging component, debugging Python programming...

4 minutes read.

How to Define a Function in Python?

What is a Function? In programming, a piece of code that executes a specific task or a group of related operations is known as a function. What does Python Functions Do? If you...

6 minutes read.

Import py file in Python

In Python programming language, a module is a single layer of block of Python code that can be loaded and used by importing into other Python block of code. A module...

4 minutes read.

Python String ljust() method

Python String ljust() method The string.ljust() method in Python will left align the string, where the padding is done using the parameter fillchar (space is default). Syntax String.ljust(width[, fillchar]) Parameter width: This parameter represents the...

2 minutes read.

Python Program to Find the Greatest Among Three Numbers

Python Program to find the greatest among three numbers We have many approaches to get the largest of three numbers, and here we will discuss a few of them. This python...

2 minutes read.

Python Argmin

Introduction The argmin function is defined as numpy.argmin(). This function returns the index of the minimum value or element from a Numpy array in a specific axis. An array is taken...

3 minutes read.

Python Permutations and Combinations

In mathematics, we all studied what is meant by permutations and combinations. “Permutations” define the way of arranging the elements in sequential order. “Combinations” mean the way of selecting the...

7 minutes read.

Enumerate() Function in Python

The enumerate() function in Python is used to convert a data collection object into an enumerate object. It returns an object that contains a counter as a key for each...

3 minutes read.

Python String index() method

Python String index() method The string.index() method in Python finds the lower index of the first occurrence of the specified value or raise a ValueError if the substring is not found. Syntax index(sub[, start[, end]]) Parameter sub:...

2 minutes read.