Reddit has become one of my favorite sources of cybersecurity articles. Several subreddits have excellent write-ups and posts for those interested in security, no matter what skill level.
I thought it would be nice to automatically receive a list of new posts from my favorite subreddits, so, I spun up a python script retrieve a list of new posts and a python script to email the list to myself. The full scripts are below.
First, I needed to read about using the Reddit API. I’ve worked with a few APIs before and the first step is almost always authenticating, often with a client secret and id.
With a quick google search, I found a great article which describes how to register your application with reddit, obtain a client secret and id, and even how to use the PRAW python library to read posts.
I created a praw.ini file in same directory as my script and saved the fields client_id, client_secret, and useragent(PyScrape Bot 0.1).
Then, I wrote the script to pull any posts created on the previous day, and store the title and url of each post in a string “body”.
I appended to a string instead of just writing to a file because I was originally going to return the “body” string to a powershell script, which would use my logged-in windows credentials and outlook to send the email.
But I decided to use gmail instead.
My gmail application was taken almost directly from the google api docs for python. They provide very good documentation for authenticating and for sending emails.
To create your own email application, start by following the instructions on the API Quickstart page. The first thing the application must do is authenticate.
The Quickstart guide does a good job of describing what is going on in this method. Essentially, the method checks for previously stored credentials, and if they are not found or not valid, tries to reauthenticate.
It appears that the client will need to reathenticate if the scope is changed(read, send, etc.). This is done with the oauth2client tools sub module and the run_flow function.
run_flow will attempt to open an authorization server page in the user’s web borwser. If the user is not already signed in, they will need to do so.
Once signed in the page will ask the user to allow permissions to the application. These should match the permissions associated with the scope. A list of different scopes and their permissions can be found here.
The credentials will be stored so you will not need to be signed in to your google account or allow permissions next time.
Once the application properly authenticates, the main method makes two function calls to generate a “service”.
We then create a message in the MIME format and send.
When I get time, I will update this post with more details about what is happening after the application obtains credentials. For now the links I have provided should explain most of it.