I want to capture the limited number of packet. for example, while I am using the command python python.py -I eth0 -c 10 then I wan to capture only 10 number of packet and exit but I am getting error.the below are the code and erro I am getting.
!/usr/bin/python
import argparse
import pyshark
import time
import re as regex
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--interface', metavar=" ", type=str, required = True, help = 'To specify the interface ')
parser.add_argument('-v', '--verbose', required = False, action = 'store_true', help = 'To print the all layer of packet')
parser.add_argument('-o', '--output', metavar=' ', help = 'To capture and save the pcap in a file')
parser.add_argument('-p', '--protocol', metavar=' ', help= 'To capture packet using ptotocl filter')
parser.add_argument('-u', '--udp', action = 'store_true', help = 'To capture udp packet only')
parser.add_argument('-t', '--tcp', action = 'store_true', help = 'To capture tcp packet only')
parser.add_argument('-c', '--count', metavar=' ',default=1, help = 'To capture limited number of packet')
args = parser.parse_args()
if args.protocol:
capture = pyshark.LiveCapture(interface=args.interface, display_filter=args.protocol)
elif args.udp:
capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='udp')
elif args.tcp:
capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='tcp')
else:
capture = pyshark.LiveCapture(interface=args.interface, output_file=args.output)
capture.sniff(packet_count = args.count)
packet_list = []
for packet in capture.sniff_continuously():
if 'IP Layer' in str(packet.layers):
protocol = regex.search(r'(Protocol:)(.*)',str(packet.ip))
protocol_type = protocol.group(2).strip().split(' ')[0]
# proto = protocol_type
localtime = time.asctime(time.localtime(time.time()))
proto = protocol_type
src_addr = packet.ip.src
dst_addr = packet.ip.dst
length = packet.length
print (localtime, '\t' , proto, '\t' ,src_addr, '\t', dst_addr, '\t' , length)
if args.verbose:
print(packet.show())
error
python python.py -i eth0 -c 10
Traceback (most recent call last):
File "/home/kali/python.py", line 32, in <module>
capture.sniff(packet_count = args.count)
File "/home/kali/.local/lib/python3.10/site-packages/pyshark/capture/capture.py", line 144, in load_packets
self.apply_on_packets(
File "/home/kali/.local/lib/python3.10/site-packages/pyshark/capture/capture.py", line 256, in apply_on_packets
return self.eventloop.run_until_complete(coro)
File "/usr/lib/python3.10/asyncio/base_events.py", line 646, in run_until_complete
return future.result()
File "/home/kali/.local/lib/python3.10/site-packages/pyshark/capture/capture.py", line 267, in packets_from_tshark
await self._go_through_packets_from_fd(tshark_process.stdout, packet_callback, packet_count=packet_count)
File "/home/kali/.local/lib/python3.10/site-packages/pyshark/capture/capture.py", line 299, in _go_through_packets_from_fd
if packet_count and packets_captured >= packet_count:
TypeError: '>=' not supported between instances of 'int' and 'str'
File "/home/kali/.local/lib/python3.10/site-packages/pyshark/capture/capture.py", line 299, in _go_through_packets_from_fd
if packet_count and packets_captured >= packet_count:
TypeError: '>=' not supported between instances of 'int' and 'str'
It is expected that packet_count is an integer. But packet count is taken from the command line (args) and thus is as string unless explicitly given otherwise:
parser.add_argument('-c', '--count', metavar=' ',default=1, help = 'To capture limited number of packet')
...
capture.sniff(packet_count = args.count)
To fix this args.count either must be converted to int explicitly or the proper type should be given when parsing the args with the type argument:
parser.add_argument('-c', '--count', type=int, metavar=' ', default=1, help = 'To capture limited number of packet')
Related
I want to capture the limited number of packet. for example, while I am using the command python python.py -I eth0 -c 10 then I wan to capture only 10 number of packet and exit but I am printing many packets instead of 10. please tell me where am I wrong.
#!/usr/bin/python
import argparse
import pyshark
import time
import re as regex
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--interface', metavar=" ", type=str, required = True, help = 'To specify the interface ')
parser.add_argument('-v', '--verbose', required = False, action = 'store_true', help = 'To print the all layer of packet')
parser.add_argument('-o', '--output', metavar=' ', help = 'To capture and save the pcap in a file')
parser.add_argument('-p', '--protocol', metavar=' ', help= 'To capture packet using ptotocl filter')
parser.add_argument('-u', '--udp', action = 'store_true', help = 'To capture udp packet only')
parser.add_argument('-t', '--tcp', action = 'store_true', help = 'To capture tcp packet only')
parser.add_argument('-c', '--count', metavar=' ',type=int, default=1, help = 'To capture limited number of packet')
args = parser.parse_args()
if args.count:
capture = pyshark.LiveCapture(interface=args.interface)
capture.sniff(packet_count = args.count)
elif args.protocol:
capture = pyshark.LiveCapture(interface=args.interface, display_filter=args.protocol)
elif args.udp:
capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='udp')
elif args.tcp:
capture = pyshark.LiveCapture(interface=args.interface, bpf_filter='tcp')
else:
capture = pyshark.LiveCapture(interface=args.interface, output_file=args.output)
# capture.sniff(packet_count = args.count)
packet_list = []
for packet in capture.sniff_continuously():
if 'IP Layer' in str(packet.layers):
protocol = regex.search(r'(Protocol:)(.*)',str(packet.ip))
protocol_type = protocol.group(2).strip().split(' ')[0]
# proto = protocol_type
localtime = time.asctime(time.localtime(time.time()))
proto = protocol_type
src_addr = packet.ip.src
dst_addr = packet.ip.dst
length = packet.length
print (localtime, '\t' , proto, '\t' ,src_addr, '\t', dst_addr, '\t' , length)
if args.verbose:
print(packet.show())
output
I am capturing more than 10 packets.
capture.sniff(packet_count = args.count)
This will immediately read the given number of packets
for packet in capture.sniff_continuously():
This will read packets without any limit.
So if you want to only read the number of packets don't immediately call sniff when parsing the args.count argument but instead apply packet_count = args.count later to sniff_continously:
for packet in capture.sniff_continuously(packet_count = args.count):
I am trying to do the port scanner from the Violent Python and I ran into following problem. This post will be similar to this post ("https://stackoverflow.com/questions/17807992/violent-python-port-inputs-not-being-seperated") but it is a different problem. I want to run multiple port like this
python PortScanner.py -H www.google.com -p 21, 22, 80
but it scanned only the initial first port (21) then exited the program So I want to know how can I fix this code to run multiple ports.
Note: It also said that args in (option, args) = parser.parse_args() is not accessible by Pylance so is it concern to it or how can I fix it as well.
import optparse
import socket
from socket import *
def connscan(tgtHost,tgtPorts):
try:
connSkt= socket(AF_INET,SOCK_STREAM)
connSkt.connect((tgtHost, tgtPorts))
connSkt.send('Violent Python\r\n')
results = connSkt.recv(100)
print ('[+]%d/tcp open'% tgtPorts)
print ('[+]' + str(results))
connSkt.close()
except:
print ('[-]%d/tcp closed'% tgtPorts)
def PortScan(tgtHost,tgtPorts):
try:
tgtIP=gethostbyname(tgtHost)
except:
print ("[-] Cannot resolve '%s': Unkown host"%tgtHost)
return
try:
tgtName= gethostbyaddr(tgtIP)
print ("\n[+] Scan Result for: "+ tgtName[0])
except:
print ("\n[+] Scan Result for: " + tgtIP)
setdefaulttimeout(1)
for tgtPort in tgtPorts:
print ("Scanning Port " + tgtPort)
connscan(tgtHost,int(tgtPort))
def main():
parser = optparse.OptionParser('Usage: %prog -H ' +\
'<target host> -p <target port>')
parser.add_option('-H', dest = 'tgtHost', type = 'string', \
help = 'specify target host')
parser.add_option('-p', dest = 'tgtPort', type = 'int', \
help = 'Specify target port' )
(options,args) = parser.parse_args()
tgtHost = options.tgtHost
tgtPorts = str(options.tgtPort).split(',')
if ( tgtHost == None) | (tgtPorts[0] == None):
print(parser.usage)
exit (0)
print(*tgtPorts, sep=", ")
PortScan(tgtHost,tgtPorts)
if __name__ == '__main__':
main()
I managed to solve the problem by changing the type of tgtPort from int to string and use quote as following at the command line python PortScanner.py -H www.google.com -p "21, 22, 80".
I have a project that needs to get a recorded file and then process by the code and extract the text from file and match the extracted file with the other text and verify it.
my problem is:
I can't use recorded file in code and it does'nt read the file
init function is the fundamental of code.
verify functtion confirm the matched speech and text.
import argparse
import json
import os
import queue
import random
import sys
from difflib import SequenceMatcher
import numpy as np
import sounddevice as sd
import vosk
q = queue.Queue()
def int_or_str(text):
"""Helper function for argument parsing."""
try:
return int(text)
except ValueError:
return text
def callback(indata, frames, time, status):
"""This is called (from a separate thread) for each audio block."""
if status:
print(status, file=sys.stderr)
q.put(bytes(indata))
def init():
parser = argparse.ArgumentParser(add_help=False)
parser.add_argument(
'-l', '--list-devices', action='store_true',
help='show list of audio devices and exit')
args, remaining = parser.parse_known_args()
if args.list_devices:
print(sd.query_devices())
parser.exit(0)
parser = argparse.ArgumentParser(
description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter,
parents=[parser])
parser.add_argument(
'-f', '--filename', type=str, metavar='FILENAME',
help='audio file to store recording to')
parser.add_argument(
'-m', '--model', type=str, metavar='MODEL_PATH',
help='Path to the model')
parser.add_argument(
'-d', '--device', type=int_or_str,
help='input device (numeric ID or substring)')
parser.add_argument(
'-r', '--samplerate', type=int, help='sampling rate')
args = parser.parse_args(remaining)
try:
if args.model is None:
args.model = "model"
if not os.path.exists(args.model):
print("Please download a model for your language from https://alphacephei.com/vosk/models")
print("and unpack as 'model' in the current folder.")
parser.exit(0)
if args.samplerate is None:
device_info = sd.query_devices(args.device, 'input')
# soundfile expects an int, sounddevice provides a float:
args.samplerate = int(device_info['default_samplerate'])
model = vosk.Model(args.model)
if args.filename:
dump_fn = open(args.filename, "wb")
else:
dump_fn = None
except KeyboardInterrupt:
print('\nDone')
parser.exit(0)
except Exception as e:
parser.exit(type(e).__name__ + ': ' + str(e))
return model, args
def verify(random_sentence, model, args):
num, T_num, F_num, num_word = 0, 0, 0, 1
with sd.RawInputStream(samplerate=args.samplerate, blocksize=8000, device=args.device, dtype='int16',
channels=1, callback=callback):
rec = vosk.KaldiRecognizer(model, args.samplerate)
print("{}) ".format(num_word), random_sentence, end='\n')
print('=' * 30, end='\n')
run = True
while run:
data = q.get()
if rec.AcceptWaveform(data):
res = json.loads(rec.FinalResult())
res['text'] = res['text'].replace('ي', 'ی')
if SequenceMatcher(None, random_sentence, res['text']).ratio() > 0.65:
T_num, num, num_word += 1
else:
F_num, num, num_word += 1
run = False
print('=' * 30)
print('True Cases : {}\n False Cases : {}'.format(T_num, F_num))
if __name__ == "__main__":
model, args = init()
verify(random_sentences, model, args)
I have been working on a similar project. I modified the code from VOSK Git repo and wrote the following function that takes file name / path as the input and outputs the captured text. Sometimes, when there is a long pause (~seconds) in the audio file, the returned text would be an empty string. To remedy this problem, I had to write additional code that picks out the longest string that was captured. I could make do with this fix.
def get_text_from_voice(filename):
if not os.path.exists("model"):
print ("Please download the model from https://alphacephei.com/vosk/models and unpack as 'model' in the current folder.")
exit (1)
wf = wave.open(filename, "rb")
if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getcomptype() != "NONE":
print ("Audio file must be WAV format mono PCM.")
exit (1)
model = Model("model")
rec = KaldiRecognizer(model, wf.getframerate())
rec.SetWords(True)
text_lst =[]
p_text_lst = []
p_str = []
len_p_str = []
while True:
data = wf.readframes(4000)
if len(data) == 0:
break
if rec.AcceptWaveform(data):
text_lst.append(rec.Result())
print(rec.Result())
else:
p_text_lst.append(rec.PartialResult())
print(rec.PartialResult())
if len(text_lst) !=0:
jd = json.loads(text_lst[0])
txt_str = jd["text"]
elif len(p_text_lst) !=0:
for i in range(0,len(p_text_lst)):
temp_txt_dict = json.loads(p_text_lst[i])
p_str.append(temp_txt_dict['partial'])
len_p_str = [len(p_str[j]) for j in range(0,len(p_str))]
max_val = max(len_p_str)
indx = len_p_str.index(max_val)
txt_str = p_str[indx]
else:
txt_str =''
return txt_str
Make sure that the correct model is present in the same directory or put in the path to the model. Also, note that VOSK accepts audio files only in wav mono PCM format.
I'm new to Python and the socket library, and the book I'm reading is called Black Hat Python. There's an exercise in the book that requires the reader to essentially glue together (or re-write) pieces of code in order to create a Netcat clone. I believe I have successfully done this, as I can run the command "python3 netcat.py --help" without any issues. However, when I try to run the command "python3 netcat.py -t 192.168.0.58 -p 5555 -c -l", I'm given this: AttributeError: 'NetCat' object has no attribute 'run'
How do I fix this?
Here's the code:
import argparse
import socket
import shlex
import subprocess
import sys
import textwrap
import threading
def execute(cmd):
cmd = cmd.strip()
if not cmd:
return
output = subprocess.check_output(shlex.split(cmd), stderr=subprocess.STDOUT)
return output.decode()
class NetCat:
def __init__(self, args, buffer=None):
self.args = args
self.buffer = buffer
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def run(self):
if self.args.listen:
self.listen()
else:
self.send()
def send(self):
self.socket.connect((self.args.target, self.args.port))
if self.buffer:
self.socket.send(self.buffer)
try:
while True:
recv_len = 1
response = ''
while recv_len:
data = self.socket.recv(4096)
recv_len = len(data)
response += data.decode
if recv_len < 4096:
break
if response:
print(response)
buffer = input('> ')
buffer += '\n'
self.socket.send(buffer.encode())
except KeyboardInterrupt:
print("User terminated.")
self.socket.close()
sys.exit()
def listen(self):
self.socket.bind((self.args.target, self.args.port))
self.socket.listen(5)
while True:
client_socket, _ = self.socket.accept()
client_thread = threading.Thread(target=self.handle,args=(client_socket,))
client_thread.start()
def handle(self, client_socket):
if self.args.execute:
output = execute(self.args.execute)
client_socket.send(output.encode())
elif self.args.upload:
file_buffer = b''
while True:
data = client_socket.recv(4096)
if data:
file_buffer += data
else:
break
with open(self.args.upload, 'wb') as f:
f.write(file_buffer)
message = f'Saved file {self.args.upload}'
client_socket.send(message.encode())
elif self.args.command:
cmd_buffer = ''
while True:
try:
client_socket.send(b'BHP: #> ')
while '\n' not in cmd_buffer.decode():
cmd_buffer += client_socket.recv(64)
response = execute(cmd_buffer.decode())
if response:
client_socket.send(response.encode())
cmd_buffer = b''
except Exception as e:
print(f'Server killed {e}')
self.socket.close()
sys.exit()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Net Tool', formatter_class=argparse.RawDescriptionHelpFormatter,epilog=textwrap.dedent('''Example:
netcat.py -t 192.168.1.108 -p 5555 -l -c # command shell
netcat.py -t 192.168.1.108 -p 5555 -l -u=mytest.txt # upload to file
netcat.py -t 192.168.1.108 -p 5555 -l -e=\"cat /etc/passwd\" # execute command
echo 'ABC' | ./netcat.py -t 192.168.1.108 -p 135 # echo text to server port 135
netcat.py -t 192.168.1.108 -p 5555 # connect to server
'''))
parser.add_argument('-c', '--command', action='store_true', help='command shell')
parser.add_argument('-e', '--execute', help='execute specified command')
parser.add_argument('-l', '--listen', action='store_true', help='listen')
parser.add_argument('-p', '--port', type=int, default=5555, help='specified port')
parser.add_argument('-t', '--target', default='192.168.1.203', help='specified IP')
parser.add_argument('-u', '--upload', help='upload file')
args = parser.parse_args()
if args.listen:
buffer = ''
else:
buffer = sys.stdin.read()
nc = NetCat(args, buffer.encode())
nc.run()
This looks like an indentation error. The only method that currently belongs to the class NetCat is __init__. The methods below it, starting with run(self) do not have the same indentation as the __init__ so they don't "belong" to the class NetCat.
Indentation is extremely important in python. It specifies so-called code blocks. If you put the definition for the method run on the same indentation level as the method __init__, then the method run will "belong" to the class NetCat.
On a side note, it is standard to indent with 4 spaces in python. I highly advise you to follow this standard ASAP, as habits are easy to learn but hard to break. I suggest to use a proper code editor like Visual Studio Code or even Notepad++ as they auto-indent when appropriate.
==============================================
EDIT:
I've indented the code in such a way that it should work. Note the difference in indentation for all the methods starting from run. Since they are now in the code block for the class NetCat, they "belong" to this class. I cannot overstate how important indentation is in python. It is one of the core concepts of python, and knowing what it does and how it behaves is absolutely necessary if you want to write any code in python.
import argparse
import socket
import shlex
import subprocess
import sys
import textwrap
import threading
def execute(cmd):
cmd = cmd.strip()
if not cmd:
return
output = subprocess.check_output(
shlex.split(cmd), stderr=subprocess.STDOUT)
return output.decode()
class NetCat:
def __init__(self, args, buffer=None):
self.args = args
self.buffer = buffer
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def run(self):
if self.args.listen:
self.listen()
else:
self.send()
def send(self):
self.socket.connect((self.args.target, self.args.port))
if self.buffer:
self.socket.send(self.buffer)
try:
while True:
recv_len = 1
response = ''
while recv_len:
data = self.socket.recv(4096)
recv_len = len(data)
response += data.decode
if recv_len < 4096:
break
if response:
print(response)
buffer = input('> ')
buffer += '\n'
self.socket.send(buffer.encode())
except KeyboardInterrupt:
print("User terminated.")
self.socket.close()
sys.exit()
def listen(self):
self.socket.bind((self.args.target, self.args.port))
self.socket.listen(5)
while True:
client_socket, _ = self.socket.accept()
client_thread = threading.Thread(
target=self.handle, args=(client_socket,))
client_thread.start()
def handle(self, client_socket):
if self.args.execute:
output = execute(self.args.execute)
client_socket.send(output.encode())
elif self.args.upload:
file_buffer = b''
while True:
data = client_socket.recv(4096)
if data:
file_buffer += data
else:
break
with open(self.args.upload, 'wb') as f:
f.write(file_buffer)
message = f'Saved file {self.args.upload}'
client_socket.send(message.encode())
elif self.args.command:
cmd_buffer = ''
while True:
try:
client_socket.send(b'BHP: #> ')
while '\n' not in cmd_buffer.decode():
cmd_buffer += client_socket.recv(64)
response = execute(cmd_buffer.decode())
if response:
client_socket.send(response.encode())
cmd_buffer = b''
except Exception as e:
print(f'Server killed {e}')
self.socket.close()
sys.exit()
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Net Tool', formatter_class=argparse.RawDescriptionHelpFormatter, epilog=textwrap.dedent('''Example:
netcat.py -t 192.168.1.108 -p 5555 -l -c # command shell
netcat.py -t 192.168.1.108 -p 5555 -l -u=mytest.txt # upload to file
netcat.py -t 192.168.1.108 -p 5555 -l -e=\"cat /etc/passwd\" # execute command
echo 'ABC' | ./netcat.py -t 192.168.1.108 -p 135 # echo text to server port 135
netcat.py -t 192.168.1.108 -p 5555 # connect to server
'''))
parser.add_argument('-c', '--command', action='store_true',
help='command shell')
parser.add_argument('-e', '--execute', help='execute specified command')
parser.add_argument('-l', '--listen', action='store_true', help='listen')
parser.add_argument('-p', '--port', type=int,
default=5555, help='specified port')
parser.add_argument(
'-t', '--target', default='192.168.1.203', help='specified IP')
parser.add_argument('-u', '--upload', help='upload file')
args = parser.parse_args()
if args.listen:
buffer = ''
else:
buffer = sys.stdin.read()
nc = NetCat(args, buffer.encode())
nc.run()
I got a python code to backup mongodb on daily basis but I am getting attribute error. The error details are below.
Traceback (most recent call last):
File "C:\Users\sanja\Desktop\Mongo backup.py", line 76, in <module>
backup(args)
File "C:\Users\sanja\Desktop\Mongo backup.py", line 25, in backup
url = args.url
AttributeError: 'Namespace' object has no attribute 'url'
import os
import argparse
import logging
import datetime
import urlparse
import subprocess
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser(description='Backup Mongolab DBs')
parser.add_argument('-u', '--url mongodb://192.168.32.11:27017/test',
type=str,
required=False,
default=None,
help='Mongo DB URL for Backups')
parser.add_argument('-o', '--output_dir F:\\DB_backup',
type=str,
required=False,
default='./',
help='Output directory for the backup.')
def backup(args):
today = datetime.datetime.now()
url = args.url
if url is None:
logging.info('Fetching MONGOLAB_URI using heroku config:get')
url = subprocess.check_output([
'heroku',
'config:get',
'MONGOLAB_URI'
]).strip()
url = urlparse.urlparse(url)
assert url.scheme == 'mongodb', 'mongodb://192.168.32.11:27017/test'
# netloc = url.netloc
# username = url.username
# password = url.password
hostname = url.hostname
port = url.port
db = url.path[1:]
output_dir = os.path.abspath(os.path.join(os.path.curdir,
args.output_dir))
assert os.path.isdir(output_dir), 'Directory %s can\'t be found.' %
output_dir
output_dir = os.path.abspath(os.path.join(output_dir,
'%s__%s'% ( db, today.strftime('%Y_%m_%d_%H%M%S'))
))
logging.info('Backing up %s from %s to %s' % (db, hostname, output_dir))
backup_output = subprocess.check_output(
[
'mongodump',
'-host 192.168.32.11', '%s' % hostname,
# '-u', '%s' % username,
# '-p', '%s' % password,
'-d test', '%s' % db,
'--port 27017', '%s' % port,
'-o F:\\DB_backup', '%s' % output_dir
])
logging.info(backup_output)
if __name__ == '__main__':
args = parser.parse_args()
try:
backup(args)
except AssertionError, msg:
logging.error(msg)
When using argparse, the error
AttributeError: 'Namespace' object has no attribute 'property'
means that the property is not defined in the args parameter. In this case, you expected to define an argument of the name url, but looking at your code:
parser.add_argument('-u', '--url mongodb://192.168.32.11:27017/test', ...
you created a property called '--url mongodb://192.168.32.11:27017/test'. Your declaration should be:
parser.add_argument('-u', '--url', ...
You can't put a value in with the declaration; maybe you meant to define a default instead?
parser.add_argument('-u', '--url',
type=str,
required=False,
default='mongodb://192.168.32.11:27017/test',
help='Mongo DB URL for Backups')
The same applies for the other argument defined.