How to Logout from GMail using Python - python-3.x

I am trying to build a desktop Python3 application that will login to GMail and perform a few tasks. I have used the quickstart.py sample code given in the Google Developers Guide and it works perfectly. My application logs in and retrieves data.
However, after the program executes and terminates, the browser remains logged into GMail, unless the user specifically opens GMail on his browser and actually logsout. This is a security hazard as the user may forget to logout.
I am looking for way in which my python program will automatically log the user out before the program terminates. Will be grateful if someone can guide me on how this can be done.

The gmail API creates a file on CWD named "token.pickle" if you delete the file then logging in again with your program will require authentication.
So you can write a short program like this :
import os
files = os.listdir(".") # path to where credentials is stored
for file in files:
if file == 'token.pickle':
choice = input("""
Do you want to delete {}
1) yes.
2) no """.format(file))
if str(choice) == '1':
os.remove(file)
break
print("Done")

this is absurdly simple and i got the idea from here.
import webbrowser
webbrowser.open('https://mail.google.com/mail/u/0/?logout&hl=en', new=2)

As an updated answer for #Michael Gregory's solution, the file now is called: token_gmail_v1.pickle
so you it's now:
os.remove("./token_gmail_v1.pickle") # or -> os.remove("./*.pickle")
# as long as it's the only .pickle file
# in your working directory since this method is a dangerous one.
Instead of
os.remove("./token.pickle")
Side note: You can use it to check if the user is connected as well.
import os.path
isConnected= os.path.isfile("./token_gmail_v1.pickle")

Related

(-2147024891, 'Access is denied.', None, None)

I am developing a Django (v 3.2.6) application (Python 3.9.1.) which needs to write into an Excel file using pywin32.com.
On the client side it works fine, but when I put in production using IIS (v 10) on a Windows 11 server, I get the error above.
I have a routine that reads in a file input by the user and writes to the project directory:
if request.method == 'POST':
# Create a form instance and populate it with the file from the request (binding):
form = Name1_uploadForm(request.POST, request.FILES)
if form.is_valid():
# Create variable for uploaded file
uploaded_excel_file = form.cleaned_data['excel_file']
# Write it to BASE_DIR
with open(os.path.join(settings.BASE_DIR, form.cleaned_data['excel_file'].name), 'wb+') as destination:
for chunk in uploaded_excel_file.chunks():
destination.write(chunk)
# Allow the write process to conclude
time.sleep(12)
# Close the file
destination.close()
# Call conversion function
Name1_extraction(os.path.join(settings.BASE_DIR, form.cleaned_data['excel_file'].name))
# redirect to a new URL:
return HttpResponseRedirect(reverse('index') )
else:
form = Name1_uploadForm()
This calls another function (below) that should open that same file:
def Name1_extraction(uploaded_excel_file):
const = win32.constants
# Need to run CoInitialize to use win32com.client
pythoncom.CoInitialize()
# Open Name1 excel with Win32com
excelFile = win32.gencache.EnsureDispatch('Excel.Application')
The complete error is the following:
enter image description here
enter image description here
enter image description here
The error occurs when the following line of code is executed:
excelFile = win32.gencache.EnsureDispatch('Excel.Application')
The application pool is IIS AppPool\DefaultAppPool.
DefaultAppPool has been granted full access to folders C:\Windows\SysWOW64\config\systemprofile\Desktop and C:\Windows\System32\config\systemprofile\Desktop
With these actions I would not expect to see any errors
Thank you for any help provided.
Microsoft does not recommend or support server-side Automation of Office, and Microsoft strongly recommends that developers look for alternatives to Automation of Office when they need to develop server-side solutions.
Due to limitations in the design of Office, changing the Office configuration alone is not sufficient to resolve all issues. Microsoft strongly recommends some alternatives that don't require a server-side installation of Office and can perform most common tasks more efficiently and faster than Automation.
Most server-side automation tasks involve document creation or editing. Office 2007 supports the new Open XML file format, which allows developers to create, edit, read, and transform file content on the server side. This is the recommended and supported method of handling changes to Office files from the service.
How to use the Open XML SDK 2.5 for Office, please refer to the Microsoft documentation:
https://learn.microsoft.com/en-us/office/open-xml/open-xml-sdk
Considerations for server-side Automation of Office, please refer to this Microsoft blog:
https://support.microsoft.com/en-us/topic/considerations-for-server-side-automation-of-office-48bcfe93-8a89-47f1-0bce-017433ad79e2
I've had a similar problem:
I had a Python program with the xlwings library and I created a .bat file.
When I launched it by hand it worked perfectly, but with Windows 10 Scheduler I received an error "(-2147024891, 'Access denied.', None, None)".
I carried out the automatic correction of the Excel file which can be done by going to Excel > File > Info > Verify document.
My problem was that the Windows Scheduler didn't accept comments in the .xlsm file.
I deleted all the comments and then the Windows Scheduler started

Logging for Azure Function in python with SEQ

I'm working on the Azure Function (durable function) that implements an HTTP trigger. All it does is waiting for an HTTP call from the backend that shares a link to a blob storage object (image) so it can be processed by a function. I need to implement a reliable logging solution using SEQ, that's being used for other projects in our company (mostly .NET).
Using some official documentation from here all I'm receiving in the SEQ console is a stream of unstructured events and it's hard to gain where and when the processing starts, how much time did it take, etc. It makes it impossible to troubleshoot.
With .NET projects we were using Serilog that allows you to write so-called enrichers and filters, so you can structurize the logs and the information that is really needed, including the call performance (e.g. elapsed time). I don't see anything even close to that available for Python 3. Can anyone suggest where do I start? What's the best approach to capture the events I'm looking for?
Thanks.
Ok guys, here's the answer:
You need to install the lib called seqlog via requirements.txt for the purpose
In the Python script where you plan to use logger import respective namespace, i.e. import logging
Define SEQ configuration in a JSON file (something like this):
In the init.py load SEQ config:
with open('./seq.config.json', 'r') as f:
seq_config = json.load(f)
f.close()
Use logging object to stream the logs to SEQ:
logging.info("[" + obj.status + "] >> Data has been processed!")
Enjoy the logs posted to the SEQ console
p.s. if you're debugging locally, set http://localhost+port in the seq.config.json instead of the remote console address
Hope this info will help someone.

How to handle data import and export from a Windows Universal app

I am developing a Windows Universal app that collects results of races. It saves each race result in a sql-lite database in an application folder so the user can view previous results. I have further requirements, however, for saving and opening race results.
I need to be able to export the results of a race as a CSV file so that they can be opened by a third-party application that might be running on a separate machine on a different operating system.
I need to be able to export the results as an HTML file that can be uploaded/included in the user's own web site.
I need the user to be able to print the results (which I was thinking could just be done by printing the HTML file from a browser)
I would like the user to be able to choose to import the results of a race created by my own legacy application in my own format.
It seems, however, that we are restricted in a Windows Universal app to saving files to just very specific folders under very specific circumstances if we have requested that app capability. Therefore I am getting access denied errors both saving and reading files using the FileOpenPicker and FileSavePicker.
I think I probably need to view the export and import of results in a different way, but after a lot of searching I have not been able to come up with the right and recommended solution to this. So the question is how should I be handling the import and export of results? Should I be using the user's documents folder, or their OneDrive? Do I need to create a web application for my app so that the user can store results in the cloud and download them from there?
CSV and HTML are both text files with some encoding. So your question is about how to read/write files with JS.
Here is example how to create html page with FileSavePicker:
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.suggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.documentsLibrary;
savePicker.fileTypeChoices.insert("Web page", [".html"]);
savePicker.suggestedFileName = "New page";
savePicker.pickSaveFileAsync().then(function (file)
{
if (file) {
var _WriteThis="<!DOCTYPE html>" + "\r\n";
_WriteThis = _WriteThis + "<html><head><title>Web page title</title>" + "\r\n";
// .....
Windows.Storage.FileIO.writeTextAsync(file, _WriteThis, Windows.Storage.Streams.UnicodeEncoding.utf8);
}
});
This example doesn't required any special rules and you can save file anywhere on you PC HDD or USD stick without setting capabilities in manifest (except system folders)
Same way you can save in csv format

fabric -- cant run commands after user is switched

I have been recently introduced to fabric and trying to approach the following:
access remote host
su root
perform a command, for example change password for multiple users
done!
Please note that I cant use sudo, nor connect directly to the remote host using root. The commands I need to perform can only be performed if I explicitly change user to root.
I was able to approach the main concept of getting to the remote host and play with some commands, using fabric, but the problem im having is that once I switch to root "su root" I cant perform the rest of the commands unless I exit.
example of what im trying to approach:
def mytask():
with settings(user="root"):
run('whoami')
run('echo "TEST using root user"')
run('echo "ITS WORKING!!!"')
or something like this
def mytask():
run ('su root')
run ('passwd testUser')
In both cases once I enter the root password nothing would get executed, I would get the remote command line back, unless I exit back to the original user. I have seen few suggestions about using "fexpect" for prompts but not sure if that would make a difference.
I'm developing on a Linux environment.
You have to use fexpect and fexpect run command
from ilogue import fexpect
prompt = ['Password', 'mypassword'] # ('prompt', 'answer') Case sensitive
def test():
with fexpect.expecting(prompt):
fexpect.local("su -")

Actionscript 3.0 Disable navigateToURL

A web game I play on that allows user uploaded content has been having a lot of issues with people using the navigateToURL function to send players to random websites. I was curious if there was a way to disable this function using Actionscript 2 or 3. I have seen a way to do it using the HTML embed but I do not have administrative access to the website.
After doing some more research, I have come up with a solid answer:
You should use a combination of PHP and an executable called swfdump on the server side to validate the user uploaded content.
swfdump is an exe file located in the bin folder of the Flex SDK. You can run it from PHP using exec.
It will read the bytecode of the swf and produce a report. From that you can easily locate which files contain navigateToURL() and reject the files.
I tested a file of my own using swfdump -abc -out myfilereport.swfx myfile.swf
and in that output I found this:
findpropstrict flash.net:navigateToURL
findpropstrict flash.net:URLRequest
pushstring "http://www.plasticsturgeon.com"
constructprop flash.net:URLRequest (1)
callproperty flash.net:navigateToURL (1)
The url I was using was "http://www.plasticsturgeon.com". But it would be far easuer to just eliminate any swf that includes flash.net.navigateToURL. Once you identify tha is present you can generate an error notice to your end user.
So using this method you can find and reject any swf that is using navigate to URL. You could even create a batch to run and invalidate any existing assert with this problem.
More information about using bytecode:
http://code.google.com/p/redtamarin/wiki/ABC
And about decompiling ASbytecode:
http://dougmccune.com/flex/FOTB_Decompiling_Doug_McCune.pdf

Resources