Windows logoff using Python

9.6k views Asked by At

Which Python function should I use, to log off current user. I found an example that is locking my pc, like Win+L combination

ctypes.windll.user32.LockWorkStation ()

but I need a similar function, which will log off.

3

There are 3 answers

1
Sideshow Bob On

Try os.system("shutdown -l").

shutdown -l is the windows shell command for logoff

0
Nick Bastin On

You can do this, but only really as a service that runs as the SYSTEM user. If you try to log off the user you are running as, you will terminate your script (regardless of the way you accomplish this, the current task will terminate when the user environment terminates).

However, if you write your backup to function as a service, you can use win32api (via pywin32) to terminate all user sessions (this isn't all that nice, but lets presume that's ok with your users) and then do the backup. There is a problem to be had if a user logs back in - you'll have to trap a user logon event - but otherwise this is relatively pain free.

0
lunixbochs On

This should cause the current user to logout:

ctypes.windll.user32.ExitWindowsEx(0, 1)

Ctypes should be able to convert those params to unsigned ints without problems. If it throws an error about argument types, try wrapping 0 and 1 like this: ctypes.c_ulong(0)

Documented here: ExitWindowsEx

Side note: if you make a practice of logging out active users without prompting them with a dialog (even if it has a 60 second or timer), they will likely be very unhappy.