Trying to open iOS devices on my network using python script

Trying to use pybonjour but not sure if this is what i need. https://code.google.com/p/pybonjour/

I want to be able to open iOS devices that appear on my network automatically, will later work with a script based on this, but first I want to just open iOS devices as soon as it appears / disappears on my wifi network.

So the question is, how do I do this? on a Windows computer with python27 and the pybonjour package, these two examples work on the pybonjour page, but what command do I run to detect iOS devices using scripts included in my network? or it will be only the discovery services running on my computer that I run this script on!

If I go in the wrong direction, please let me know, I can not find the documentation on this package!

python browse_and_resolve.py xxxxxx 

thanks Matt.

Updating ...

This article and browser were helpful, http://marknelson.us/2011/10/25/dns-service-discovery-on-windows/ in finding the services I need to search.

Example; (this was discovered by my apple tv, not at home, so I can’t check what the iphone is called! I guess the iphone!

 python browse_and_resolve.py _appletv._tcp 

In addition, if you have the windows dns-sd.exe utility, this will lead to a search for all services available on the network. I used this to find what I was looking for.

 dns-sd -B _services._dns-sd._udp 

Updating ...

"Bonjour is used in two ways: - publishing a service - detecting (viewing) available services."

For what I want to do, I don’t think this will work, since the ipad / iPhone will not advertise the service unless I launch an application that advertises alone (or jailbreak my iPhone / ipad and then ssh will be open) . Any ideas?

+6
source share
3 answers

What you are trying to do (a) probably cannot be done, and (b) probably would not be very useful if it could.

Bonjour's point is to look for services, not devices. Of course, each service is provided by some device, so indirectly you can discover devices with it ... but only by discovering the service they advertise.

As far as I know, (except for Apple TV) they don’t advertise any services, unless you use an application that uses Bonjour to search for the same application on other computers. (Except for malicious devices that often advertise SSH, AFP, etc.)

There are several ways, indirectly, to get a list of all the services that are advertised by someone on the network. The easiest way is to use Bonjour Browser for Windows . (I never used it, but the original tool for Mac and the Java port, both of which I used, offer this Windows port for Windows users.) Run it and you will get a list of services and you can click on each of them to get information.

So, you can make sure that your iPhone and iPad do not advertise any services, which will show that they cannot be detected through Bonjour.

Meanwhile, even if you find a device, what do you plan to do? Presumably, you want to somehow contact the device, right? Regardless of the service you are trying to contact ... just browse this service, and then, if necessary, filter it to iOS devices. It has become easier than browsing iOS devices and then filtering to those who have the service you want.


As for the way to detect iOS devices ... Well, there are at least two possibilities. I don’t know if any of them will work, but ...

First, even if the iOS device doesn’t advertise anything for you, I assume that it is viewing services that you can advertise. How else did he discover that there is an Apple TV for AirTunes, iTunes on the local network for synchronization, etc.?

So, use Bonjour Browser to get a list of all the services that your iTunes desktop, Apple TV, etc. are running on. Then turn off all services on your desktop, use PyBonjour to advertise which services seem plausible (and, if necessary, use netcat to host trivial listeners on the ports you advertise). Then turn on your iPhone and see if it connects to any of them. You might want to leave it for a while or turn off WiFi and turn on WiFi again. (I assume that despite Apple’s recommendations, he doesn’t constantly look at most services, but checks it every time and / or every time his network status changes. After all, Apple’s recommendations are for interactive foreground applications, not background services.)

Unfortunately, even if you can find a service to which all iOS devices will connect, you cannot distinguish iOS devices from others just by getting connections there. For example, I’m sure that any Mac or Windows with iTunes installed will pick up your fake AirTunes service, and any Mac will end up in your AirPrint and so on. So how do you distinguish this from the fact that the iPhone hit it? You may need to actually execute enough protocol to get information from them. It will be especially difficult for Apple without documents.

But I hope you are lucky and there will be something that all iOS devices want to talk to and nothing else. iTunes Sync seems like an obvious opportunity.

In addition, there are a few things that they need to broadcast, or they simply won’t work. You cannot get into the WiFi network without broadcasts. And most home Wi-Fi networks use DHCP, which means that they must also relay DHCP discovery (and request). There may be some kind of heuristic signature in these messages. If nothing else, enabling DDNS should force the device to send its hostname, and you can guess based on this (for example, if you do not change the default values, hostname.lower().endswith('iphone') ).

The easiest way is probably to configure the desktop as the primary access point for your home network. I find this to be as simple as enabling access to an Internet connection somewhere in the control panel. (Setting up a DHCP relay agent is much smaller than a full router, but I have no idea how you even start doing it on Windows.) Then you can capture DHCP broadcasts (or, otherwise, 802.11) when they come in. Wireshark will easily capture and analyze messages for you so you can watch and see if it looks like it's worth going on. (See RFC 2131 for details on a format that is not obvious from Wireshark cryptographic single-line descriptions.)

You can do it even further and see the Internet connections that each host makes when they are connected to the Internet. Any device that periodically checks the App Store, iOS update server, etc. .... Well, if one of the devteam jailbreak lives in your house, this is probably the iPhone, right? The disadvantage is that some of these checks can be very periodic, and detecting the iPhone 6 hours after it is connected to your network is not very interesting.

+4
source

Use python-nmap , not Bonjour. Or you can use pyzeroconf (Bonjour is a zeroconf implementation), but it is a bit outdated (but should still work).

python-nmap is probably the easiest way, let you want to find all connected devices with ā€œiPhoneā€ or ā€œiPadā€ in your hostname (just a simplified 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 

A limitation of this approach is that it relies on a person who has not changed his host name, which originally included their name and device name. It also assumes that there is a port on the iOS device that will return the host name (this may not be the case). You can use osscan , which is preferred by running it as a command using the python-nmap library. This is certainly 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 the python-nmap method has nm.commandline() method):

 nmap -O -v ip 

Also try adding --osscan-guess; --fuzzy --osscan-guess; --fuzzy for best results. Example:

 nmap -O -v --osscan-guess ip 

Then just search for the output for the keywords of your iOS device (see this example ). This is understandable to humans. Please note that you will need to run all this as an administrator so that it works correctly (Windows: runas , other: sudo ).

+3
source

So I’ve been working on this issue for about a year now. I made it work on my Mac pretty quickly, but it was very difficult for me to make it work right on my PC. I tried many different approaches. I have a home automation system that turns on heating and hot water (via the Arduino and RF module) when I or my partner is at home (that is, our iPhones show up in home Wi-Fi). In the end, I used nslookup to find the IP address for the iPhone (in case the IP address has changed since they are dynamic (but they never actually change on my router)) and nmap to determine if the iPhone is turned on. network. If the iPhone is in very deep sleep, nmap does not always find the phone, so I did 10 checks before he said that the phone was at home. Below is part of my python home automation code. I used streams. Any questions with the code below 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 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\ iPhone has returned home' %phone) occupancyStatus(phone, True) waitEventAdjustable.set() #else: #msg.log('%s\ iPhone still at home' %phone) else: iPhone[phone]['count'] -= 1 if v[phone]['home'] == True and iPhone[phone]['count'] == 0: msg.log('%s\ iPhone has left home' %phone) occupancyStatus(phone, False) waitEventAdjustable.set() #else: #msg.log('%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 directly to your own script, because there are some parts that I did not copy to try to make things simple and easy to read, but I hope the above code gives everyone a sense of how I made things up.

0
source

Source: https://habr.com/ru/post/944671/


All Articles