i need to send a packet using scapy to a dns server i made, and for some reason the server doesnt get the packet
this is the dns server
-- coding: utf-8 --
from scapy.all import *
def le_check(p):
return (DNS in p and p[0][DNSQR].qtype == 1 and p[0][UDP].dport==53)
def main():
data_base = {'www.google.com': ('172.217.23.164','173.194.79.104','173.194.79.99')}
p1=sniff(count=1, lfilter=le_check)
x=p1[0][DNSQR].qname
if x in data_base:
list=data_base[x]
else:
list= "no such name"
print p1[0][DNSQR].qname
print list
send(IP(dst=p1[0][IP].src)/UDP(sport=53, dport=53)/Raw(list))
if __name__ == '__main__':
main()
code from scapy
sendp(IP(dst=MY_IP)/UDP(sport=24601,dport=53)/DNS(qdcount=1,rd=1)/DNSQR(qname="www.google.com",qtype=1))
Related
`#!/usr/bin/env python
from scapy.all import *
from threading import Thread
def icmp_spoof(pkt):
if pkt.haslayer(ICMP) and pkt[IP].src == "10.9.0.1":
src_ip = pkt[IP].dst
dst_ip = pkt[IP].src
seq_num = pkt[ICMP].seq
id_num = pkt[ICMP].id
icmp_reply = IP(src=src_ip, dst=dst_ip)/ICMP(type='echo-reply', id=id_num, seq=seq_num)/Raw(load=pkt[Raw].load)
send(icmp_reply, verbose=0)
def sniff_icmp():
sniff(filter="icmp and src host 10.9.0.1", prn=icmp_spoof)
if __name__ == '__main__':
t = Thread(target=sniff_icmp)
t.start()`
this program is spoofing the packets but it is not printing the sniffed packets what chan could be made in order to print the sniffed packets
This image shows the ICMP packets spoofed
This is how I want this packet info printed
I am going to send DNS queries over UDP to a DNS server using the Python3 programming language. This is a description:
Your program must send requests for either IPv4 ("A) or IPv6 ("AAAA") addresses
Your program must take 3 command-line arguments:
The type of of address requested (denoted with the --type flag), which can have the value 'A' or 'AAAA'
The host name being queried (denoted with the --name flag)
The IP address of the DNS server to query (denoted with the --server flag)
why when I print(raw_bytes2), I received nothing
#!/usr/bin/env python3
# Python DNS query client
#
# Example usage:
# ./dns.py --type=AAAA --name=www.google.com --server=8.8.8.8
# Should provide equivalent results to:
# dig www.google.com AAAA #8.8.8.8 +noedns
# (note that the +noedns option is used to disable the pseduo-OPT
# header that dig adds. Our Python DNS client does not need
# to produce that optional, more modern header)
import argparse
import ctypes
import random
import socket
import struct
import sys
def main():
# Setup configuration
parser = argparse.ArgumentParser(description='DNS client for ECPE 170')
parser.add_argument('--type', action='store', dest='qtype',
required=True, help='Query Type (A or AAAA)')
parser.add_argument('--name', action='store', dest='qname',
required=True, help='Query Name')
parser.add_argument('--server', action='store', dest='server_ip',
required=True, help='DNS Server IP')
args = parser.parse_args()
qtype = args.qtype
qname = args.qname
server_ip = args.server_ip
port = 53
server_address = (server_ip, port)
if qtype not in ("A", "AAAA"):
print("Error: Query Type must be 'A' (IPv4) or 'AAAA' (IPv6)")
sys.exit()
# Create UDP socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((server_ip, port))
# Generate DNS request message
# type
raw_bytes = bytearray()
if qtype == "A":
raw_bytes.append(0x00)
raw_bytes.append(0x01)
elif qtype == "AAAA":
raw_bytes.append(0x00)
raw_bytes.append(0x1c)
#qname
split = qname.split(".")
string = ""
for i in split:
hexs = hex(len(i))
string += str(hexs)+i
#string += "0x00"
raw_bytes +=bytes(string,'ascii')
#sever 8.8.8.8
raw_bytes.append(0x08)
raw_bytes.append(0x08)
raw_bytes.append(0x08)
raw_bytes.append(0x08)
# Send request message to server
# print(raw_bytes)
bytes_send = s.sendto(raw_bytes,server_address)
# Receive message from server
max_bytes = 4096
(raw_bytes2,src_addr) = s.recvfrom(max_bytes)
print(raw_bytes2)
# Close socket
# ---------
s.close()
# Decode DNS message and display to screen
print(bytes_send)
# dns.decode_dns(raw_bytes)
if __name__ == "__main__":
sys.exit(main())
I'm new to python and I'm trying to ping my office network and trying to get the hostnames for an inventory system I'm trying to build for work. When I run the script below, I get the IP Address and get either Online or Offline, but I don't get the correct hostname. I only get the hostname of the computer sending out the ping. I think I need to capture it with a string but not sure how to do that. Ultimately this will be run in a GUI with the push of a button.
import ipaddress
from subprocess import PIPE, Popen
import socket
network = ipaddress.ip_network('192.168.1.0/24')
for i in network.hosts():
i = str(i)
h = socket.gethostname()
toping = Popen(['ping', '-c', '5', '-w', '100', i], stdout=PIPE)
output = toping.communicate()[0]
hostalive = toping.returncode
if hostalive == 0:
print(i)
print(h)
print("Is Online")
else:
print(i)
print("Is Offline")
I'm working on a project and I want to use RFID as a position reference(when raspberry pi and MFRC522 read the data, send it to server and make sure where is the position or adjust position while RFID reader is fixed)
My code is below:
import RPi.GPIO as GPIO
import MFRC522
import signal
import socket
HOST = '192.168.11.48'
PORT = 9009
continue_reading = True
# Capture SIGINT for cleanup when the script is aborted
def end_read(signal,frame):
global continue_reading
print("Ctrl+C captured, ending read.")
continue_reading = False
GPIO.cleanup()
# Hook the SIGINT
signal.signal(signal.SIGINT, end_read)
# Create an object of the class MFRC522
MIFAREReader = MFRC522.MFRC522()
# Welcome message
print("Welcome to the MFRC522 data read example")
# This loop keeps checking for chips. If one is near it will get the UID and authenticate
with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as sock:
sock.connect((HOST,PORT))
#print("closing client")
while True:
while continue_reading:
# Scan for cards
(status,TagType) = MIFAREReader.MFRC522_Request(MIFAREReader.PICC_REQIDL)
# If a card is found
if status == MIFAREReader.MI_OK:
print("Card detected")
# Get the UID of the card
(status,uid) = MIFAREReader.MFRC522_Anticoll()
# If we have the UID, continue
if status == MIFAREReader.MI_OK:
# Print UID
print("Card read UID: "+str(uid[0])+","+str(uid[1])+","+str(uid[2])+","+str(uid[3]))
# This is the default key for authentication
key = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
# Select the scanned tag
MIFAREReader.MFRC522_SelectTag(uid)
# Authenticate
status = MIFAREReader.MFRC522_Auth(MIFAREReader.PICC_AUTHENT1A, 8, key, uid)
data = "str(uid[0])"
msg = data
sock.sendall(msg.encode())
data = sock.recv(128)
print('date from Echo server is [%s]'%data.decode())
# Check if authenticated
if status == MIFAREReader.MI_OK:
MIFAREReader.MFRC522_Read(8)
MIFAREReader.MFRC522_StopCrypto1()
else:
print("Authentication error")
I am using echo server to make sure that it's working
code for echo server is:
import socketserver
HOST = ''
PORT = 9009
class MyTcpHandler(socketserver.BaseRequestHandler):
def handle(self):
print("[%s]conneted"%self.client_address[0])
try:
while True:
self.data = self.request.recv(1024)
if self.data.decode() == "/quit":
print('ended by user [%s]'%self.client_address[0])
return
print('[%s]'%self.data.decode())
self.request.sendall(self.data)
except Exceptions as e:
print(e)
def runServer():
print("starting echo server")
print("if you want to close echo server, click Ctrl+C")
try:
server = socketserver.TCPServer((HOST,PORT), MyTcpHandler)
server.serve_forever()
except KeyboardInterrupt:
print("--- closing server")
runServer()
I ran fist piece of code while the second one was running, but only result I got was -
Welcome to the MFRC522 data read example
Card detected
Card read UID:178,29,209,48
size:8.
Anyone had idea what I should change to make it work?
thanks
So as part of my project (2D Multiplayer Card Game), I've figured out how to host and run a server script online. My plan is to have two separate kivy clients connect to the server (which will just be a script with commands).
However I'm somewhat confused about the order of operations because I think the client connection is potentially in conflict with the message loop so I'm wondering if someone could basically tell me what I should be doing:
I'm going to be using this as my serverscript:
import socket
serversocket = socket.socket()
host = 'INSERTIPHERE'
port = PORTHERE
serversocket.bind(('', port))
serversocket.listen(1)
while True:
clientsocket,addr = serversocket.accept()
print("got a connection from %s" % str(addr))
msg = 'Thank you for connecting' + "\r\n"
clientsocket.send(msg.encode('ascii'))
clientsocket.close()
This is my client connection function
def Main():
host = 'INSERTIPHERE'
port = PORTHERE
mySocket = socket.socket()
mySocket.connect((host, port))
message = input(' -> ')
while message != 'q':
mySocket.send(message.encode())
data = mySocket.recv(1024).decode()
print('Received from server: ' + data)
message = input(' -> ')
mySocket.close()
Note: I understand that the server and client aren't perfectly aligned in functions but provided I can at least a connection confirmation for now, I can work from there.
I'm basically wondering how do I put this code into a simple kivy app like this:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class BoxWidget(BoxLayout):
pass
class BoxApp(App):
def build(self):
return BoxWidget()
if __name__ == '__main__':
BoxApp().run()
My best guess is that you want to:
Establish the connection before opening the client
Passing the server connection to the primary widget (in this case the Box Widget) as you're running an instance of the client (ie BoxApp(server).run()?)
Use that connection in a message loop function of the BoxWidget
I also understand that Kivy has built in solutions with Twisted but I'm having trouble with the python 2-3 differences.
Thank you for reading.
Just to clarify: All I want to do right now is open a blank window and also have a confirmation message sent to the command line (or failing that a label in the window).
You can use threading so you don't interrupt the main thread in kivy.
I rewrote your example a bit, so what you send from the server, will be the text of a label.
server.py
import socket
serversocket = socket.socket()
host = 'localhost'
port = 54545
serversocket.bind(('', port))
serversocket.listen(1)
clientsocket,addr = serversocket.accept()
print("got a connection from %s" % str(addr))
while True:
msg = input("> ") + "\r\n"
clientsocket.send(msg.encode('ascii'))
client.py
import socket
class MySocket:
def __init__(self,host="localhost",port=54545):
self.sock = socket.socket()
self.sock.connect((host, port))
def get_data(self):
return self.sock.recv(1024)
main.py
from kivy.app import App
from kivy.uix.label import Label
from client import *
from threading import Thread
class MyLabel(Label):
def __init__(self, **kwargs):
super(MyLabel,self).__init__(**kwargs)
self.sock = MySocket()
Thread(target=self.get_data).start()
def get_data(self):
while True:
self.text = self.sock.get_data()
class BoxApp(App):
def build(self):
return MyLabel()
if __name__ == '__main__':
BoxApp().run()
Now just run server.py in one terminal, then main.py from another
I got a basic version of it working with buttons. Both on local machine and online. This Solution is likely not viable for many real time apps or even a chat server since the reply has to be initiated. However for my goal of a multiplayer card game it should more than suffice with proper conditionals.
video of test on local machine
EDIT: In the video I talk about double clicking. I have just realized this is because the first click is putting the window back in focus.
EDIT 2: Using TextInput in kv file instead of input in Python file.
server script:
import socket
def Main():
host = '127.0.0.1'
port = 7000
mySocket = socket.socket()
mySocket.bind((host,port))
mySocket.listen(1)
conn, addr = mySocket.accept()
print ("Connection from: " + str(addr))
message = 'Thank you connecting'
conn.send(message.encode())
while True:
data = conn.recv(1024).decode()
strdata = str(data)
print(strdata)
reply = 'confirmed'
conn.send(reply.encode())
mySocket.close()
if __name__ == '__main__':
Main()
This is a pretty simple server. Listen for a single client, confirm connection, open a send and receive message loop.
This is the client script which isn't hugely complicated really:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
import socket
class BoxWidget(BoxLayout):
s = socket.socket()
host = '127.0.0.1'
port = 7000
display = ObjectProperty()
def connect_to_server(self):
# called by a Button press
# Connects to the server
self.s.connect((self.host, self.port))
# Receives confirmation from Server
data = self.s.recv(1024).decode()
# Converts confirmation to string
strdata = str(data)
# Prints confirmation
print(strdata)
def send_message(self):
# Is called by the function below
# Encodes and sends the message variable
self.s.send(self.message.encode())
# Waits for a reply
self.receive_message()
def message_to_send(self):
# Defines Message to send
self.message = self.display.text
# Calls function to send the message
self.send_message()
# Note
# When I used message = input directly in send_message,
# the app would crash. So I defined message input
# in its own function which then calls the
# send function
# message_to_send is the function actually
# called by a button press which then
# starts the chain of events
# Define Message, Send Message, get Reply
def receive_message(self):
# Decodes a reply
reply = self.s.recv(1024).decode()
# Converts reply to a str
strreply = str(reply)
# prints reply
print(strreply)
class ServerApp(App):
def build(self):
box = BoxWidget()
return box
if __name__ == '__main__':
ServerApp().run()
Edit: Forgot to include the kv file
<BoxWidget>:
display: display
Button:
text: 'Hello'
on_press: root.message_to_send()
Button:
text: 'Connect'
on_press: root.connect_to_server()
TextInput:
id: display
In future iterations, I'll be replacing print statements with conditionals (ie did client one draw a card? if so client 2's opponent draws a face-down card etc).
Relatively rudimentary as it is now but there is a lot you could do from here.