×

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

How to run a Program in Python

How to run a Program in Python Writing a program in Python is an easy task, beginners who are ready to kickstart their career in the world of programming can create...

3 minutes read.

Python Assert

Python Assert Python provides an assert statement which is used to check the logical expression. If the given logical expression is true, then it precedes for the next line; otherwise, it raises an...

2 minutes read.

Anaconda in Python 3

What is Anaconda in Python 3? Anaconda is an open-source package combining Python and R programming languages used for data analytics and processing data. It consists of a huge number of...

4 minutes read.

BOTTLE Python Web Framework

The Bottle is a lightweight WSGI micro web framework for python. It acts like a thin wrapper around a web server where it is distributed as a single file module...

4 minutes read.

Difference between Package and Module in Python

What are Python modules? A file with the “.py” suffix that includes Python or C executable code is known as a module. Multiple Python commands and expressions make compose a module....

3 minutes read.

Python pow() Function

Python pow() Function The pow() function in Python return the parameter ‘x’ to the power ‘y’ and if the parameter ‘z’ is present, it returns x to the power y, modulo z (computed more efficiently than pow(x, y) % z). Syntax pow(x, y[, z]) Parameter x: This parameter represents the base...

1 minute read.

Joint Plot in Python

Introduction to Joint plots: The joint plot is the finest approach to evaluate both the specific distribution of each variable and also the connection between the two variables. Three different plots make...

4 minutes read.

Python List pop() method

Python List pop() method The list.pop() method removes the item at the specified position in the list, and return it. If no index is specified, this method removes and returns the last item in the list. Syntax list.pop([i]) Parameter i:...

1 minute read.

How to Substring a String in Python

String Unicode characters collection is referred to as a String. It consists of a succession of characters, including alphanumeric and special characters. Substring: Core Concept A substring is a piece of a string....

5 minutes read.

Palindrome In Python

What is Palindrome? A Palindrome can be defined as the number or a string that resides unchanged when it is reversed. Example: 14341 Output: Yes, this is a Palindrome number Example: RACECAR Output: Yes, this...

2 minutes read.

Python Lists vs Tuples

The difference between lists and tuples is one of the most frequently asked questions in an interview related to python language. Lists and Tuples are two of Python’s built-in data...

4 minutes read.

Python Loop through a Dictionary

Introduction in this tutorial, we will discuss in python How to Loop Through a Dictionary. In contrast to other Data Types, which can only retain a single value as an element, a Dictionary...

4 minutes read.

Python complex() class

Python complex() class The complex() class in Python returns a complex number or converts a string or number to a complex number. Syntax class complex([real[, imag]]) Parameter Real: This parameter consists of a number representing the real...

1 minute read.

How to check the version of the Python Interpreter?

As we all know what an interpreter is, and how important it is. We should also be aware of the fact that it is important to have knowledge of the...

2 minutes read.

How to Install PIP In Python

How to Install PIP In Python The libraries for Python have made our work easier than we expected. From a simple addition of two numbers to applying algorithms on the big...

4 minutes read.

Find Last Occurrence of Substring using Python

Introduction When planning to work with strings, we may need to determine whether a substring is present. This issue is rather typical, and there have been numerous discussions about how to...

3 minutes read.

Python String rsplit() method

Python String rsplit() method The string.rsplit() method in Python splits a string into a list, starting from the right. If the "max" parameter is not specified, this method will return the...

1 minute read.

Simple GUI calculator using PyQt5 in Python

GUI: The user is provided with information using manipulable visual widgets that don't require command-line input. These interface components respond to the user's interactions per the pre-programmed script, assisting each user's...

4 minutes read.

Python Namespace

In python, the namespace is a very important concept that should be understood before using any function or variables. When we write code, we often use variables, libraries, functions, modules, etc....

4 minutes read.

Merge Sort using Python

Merge Sort is a technique that is used for sorting elements in an array using a special method known as divide and conquer. It is the best example of the...

5 minutes read.