Check if the Windows screen is locked - python

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

Related

Manually changing the sound output device on linux

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.

Identify if power state change is caused by user or by power policy

I am writing a windows service in Python and this service needs to know, when a power state event occurs, what caused it. This could be the user or a power policy.
Right now, I successfully detect the events using WM_POWERBROADCAST, but I did not find any documentation about a way to achieve my goal.
Here is my current lead:
When a user turns of the computer manually, the user does necessarily input data. In user space this can be detected with GetLastInputInfo function. So, when a power event occurs, and if the last user input is recent, the power change was caused by the user. This does not work in a service that executes on session 0, which is a problem. I may use the CreateProcessAsUser function, but i'd like to avoid it.
Is there a proper way to detect if the suspend / shutdown messages are consequence of a power policy in a windows service ?
UPDATE: I tried GetLastInputInfo and it actually does not work when the user uses the power button (at least not on my computer).
I ended up using CallNtPowerInformation:
class SYSTEM_POWER_INFORMATION(Structure):
_fields_ = [
("MaxIdlenessAllowed", c_ulong),
("Idleness", c_ulong),
("TimeRemaining", c_ulong),
("CoolingMode", c_ubyte)
]
call_nt_power_information = windll.powrprof.CallNtPowerInformation
call_nt_power_information.restype = c_uint
def get_idle_timer():
# Get the time remaining before idle
info = SYSTEM_POWER_INFORMATION()
r = call_nt_power_information(SystemPowerInformation, None, 0, pointer(info), sizeof(SYSTEM_POWER_INFORMATION))
if r != 0:
raise Exception("Call to CallNtPowerInformation failed with code " + r)
return info.TimeRemaining
If the power event occurs when the system is considered as idle by windows, i assume it has been initiated by a power scheme. Of course this is not ideal but works in most cases. I would still be interested in finding a better way but it seems there isn't.

How to disable media_automount_open in Ubuntu through a script

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

Root priv can't be dropped in python even after seteuid. A bug?

Root priv can't be dropped in python even after seteuid. A bug?
EDIT Summary: I forgot to drop gid. The accepted answer may help you, though.
Hi. I can't drop the root privilege in python 3.2 on my linux. In fact, even after seteuid(1000), it can read root-owned 400-mode files. The euid is surely set to 1000!
I found after empty os.fork() call, the privileged access is correctly denied. (But it's only in the parent. The child can still read illegitimately.) Is it a bug in python, or is linux so?
Try the code below. Comment out one of the three lines at the bottom, and run as root.
Thanks beforehand.
#!/usr/bin/python3
# Python seteuid pitfall example.
# Run this __as__ the root.
# Here, access to root-owned files /etc/sudoers and /etc/group- are tried.
# Simple access to them *succeeds* even after seteuid(1000) which should fail.
# Three functions, stillRoot(), forkCase() and workAround() are defined.
# The first two seem wrong. In the last one, access fails, as desired.
# ***Comment out*** one of three lines at the bottom before execution.
# If your python is < 3.2, comment out the entire def of forkCase()
import os
def stillRoot():
"""Open succeeds, but it should fail."""
os.seteuid(1000)
open('/etc/sudoers').close()
def forkCase():
"""Child can still open it. Wow."""
# setresuid needs python 3.2
os.setresuid(1000, 1000, 0)
pid = os.fork()
if pid == 0:
# They're surely 1000, not 0!
print('uid: ', os.getuid(), 'euid: ', os.geteuid())
open('/etc/sudoers').close()
print('open succeeded in child.')
exit()
else:
print('child pid: ', pid)
open('/etc/group-').close()
print('parent succeeded to open.')
def workAround():
"""So, a dummy fork after seteuid is necessary?"""
os.seteuid(1000)
pid = os.fork()
if pid == 0:
exit(0)
else:
os.wait()
open('/etc/group-').close()
## Run one of them.
# stillRoot()
# forkCase()
# workAround()
Manipulating process credentials on Unix systems is tricky. I highly recommend gaining a thorough understanding of how the Real, Effective, and Saved-Set user ids are interrelated. It's very easy to screw up "dropping privileges".
As to your specific observations... I'm wondering if there's a simple cause you may have overlooked. Your code is preforming a inconsistent tests and you've neglected to specify the exact file permissions on your /etc/sudoers and /etc/group- files. Your could would be expected to behave exactly as you describe if /etc/sudoers has permissions mode=440, uid=root, gid=root (which are the default permissions on my system) and if /etc/group- has mode=400.
You're not modifying the process's GID so if /etc/sudoers is group-readable, that would explain why it's always readable. fork() does not modify process credentials. However, it could appear to do so in your example code since you're checking different files in the parent and child. If /etc/group- does not have group read permissions where /etc/sudoers does, that would explain the apparent problem.
If all you're trying to do is "drop privileges", use the following code:
os.setgid( NEW_GID )
os.setuid( NEW_UID )
Generally speaking, you'll only want to manipulate the effective user id if your process needs to toggle it's root permissions on and off over the life of the process. If you just need to do some setup operations with root permissions but will no longer require them after those setup operations are complete, just use the code above to irrevokably drop them.
Oh, and a useful debugging utility for process credential manipulation on Linux is to print the output of /proc/self/status, the Uid and Gid lines of this file display the real, effective, saved-set, and file ids held by the current process (in that order). The Python APIs can be used to retrieve the same information but you can consider the contents of this file as "truth data" and avoid any potential complications from Python's cross-platform APIs.

Dragon NaturallySpeaking Programmers

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.

Categories