I got the following code:
import bluetooth
def apparaat():
nearby_devices = bluetooth.discover_devices(lookup_names = True, flush_cache = True, duration = 15)
for address in nearby_devices:
print("Gevonden apparaten: " + str(address))
print("Gevonden apparaten: " + str(nearby_devices))
apparaat()
When I run the script the out put is:
Gevonden apparaten: []
When I scan for bluetooth devices on my raspberry PI it returns a couple. What im a missing here?
Can you try to run this code? I found that someone ported this bluetooth package from python 2.7 to 3.x and it might have introduced some bugs when printing unicode strings.
import bluetooth
x = bluetooth.discover_devices()
n = bluetooth.lookup_name(x[0])
print(n)
(source: https://groups.google.com/forum/#!topic/pybluez/Kq-ViMBo6es)
Related
Import scapy version 2.4.0. I am only using version 2.4.0 for my project
import scapy.all as scapy
import sys
by using IP address this function return related MAC address of the target
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
def sniff(interface):
scapy.sniff(iface=interface, store=False, prn=process_sniffed_packet)
This function checks whether default gateway MAC address is equal to my PC's MAC address table. if not it says "[+] You are under attack!!
def process_sniffed_packet(packet):
if packet.haslayer(scapy.ARP) and packet[scapy.ARP].op == 2:
count = 1
try:
real_mac = get_mac(packet[scapy.ARP].psrc)
response_mac = packet[scapy.ARP].hwsrc
if real_mac != response_mac:
count = count+1
print(str(count) + "[+] You are under attack!!")
sys.stdout.flush()
except IndexError:
pass
in Linux, we can use a value like 'etho' but In windows, I have to use GUID value to get the result. I am running this code in Windows Machine.
sniff('{1619EEF1-4D71-4831-87AC-8E5DC3AA516A}')
But this code return error
This is the Error that got raised
raise ValueError("Unknown network interface %r" % name)
ValueError: Unknown network interface '{1619EEF1-4D71-4831-87AC-
8E5DC3AA516A}'
On Windows, you need to provide a complete interface name / object, to be able to sniff on it.
First, have a look at what is available using IFACES.show() in a Scapy shell.
Then to get the interface, you can either use:
iface = IFACES.dev_from_name("...") (or dev_from_pcapname, dev_from_id... have a look at help(IFACES) to see what’s available)
iface = "the full name as printed above"
Then use it via sniff(iface=iface).
You could provide the pcap_name, but not the GUID: for instance, it would be something like \\Device\\NPF_{...} rather than just {...}.
Also, please use scapy 2.4.3rc1 (or at least 2.4.2) to be sure you’re up-to-date
I solved the scapy error ValueError: Unknown network interface on windows by installing npcap
When I try to get Rssi information from my around wireless network with Scapy , I'm getting some error. Also , I am using ALFA-036NH , my monitor mode is open and OS is Kali Linux. I used below codes :
from scapy.all import *
from datetime import datetime
import os
import signal
import sys
def PacketHandler(pkt) :
if pkt.haslayer(Dot11) :
if pkt.type == 0 and pkt.subtype == 8 :
if pkt.haslayer(Dot11Beacon) or pkt.haslayer(Dot11ProbeResp):
try:
extra = pkt.notdecoded
rssi = -(256 - ord(extra[-4:-3]))
except:
rssi = -100
print "WiFi signal strength:", rssi
sniff(iface="wlan0mon", prn = PacketHandler)
However, all of networks giving -100 dbm. Thanks for your interest.
Please retry using the latest scapy github version (or 2.4.1+). It has improved support for RSSI, which is now available (if present), via the dBm_AntSignal field.
pkt.dBm_AntSignal
You don’t need the function you provided.
PS: where did you find such code ? Did you do it yourself? Thanks
I tried upload scenario with keyboard press simulation through ctypes package in python for selenium webdriver. It is working fine with my local machine installed with windows 8.1.
But when i run the same code in my development server which is a linux box, that will call a remote machine of windows 7 OS, i got error like windll not found in this part of my code
def SendInput(*inputs):
nInputs = len(inputs)
LPINPUT = INPUT * nInputs
pInputs = LPINPUT(*inputs)
cbSize = ctypes.c_int(ctypes.sizeof(INPUT))
return ctypes.windll.user32.SendInput(nInputs, pInputs, cbSize)
So I did change my code to a if else statement which prompts if the OS is windows got to above snippet of code else go to below snippet of code,
cdll.LoadLibrary("libc.so.6")
Xtst = cdll("libXtst.so.6")
Xlib = cdll("libX11.so.6")
dpy = Xtst.XOpenDisplay(None)
def SendInput(txt):
for c in txt:
sym = Xlib.XStringToKeysym(c)
code = Xlib.XKeysymToKeycode(dpy, sym)
Xtst.XTestFakeKeyEvent(dpy, code, True, 0)
Xtst.XTestFakeKeyEvent(dpy, code, False, 0)
Xlib.XFlush(dpy)
But after adding this i am getting error in my linux box like
TypeError: 'LibraryLoader' object is not callable.
I did search for resources over internet, but i was not able to get them. Can someone help me to get it through.
I am subscribing to topic "/camera/depth/points" and message PointCloud2 on a turtlebot (deep learning version) with ASUS Xtion PRO LIVE camera.
I have used the python script below under the gazebo simulator environment and i can receive x, y, z and rgb values successfully.
However, when i run it in the robot, the rgb values are missing.
Is this a problem of my turtlebot version, or camera or is it that i have to specify somewhere that i want to receive PointCloud2 type="XYZRGB"? or is it a sync problem? Any clues please thanks!
#!/usr/bin/env python
import rospy
import struct
import ctypes
import sensor_msgs.point_cloud2 as pc2
from sensor_msgs.msg import PointCloud2
file = open('workfile.txt', 'w')
def callback(msg):
data_out = pc2.read_points(msg, skip_nans=True)
loop = True
while loop:
try:
int_data = next(data_out)
s = struct.pack('>f' ,int_data[3])
i = struct.unpack('>l',s)[0]
pack = ctypes.c_uint32(i).value
r = (pack & 0x00FF0000)>> 16
g = (pack & 0x0000FF00)>> 8
b = (pack & 0x000000FF)
file.write(str(int_data[0])+","+str(int_data[1])+","+str(int_data[2])+","+str(r)+","+str(g)+","+str(b)+"\n")
except Exception as e:
rospy.loginfo(e.message)
loop = False
file.flush
file.close
def listener():
rospy.init_node('writeCloudsToFile', anonymous=True)
rospy.Subscriber("/camera/depth/points", PointCloud2, callback)
rospy.spin()
if __name__ == '__main__':
listener()
The contents of Published topics are determined by the software that provides them - i.e. the drivers for your camera. To fix this you therefore need to get the right driver and use the topic that it says contains the required information.
You can find recommended drivers for your cameras on the ROS wiki or on some community websites - like this. In your case, the ASUS devices should use openni2 and set depth_registration:=true - as documented here.
At this point, /camera/depth_registered/points should now show the combined xyz and RGB point cloud. To use it, your new listener() code should look something like this:
def listener():
rospy.init_node('writeCloudsToFile', anonymous=True)
# Note the change to the topic name
rospy.Subscriber("/camera/depth_registered/points", PointCloud2, callback)
rospy.spin()
Is it possible for this code to be modified to include Bluetooth Low Energy devices as well? https://code.google.com/p/pybluez/source/browse/trunk/examples/advanced/inquiry-with-rssi.py?r=1
I can find devices like my phone and other bluetooth 4.0 devices, but not any BLE. If this cannot be modified, is it possible to run the hcitool lescan and pull the data from hci dump within python? I can use the tools to see the devices I am looking for and it gives an RSSI in hcidump, which is what my end goal is. To get a MAC address and RSSI from the BLE device.
Thanks!
As I said in the comment, that library won't work with BLE.
Here's some example code to do a simple BLE scan:
import sys
import os
import struct
from ctypes import (CDLL, get_errno)
from ctypes.util import find_library
from socket import (
socket,
AF_BLUETOOTH,
SOCK_RAW,
BTPROTO_HCI,
SOL_HCI,
HCI_FILTER,
)
if not os.geteuid() == 0:
sys.exit("script only works as root")
btlib = find_library("bluetooth")
if not btlib:
raise Exception(
"Can't find required bluetooth libraries"
" (need to install bluez)"
)
bluez = CDLL(btlib, use_errno=True)
dev_id = bluez.hci_get_route(None)
sock = socket(AF_BLUETOOTH, SOCK_RAW, BTPROTO_HCI)
sock.bind((dev_id,))
err = bluez.hci_le_set_scan_parameters(sock.fileno(), 0, 0x10, 0x10, 0, 0, 1000);
if err < 0:
raise Exception("Set scan parameters failed")
# occurs when scanning is still enabled from previous call
# allows LE advertising events
hci_filter = struct.pack(
"<IQH",
0x00000010,
0x4000000000000000,
0
)
sock.setsockopt(SOL_HCI, HCI_FILTER, hci_filter)
err = bluez.hci_le_set_scan_enable(
sock.fileno(),
1, # 1 - turn on; 0 - turn off
0, # 0-filtering disabled, 1-filter out duplicates
1000 # timeout
)
if err < 0:
errnum = get_errno()
raise Exception("{} {}".format(
errno.errorcode[errnum],
os.strerror(errnum)
))
while True:
data = sock.recv(1024)
# print bluetooth address from LE Advert. packet
print(':'.join("{0:02x}".format(x) for x in data[12:6:-1]))
I had to piece all of that together by looking at the hcitool and gatttool source code that comes with Bluez. The code is completely dependent on libbluetooth-dev so you'll have to make sure you have that installed first.
A better way would be to use dbus to make calls to bluetoothd, but I haven't had a chance to research that yet. Also, the dbus interface is limited in what you can do with a BLE connection after you make one.
EDIT:
Martin Tramšak pointed out that in Python 2 you need to change the last line to print(':'.join("{0:02x}".format(ord(x)) for x in data[12:6:-1]))
You could also try pygattlib. It can be used to discover devices, and (currently) there is a basic support for reading/writing characteristics. No RSSI for now.
You could discover using the following snippet:
from gattlib import DiscoveryService
service = DiscoveryService("hci0")
devices = service.discover(2)
DiscoveryService accepts the name of the device, and the method discover accepts a timeout (in seconds) for waiting responses. devices is a dictionary, with BL address as keys, and names as values.
pygattlib is packaged for Debian (or Ubuntu), and also available as a pip package.