tKinter - How to merge with an existing application? - windows

I'm sorry, I'm as new to programming as can be (I have a sys-admin background but I'm really interested in the development side of problem solving). If I ask illogical questions or I'm not posting how I should, please understand I'm trying to learn and I'm very open to corrections.
TLTR: I'm very new and heavily modified a Python 2.7 code I found online years ago for a method to "lock" windows folders. I'm looking to update my app/program to utilize tKinter to replace the current command prompt password entry process in place but lack the programming knowledge for logically what I'm missing.
How it works functional:
Run the .exe (I converted the .py file not knowing I could run easy by changing extension from py to .pyw, again very new)
Pop-up prompt requests password (not tKinter, just a command prompt box I customized the size, banner, and prompt for)
When correct password is entered, a folder that is hidden elsewhere on the PC becomes unhidden, the name changes, and it appears on the desktop. (If no folder was created in the first place, it will create one; not included in code below.)
After files are added, the same password can be entered which changes the desktop folder's attribute to be hidden and placed back to the hidden location
If password fails, the pop-up prompt states there's an incorrect password then loops back to the password entry. (Left this part out below as idk how much code I should be giving)
import base64
import os
import time
import sys
import getpass
import shutil
#Set Password
pw = "p#ssword"
encode = base64.b64encode(pw)
#Custom window size
os.system("mode con: cols=40 lines=4")
def goto(linenum):
global line
line = linenum
line = 1
while True:
#Customizable welcome banner
print "****************************************"
print " Welcome:"
print "****************************************"
pw = (getpass.getpass('Password: '))
pass
goto(1)
#Hides password input
if pw == base64.b64decode(encode):
# Sets the path where you want BitLocker to show up
os.chdir("C:\Users\WINUSER\Desktop")
#Checks for existing BitLocker folder
if not os.path.exists("BitLocker"):
#If BitLocker folder isn't found, it checks for BitLocker.{CLSID}
if not os.path.exists("BitLocker.{A0953C92-50DC-43bf-BE83-3742FED03C9C}"):
#If BitLocker.{CLSID} isn't found on Desktop, it changes the folder name in hidden location to BitLocker, unhides it and moves it back to the desktop
os.rename("C:\\Users\\WINUSER\\Videos\\Captures\\BitLocker.{A0953C92-50DC-43bf-BE83-3742FED03C9C}", "C:\\Users\\WINUSER\\Desktop\\BitLocker.{A0953C92-50DC-43bf-BE83-3742FED03C9C}")
os.popen('attrib -h BitLocker.{A0953C92-50DC-43bf-BE83-3742FED03C9C}')
os.rename("BitLocker.{A0953C92-50DC-43bf-BE83-3742FED03C9C}","BitLocker")
I'm looking to add a tKinter GUI that works as a password entry than does the folder moves, etc. Would it be better to have 2 programs, 1 tKinter for a PW entry prompt that, when entered correct, calls to open another program to change the folder's attributes?
I've been seen code like what's below on here, but don't know how to incorporate it into what I currently have. I'm not too proud to be pointed towards documentation.
from tkinter import *
def show():
p = password.get() #get password from entry
print(p)
app = Tk()
password = StringVar() #Password variable
passEntry = Entry(app, textvariable=password, show='*')
submit = Button(app, text='Show Console',command=show)
passEntry.pack()
submit.pack()
app.mainloop()
Thank you

Related

Opening Files inside of a Folder in Python

I am writing a program that allows the user to associate "tags" to specific pictures or documents.
Ex. "A family picture" and a "Friends Picture" are in the same file. The user wants a list of all pictures associated with their family. Instead of opening the Friends Picture it would open the Family Picture.
When the program opens I want it to open all the files one by one allowing the user to associate the desired tags. How can I go about having the computer open multiple documents one at a time with the fact that none of the files have the same name? I would like to avoid hard coding it as it would be near impossible, to my understanding.
In the code example below you can see that var_a is being used to name the window the same as the picture and also try to have the computer search for the users desired picture/document. Because you can't use variables in directories I have no clue what to do now.
import pygame
var_a = input("Whats the name of the picture/document")
window1 = pygame.display.set_mode((1370, 750))
pygame.display.set_caption(var_a)
image1=pygame.image.load("/Users/verdenstudent1509/Desktop/Computers/FRC Game/var_a")
window1.blit(image1, (1370/3, 750/3))
pygame.display.update()
I expected the program to open the file that I typed into the input as var_a but instead, I got this error:
Traceback (most recent call last):File "/Users/verdenstudent1509/Documents/(PhotoLibraryUTO).py", line 9, in
image1=pygame.image.load("/Users/verdenstudent1509/Desktop/Computers/FRC Game/'var_b'")
pygame.error: Couldn't open /Users/verdenstudent1509/Desktop/Computers/FRC Game/'var_b'
The name of the file is not "var_a", the name of the file is the content of var_a.
Strings can be concatenated by the +-operator:
pathname = "/Users/verdenstudent1509/Desktop/Computers/FRC Game/" + var_a
I recommend to handle the exception, which may occur if the file was not found, because the filename is wrong, by a try-except statement:
try:
image1=pygame.image.load(pathname)
except:
print(pathname + " is not a file")
First define the folder path.
For example:
f = "/Users/zaidahamed/croppingImage/output"
Then use a for loop to access each image and perform action on each one of it.
For example, i am trying to crop the image from the center to have 12x12 cm cropped image as output.
Code example:
for file in os.listdir(f):
# open 1 image
f_img = f+"/"+file
img = Image.open(f_img)
# perform action
im_new = crop_center(img, 1050, 1050)
# save changes
im_new.save(f_img, quality=100)
print("Crop success")

OpenEdge 10.2A - INPUT THROUGH set does not work after Windows Update 1703 on Windows 10

We were using below code to get the name of the computer.
def new shared var cHost as char format "x(40)" no-undo.
INPUT THROUGH hostname NO-ECHO.
SET cHost.
INPUT CLOSE.
DISPLAY chost.
After we have updated our computers (Windows 10 - 1703), it no longer works. It seems SET cHost is the part where it fails. I have tried IMPORT UNFORMATTED cHost but it does not work.
PS: I can get computer name using OS-GETENV("COMPUTERNAME") but I have to do it using INPUT THROUGH statement.
Edit: It seems that it is not only a problem with 10.2A but a more general one. Also it is not just related to hostname but all console applications and ms-dos commands. Now I will try to replace INPUT THROUGH statement with another Progress command if there is any, or try to communicate with existing console applications with some other method.
The first thing I would do is to verify that the 'hostname' command is still working properly from a command window.
Assuming that it is I would code your snippet something like this:
INPUT THROUGH VALUE( "hostname" ).
IMPORT UNFORMATTED cHost.
INPUT CLOSE.
DISPLAY cHOST format "x(60)".
Which might reveal a more useful error message than "it no longer works".
Since COMPUTERNAME meets your needs but you must use INPUT THROUGH for some very mysterious reason you might also try:
INPUT THROUGH VALUE( "echo %COMPUTERNAME%" ).
IMPORT UNFORMATTED cHost.
INPUT CLOSE.
DISPLAY cHOST format "x(60)".
It seems the problem may not be limited to Openedge version 10. I am running a windows 10 winver 1703 device for development, using Progress/Openedge 8.3 and I am no longer able to execute this.
def var a as char format "x(70)".
input through "echo %cd%" no-echo.
import unformatted a.
input close.
message a. pause.
This runs on a windows server 2012 R2, using progress/openedge 8.3.
Where is no longer works, it just exits from within the program when it hits the import command.
Since it seems as a bug, until someone comes up with a better solution, this is how I will change my codes:
DEF VAR cHost AS CHAR FORMAT "x(40)" NO-UNDO.
OS-CREATE-DIR VALUE("c:\temp").
OS-COMMAND SILENT VALUE("hostname >c:\temp\hostname.txt").
INPUT FROM VALUE("c:\temp\hostname.txt").
IMPORT UNFORMATTED cHost.
INPUT CLOSE.
MESSAGE cHost.
This code can be used for other ms-dos commands and console applications as well.
DEF VAR cHost AS CHAR FORMAT "x(40)" NO-UNDO.
OS-CREATE-DIR VALUE("c:\temp").
OS-COMMAND SILENT VALUE("ECHO %cd% >c:\temp\result.txt").
INPUT FROM VALUE("c:\temp\result.txt").
IMPORT UNFORMATTED cHost.
INPUT CLOSE.
MESSAGE cHost.
Thanks for your help.

Keyring using variables that read service and username in windows credentials

So the issue is we have an openLDAP server for authentication of our NAS drives in the office. Every time a computer is restarted the user has to input their password again to access the drives. Simply running a batch script to log into their drives in the morning works but the big boss doesn't like that their passwords are just sitting in raw text in the file.
So I've been plugging away in python to try and get a simple program to retrieve their password from windows credentials and toss that into a NET USE in os.system:
os.system("net use X: \\\\x.x.x.x password /user:username#domain.com")
I can retrieve the user name from a file simply enough from a variable opening a file and reading from a line. The issue is the password.
test_a = open('passtest.cfg', 'r')
test_b = open('passtest2.cfg', 'r')
test2_a = test_a.readline()
test2_b = test_b.readline()
drivepass = keyring.get_password(test2_a, test2_b)
The issue seems to be that keyring doesn't like reading from variables for some reason or another. At least i can't seem to figure out why it doesn't. It works just fine if i use:
drivepass = keyring.get_password("x.x.x.x", "username#domain.com")
The REAL problem is we need it simple enough that we can just move it around from workstation to workstation and just change the username#domain.com in a file and run it. So in the end the end product looks something like
os.system("net use X: \\\\x.x.x.x\foldername" + drivepass + "/user:" + test2_b)
It seems I've accidentally solved my own problem.
Didn't work:
drivepass = keyring.get_password(test2_a, test2_b)
Works:
drivepass = keyring.get_password("x.x.x.x", test2_b)
So the service arg in keyring apparently needs to not be a variable. to be fair though it doesn't need to be anyways. Hopefully somewhere down this line this helps somebody else.

How to read firefox's about:config entries using Python?

How could I read about:config entries for firefox version 30.0 using Python ? I tried to use what is pointed by this answer (in JavaScript) but it did not help.
Yeah, that's a problem. Firefox comes with default values for most preferences, and only stores values different from the default in the profile. Added to this, each add-on may come with additional default values and create new preferences at runtime.
The default pref files might be contained within zip files, which complicates matters a little.
Files
Files you'd have to check for default preferences (in a standard Firefox distribution)
$APPDIR/omni.ja:greprefs.js
$APPDIR/omni.ja:defaults/preferences/*.js
$APPDIR/browser/omni.ja:greprefs.js
$APPDIR/browser/omni.ja:defaults/preferences/*.js
$PROFILE/extensions/*/defaults/preferences/*.js
$PROFILE/extensions/*.xpi:defaults/preferences/*.js
While preferences that were overridden from the default reside in $PROFILE/prefs.js.
So first you need to figure out $APPDIR (installation path of Firefox) and then $PROFILE (Firefox user profile path).
Then you need to read some files either in some directories (easy) or in some zip files (hard). A major problem is that you cannot just use zipfile to read omni.ja (and potentially some of the xpi files) because a typical python zipfile implementation is too rigid in the interpretation of the zip structure and fails to open these files. So you'd need your own zipfile implementation that can deal with this.
Format
In the *.js files there are essentially two types of lines (+ blank lines, comment lines):
pref("name", value)
user_pref("name", value)
The pref lines are default preferences, user_pref lines are user preferences (overridden from default).
Values
value is a Javascript expression such as "abc", true, 1 or 2 * 3. The latter is a problem, as you'd need a JS engine to properly evaluate it. But this isn't really a problem in practice, as you won't find expressions computing something in the wild (usually).
Conclusion
Really replicating the preferences system (or about:config) isn't an easy task and full of obstacles. It is probably far easier just reading user pref.js to see what's overridden and knowing the default values.
Example (just prefs.js)
import re
import json
PROFILE = "/path/to/firefox/profile"
def read_user_prefs(preffile):
r = re.compile(r"\s*user_pref\(([\"'])(.+?)\1,\s*(.+?)\);")
rv = {}
for l in preffile:
m = r.match(l)
if not m:
continue
k, v = m.group(2), m.group(3)
try:
rv[k] = json.loads(v)
except Exception as ex:
print "failed to parse", k, v, ex
return rv
with open("{}/prefs.js".format(PROFILE), "rb") as p:
prefs = read_user_prefs(p)
for k, v in prefs.items():
print u"({type:<16}) {key}: {value}".format(
key=k, value=v, type=str(type(v)))
print
print "Chrome debugging enabled:",
print prefs.get("devtools.chrome.enabled", False)
print "Last sync:",
print prefs.get("services.sync.tabs.lastSync", 0.0)
print "Pref that might not exist:",
print prefs.get("does.not.exist", "default")
Alternatives
Write a firefox-addon that dumps interesting Preferences to a known file, or uses another form of IPC (sockets, whatever) to communicate with your python script.

how to bring the choose.file() dialog to the foreground

I'm using the function choose.dir() in a script that is run with rscript.exe under Windows XP. The problem is that the directory choosing dialog does not pop up as a top-level window. How can I bring the dialogue to the foreground?
In the meantime, I solved my problem by using visual basic script. Of course, this only works with windows:
tf <- tempfile(fileext = '.vbs')
cat('Set folder = CreateObject("Shell.Application") _
.BrowseForFolder(0, "Please choose a folder" _
, &H0001, 17)
Wscript.Echo folder.Self.Path
', file = tf)
tail(shell(paste('Cscript', tf), intern = T), 1)
After searching the rhelp archives it appears the answer is that you can't use choose.dir and file.choose in a non-interactive session. You might be able to do something similar, since list.files, file.info, file.access and files can be used to gather information, you can display this by writing to a graphics device and executing a system() call to get it displayed, and readLines can be used to get user input.

Resources