Is there a way to auto-check if the current user locked his PC? (usually activated by Win+L). One hacky method I see is somehow catch all key combinations, but then the question is how to know that the user has returned?
Maybe there is some flag that can be accessed through python or windows terminal?
EDIT: I tried the code from here: Detect when computer is unlocked Windows
It detects when screen is locked, but not when it's unlocked, it continues to write "Screen is still locked" indefinitely. So what can be the problem? I have Python 3.4, 64-bit Win7.
EDIT2: Actually the result is always 0 for me, even without any locking, so in fact it doesn't detect anything.
import ctypes
user32 = ctypes.windll.User32
OpenDesktop = user32.OpenDesktopA
SwitchDesktop = user32.SwitchDesktop
DESKTOP_SWITCHDESKTOP = 0x0100
hDesktop = OpenDesktop ("default", 0, False, DESKTOP_SWITCHDESKTOP)
result = SwitchDesktop (hDesktop)
print(result)
Open comp mgmt, open remote console, input computer name
Once connected to remote console check security logs
Note: you can set a base computer to receive log files of your choice, enabling you to automatically see when a user logs on/off/lock/unlocks
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.
I have a script to scan a directory to see when new files are added, and then process their contents. They're video files, so they're often very large, and they're being transferred over a network and often take a long time to transfer. So I need to make sure they have finished copying before going on.
At the moment, once I've found a new file in the directory I'm using os.path.mtime to check the modification date, and comparing that to the last time the file was scanned, to see if it is still being modified. The theory being that if it's no longer being modified then it should have finshed transferring.
if getmtime(path.join(self.rootFolder, thefile)) < self.lastchecktime: newfiles.append[thefile]
but that doesn't seem to work - the script gets triggered too early and the processing fails because the file is not fully loaded. Could it be that there is not enough of a pause between scans that the mtime stays the same…? I give it 10 seconds between scans - that should be enough, surely.
Is there an easy / more pythonic way of doing this? The files are on a windows server running on a VM.
Do you have any control over the adding of the files? If so, you could create an empty file with a name like videoname-complete once a video has finished uploading, and watch for those files.
Wouldn't your check be "is my modified time greater than last checked?".
if os.path.getmtime(path) > self.lastAccessedTime:
# do something as modified time is greater than last time I checked
pass
I'm not a windows guy, but I'm sure there will be some equivalent library to inotify for windows. It is a really nice way to listen for file or directory changes on file system level. I'm leaving some sample code which works on linux with pyinotify, would be helpful for someone on linux.
class PTmp(pyinotify.ProcessEvent):
def process_IN_CLOSE_WRITE(self, event):
print "Changed: %s " % os.path.join(event.path, event.name)
wm = pyinotify.WatchManager()
mask = pyinotify.IN_CLOSE_WRITE
notifier = pyinotify.Notifier(wm, PTmp())
wdd = wm.add_watch(FILE_LOCATION, mask, rec=True)
while True:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
notifier.stop()
break
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
Is there anyway to encorporate Dragon NaturallySpeaking into an event driven program? My boss would really like it if I used DNS to record user voice input without writing it to the screen and saving it directly to XML. I've been doing research for several days now and I can not see a way for this to happen without the (really expensive) SDK, I don't even know that it would work then.
Microsoft has the ability to write a (Python) program where it's speech recognizer can wait until it detects a speech event and then process it. It also has the handy quality of being able to suggest alternative phrases to the one that it thinks is the best guess and recording the .wav file for later use. Sample code:
spEngine = MsSpeech()
spEngine.setEventHandler(RecoEventHandler(spEngine.context))
class RecoEventHandler(SpRecoContext):
def OnRecognition(self, StreamNumber, StreamPosition, RecognitionType, Result):
res = win32com.client.Dispatch(Result)
phrase = res.PhraseInfo.GetText()
#from here I would save it as XML
# write reco phrases
altPhrases = reco.Alternates(NBEST)
for phrase in altPhrases:
nodePhrase = self.doc.createElement(TAG_PHRASE)
I can not seem to make DNS do this. The closest I can do-hickey it to is:
while keepGoing == True:
yourWords = raw_input("Your input: ")
transcript_el = createTranscript(doc, "user", yourWords)
speech_el.appendChild(transcript_el)
if yourWords == 'bye':
break
It even has the horrible side effect of making the user say "new-line" after every sentence! Not the preferred solution at all! Is there anyway to make DNS do what Microsoft Speech does?
FYI: I know the logical solution would be to simply switch to Microsoft Speech but let's assume, just for grins and giggles, that that is not an option.
UPDATE - Has anyone bought the SDK? Did you find it useful?
Solution: download Natlink - http://qh.antenna.nl/unimacro/installation/installation.html
It's not quite as flexible to use as SAPI but it covers the basics and I got almost everything that I needed out of it. Also, heads up, it and Python need to be downloaded for all users on your machine or it won't work properly and it works for every version of Python BUT 2.4.
Documentation for all supported commands is found under C:\NatLink\NatLink\MiscScripts\natlink.txt after you download it. It's under all the updates at the top of the file.
Example code:
#make sure DNS is running before you start
if not natlink.isNatSpeakRunning():
raiseError('must start up Dragon NaturallySpeaking first!')
shutdownServer()
return
#connect to natlink and load the grammer it's supposed to recognize
natlink.natConnect()
loggerGrammar = LoggerGrammar()
loggerGrammar.initialize()
if natlink.getMicState() == 'off':
natlink.setMicState('on')
userName = 'Danni'
natlink.openUser(userName)
#natlink.waitForSpeech() continuous loop waiting for input.
#Results are sent to gotResultsObject method of the logger grammar
natlink.waitForSpeech()
natlink.natDisconnect()
The code's severely abbreviated from my production version but I hope you get the idea. Only problem now is that I still have to returned to the mini-window natlink.waitForSpeech() creates to click 'close' before I can exit the program safely. A way to signal the window to close from python without using the timeout parameter would be fantastic.