So I'm creating a Password Manager, and as a security feature I wanted to add session time that logs the user out after some time of inactivity (in the example code 3 seconds), and I have this code :
import os
import time
import threading
# Checks what OS you're using
def check_platform():
if os.name == "nt":
platform = "Windows"
else:
platform = "Linux"
return platform
# Starts inactivity timer
def start_timer():
platform = check_platform()
if platform == "Windows":
def timer_start():
while True:
time.sleep(1)
check_if_idle_windows()
thread1 = threading.Thread(target=timer_start)
thread1.start()
elif platform == "Linux":
def timer_start():
while True:
time.sleep(1)
check_if_idle_linux()
thread1 = threading.Thread(target=timer_start)
thread1.start()
# Checks if the user is idle on Windows
def check_if_idle_windows():
import win32api
idle_time = (win32api.GetTickCount() - win32api.GetLastInputInfo()) / 1000.0
if idle_time > 3:
os.system("cls")
print("You have been logged out due to inactivity.")
os._exit(0)
# Checks if the user is idle on Linux
def check_if_idle_linux():
### Code to get idle time here ###
if idle_time > 3:
os.system("clear")
print("You have been logged out due to inactivity.")
os._exit(0)
def random_function_for_main_thread():
while True:
my_string = input("Enter something or stay inactive for 3 seconds : ")
print("You entered something.")
def main():
start_timer()
random_function_for_main_thread()
if __name__ == "__main__":
main()
What can I use to get idle time on Linux?
I tried this and this, and neither of them worked.
Hope my question isn't repeated, thank you.
import os
import time
import threading
# Starts inactivity timer
def start_timer():
platform = check_platform()
if platform == "Windows":
def timer_start():
while True:
time.sleep(1)
check_if_idle_windows()
thread1 = threading.Thread(target=timer_start)
thread1.start()
elif platform == "Linux":
def timer_start():
while True:
time.sleep(1)
check_if_idle_linux()
thread1 = threading.Thread(target=timer_start)
thread1.start()
# Checks what OS you're using
def check_platform():
if os.name == "nt":
platform = "Windows"
else:
platform = "Linux"
return platform
# Checks if the user is idle on Windows
def check_if_idle_windows():
import win32api
idle_time = (win32api.GetTickCount() - win32api.GetLastInputInfo()) / 1000.0
if idle_time > 3:
os.system("cls")
print("You have been logged out due to inactivity.")
os._exit(0)
# Checks if the user is idle on Linux
def check_if_idle_linux():
import subprocess
idle_time = int(subprocess.getoutput('xprintidle')) / 1000 # Requires xprintidle (sudo apt install xprintidle)
if idle_time > 3:
os.system("clear")
print("You have been logged out due to inactivity.")
os._exit(0)
def random_function_for_main_thread():
while True:
my_string = input("Enter something or stay inactive for 3 seconds : ")
print("You entered something.")
def main():
start_timer()
random_function_for_main_thread()
if __name__ == "__main__":
main()
Related
This is a program related to windows operations. I have made different versions of this program. So I tried writing a version using classes. I am a beginner and thought this will help me understand the concept but I am getting some errors like
Method 'shutdown_windows' may be 'static'
There are many errors like this and I would like to get some insight about them and how to solve them
This is my code:
import os
import datetime
import time
class WindowsOperations(object):
def __init__(self, shutdown, restart, open_app, close_app):
self.shutdown = shutdown
self.restart = restart
self.open_app = open_app
self.close_app = close_app
def shutdown_windows(self):
time.sleep(remaining_time)
while True:
if time_hour == datetime.datetime.now().hour and time_minutes == datetime.datetime.now().minute: #
os.system("shutdown /s /t 1")
break
def restart_windows(self):
time.sleep(remaining_time)
while True:
if time_hour == datetime.datetime.now().hour and time_minutes == datetime.datetime.now().minute:
os.system("shutdown /r /t 1")
break
def open_application(self):
app_name_open = input("Enter the application name you want to open: ").lower() + ".exe"
time.sleep(remaining_time)
while True:
if time_hour == datetime.datetime.now().hour and time_minutes == datetime.datetime.now().minute:
os.startfile(app_name_open)
break
def close_application(self):
app_name_close = input("Enter the application name you want to close: ").lower() + ".exe"
time.sleep(remaining_time)
while True:
if time_hour == datetime.datetime.now().hour and time_minutes == datetime.datetime.now().minute:
os.system("TASKKILL /F /IM " + app_name_close)
break
choice = int(input("Enter your choice \n1.Shutdown Windows \n2.Restart Windows "
"\n3.Open an application \n4.Close an application \n:"))
time_hour = int(input("Enter hour: "))
time_minutes = int(input("Enter minutes: "))
time_now = datetime.datetime.now()
remaining_time = ((time_minutes - time_now.minute) * 60 + (time_hour - time_now.hour) * 3600) % 86400
print(remaining_time)
my_windows_operation = WindowsOperations('shutdown', 'restart', 'open_app', 'close_app')
if choice == 1:
my_windows_operation.shutdown_windows()
elif choice == 2:
my_windows_operation.restart_windows()
elif choice == 3:
my_windows_operation.open_application()
elif choice == 4:
my_windows_operation.close_application()
else:
print("Please enter a valid input")
Please do modify the code if necessary and give me some tips
The second "Parameter 'shutdown' unfilled" is an error. It's coming because you've defined WindowsOperations intitializer to take 4 parameters:
def __init__(self, shutdown, restart, open_app, close_app):
But when actually creating the object you are passing noothing:
my_windows_operation = WindowsOperations()
You definitely need to fix that.
The first "Method 'shutdown_windows' may be 'static'" is more of a suggestion. It's coming because the method shutdown_windows does not use self - i.e. it need not be part of the class to do it's job.
I'm trying to create a timer that starts when a condition for an if statement is met and then stops and returns the duration when elif condition is met, is this possible?
The purpose of the application is to send a true or false value to AWS IoT from an Android application. The Python script is subscribed to AWS and receives the value and uses it to determine whether the led should be on or off.
The code I have:
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import RPi.GPIO as GPIO
import sys
import logging
import time
from time import sleep
from timeit import default_timer as timer
import getopt
import grovepi
msgpay = None
# Custom MQTT message callback
def customCallback(client, userdata, message):
print("Received a new message: ")
print(message.payload)
print("from topic: ")
print(message.topic)
print("--------------\n\n")
global msgpay
msgpay = message.payload
led = 5
grovepi.pinMode(led, "OUTPUT")
start_time = timer()
if msgpay == "true":
print("turning on")
grovepi.digitalWrite(led, 1)
#time.sleep(3)
elif msgpay == "false":
print("turning off")
grovepi.digitalWrite(led, 0)
duration = timer() - start_time
print duration
Any help how to go about this would be appreciated.
Thanks
I'll try to connect a button on my RPi to control mplayer, first button press shall start the player, and each later button press shall play another entry in the playlist.
As a minimal example I created following script on Linux Mint 18 and Python3.4.3:
from time import sleep
from subprocess import Popen, PIPE, DEVNULL
cmd = ["mplayer", "-shuffle", "-playlist", "/path/to/playlist.m3u"]
if __name__ == '__main__':
first = False
p = None
i = 0
if first == False: # should simulate first button
print("player starting")
p = Popen(cmd, stdin=PIPE, stdout=DEVNULL)
print("player started")
first = True
while 1:
sleep(1)
i += 1
print(str(i)+ " " +str(first))
if i == 5 and first == True: # should simulate each later button
i = 0
print("sending keystroke to mplayer")
p.communicate(b"\n")[0] # mplayer plays next song, but the program is lost
print("sended keystroke to mplayer - never printed")
And the output is:
player starting
player started
1 True
2 True
3 True
4 True
5 True
sending keystroke to mplayer
And now I'm expecting a restart of the loop, but it's missing.
Debugging did not help me.
Do you have any ideas how to solve the problem and how to return into the loop?
Thank you.
I solved it with mplayer slave:
from time import sleep
from subprocess import Popen
pathtoControlFile = "/home/immi/mplayer-control"
cmd = ["mplayer", "-slave", "-input", "file="+pathtoControlFile, "-shuffle", "-playlist", "/media/immi/9A005723005705A3/Musik/playlist.m3u"]
if __name__ == '__main__':
first = False
i = 0
if first == False: # initial start
print("player starting")
p = Popen(cmd)
print("player started")
first = True
while 1:
sleep(1)
i += 1
print(str(i)+ " " +str(first))
if i == 5 and first == True: # each later button
i = 0
print("sending keystroke to mplayer")
with open(pathtoControlFile, "wb+", buffering=0) as fileInput:
p = Popen(["echo", "pt_step next"], stdout=fileInput)
So I wrote a python that will find what the pin the users inputs, everything works fine except one thing, and that's that the script won't exist once the pin is found. Is there a why I can kill all of the other threads once I found the pin?
#!/usr/bin/env python
#
#
#
from threading import Thread
from random import randint
from time import sleep
from sys import exit
from os import system
system('clear');sleep(0.7)
Pin = int(raw_input('Enter a pin: '))
def Up():
global Pin
for pin in xrange(1111,10000):
system('clear')
print pin
if pin == Pin:
system('clear')
print 'U Pin Found: %d'%pin;sleep(0.7)
for i in range(3):
exit()
def Down():
global Pin
pins = xrange(10000)
for pin in reversed(pins):
system('clear')
print pin
if pin == Pin:
system('clear')
print 'D Pin Found: %d'%pin;sleep(0.7)
exit()
def Random():
global Pin
while True:
pins = randint(1111,10000)
print pins
if pins == Pin:
system('clear')
print 'R Pin Found: %d'%pins;sleep(0.7)
exit()
Task1 = Thread(target=Up,args=())
Task2 = Thread(target=Down,args=())
Task3 = Thread(target=Random,args=())
Task1.start()
Task2.start()
Task3.start()
You can't simply terminate them. However you can ask to stop. Please see example:
from threading import Thread
from random import randint
from time import sleep
from sys import exit
from os import system
system('clear');sleep(0.7)
Pin = int(raw_input('Enter a pin: '))
terminateAll = false
def Up():
global Pin
for pin in xrange(1111,10000):
if terminateAll:
exit()
system('clear')
print pin
if pin == Pin:
terminateAll = true
system('clear')
print 'U Pin Found: %d'%pin;sleep(0.7)
for i in range(3):
exit()
def Down():
global Pin
pins = xrange(10000)
for pin in reversed(pins):
if terminateAll:
exit()
system('clear')
print pin
if pin == Pin:
terminateAll = true
system('clear')
print 'D Pin Found: %d'%pin;sleep(0.7)
exit()
def Random():
global Pin
while True:
if terminateAll:
exit()
pins = randint(1111,10000)
print pins
if pins == Pin:
terminateAll = true
system('clear')
print 'R Pin Found: %d'%pins;sleep(0.7)
exit()
Task1 = Thread(target=Up,args=())
Task2 = Thread(target=Down,args=())
Task3 = Thread(target=Random,args=())
Task1.start()
Task2.start()
Task3.start()
All you need to do is make the thread objects daemons by setting their daemon to attribute to True before starting them.
The default value is False. Any daemon threads still running when the main program thread ends will automatically be terminated.
A logical place to do this is right after calling their constructor:
...
Task1 = Thread(target=Up,args=())
Task1.daemon = True
Task2 = Thread(target=Down,args=())
Task2.daemon = True
Task3 = Thread(target=Random,args=())
Task3.daemon = True
Task1.start()
Task2.start()
Task3.start()
I'm using python 2.5(x86) in Windows7 x64.
I wrote the code following this book.
http://nostarch.com/ghpython.htm
But it doesn't work in my environment.
PDBG_ERR> -- IGNORING ERROR --
PDBG_ERR> process_restore: [87] WriteProcessMemory
I suppose the problem comes from Windows version because somebody mentioned it in the below url page and I heard it works in Windows XP.
http://bbs.csdn.net/topics/380255167
PyDBG process snapshots not working
from pydbg import *
from pydbg.defines import *
import threading
import time
import sys
class snapshotter(object):
def __init__(self,exe_path):
self.exe_path = exe_path
self.pid = None
self.dbg = None
self.running = True
pydbg_thread = threading.Thread(target=self.start_debugger)
pydbg_thread.setDaemon(0)
pydbg_thread.start()
while self.pid == None:
time.sleep(1)
monitor_thread = threading.Thread(target=self.monitor_debugger)
monitor_thread.setDaemon(0)
monitor_thread.start()
def monitor_debugger(self):
while self.running == True:
input = raw_input("Enter: 'snap','restore' or 'quit'")
input = input.lower().strip()
if input == "quit":
print "[*] Exiting the snapshotter."
self.running = False
self.dbg.terminate_process()
elif input == "snap":
print "[*] Suspending all threads."
self.dbg.suspend_all_threads()
print "[*] Obtaining snapshot."
self.dbg.process_snapshot()
print "[*] Resuming operation."
self.dbg.resume_all_threads()
elif input == "restore":
print "[*] Suspending all threads."
self.dbg.suspend_all_threads()
print "[*] Restoring snapshot."
self.dbg.process_restore()
print "[*] Resuming operation."
self.dbg.resume_all_threads()
def start_debugger(self):
self.dbg = pydbg()
pid = self.dbg.load(self.exe_path)
self.pid = self.dbg.pid
self.dbg.run()
exe_path = "C:\\WINDOWS\\System32\\calc.exe"
snapshotter(exe_path)
How can I avoid this error and make it work?