I am trying to run this code and not able to due to error in the last line. I added line 4 from various answers found here. But still not able to get an output.
I get these problems on Pycharm Community 2022.3.2
The same even when I use Text Editor or VSCode on Ubuntu 22.04
#!/usr/bin/env python3
# Import scapy
import scapy.all as scapy
from scapy.layers.l2 import ARP, Ether
# We need to create regular expressions to ensure that the input is correctly formatted.
import re
# Basic user interface header
print('Hello, We are on!!')
# Regular Expression Pattern to recognise IPv4 addresses.
ip_add_range_pattern = re.compile("^(?:[0-9]{1,3}\.){3}[0-9]{1,3}/[0-9]*$")
# Get the address range to ARP
while True:
ip_add_range_entered = input("\nPlease enter the ip address and range that you want to send the ARP request to (ex 192.168.1.0/24): ")
if ip_add_range_pattern.search(ip_add_range_entered):
print(f"{ip_add_range_entered} is a valid ip address range")
break
# Try ARPing the ip address range supplied by the user.
# The arping() method in scapy creates a pakcet with an ARP message
# and sends it to the broadcast mac address ff:ff:ff:ff:ff:ff.
# If a valid ip address range was supplied the program will return
# the list of all results.
arp_result = scapy.arping(ip_add_range_entered)
I tried installing arping using sudo apt install arping, without luck.
Added line 4 from different answers available here
I installed full Scapy using pip install --pre scapy[complete], no luck.
Hope to get a list of device connected to my network. Ultimate aim to log them and get and alert when there is a new device on the network.
Thanks.
Edit 1:
Everything goes fine until I enter the IP properly. It even suggests wrong entry if I make a mistake. Once I enter the right IP range, it says, it is a valid IP range and then throws error
Traceback (most recent call last):
File "/home/computerw/PycharmProjects/desk-app-QT/main.py", line 37, in <module>
arp_result = scapy.arping(ip_add_range_entered)
File "/home/computerw/PycharmProjects/desk-app-QT/venv/lib/python3.10/site-packages/scapy/layers/l2.py", line 890, in arping
ans, unans = srp(
File "/home/computerw/PycharmProjects/desk-app-QT/venv/lib/python3.10/site-packages/scapy/sendrecv.py", line 687, in srp
s = iface.l2socket()(promisc=promisc, iface=iface,
File "/home/computerw/PycharmProjects/desk-app-QT/venv/lib/python3.10/site-packages/scapy/arch/linux.py", line 484, in __init__
self.ins = socket.socket(
File "/usr/lib/python3.10/socket.py", line 232, in __init__
_socket.socket.__init__(self, family, type, proto, fileno)
PermissionError: [Errno 1] Operation not permitted
Related
I am using the following code with python3.8.2 connecting to Cisco network devices (switch, router), running in an eveNG lab environment. I am connecting from a mac laptop, to a router using telnet on IP 10.9.249.3 and port 32769.
Problem is that when I run this code I do not get any output. I can however see the commands being run and the running config output on the device itself using a separate connection. The code execution just stays put waiting for an event.
from telnetlib import Telnet
HOST = "10.9.249.3"
tn = Telnet(HOST,32769)
tn.write(b"terminal length 0\n")
tn.write(b"show runn\n")
tn.write(b"exit\n")
print(tn.read_all().decode('ascii'))
tn.exit()
When I do a control-break I get the following output:
^CTraceback (most recent call last):
File "p1.py", line 12, in <module>
print(tn.read_all().decode('ascii'))
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/telnetlib.py", line 335, in read_all
self.fill_rawq()
File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/telnetlib.py", line 526, in fill_rawq
buf = self.sock.recv(50)
KeyboardInterrupt
I found similar issues posted and tried their suggestions like changing to a different Telnet read_*() method but no change in the output.
One thing I have noticed is that when I connect to the network device, I have to do the following to disconnect the (manual) telnet connection:
ctrl-]
telnet> quit
Connection closed.
Thanks and regards,
Abid Ghufran
I have been trying to get the ipaddress of the person who logged into the machine using the below code but I get a error.
>>> import socket
>>> socket.gethostbyname_ex(socket.gethostname())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
socket.gaierror: [Errno -2] Name or service not known
The same code works in other linux box.
Not sure I fix it.
Error has occurred just because of not setting up hostname properly. Set the hostname at three different places, which are in -
/etc/hostname
/etc/hosts
run command $ hostname
then logout and login again. You are done.
Check what is being returned by socket.gethostname() and see if you can ping it. Basically this is a lookup failure. Check your /etc/hosts to see if it is listed. I know it seems strange, but I think if the hostname being returned does not have an entry, you'll get a name service failure which is what that is.
If you are working with IPv6 or with servers with multiple network interfaces, this command will not work correctly.
Instead, you can use this command that tries to connect to the Google DNS server at 8.8.8.8 at port 53, and return your ip:
import socket
print([(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1])
I have a problem with a python server I am creating. It works on my home machine, but when I've tried to run it on a different machine it does not work. When compiled using pyinstaller, the window immideatly closes, and when ran as a raw python file (python 2.7.10 is installed on both my home machine and the machine it is not working on) it throws the error:
Traceback (most recent call last):
File "fileModifyServer.py", line 136, in <module>
startServer()
File "fileModifyServer.py", line 11, in startServer
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
File "N:\Python27\lib\socket.py", line 191, in __init__
_sock = _realsocket(family, type, proto)
socket.error: [Errno 10022] An invalid argument was supplied
My code it is referencing to is as follows:
import socket
def startServer():
global serversocket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((socket.gethostname(), 8010))
serversocket.listen(5)
print "Server started"
The traceback you have is strange. It indicates a line when attempting to instantiate the socket, which would indicate a problem with your python installation or network stack. It also indicates that error occurred on line 11, but in your code the line in question appears on line 6. I'm not sure how it happened here, but I know this can happen if you edit files while your program is running and then it crashes. The traceback simply prints out the line number from the file in question that caused the error, and the file source doesn't appear to be read until the error occurs; Therefore the traceback will reflect the line in the modified file, which isn't the line that was present when the program was compiled, and thus is not the line that actually caused the problem.
Without looking at the traceback, I do see an error with your code. You are attempting to bind your server to an invalid interface. The hostname returned by socket.gethostname is not an interface. From the documentation:
If you want to know the current machine’s IP address, you may want to use gethostbyname(gethostname()).
This operation assumes that there is a valid address-to-host mapping for the host, and the assumption does not always hold.
# for example
local_ip_address = socket.gethostbyname(socket.gethostname())
Which will return a string representation of your local ip address. Unfortunately, that would still throw an error, as it is not an interface that you can bind to.
Some interfaces that you can bind to include "0.0.0.0", which means all available interfaces, and "localhost", which means "local" connections only, so no external network traffic allowed.
I’m trying to make a TCP port scanner, but I’m sticking to a very simple example that I lined together from a more advanced example I found online.
I don’t get any errors.
I’m expecting the code to show me that port 80 is open since I started my Apache server on my Linux box.
Here is the code:
#!/usr/bin/python
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
ip = "127.0.0.1"
port = 80
response = sr1(IP(dst=ip)/TCP(dport=port, flags="S"),verbose=False, timeout=0.2)
if response :
if response[TCP].flags == 18 :
print "Port open"
Warning I had (but that does not show up any more):
WARNING: No route found for IPv6 destination :: (no default route?)
I read that including these two lines below would help on the error:
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
Nmap scan:
STATE SERVICE
80/tcp open http
The output is… Nothing at all.
I tried several things like changing the port to different other ports, some which I had open and some which I did not.
Any ideas as to what I did wrong?
The scapy docs mention that the loopback address is a special case
The loopback interface is a very special interface. Packets going
through it are not really assembled and dissassembled. The kernel
routes the packet to its destination while it is still stored an
internal structure. What you see with tcpdump -i lo is only a fake to
make you think everything is normal. The kernel is not aware of what
Scapy is doing behind his back, so what you see on the loopback
interface is also a fake. Except this one did not come from a local
structure. Thus the kernel will never receive it.
In order to speak to local applications, you need to build your
packets one layer upper, using a PF_INET/SOCK_RAW socket instead of a
PF_PACKET/SOCK_RAW (or its equivalent on other systems that Linux):
>>> conf.L3socket
<class __main__.L3PacketSocket at 0xb7bdf5fc>
>>> conf.L3socket=L3RawSocket
>>> sr1(IP(dst="127.0.0.1")/ICMP())
<IP version=4L ihl=5L tos=0x0 len=28 id=40953 flags= frag=0L ttl=64 proto=ICMP chksum=0xdce5 src=127.0.0.1 dst=127.0.0.1 options=''
|\>
However testing this on my OS-X machine results in the following error:
>>> conf.L3socket=L3RawSocket
>>> sr1(IP(dst="127.0.0.1")/ICMP())
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scapy/sendrecv.py", line 334, in sr1
s=conf.L3socket(filter=filter, nofilter=nofilter, iface=iface)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scapy/supersocket.py", line 64, in __init__
self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
AttributeError: 'module' object has no attribute 'AF_PACKET'
So your mileage may vary
EDIT
Apparently this is a known bug in scapy on BSD like systems (including OS-X): http://bb.secdev.org/scapy/issue/174/sniffing-loopback-in-mac-os-x-darwin
I'm getting re-started with App Engine after not having used it in a while. I'm using the 64-bit Linux Go runtime, version 1.8.1.
I believe I'm following the steps from the documentation correctly, and I believe I'm doing what's worked correctly in the past, but I'm getting this error when attempting to launch dev_appserver.py:
$ dev_appserver.py .
INFO 2013-07-11 07:24:45,919 sdk_update_checker.py:244] Checking for updates to the SDK.
INFO 2013-07-11 07:24:46,230 sdk_update_checker.py:288] This SDK release is newer than the advertised release.
WARNING 2013-07-11 07:24:46,443 simple_search_stub.py:955] Could not read search indexes from /tmp/appengine.batterybotinfo.darshan/search_indexes
Traceback (most recent call last):
File "/home/darshan/bin/dev_appserver.py", line 182, in
_run_file(__file__, globals())
File "/home/darshan/bin/dev_appserver.py", line 178, in _run_file
execfile(script_path, globals_)
File "/home/darshan/software/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 695, in
main()
File "/home/darshan/software/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 688, in main
dev_server.start(options)
File "/home/darshan/software/google_appengine/google/appengine/tools/devappserver2/devappserver2.py", line 659, in start
apis.start()
File "/home/darshan/software/google_appengine/google/appengine/tools/devappserver2/api_server.py", line 137, in start
super(APIServer, self).start()
File "/home/darshan/software/google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", line 295, in start
if self._start_all_dynamic_port(host_ports):
File "/home/darshan/software/google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", line 348, in _start_all_dynamic_port
server.start()
File "/home/darshan/software/google_appengine/google/appengine/tools/devappserver2/wsgi_server.py", line 194, in start
socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
TypeError: getaddrinfo() argument 1 must be string or None
My first thought was that I might be using an incorrect version of Python. Sure enough, I'm using 2.7.5, and the documentation clearly states that 2.5 is necessary. However, the documentation seems to be outdated, because after installing 2.5 and setting my system to use it, I got this error:
Error: Python 2.5 is not supported. Please use version 2.7.
Okay, so back to 2.7.5 and my initial error.
I'm not sure if this is a bug in the dev_appserver.py Python code (I'm guessing not, as it's been out for a month), an issue with my Python installation, or something else about my system that isn't configured according to Google's expectations.
I'd rather not mess with the dev_appserver.py code unless necessary, but I'm happy to poke at it to help figure out what's going wrong. The error is on line 194; here are lines 190-195:
# AF_INET or AF_INET6 socket
# Get the correct address family for our host (allows IPv6 addresses)
host, port = self.bind_addr
try:
info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
socket.SOCK_STREAM, 0, socket.AI_PASSIVE)
I've determined that the containing method is called twice. The first time host is always "127.0.0.1" and port is 0. The second time is the one that crashes; host is always 10 (an int, not a string), and port is a seemingly-random five-digit int.
I've tried hard-coding host to "127.0.0.1" and port to either 8080 or 0, but then I get another error. I feel in over my head, and I suspect I'm not going to resolve the real issue by changing things I don't really understand. Googling for the error message hasn't helped.
Persistent Googling eventually paid off. Despite this question having a very different (and much more informative) error message, the solution turned out to be the same: ensure that /etc/hosts contains only a single entry for localhost.
Notably, my system contained both of these lines:
127.0.0.1 localhost
::1 localhost
Commenting out the second (and adding a comment to document why) solved my issue:
127.0.0.1 localhost
# Having multiple localhost entries causes App Enginge dev_appserver.py to fail.
# IPv6 not currently needed, and the dev server IS needed, so commenting out.
#::1 localhost
dev_appserver.py now starts and works properly.
If you edit lines 189-194 to this, it should work until Google releases an update. This is basically just checking the type of host and returning early if it isn't a string.
189 # AF_INET or AF_INET6 socket
190 # Get the correct address family for our host (allows IPv6 addresses)
191 host, port = self.bind_addr
192 try:
193 if type(host) is not str:
194 return
195 info = socket.getaddrinfo(host, port, socket.AF_UNSPEC,
196 socket.SOCK_STREAM, 0, socket.AI_PASSIVE)