i wrote this program to sniff icmp packets in the network and print there source address. The code is as follows:
from scapy.all import *
def fun_callback(pkt):
print str(pkt.payload.src)
sniff(prn = fun_callback, filter = 'icmp', timeout =5)
After running this program, I am getting this error.
[root#localhost icmp]# python test.py
WARNING: Failed to execute tcpdump. Check it is installed and in the PATH
WARNING: No route found for IPv6 destination :: (no default route?)
192.168.134.131
192.168.134.131
192.168.134.2
192.168.134.2
fe80::20c:29ff:fee4:a130
134.160.38.1
192.168.134.131
Traceback (most recent call last):
File "test.py", line 5, in <module>
sniff(prn = fun_callback, filter = 'icmp', timeout =5)
File "/usr/lib/python2.7/site-packages/scapy/sendrecv.py", line 586, in sniff
r = prn(p)
File "test.py", line 4, in fun_callback
print str(pkt.payload.src)
File "/usr/lib/python2.7/site-packages/scapy/packet.py", line 176, in __getattr__
fld,v = self.getfield_and_val(attr)
File "/usr/lib/python2.7/site-packages/scapy/packet.py", line 172, in getfield_and_val
return self.payload.getfield_and_val(attr)
File "/usr/lib/python2.7/site-packages/scapy/packet.py", line 172, in getfield_and_val
return self.payload.getfield_and_val(attr)
File "/usr/lib/python2.7/site-packages/scapy/packet.py", line 1057, in getfield_and_val
raise AttributeError(attr)
AttributeError: src
[root#localhost icmp]#
Why this exception is occurring?
You have sniffed a packet with a payload without src attribute. If you want a quick fix for your code, write:
def fun_callback(pkt):
if hasattr(pkt.payload, "src"):
print str(pkt.payload.src)
The problem is, you don't really known what pkt.payload will be. If you want a better fix, try something like:
def fun_callback(pkt):
if IP in pkt: print pkt[IP].src
elif IPv6 in pkt: print pkt[IPv6].src
Or better, with .sprintf():
sniff(prn=lambda pkt: pkt.sprintf("{IP:%IP.src%}{IPv6:%IPv6.src%}"),
filter='icmp', timeout=5))
Related
I am trying to build a Networkscanner that scans my localnetwork.
Here is how I would do it:
Create an ARP Request.
Create an Ethernet Frame.
Place the ARP Request inside the Ethernet Frame.
Send the combined frame and receive responses.
Then parse the responses and print the results.
Here is my code so far:
#!/usr/bin/env python3
import scapy.all as scapy
IP = 'here i would enter my IP adress'
def scan(ip):
arp_packet = scapy.ARP(pdst=ip)
broadcast_packet = scapy.Ether(dst='ff:ff:ff:ff:ff:ff')
arp_broadcast_packet = broadcast_packet/arp_packet
scapy.srp(arp_broadcast_packet, timeout = 1, verbose = False)
scan(IP)
However I am getting the error message :
AttributeError: 'L2bpfSocket' object has no attribute 'ins'
Here is the complete message:
Traceback (most recent call last):
File "/Users/Uni/Dropbox/Mein Mac (Elias MacBook Pro)/Desktop/wifi2.py", line 12, in <module>
scan(IP)
File "/Users/Uni/Dropbox/Mein Mac (Elias MacBook Pro)/Desktop/wifi2.py", line 10, in scan
scapy.srp(arp_broadcast_packet, timeout = 1, verbose = False)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/scapy/sendrecv.py", line 552, in srp
s = conf.L2socket(promisc=promisc, iface=iface,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/scapy/arch/bpf/supersocket.py", line 242, in __init__
super(L2bpfListenSocket, self).__init__(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/scapy/arch/bpf/supersocket.py", line 62, in __init__
(self.ins, self.dev_bpf) = get_dev_bpf()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/scapy/arch/bpf/core.py", line 114, in get_dev_bpf
raise Scapy_Exception("No /dev/bpf handle is available !")
scapy.error.Scapy_Exception: No /dev/bpf handle is available !
Exception ignored in: <function _L2bpfSocket.__del__ at 0x7fc3220493a0>
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/scapy/arch/bpf/supersocket.py", line 139, in __del__
self.close()
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/scapy/arch/bpf/supersocket.py", line 211, in close
if not self.closed and self.ins is not None:
AttributeError: 'L2bpfSocket' object has no attribute 'ins'
Elias-MBP:~ Uni$
I read that it could be do to the program trying to close a L2bpfSocket that couldn't be created, therefore not having a Attribute ins.
However I have no clue how to fix this, or why the L2bpfSocket couldn't be created in the first place.
Make sure you're running your script as root.
The second issue isn't important, the main one being that Scapy can't open a /dev/bpf handler.
I saw this interesting idea from Kalle Hallden's video. It is about alerting you when someone's IP connects to the network
import sys
import subprocess
import os
from decouple import config
IP_NETWORK = config('IP_NETWORK')
IP_DEVICE = config('IP_DEVICE')
proc = subprocess.Popen(["ping", IP_NETWORK],stdout=subprocess.PIPE)
while True:
line = proc.stdout.readline()
if not line:
break
#the real code does filtering here
connected_ip = line.decode('utf-8').split()[3]
if connected_ip == IP_DEVICE:
subprocess.Popen(["say", "Linnea just connected to the network"])
Error
Traceback (most recent call last):
File "C:\Users\utkar\Downloads\net-listen.py", line 6, in <module>
IP_NETWORK = config('IP_NETWORK')
File "C:\Users\utkar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\decouple.py", line 199, in __call__
return self.config(*args, **kwargs)
File "C:\Users\utkar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\decouple.py", line 83, in __call__
return self.get(*args, **kwargs)
File "C:\Users\utkar\AppData\Local\Programs\Python\Python38-32\lib\site-packages\decouple.py", line 68, in get
raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option))
decouple.UndefinedValueError: IP_NETWORK not found. Declare it as envvar or define a default value.
Process returned 1 (0x1) execution time : 0.150 s
Press any key to continue . . .
Seems like you forgot to setup a settings.ini. It should look something like this:
[settings]
IP_Network=YOUR NETWORK IP
IP_DEVICE=YOUR DEVICE IP
I am trying to do parallel ssh on servers. While doing this, i am getting "TypeError: 'NoneType' object is not iterable" this error. Kindly help.
My script is below
from pssh import ParallelSSHClient
from pssh.exceptions import AuthenticationException, UnknownHostException, ConnectionErrorException
def parallelsshjob():
client = ParallelSSHClient(['10.84.226.72','10.84.226.74'], user = 'root', password = 'XXX')
try:
output = client.run_command('racadm getsvctag', sudo=True)
print output
except (AuthenticationException, UnknownHostException, ConnectionErrorException):
pass
#print output
if __name__ == '__main__':
parallelsshjob()
And the Traceback is below
Traceback (most recent call last):
File "parallelssh.py", line 17, in <module>
parallelsshjob()
File "parallelssh.py", line 10, in parallelsshjob
output = client.run_command('racadm getsvctag', sudo=True)
File "/Library/Python/2.7/site-packages/pssh/pssh_client.py", line 520, in run_command
raise ex
TypeError: 'NoneType' object is not iterable
Help me with the solution and also suggest me to use ssh-agent in this same script. Thanks in advance.
From reading the code and debugging a bit on my laptop, I believe the issue is that you don't have a file called ~/.ssh/config. It seems that parallel-ssh has a dependency on OpenSSH configuration, and this is the error you get when that file is missing.
read_openssh_config returns None here: https://github.com/pkittenis/parallel-ssh/blob/master/pssh/utils.py#L79
In turn, SSHClient.__init__ blows up when trying to unpack the values it expects to receive: https://github.com/pkittenis/parallel-ssh/blob/master/pssh/ssh_client.py#L97.
The fix is presumably to get some sort of OpenSSH config file in place, but I'm sorry to say I know nothing about that.
EDIT
After cleaning up some of parallel-ssh's exception handling, here's a better stack trace for the error:
Traceback (most recent call last):
File "test.py", line 11, in <module>
parallelsshjob()
File "test.py", line 7, in parallelsshjob
output = client.run_command('racadm getsvctag', sudo=True)
File "/Users/smarx/test/pssh/venv/lib/python2.7/site-packages/pssh/pssh_client.py", line 517, in run_command
self.get_output(cmd, output)
File "/Users/smarx/test/pssh/venv/lib/python2.7/site-packages/pssh/pssh_client.py", line 601, in get_output
(channel, host, stdout, stderr, stdin) = cmd.get()
File "/Users/smarx/test/pssh/venv/lib/python2.7/site-packages/gevent/greenlet.py", line 480, in get
self._raise_exception()
File "/Users/smarx/test/pssh/venv/lib/python2.7/site-packages/gevent/greenlet.py", line 171, in _raise_exception
reraise(*self.exc_info)
File "/Users/smarx/test/pssh/venv/lib/python2.7/site-packages/gevent/greenlet.py", line 534, in run
result = self._run(*self.args, **self.kwargs)
File "/Users/smarx/test/pssh/venv/lib/python2.7/site-packages/pssh/pssh_client.py", line 559, in _exec_command
channel_timeout=self.channel_timeout)
File "/Users/smarx/test/pssh/venv/lib/python2.7/site-packages/pssh/ssh_client.py", line 98, in __init__
host, config_file=_openssh_config_file)
TypeError: 'NoneType' object is not iterable
This was seemingly a regression in the 0.92.0 version of the library which is now resolved in 0.92.1. Previous versions also work. OpenSSH config should not be a dependency.
To answer your SSH agent question, if there is one running and enabled in the user session it gets used automatically. If you would prefer to provide a private key programmatically can do the following
from pssh import ParallelSSHClient
from pssh.utils import load_private_key
pkey = load_private_key('my_private_key')
client = ParallelSSHClient(hosts, pkey=pkey)
Can also provide an agent with multiple keys programmatically, per below
from pssh import ParallelSSHClient
from pssh.utils import load_private_key
from pssh.agent import SSHAgent
pkey = load_private_key('my_private_key')
agent = SSHAgent()
agent.add_key(pkey)
client = ParallelSSHClient(hosts, agent=agent)
See documentation for more examples.
i need to debug a program i wrote in Eclipse with PyDev plugin. However I can not debug it because Eclipse obviously does not have the permission to do so.
I always get the following error when debugging reaches the send() function.
socket.error: [Errno 1] Operation not permitted
Running Eclipse with gksudo does not work either. It opens, but it says the editor could not be found.
Could not open the editor: No editor descriptor for id
org.python.pydev.editor.PythonEditor
How do I fix this?
I can't post the full code, it's too long. Here is a kind of breakdown, which causes the same error. Eclipse is not allowed the execute the send() function. Executing it with sudo in the command shell works.
from scapy.all import *
from scapy.layers.inet import IP, UDP
class SomeIP(Packet):
name = "SomeIP Packet"
fields_desc=[XShortField("X", 0x1000),
XShortField("Y", 0x1000)]
SIP = SomeIP()
packet = IP(src="129.168.101.164",dst="192.168.101.143")/UDP(sport=1000, dport=1000)/SIP
send(packet, verbose=False)
Here is the error I get - the first line can be ignored.
WARNING: No route found for IPv6 destination :: (no default route?)
Traceback (most recent call last):
File "scapy_test.py", line 19, in <module>
send(packet, verbose=False)
File "/usr/lib/python2.7/dist-packages/scapy/sendrecv.py", line 251, in send
__gen_send(conf.L3socket(*args, **kargs), x, inter=inter, loop=loop, count=count,verbose=verbose, realtime=realtime)
File "/usr/lib/python2.7/dist-packages/scapy/arch/linux.py", line 307, in __init__
self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
File "/usr/lib/python2.7/socket.py", line 187, in __init__
_sock = _realsocket(family, type, proto)
socket.error: [Errno 1] Operation not permitted
Could you use another port number? If I understand your code correctly you try to open a port on number 1000. Since port numbers up to 1024 can only be used by root, setting the port number to something higher than 1024 could maybe solve the problem.
I'm trying to connect to connect to amazon EC2 via fabric using the script below. But I'm met with a problem that I'm not sure how to solve it.
import os
from fabric.api import run, env, local, cd
WORK = os.getenv('HOME') + '/Work/myproject/'
env.user = 'ubuntu'
env.hosts = [
'128.248.268.288'
]
env.key_filename = [
'%s/aws/myproject.pem' % WORK
]
def deploy():
print("Executing on %(host)s as %(user)s" % env)
with cd('/sites/myproject.com/code/'):
run('ls')
This is the traceback. I'm not sure how to solve the problem.
Traceback (most recent call last):
File "/Library/Python/2.6/site-packages/fabric/main.py", line 540, in main
commands[name](*args, **kwargs)
File "/Users/mickeyckm/Work/myproject/codes/giivee/fabfile.py", line 18, in deploy
run('ls')
File "/Library/Python/2.6/site-packages/fabric/network.py", line 391, in host_prompting_wrapper
return func(*args, **kwargs)
File "/Library/Python/2.6/site-packages/fabric/operations.py", line 422, in run
channel = connections[env.host_string]._transport.open_session()
File "/Library/Python/2.6/site-packages/fabric/network.py", line 65, in __getitem__
self[real_key] = connect(user, host, port)
File "/Library/Python/2.6/site-packages/fabric/network.py", line 140, in connect
client.load_system_host_keys()
File "/Library/Python/2.6/site-packages/paramiko/client.py", line 151, in load_system_host_keys
self._system_host_keys.load(filename)
File "/Library/Python/2.6/site-packages/paramiko/hostkeys.py", line 155, in load
e = HostKeyEntry.from_line(line)
File "/Library/Python/2.6/site-packages/paramiko/hostkeys.py", line 67, in from_line
key = RSAKey(data=base64.decodestring(key))
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/base64.py", line 321, in decodestring
return binascii.a2b_base64(s)
binascii.Error: Incorrect padding
Any help/hint would be great appreciated.
Cheers,
Mickey
I saw some places where Incorrect Padding error was resulted from binascii module and it was mostly when the string you pass has some extraneous white-space characters.
>>> import binascii
>>> binascii.a2b_base64('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
binascii.Error: Incorrect padding
In your case, it the various properties you set for your env object. Do something like this for your key file location and see if that works.
filelocation = os.path.join(WORK,'aws/myproject.pem')
env.key_filename = [filelocation]
Look at your ~/.ssh/known_hosts file. It may contain lines with duplicate entries or be corrupted in some other way.
I had a similar problem and tracked it down to some corruption in my .ssh/known_hosts file.
I thus added to my .bashrc
alias deploy='mv ~/.ssh/known_hosts ~/.ssh/known_hosts.tmp; fab <myfabscript>; mv ~/.ssh/known_hosts.old ~/.ssh/known_hosts'
(obviously putting the right fabric script where <myfabscript> is) and now all works fine when I simply run "deploy"!