Retrieving user name properties for a file - python

I am able to use the following code to get the size and last modified date. How can I get the user the file was last modified by?
file = "myFileName.xlsx"
size = str(os.path.getsize(file))
lastModified = str(time.ctime(os.path.getmtime(file)))
Thanks

This is not a perfect solution, but you can get the user's name by prompting the user to enter a password(if you password protect the file). The getpass() function in the getpass module will prompt the user to enter a password when they try modifying the file. At this point, the getuser() function will fetch the user's name from os.environ.get('USERNAME').
import time
import getpass
file = "test.txt"
if file:
getpass.getpass()
user = getpass.getuser()
size = str(os.path.getsize(file))
lastModified = str(time.ctime(os.path.getmtime(file)))
print(size, lastModified, user) #316139 Thu Mar 15 02:11:33 2018 user_name
Depending upon your OS configuration and whether the files are stored locally or on the network (such as shared Active Directory sites), the solution will be different. In this case, your question should be more elaborate.

Related

Configparser writes to fie but returns empty result

So this function is a cut-out, from a class that should create and then extract information from an ini file. The problem I have is that the ini file definitely shows that all the added sections exist, but whenever I want the program to extract information or read from the file, it returns [], an empty list. I tried this function in a more basic version using Anaconda Navigator, well it turned out there it worked.
The screenshot shows the ini file.
As seen in the screenshot, the file is indeed not empty and the function successfully wrote to it, problem is whenever the function should print from it or when I want another function to read it, it returns [].
Code is as following:
class cSetup():
import os
import time
import datetime
import configparser as configparser
"""Class creates an ini file, this ini file contains a number of settings which can be read by the get function.
the program will later access this file to check for certain settings.
If the file is not existing yet, a function within the class will create it
"""
config = configparser.ConfigParser()
def write_setup(self):
if os.path.exists("Setup.ini"):
setup_file = open("Setup.ini", "r")
print(self.config.read(setup_file))
setup_file.close()
else:
"""This function is the initial setup, it writes all the necessary information to a .ini file."""
global config
"""Asks user for a name"""
Name = input("Please enter your name, note this can be changed in the settings""\n"
"Please enter the name here: ")
self.time.sleep(1)
"""asks user for prefered input method"""
PreferredInput = input("Input method required: 0 Shutdown, 1 Voice Commands, 2 Text Commands, 3 Dev Mode: ")
setup_file = open("Setup.ini", "w")
setup_file
self.config.write(setup_file)
self.config.add_section("Setup state")
self.config.set("Setup state", "Activated?", "True") # Convert to Bool later
section_option = "Settings"
self.config.add_section(section_option)
self.config.set(section_option, "Name", Name)
self.config.set(section_option, "Preferred Input", PreferredInput) # Convert to int later
self.config.write(setup_file)
setup_file = open("Setup.ini", "r")
print(self.config.read(setup_file))
setup_file.close()

What is the credentials.txt format used by selenium?

The README for the project at https://github.com/apurvmishra99/facebook-scraper-selenium includes the instruction:
Store your email and password for Facebook login in credentials.txt
This project doesn't contain any code that tries to read or parse credentials.txt, so I assume that the format has to be standard to selenium or to Python.
What exactly is the format this file should be in?
It's not a selenium or python thing. That file was deleted during one of the developer's commits:
I've had a look for you, and if you look in this file in the project: https://github.com/apurvmishra99/facebook-scraper-selenium/blob/master/fb-scraper/settings.py
You can see it gets the email and password:
# User credentials
EMAIL = os.getenv("EMAIL")
PASSWORD = os.getenv("PASSWORD")
os.getenv is python, and does:
os.getenv(key, default=None) Return the value of the environment
variable key if it exists, or default if it doesn’t. key, default and
the result are str.
What you can try is create environment variables called "EMAIL" and "PASSWORD" set the respectively and then run the main.py
Also be aware that in the same settings files the binaries are set as so:
# Required binaries
BROWSER_EXE = '/usr/bin/firefox'
GECKODRIVER = '/usr/bin/geckodriver'
FIREFOX_BINARY = FirefoxBinary(BROWSER_EXE)
You'll need to ensure these reflect your system.

Move Lotus Notes Email to a Different Folder Python

After extracting some of the email's data, I would like to move the email to a specified folder with python. I've searched and haven't seemed to find what I need.
Has anyone done this before?
Per a comment, I've added my current logic in hopes that it will clarify my problem. I loop through my folder, extract the details. After doing that, I want to move the email to a different folder.
import win32com.client
import getpass
import re
'''
Loops through Lotus Notes folder to view messages
'''
def docGenerator(folderName):
# Get credentials
mailServer = 'server'
mailPath = 'PubDir\inbox.nsf'
# Password
pw = getpass.getpass('Enter password: ')
# Connect
session = win32com.client.Dispatch('Lotus.NotesSession')
# Initializing the session and database
session.Initialize(pw)
db = session.GetDatabase(mailServer, mailPath)
# Get folder
folder = db.GetView(folderName)
if not folder:
raise Exception('Folder "%s" not found' % folderName)
# Get the first document
doc = folder.GetFirstDocument()
# If the document exists,
while doc:
# Yield it
yield doc
# Get the next document
doc = folder.GetNextDocument(doc)
# Loop through emails
for doc in docGenerator('Folder\Here'):
# setting variables
subject = doc.GetItemValue('Subject')[0].strip()
invoice = re.findall(r'\d+',subject)[0]
body = doc.GetItemValue('Body')[0].strip()
# Move email after extracting above data
# ???
As you will move the document before getting the next one, I'd recommend to replace your loop with
doc = folder.GetFirstDocument()
while doc:
docN = folder.GetNextDocument(doc)
yield doc
doc = docN
And then to move the message to the proper folder you need
doc.PutInFolder(r"Destination\Folder")
doc.RemoveFromFolder(r"Origin\Folder")
Of course, take care of escaping your backslashes or using raw strings literals to pass correctly the view name.
doc.PutInFolder creates the folder if it doesn't exist. In that case the user needs to have permissions to create public folders, otherwise the created folder will be private. (If the folder already exists, of course, this is not a problem.)

Storing a username and password, then allowing user update. Python [duplicate]

This question already has answers here:
I need to securely store a username and password in Python, what are my options? [closed]
(8 answers)
Closed 5 years ago.
I am trying to create a program that asks the user for, in this example, lets say a username and password, then store this (I assume in a text file). The area I am struggling with is how to allow the user to update this their password stored in the text file? I am writing this in Python.
import getpass
import os
import bcrypt
new=None
def two_hash():
master_key = getpass.getpass('enter pass word ')
salt = bcrypt.gensalt()
combo = salt + master_key
hashed = bcrypt.hashpw(combo , salt)
allow = raw_input('do you want to update pass ')
if allow == 'y':
new = getpass.getpass('enter old pass word ')
combo = salt + new
bcrypt.hashpw(combo , salt)
if ( bcrypt.hashpw(combo , salt) == hashed ):
new = getpass.getpass('enter new pass ')
print new
else :
pass
if __name__ == '__main__':
two_hash()
Note 1 : i wanted to split my code to some function but i can't so help for split it to some function
Because you've asked to focus on how to handle the updates in a text file, I've focused on that part of your question. So, in effect I've focused on answering how would you go about having something that changes in a text file when those changes impact the length and structure of the text file. That question is independent of the thing in the text file being a password.
There are significant concerns related to whether you should store a password, or whether you should store some quantity that can be used to verify a password. All that depends on what you're trying to do, what your security model is, and on what else your program needs to interact with. You've ruled all that out of scope for your question by asking us to focus on the text file update part of the problem.
You might adopt the following pattern to accomplish this task:
At the beginning see if the text file is present. Read it and if so assume you are doing an update rather than a new user
Ask for the username and password. If it is an update prompt with the old values and allow them to be changed
Write out the text file.
Most strategies for updating things stored in text files involve rewriting the text file entirely on every update.
Is this a single user application that you have? If you can provide more information one where you're struggling
You can read the password file (which has usernames and passwords)
- When user authenticate, match the username and password to the combination in text file
- When user wants to change password, then user provides old and new password. The username and old password combination is compared to the one in text file and if matches, stores the new
Try using JSON.
An example of a json file would be this:
{
"Usernames": {
"Username": [
{
"Password": "Password123"
}
]
}
}
Then to edit the json:
jsonloads = json.loads(open('json.json').read()) #Load the json
username = input("Enter your username: ") #Get username as a string
for i in jsonloads["Usernames"]: #Iterate through usernames
if i == username: #If the username is what they entered
passw = input("New password: ") #Ask for new password
jsonloads["Usernames"][i][0]["Password"] = passw #Set the password
jsonFile = open("json.json", "w+") #Open the json
jsonFile.write(json.dumps(jsonloads, indent=4)) #Write
jsonFile.close() #Close it
break #Break out of the for loop
else: #If it remains unbroken
print("You aren't in the database. ")
user = input("Username: ") #Ask for username
passw = input("Password: ") #Ask for password for username
item = {"Password":pass} #Make a dict
jsonloads["Usernames"].update({user: item}) #Add that dict to "Usernames"
with open('json.json','w') as f: #Open the json
f.write(json.dumps(jsonloads, indent=4)) #Write
Something like that should work, haven't tested it though.
Also, remember to always encrypt passwords!

Python - Getting textboxes input data by Selenium

lastly I'm working about a Python project which uses the library "selenium". The project should type in passwords according to the usernames that it has got. My problem is that I don't know how to get data from a text box.
For example, if I want to use the project on "Facebook", at first I have to get the E-mail which the user typed in (kind of like putting it as a string variable), and then I have to type in the correct password (I know how to do that). My main problem is that the command " .text " doesn't work because the E-mail isn't found in any attribute of the textbox, so I can't call it.
Does someone have a solution please?
The current lines are :
driver = webdriver.Chrome('C:\\Users\User\Desktop\chromedriver.exe')
driver.get('https://www.facebook.com/stype=lo&jlou=AfdFutu6bihEQajPctMRwj2ySoaIGAE71YZ0aBZe9FYV4Xd2XuZ3SGth5wernWcF7s4pSvZH5W6f0ed2BfafHrkbupDcW4GDQECBTnhQID1FQ&smuh=4370&lh=Ac_eTqeC_DcDMq9f')
mail = driver.find_element_by_id('email').text
The problem is that the current "mail" variable is an empty string, because the E-mail textbox of Facebook's website is empty as it's waiting for the client to type in his E-mail. I'm trying to get the client's E-mail AFTER he typed it in.
Thanks in advance!
You can get value from input field simply as
email_input = driver.find_element_by_xpath('//input[#type="email"]')
print(email_input.get_attribute('value'))
Update
If you want to get text from input after user enter email:
driver = webdriver.Chrome('C:\\Users\User\Desktop\chromedriver.exe')
driver.get('https://www.facebook.com/stype=lo&jlou=AfdFutu6bihEQajPctMRwj2ySoaIGAE71YZ0aBZe9FYV4Xd2XuZ3SGth5wernWcF7s4pSvZH5W6f0ed2BfafHrkbupDcW4GDQECBTnhQID1FQ&smuh=4370&lh=Ac_eTqeC_DcDMq9f')
email = input("Please enter your Email: ")
email_input = driver.find_element_by_xpath('//input[#type="email"]')
email_input.send_keys(email)
print(email_input.get_attribute('value')) # or just print(email)
Note, that user should enter email value to command line, but not to browser input field

Categories

Resources