Trying to use pybonjour but not sure if it is what I need. https://code.google.com/p/pybonjour/
I want to be able to discover iOS devices that appear on my network automatically, will be running a script later on based on this, but first I want to just discover a iOS devices as soon as it appear/disappears on my wifi network.
So the question, how do I do this? running on a windows machine with python27 and the pybonjour package installed, the two examples work from the pybonjour page, but what command do I run to discover iOS devices using the scripts included on my network? or will this only discovery services running on my pc that i run this script on!
If I am going in the wrong direction please let me know, I can't seem to find the documentation on this package!
python browse_and_resolve.py xxxxxx
Thx
Matt.
Update...
This article and the browser was helpful, http://marknelson.us/2011/10/25/dns-service-discovery-on-windows/ in finding the services I needed to search for.
example; (this discovered my apple tv's, not at home atm so can't check what the iphone is called! I assume iphone!
python browse_and_resolve.py _appletv._tcp
Also if you have the windows utility dns-sd.exe this will search for all the services available on the network. I used this to find what I was looking for.
dns-sd -B _services._dns-sd._udp
Update...
"Bonjour is used in two ways: - publishing a service - detecting (browsing for) available services".
For what I want to do, I don't think it will work as the ipad/iPhone won't advertise a service unless I'm running a app that advertise one (or jailbreak my iPhone/ipad and then ssh will be open). Any more ideas?
What you're trying to do (a) probably can't be done, and (b) probably wouldn't be much use if it could.
The point of Bonjour is to discover services, not devices. Of course each service is provided by some device, so indirectly you can discover devices with it… but only by discovering a service that they're advertising.
As far as I know, (except Apple TVs) don't advertise any services, except while you're running an app that uses Bonjour to find the same app on other machines. (Except for jailbroken devices, which often advertise SSH, AFP, etc.)
There are a few ways to, indirectly, get a list of all services being advertised by anyone on the network. The simplest is probably to use Bonjour Browser for Windows. (I've never actually used it, but the original Mac tool and the Java port, both of which I have used, both suggest this Windows port for Windows users.) Fire it up and you'll get a list of services, and you can click on each one to get the details.
So, you can verify that your iPhone and iPad aren't advertising any services, which will show that there is no way to detect them via Bonjour.
Meanwhile, even if you did find a device, what are you planning to do? Presumably you want to communicate with the device in some way, right? Whatever service you're trying to communicate with… just browse for that service—and then, if appropriate, filter down to iOS devices. That's got to be easier than browsing for iOS devices and then filtering down to those that have the service you want.
As for whether there's any way to detect iOS devices… Well, there are at least two possibilities. I don't know if either of them will work, but…
First, even if the iOS device isn't advertising anything for you, I assume it's browsing for services you can advertise. How else does it find that there's an Apple TV to AirTunes to, an iTunes on the LAN to sync with, etc.?
So, use Bonjour Browser to get a list of all services your iTunes-running desktop, Apple TV, etc. are advertising. Then turn off all the services on your desktop, use PyBonjour to advertise whichever services seem plausibly relevant (and, if need be, use netcat to put trivial listeners on the ports you advertise). Then turn on your iPhone, and see if it connects to any of them. You may want to leave it running for a while, or switch WiFi off and back on. (I'm guessing that, despite Apple's recommendations, it doesn't browse continuously for most services, but just checks every once in a while and/or every time its network status changes. After all, Apple's recommendations are for foreground interactive apps, not background services.)
Unfortunately, even if you can find a service that all iOS devices will connect to, you may not be able to distinguish iOS devices from others just by getting connections there. For example, I'm pretty sure any Mac or Windows box running iTunes will hit up your fake AirTunes service, and any Mac will hit your AirPrint, and so on. So, how do you distinguish that from an iPhone hitting it? You may need to actually serve enough of the protocol to get information out of them. Which will be particularly difficult for Apple's undocumented protocols.
But hopefully you'll get lucky, and there will be something that all iOS devices, and nothing else, will want to talk to. iTunes Sync seems like the obvious possibility.
Alternatively, there are a few things they have to broadcast, or they just wouldn't work. You can't get on a WiFi network without broadcasts. And most home WiFi networks use DHCP, which means they have to broadcast DHCP discover (and request), as well. There may be some kind of heuristic signature you can detect in these messages. If nothing else, enabling DDNS should cause the device to send its hostname, and you can guess based on that (e.g., unless you change the defaults, hostname.lower().endswith('iphone')).
The easiest way is probably to set up your desktop as the main access point for your home network. I believe it's as simple as turning on Internet Connection Sharing somewhere in the control panel. (Setting up as a DHCP relay agent is much less overhead than being a full router, but I have no idea how you'd even get started doing that on Windows.) Then you can capture the DHCP broadcasts (or, failing that, the 802.11 broadcasts) as they come in. Wireshark will capture and parse the messages for you easily, so you can watch and see if it looks like this is worth pursuing farther. (See RFC 2131 for details on the format that aren't obvious from Wireshark's cryptic one-liner descriptions.)
You can take this even farther and watch the internet connections every host makes once they're connected to the internet. Any device that's periodically checking the App Store, the iOS upgrade server, etc.… Well, unless one of the jailbreak devteam guys lives in your house, that's probably an iPhone, right? The downside is that some of these checks may be very periodic, and detecting an iPhone 6 hours after it connects to your network isn't very exciting.
Use python-nmap rather than Bonjour. Or you could use pyzeroconf (Bonjour is an implementation of zeroconf) but it is a little outdated (but should still work).
python-nmap is probably easiest, let's suppose you wanted to find all connected devices that have 'iPhone' or 'iPad' in their hostname (just a simplistic concept):
import nmap
...
def notify_me(ip, hostname):
print("I found an iOS device! IP Address: %s, Hostname: %s" % (ip, hostname))
iOS_device_list = ['iPhone', 'iPad']
iOS_devices_on_net = {}
nm = nmap.PortScanner()
# scan ip range
for i in range(2, 50, 1):
ip = "192.168.1." + str(i)
# specify ports to scan
nm.scan(ip, '62078') # Matt mentioned that it picks up iphone-sync on this port
hostname = nm[ip].hostname()
for device in iOS_device_list:
if device.lower() in hostname.lower():
iOS_devices_on_net.update({ip:hostname})
notify_me(ip, hostname)
# show all iOS devices in ip range
print iOS_devices_on_net
The limitation of this approach is that it relies on the individual having not changed their hostname which originally includes their name and device name. It also assumes that there is a port listening on the iOS device that will return a hostname (this may not be the case). You can use osscan which is preferred by running it as a command using python-nmap library. This is obviously a much better approach. My concept above is just a simple example of how it can be used.
Using nmap from the command line (I believe python-nmap has nm.commandline() method) is simplest:
nmap -O -v ip
Also try adding --osscan-guess; --fuzzy for best results. Example:
nmap -O -v --osscan-guess ip
Then just search the output for iOS device keywords (see this example). It's human-readable. Note that you'll need to be running all of this as an administrator for it to work properly (Windows: runas, other: sudo).
So I have been working on the same issue for about a year now. I got it to work on my mac fairly quickly, but had a lot of trouble getting it to work right on my PC. I have tried many many different approaches. I have a home automation system that turns on the heating and hot water (via an arduino and RF module) when I or my partner are home (that is our iPhones are detectable on the home WiFi). In the end I used 'nslookup' to find the IP address for the iPhones (in case the IP address did change as they are dynamic (but they actually never do on my router)) and 'nmap' to detect if the iPhone is on the network. If the iPhone is in very deep sleep 'nmap' does not always find the phone, so I have made it check 10 times before it says the phone is home. Below is part of my home automation code in python. I have used threading. Any questions with the below code let me know.
# Dictionary to store variables to reuse on program restart
v = {
'boilerControlCH' : 'HIH', # 'scheduled' or 'HIH' (Honey I'm Home)
'boilerControlHW' : 'scheduled',
'thermostatSetPoint' : 20.8,
'thermostatVariance' : 0.1,
'morningTime' : datetime(1970,1,1,6,0,0),
'nightTime' : datetime(1970,1,1,23,0,0),
'someOneHome' : False,
'guest' : False,
'minimumTemperatureOO' : False,
'minimumTemperature' : 4.0,
'iPhoneMark' : {'iPhoneHostname' : 'marks-iphone', 'home' : False},
'iPhoneJessica' : {'iPhoneHostname' :'jessicaesiphone', 'home' : False}
}
and
# Check if anyone at home
def occupancyStatus(person, Bol = False):
with lockOccupancyStatus:
someOneHome = False
if 'iPhone' in person:
v[person]['home'] = Bol
elif 'retest' in person:
pass
else:
v[person] = Bol
if v['guest'] == True:
someOneHome = True
for key in v:
if 'iPhone' in key:
if v[key]['home'] == True:
someOneHome = True
v['someOneHome'] = someOneHome
variablesToFile()
return
and the main code
# iPhone home status threading code
class nmapClass(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global exitCounter
nmapThread()
msg.log('Exited nmapThread')
waitEvent.set()
waitEventAdjustable.set()
serialDataWaiting.set()
exitCounter += 1
def nmapThread():
iPhone = {}
maxCounts = 10
for phone in v:
if 'iPhone' in phone:
iPhone[phone] = {}
iPhone[phone]['hostname'] = v[phone]['iPhoneHostname']
iPhone[phone]['count'] = maxCounts
#msg.log(iPhone)
while exitFlag[0] == 0:
for phone in iPhone:
if iPhone[phone]['count'] > 0:
phoneFound = False
IPAddress = '0.0.0.0'
# Find iPhones IP address using its hostname
commandNsloolup = 'nslookup %s' %iPhone[phone]['hostname']
childNslookup = pexpect.popen_spawn.PopenSpawn(commandNsloolup, timeout = None)
output = childNslookup.readline()
while '\r\n' in output:
#msg.log(output)
if 'Name:' in output:
output = childNslookup.readline()
if 'Address:' in output:
tempStr = output
startPoint = tempStr.find('192')
tempStr = tempStr[startPoint:]
IPAddress = tempStr.replace('\r\n', '')
#msg.log(IPAddress)
output = childNslookup.readline()
if IPAddress == '0.0.0.0':
pass
#msg.error('Error finding IP address for %s' %iPhone[phone]['hostname'], GFI(CF()).lineno)
else:
#commandNmap = 'nmap -PR -sn %s' %IPAddress
#commandNmap = 'nmap -p 62078 -Pn %s' %IPAddress # -p specifies ports to try and access, -Pn removes pinging
commandNmap = 'nmap -p 62078 --max-rate 100 %s' %IPAddress
childNmap = pexpect.popen_spawn.PopenSpawn(commandNmap, timeout = None)
output = childNmap.readline()
while '\r\n' in output:
if 'Host is up' in output:
phoneFound = True
break
output = childNmap.readline()
#if phoneFound:
# break
if phoneFound:
iPhone[phone]['count'] = 0
if v[phone]['home'] == False:
msg.log('%s\'s iPhone has returned home' %phone)
occupancyStatus(phone, True)
waitEventAdjustable.set()
#else:
#msg.log('%s\'s iPhone still at home' %phone)
else:
iPhone[phone]['count'] -= 1
if v[phone]['home'] == True and iPhone[phone]['count'] == 0:
msg.log('%s\'s iPhone has left home' %phone)
occupancyStatus(phone, False)
waitEventAdjustable.set()
#else:
#msg.log('%s\'s iPhone still away from home' %phone)
elif iPhone[phone]['count'] < 0:
msg.error('Error with count variable in iPhone dictionary', GFI(CF()).lineno)
longWait = True
for phone in iPhone:
if iPhone[phone]['count'] > 0:
longWait = False
#msg.log('%s: %s' %(phone, iPhone[phone]['count']))
if longWait:
#msg.log('wait long')
# 600 = run every 10 minutes
waitEvent.wait(timeout=600)
for phone in iPhone:
iPhone[phone]['count'] = maxCounts
else:
#msg.log('wait short')
waitEvent.wait(timeout=60)
return
The code may not work if you copy it straight into your own script, as there are some parts missing which I have not copied about to try and keep things simple and easy to read, but hopefully the above code gives everyone a sense of how I did things.
Related
So I am trying to create sort of a MitM setup to alter the content of TCP (HTTP) packets.
I current have a Linux bridge that looks as follows:
IoT Device ---(eth)---- Laptop ----(usb)---- 3G Modem
The bridge is setup using the normal Linux procedure (i.e., ip link) and up to now everything is working fine and the bridge is transparent for both ends.
Next, I forwarded all packets to the NFQueue:
iptables -A FORWARD -j NFQUEUE --queue-num 0
and parse them with Python:
In Python 3
def print_and_accept(pkt):
print(pkt)
http_packet = scapy.IP(pkt.get_payload())
if http_packet.haslayer(scapy.Raw) and http_packet.haslayer(TCP):
if http_packet[TCP].dport == 80 or http_packet[TCP].sport == 80:
http_packet[TCP].payload = scapy.Raw(http_packet[TCP].payload.load.decode().replace("text","txet"))
print(http_packet[TCP].payload)
del http_packet[IP].chksum, http_packet[TCP].chksum
pkt.set_payload(bytes(http_packet))
print('>> Payload Changed')
pkt.accept()
nfqueue = NetfilterQueue()
nfqueue.bind(0, print_and_accept)
try:
nfqueue.run()
except KeyboardInterrupt:
print('exiting')
nfqueue.unbind()
In Python 2 one can do the same but then use pkt.set_verdict_modified(nfqueue.NF_ACCEPT, str(http_packet), len(http_packet)) at the end.
However, when inspecting packets via Wireshark (captured on the bridge), I still see the original payload. I already tried many, many proposed solutions but nothing seems to work.
PS: If I use the workaround of drop() and send() via scapy, I don't even see the packet in Wireshark.
Thank you in advance.
UPDATE: For anyone looking for the answer, it seems that I was capturing the new (modified) packets on the wrong interface with Wireshark. Just change the interface and Voila.
If you haven't heard of SoundSwitch, its an app for windows that allows you to switch sound output/input devices with a keyboard shortcut. I've made a similar app for linux, but I cant get it to work properly. The majority of the app is done, and if you want to see the full code, its here: https://github.com/boskobs/sound-Source-Switch-4-Linux
Bellow is the part responsible for applying the changes:
os.system("pacmd set-default-sink " + str(nextindex))
output = subprocess.getoutput("pacmd list-sink-inputs")
for item in output.split("\n"):
if "index:" in item:
inputindex = item.strip().replace("index: ","")
os.system("pacmd move-sink-input " + str(inputindex) + " " + str(nextindex))
It changes the default sound output device, and transfers all of the current apps to that device. The problem occurs when I exit an app and switch the output device. Next time I start that app, the device it outputs sound to is the old one that was active before the switch. How can I make the new default output device really work as a default?
According to the FreeDesktop.org wiki as well as this answer on AskUbuntu and related posts, whenever a new stream (sound-producing program) starts up, PulseAudio will attach it to the same sink (output device) that it attached to last time it disappeared. This sounds like the effect you're seeing. You close a program which was using device A, start your Source Switch app and switch everything to device B, and the open the program again, and PulseAudio sets it to using device A again.
You can disable this behavior of PulseAudio by adding the line
load-module module-stream-restore restore_device=false
to /etc/pulse/default.pa and restarting PulseAudio. This is probably a reasonable choice for someone who is going to be using your app to manage their sound devices; you could incorporate this into your installation procedure, but the standard advice about being very careful when you mess around with system configuration files applies.
Alternatively, you can delete the stream restore database, which is stored in the files $HOME/.pulse/*stream-volumes*.gdbm. From that point on, PulseAudio will think every audio stream is brand new and will assign it to the fallback audio device, which is what you set with set-default-sink. (This also requires restarting PA.)
When the currently chosen device is not the same as the device that one of the apps is streaming to, a fix gets applied instead of a switch.
# Checking for changes
output = subprocess.getoutput("pacmd list-sinks").split("\n")
for item in range(0, len(output)-1):
if "* index: " in output[item]:
currentindexname = output[item+1].replace("name: <", "").strip()[:-1]
break
output = subprocess.getoutput("pacmd list-sink-inputs")
for item in output.split("\n"):
if "sink:" in item:
if currentindexname != item.split("<")[1].split(">")[0]:
for item in output.split("\n"):
if "index:" in item:
inputindex = item.strip().replace("index: ","")
os.system("pacmd move-sink-input " + str(inputindex) + " " + str(currentindex))
os.system('notify-send "Source" "Fixed"')
exit()
Its not ideal, but it gets the job done.
[NOTE] Make sure to click on the image links to follow this solution.
Ubuntu 20.04
Run pacmd list-cards to list the audio devices.
pacmd list-cards output
Output devices in settings should match list-cards
To set a device run pacmd set-default-sink bluez_sink.38_18_4C_12_44_0B.a2dp_sink with your own device name.
Then once this works, you can create some keyboard shortcuts.
Keyboard shortcut
add code to shortcut and set
I use ctrl + Home as mine. You can do this for all audio devices and switch between them with ease.
I'm having trouble getting my Windows 7 laptop to talk to a Newport CONEX-PP motion controller. I've tried python (Spyder/Anaconda) and a serial port streaming program called Termite and in either case the results are the same: no response from the device. The end goal is to communicate with the controller using python.
The controller connects to my computer via a USB cable they sold me that is explicitly for use with this device. The connector has a pair of lights that blink when the device receives data (red) or sends data (green). There is also a packaged GUI program that comes with the device that seems to work fine. I haven't tried every button, the ones I have tried have the expected result.
The documentation for accessing this device is next to non-existant. The CD in the box has one way to connect to it and the webpage linked above has a different way. The first way (CD from the box) creates a hierarchy of modules that ends in a module it does not recognize (this is a code snippet provided by Newport):
import sys
sys.path.append(r'C:\Newport\MotionControl\CONEX-PP\Bin')
import clr
clr.AddReference("Newport.CONEXPP.CommandInterface")
from CommandInterfaceConexPP import *
import System
instrument="COM5"
print 'Instrument Key=>', instrument
myPP = ConexPP()
ret = myPP.OpenInstrument(instrument)
print 'OpenInstrument => ', ret
result, response, errString = myPP.SR_Get(1)
That last line returns:
Traceback (most recent call last):
File "< ipython-input-2-5d824f156d8f >", line 2, in
result, response, errString = myPP.SR_Get(1)
TypeError: No method matches given arguments
I'm guessing this is because the various module references are screwy in some way. But I don't know, I'm relatively new to python and the only time I have used it for serial communication the example files provided by the vendor simply worked.
The second way to communicate with the controller is via the visa module (the CONEX_SMC_common module imports the visa module):
import sys
sys.path.append(r'C:\Newport\NewportPython')
class CONEX(CONEXSMC): def __init__(self):
super(CONEX,self).__init__() device_key = 'com5'
self.connect=self.rm.open_resource(device_key, baud_rate=57600, timeout=2000, data_bits=8, write_termination='\r\n',read_termination='\r\n')
mine.connect.read()
That last mine.connect.read() command returns:
VisaIOError: VI_ERROR_TMO (-1073807339): Timeout expired before operation completed.
If, instead, I write to the port mine.connect.write('VE') the light on the connector flashes red as if it received some data and returns:
(4L, < StatusCode.success: 0 >)
If I ask for the dictionary of the "mine" object mine.__dict__, I get:
{'connect': <'SerialInstrument'(u'ASRL5::INSTR')>,
'device_key': u'ASRL5::INSTR',
'list_of_devices': (u'ASRL5::INSTR',),
'rm': )>}
The ASRL5::INSTR resource for VISA is at least related to the controller, because when I unplug the device from the laptop it disappears and the GUI program will stop working.
Maybe there is something simple I'm missing here. I have NI VISA installed and I'm not just running with the DLL that comes from the website. Oh, I found a Github question / answer with this exact problem but the end result makes no sense, the thread is closed after hgrecco tells him to use "open_resource" which is precisely what I am using.
Results with Termite are the same, I can apparently connect to the controller and get the light to flash red, but it never responds, either through Termite or by performing the requested action.
I've tried pySerial too:
import serial
ser = serial.Serial('com5')
ser.write('VE\r\n')
ser.read()
Python just waits there forever, I assume because I haven't set a timeout limit.
So, if anyone has any experience with this particular motion controller, Newport devices or with serial port communication in general and can shed some light on this problem I'd much appreciate it. After about 7 hours on this I'm out of ideas.
After coming back at this with fresh eyes and finding this GitHub discussion I decided to give pySerial another shot because neither of the other methods in my question are yet working. The following code works:
import serial
ser = serial.Serial('com5',baudrate=115200,timeout=1.0,parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
ser.write('1TS?\r\n')
ser.read(10)
and returns
'1TS000033\r'
The string is 9 characters long, so my arbitrarily chosen 10 character read ended up picking up one of the termination characters.
The problem is that python files that come with the device, or available on the website are at best incomplete and shouldn't be trusted for anything. The GUI manual has the baud rate required. I used Termite to figure out the stop bit settings - or at least one that works.
3.5 years later...
Here is a gist with a class that supports Conex-CC
It took me hours to solve this!
My device is Conex-CC, not PP, but it's seem to be the same idea.
For me, the serial solution didn't work because there was absolutely no response from the serial port, either through the code nor by direct TeraTerm access.
So I was trying to adapt your code to my device (because for Conex-CC, even the code you were trying was not given!).
It is important to say that import clr is based on pip install pythonnet and not pip install clr which will bring something related to colors.
After getting your error, I was looking for this Pythonnet error and have found this answer, which led me to the final solution:
import clr
# We assume Newport.CONEXCC.CommandInterface.dll is copied to our folder
clr.AddReference("Newport.CONEXCC.CommandInterface")
from CommandInterfaceConexCC import *
instrument="COM4"
print('Instrument Key=>', instrument)
myCC = ConexCC()
ret = myCC.OpenInstrument(instrument)
print('OpenInstrument => ', ret)
response = 0
errString = ''
result, response, errString = myCC.SR_Get(1, response, errString)
print('Positive SW Limit: result=%d,response=%.2f,errString=\'%s\''%(result,response,errString))
myCC.CloseInstrument()
And here is the result I've got:
Instrument Key=> COM4
OpenInstrument => 0
Positive SW Limit: result=0,response=25.00,errString=''�
For Conex-CC serial connections are possible using both pyvisa
import pyvisa
rm = pyvisa.ResourceManager()
inst = rm.open_resource('ASRL6::INSTR',baud_rate=921600, write_termination='\r\n',read_termination='\r\n')
pos = inst.query('01PA?').strip()
and serial
import serial
serial = serial.Serial(port='com6',baudrate=921600,bytesize=8,parity='N',stopbits=1,xonxoff=True)
serial.write('01PA?'.encode('ascii'))
serial.read_until(b'\r\n')
All the commands are according to the manual
I am implementing a custom Bluetooth pairing agent in Python using Bluez via DBUS. The agent needs to return one of a number of fixed PIN codes (legacy PINs, not simple pair mode requests) depending on which type of device is trying to pair. The devices are Bluetooth enabled medical monitors (blood pressure, scales etc) of which I have no control.
Originally, I was looking at the first bit of the devices Mac address and returning a PIN based on the manufacture prefix. This was working well. But the device I am now trying to add support for uses the same prefix (I assume it has the same BT chip) but a different PIN as one of the other devices I need to support. The only thing unique about the devices are their names which are always constant (such as "AND 1234" or "IEM 5678") so I tried to change by agent to look at the first bit of the name instead
knownPins = {
"aandd": "12345",
"iem ": "5678",
"default": "98689"
}
#dbus.service.method("org.bluez.Agent", in_signature="o", out_signature="s")
def RequestPinCode(self, device):
pprint("RequestPinCode ({})", device)
dbdevice = dbus.Interface(bus.get_object("org.bluez", device),
"org.bluez.Device")
bits = device.split('/')
mac = bits[-1].replace("dev_","").replace("_",":").lower()
props = dbdevice.GetProperties()
if not props["Name"]:
raise Rejected()
try:
for name, pin in knownPins.items():
if props["Name"].startswith(name):
return pin
return knownPins["default"]
except:
raise Rejected()
But, in most cases props["Name"] is simply empty - i assume this is because the pair request is being initiated by the remote party and since I have not done a discover, I dont know its name.
So my question is, how can I force a inquiry at this point in the process so I can get the device name? I have tried
adapter.CreateDevice(mac)
Which gives org.bluez.Error.AlreadyExists
I have tried
adapter.RemoveDevice(device)
adapter.CreateDevice(mac)
Which gives org.bluez.Error.DoesNotExist: Device creation in progress
I assume in both instances this is because Bluez is in the middle of trying to create the device
Thanks
I writing a script that mounts and unmounts several USB devices quickly. When a new device is mounted, Ubuntu, by default, opens up a file browser window for that device. That behavior gets very annoying when it is mounting multiple devices.
I looked online, and found a tutorial explaining how to disable that feature through the gui (http://www.liberiangeek.net/2010/09/disableenable-auto-mount-ubuntu-10-0410-10-maverick-meerkat/) , but I wish to find a way to do that from within the script.
This is how I am currently mounting the devices:
def mount_all(self):
paths = self._get_partitions()
vfat_path = paths[0][0]
vfat = self.sysbus.get_object(SD.udisks_bus, vfat_path)
vfat_props = dbus.Interface(vfat, dbus_interface=SD.prop_bus)
if vfat_props.Get(vfat_path, 'DeviceIsMounted'):
self.fat = vfat_props.Get(vfat_path, 'DeviceMountPaths')[0]
else:
while True:
try:
self.fat = vfat.FilesystemMount('vfat', {}, dbus_interface=SD.device_bus)
break
except dbus.exceptions.DBusException:
time.sleep(0.1)
This turned out to be way simpler than I had thought. You can edit the .gconf properties with the tool gconftool-2 as explained here