I'm trying to connect to my bluetooth devices using python, but I fail on very first step.
Most tutorial I found have code similar to this to connect.
I use MAC address from hciconfig - I guess this is mac of my only adapter.
import bluetooth
for port in range(1, 11):
try:
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.connect(('00:1A:7D:DA:71:11', port))
print("Connected")
s.close()
except OSError as err:
print(f"Error connecting to {port}", err)
If run this above it will fail with „Device or resource busy”
If I use s.connect('') it fails with „Device or resource busy”.
I can use this adapter through bluetoothctl and other managers.
I have multiple devices working on it. So it is detected correctly by OS.
What is wrong here. How can I connect to my adapter using Python?
Related
I am trying to get all shared devices of unknown SMB servers.
While trying to connect via SMBConnection.connect() function it refuses to connect to the server and connection get lost or no connection at all. Meanwhile I get exceptions in Python I can connect to that server from my Desktop environment.
What could cause this. I have a list of SMB servers varying from Linux to Windows hosts.
from smb.SMBConnection import SMBConnection
import socket
ips ['x.x.x.x','x.x.x.x'...]
for ip in ips :
print(ip)
try:
hostname = socket.gethostbyaddr(ip)
except socket.herror as e :
print("[-][-][-]Uknknown host")
continue
smb_conn = SMBConnection(username='Guest',password="",my_name='name',remote_name=hostname)
try:
is_connected = smb_conn.connect(ip,timeout=60)
except :
print("[!] %s is up but refuses smb connection:(( "%ip)
#print("Na not responding shit")
continue
if is_connected:
print("[+] %s connected"%ip)
try:
shares = smb_conn.listShares()
for share in shares :
print(share.name)
print("\n\n\n")
except smb.smb_structs.OperationFailure as e:
print (e.message)
break
UPDATE:
While executing this script I get TimeoutError while the server is up and running and accessible through Desktop SMB connection.
SOLVED:
In some cases the SMB server is listening or port 445 and not the NetBIOS port 139. By default the connect() function tries to connect to port 139 but it can be modified by connect(ip,port,timeout) parameters.
I am using pybluez to develop a bluetooth application on linux in python. I want to know if it is possible to connect to a "localhost" for bluetooth so I can run the client and server on the same machine (as most people do for web development).
If this is not possible, how to most people develop bluetooth applications? Do they just run the client and server on different devices or is there a more clever way to handle this?
Eventually the server will run on a raspberry pi and the client will be any bluetooth enabled device (cell phone, laptop, etc.) but during development it would be great if I could run both on the same machine.
Here is my server:
import bluetooth as bt
socket = bt.BluetoothSocket(bt.RFCOMM)
host = ""
socket.bind((host, bt.PORT_ANY))
port = socket.getsockname()[1]
print("port: " + str(port))
socket.listen(1)
uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"
# bt.advertise_service(socket, "BTServer", uuid)
print("Listening on " + host + ":" + str(port))
client_sock, addr = socket.accept()
print("Connection accepted from " + addr)
data = client_sock.recv(1024)
print(data)
client_sock.close()
socket.close()
And when I call services = bt.find_service(name=None, uuid=None, address="localhost") on the client it cannot find any services.
Through further research I have found that it is not possible to run a bluetooth client and server on the same device with the same bluetooth adapter. For local testing you can either use two bluetooth enabled computers or get a bluetooth dongle.
It is not possible to run a Bluetooth client and server on the same device.
I used the pybluez python module.
When I run bluetooth.discover_devices(lookup_names=True) in the client code on my machine, it returns all other Bluetooth devices around it except my machine.
As we can not discover the machine, we can not connect to it over Bluetooth and can not use it as a Bluetooth Server.
So you have a basic understanding of the parts im using, I have:
Arduino Uno
Seeed Studio GPRS Shield v2.0 (http://www.seeedstudio.com/wiki/GPRS_Shield_V2.0)
Ultimate GPS for Adafruit V3.3 (https://www.adafruit.com/products/746?gclid=Cj0KEQjw3-W5BRCymr_7r7SFt8cBEiQAsLtM8qn4SCfVWIvAwW-x9Mu-FLeB6hLmVd0PAPVU8IAXXPgaAtaC8P8HAQ)
Here is my problem:
I have tested the Arduino stacked with the GPRS shield, and it works fine with regards to accessing the internet through TCP, sending SMS, etc.. However, my application requires me to send GPS data from the adafruit GPS to a web server that I have already coded with Django and postgresql. The backend is set up.
I need to send the data from the Uno (client) to my laptop (server), which I coded in python (This is just to check whether it is creating a connection):
#!/usr/bin/env python
import socket
# import postgres database functions
TCP_IP = '192.168.1.112'
TCP_PORT = 10000
BUFFER_SIZE = 40
server_address = (TCP_IP,TCP_PORT)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created.'
# Bind socket to TCP server and port
try:
s.bind(server_address)
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket Bind Complete.'
# Start Listening on socket
s.listen(1) # Puts socket into server mode
print 'Listening on port: ', TCP_PORT
# Now Keep Talking with the client
while (1):
# Wait to accept a connection
conn, addr = s.accept() # Wait for incoming connection with accept()
print 'Connection address:', addr
data = conn.recv(BUFFER_SIZE)
if not data: break
print "recieved data: data", data
conn.send(data) #echo
conn.close()
I dont think there is a problem with this. From this I will post data to my postgreSQL database. However, When I try to use AT commands on the SIM900 module to connect to the server using port 10000, I cannot connect:
AT+CIPSHUT
SHUT OK
AT+CGATT?
+CGATT: 1
OK
AT+CIPMUX=0
OK
AT+CSTT="fast.t-mobile.com","",""
OK
AT+CIICR
OK
AT+CIFSR
6.60.94.49
AT+CIPSTART="TCP","192.168.1.112,"10000"
OK
STATE: TCP CLOSED
CONNECT FAIL
I have tried connecting through TCP and replaced the AT+CIPSTART line with the below statement and it worked, so I know TCP works:
AT+CIPSTART="TCP","www.vishnusharma.com", "80"
Is the IP i'm using wrong? I'm new to this, but if it makes a difference, im using Ubuntu 16.04 partitioned on my Mac OSX. I have also checked the APN for T-mobile and it seems fine.
Any help would be greatly appreciated. Thank You!
The IP you're using is inside a NAT since it starts with 192.168. Unless you have a private apn with the mobile operator you're using, you won't be able to reach your Ubuntu from a public IP. Your ISP gives you a public IP address which ir administrated by your router, so if you want this to work, you'll have to do a port forwarding from your router to your Ubuntu.
To do the port forwarding you have to get in the router's configuration page (Typically 192.168.1.1 but depends on the model) an there you'll have to redirect the port XXX to 192.168.1.112:10000. After that you have to obtain your public IP (curl ifconfig.co) and use it to access from the SIM900.
First of all as a suggestion, you can combine the two shields by using SIM908 (unless you are getting more precision on your GPS shield). Since your TCP connection is working, I bet that the port 10000 on your ubuntu is blocked by the firewall. You can first try to turn off your firewall and see if it works. If it did not worked its something else. If it worked, turn on your firewall and then unblock the tcp port using the following command:
sudo ufw allow 10000/tcp
I am working on a Python script to search for bluetooth devices and connect them using RFCOMM. This devices has Passkey/Password. I am using PyBlueZ and, as far as I know, this library cannot handle Passkey/Password connections (Python PyBluez connecting to passkey protected device).
I am able to discover the devices and retrieve their names and addresses:
nearby_devices = bluetooth.discover_devices(duration=4,lookup_names=True,
flush_cache=True, lookup_class=False)
But if tried to connect to a specific device using:
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.connect((addr,port))
I get an error 'Device or resource busy (16)'.
I tried some bash commands using the hcitool and bluetooth-agent, but I need to do the connection programmatically. I was able to connect to my device using the steps described here: How to pair a bluetooth device from command line on Linux.
I want to ask if someone has connected to a bluetooth device with Passkey/Password using Python. I am thinking about to use the bash commands in Python using subprocess.call(), but I am not sure if it is a good idea.
Thanks for any help.
Finally I am able to connect to a device using PyBlueZ. I hope this answer will help others in the future. I tried the following:
First, import the modules and discover the devices.
import bluetooth, subprocess
nearby_devices = bluetooth.discover_devices(duration=4,lookup_names=True,
flush_cache=True, lookup_class=False)
When you discover the device you want to connect, you need to know port, the address and passkey. With that information do the next:
name = name # Device name
addr = addr # Device Address
port = 1 # RFCOMM port
passkey = "1111" # passkey of the device you want to connect
# kill any "bluetooth-agent" process that is already running
subprocess.call("kill -9 `pidof bluetooth-agent`",shell=True)
# Start a new "bluetooth-agent" process where XXXX is the passkey
status = subprocess.call("bluetooth-agent " + passkey + " &",shell=True)
# Now, connect in the same way as always with PyBlueZ
try:
s = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
s.connect((addr,port))
except bluetooth.btcommon.BluetoothError as err:
# Error handler
pass
Now, you are connected!! You can use your socket for the task you need:
s.recv(1024) # Buffer size
s.send("Hello World!")
Official PyBlueZ documentation is available here
Is there a way to connect two phones via Bluetooth , the script should be running on a Linux host. Any suggestions of using pybluez or any other APIs?
I have seen some examples where a Linux host is used as Client and is connect a phone (which is a server), but here I'm want to use Linux host as just a device to run the script and make two phones connect via Bluetooth.
I'm working on a script that grabs the banner from common ports of a host. I'm using sockets to make the connection but I'm facing some issues. Here is the code:
try:
connsocket = socket(AF_INET, SOCK_STREAM)
connsocket.settimeout( 5 )
connsocket.connect((ip, port))
connsocket.send("HEAD / HTTP/1.0")
results = connsocket.recv(400)
connsocket.close()
return str(results)
except:
print '[ERROR]Failed to connect or Connection timed out'
The are two major issues:
First time I run the script to a host all the banners are retrieved correctly except port 80 which exits with the timeout
The second problem is that when I relaunch the script to the same host there is no response from any port.
I suspect that the second issue is due to the connection is still open and the script fails retying to connect. With the first issue I have no idea why it's not working.
Any idea?
Regards.