Python yagmail authentication configuration - python-3.x

I'm trying to setup yagmail with an external .yagmail file with credentials but when I run the code it returns
YagInvalidEmailAddress: Emailaddress "yagmail.register('my.username#gmail.com', 'my.password')" is not valid according to RFC 2822 standards
the .yagmail file is like this
yagmail.register('my.username#gmail.com', 'my.password')
Any suggestion?

You should run the following once in python, which will store the registration in the backend (yagmail.register is just a wrapper around keyring lib functionality):
import yagmail
yagmail.register(email, pwd)
After this, you can just use the following in your script to start using yagmail:
yag = yagmail.SMTP(email)
yag.send()
If you want to omit the email as well, you can write your gmail address in the .yagmail file, which should reside in you $HOME directory.
Then, you could just use:
yag = yagmail.SMTP()
yag.send()
On some systems (CentOS for me), you also need to pip install keyrings.alt and import keyrings in your registration script.

Related

from an external python script call a python function which require root previlege(pynq library) is continuously crashed

I have to get continuous data from a python function and one of its libraries(Overlay) depends on root privilege. I have to run that python function by using Flask.
First of all, I have searched how to give root access to a python script but unfortunately, I haven't found any which mimic my case.
The approach I have taken --
1/ Python file containing Overlay library suppose the name is child.py which contains a function name status_data
from pynq import PL
from pynq import Overlay
def main_path():
ol = Overlay("/home/xilinx/pynq/overlays/design_4/design_1_wrapper.bit")
return ol
def status_data():
ol = main_path()
data = '''my_code'''
return data
2/ Flask file name is app.py where I need the continuous data via an endpoint
from create_json_data import status_data
from flask import Flask, render_template
from flask import jsonify
'''mayn others lib, doesn't include'''
'''my_code'''
#app.route("/auto_update_table")
def parse_auto_update_table(name=None):
data_json = status_data()
return jsonify(data_json)
3/ Both files are in the same folder. I have run that child.py with sudo python3 child.py and it works. Executed the Flask code by sudo python3 app.py. My guess was as app.py runs with sudo so it will take all other dependents with root privilege. But I am failed. It executes but after some moments it crashes.
Is there any workaround to call child.py file's status_data function with root privilege from app.py without crash? Security isn't an issue so I can reveal my credentials to any script file and if also require I can give password manually but only once as it is a continuous process so over and over password typing is not a tangible solution.
As I know when you give admin permission (root) to an executable (your python script).
Whatever the executable does is with admin privileges. Try with calling it with the root account itself or sudo -u root --login "python3 app.py" to see if it works or not
Also saying it doesn't work is not helping. If you have a trace back. Add it to help us answer you or any more information that helps. I can't help you like this
EDITED AFTER user10634362 COMMENT BELOW
I have found a solution. First of all, I am changing the question title as after getting the solution I have understood the present title is not fit with the situation. Though giving root privilege is quite easy. sudo python3 app.py does the work. The major flaw was in
from pynq import Overlay
and
def main_path():
ol = Overlay("/home/xilinx/pynq/overlays/design_4/design_1_wrapper.bit")
return ol
I have called this main_path function repeatedly but it needs a handsome amount of delay and it was absent there. So I got an unwanted crash. After declaring
ol = Overlay("/home/xilinx/pynq/overlays/design_4/design_1_wrapper.bit")
I have passed ol as a global variable to status_data function and it solves the issue.

cookie cutter: what's the easiest way to specify variables for the prompts

Is there anything that offers replay-type functionality, by pointing at a predefined prompt-answer file?
What works and what I'd like to achieve.
Let's take an example, using a cookiecutter to prep a Python package for pypi
cookiecutter https://github.com/audreyr/cookiecutter-pypackage.git
You've downloaded /Users/jluc/.cookiecutters/cookiecutter-pypackage before. Is it okay to delete and re-download it? [yes]:
full_name [Audrey Roy Greenfeld]: Spartacus 👈 constant for me/my organization
email [audreyr#example.com]: spartacus#example.com 👈 constant for me/my organization
...
project_name [Python Boilerplate]: GladiatorRevolt 👈 this will vary.
project_slug [q]: gladiator-revolt 👈 this too
...
OK, done.
Now, I can easily redo this, for this project, via:
cookiecutter https://github.com/audreyr/cookiecutter-pypackage.git --replay
This is great!
What I want:
Say I create another project, UnleashHell.
I want to prep a file somehow that has my developer-info and project level info for Unleash. And I want to be able to run it multiple times against this template, without having to deal with prompts. This particular pypi template gets regular updates, for example python 2.7 support has been dropped.
The problem:
A --replay will just inject the last run for this cookiecutter template. If it was run against a different pypi project, too bad.
I'm good with my developer-level info, but I need to vary all the project level info.
I tried copying the replay file via:
cp ~/.cookiecutter_replay/cookiecutter-pypackage.json unleash.json
Edit unleash.json to reflect necessary changes.
Then specify it via --config-file flag
cookiecutter https://github.com/audreyr/cookiecutter-pypackage.git --config-file unleash.json
I get an ugly error, it wants YAML, apparently.
cookiecutter.exceptions.InvalidConfiguration: Unable to parse YAML file .../000.packaging/unleash.json. Error: None of the known patterns match for {
"cookiecutter": {
"full_name": "Spartacus",
No problem, json2yaml to the rescue.
That doesn't work either.
cookiecutter.exceptions.InvalidConfiguration: Unable to parse YAML file ./cookie.yaml. Error: Unable to determine type for "
full_name: "Spartacus"
I also tried a < stdin redirect:
cookiecutter.prompts.txt:
yes
Spartacus
...
It doesn't seem to use it and just aborts.
cookiecutter https://github.com/audreyr/cookiecutter-pypackage.git < ./cookiecutter.prompts.txt
You've downloaded ~/.cookiecutters/cookiecutter-pypackage before. Is it okay to delete and re-download it? [yes]
: full_name [Audrey Roy Greenfeld]
: email [audreyr#example.com]
: Aborted
I suspect I am missing something obvious, not sure what. To start with, what is the intent and format expected for the --config file?
Debrief - how I got it working from accepted answer.
Took accepted answer, but adjusted it for ~/.cookiecutterrc usage. It works but the format is not super clear. Especially not on the rc which has to be yaml, though that's not always/often the case with rc files.
This ended up working:
file ~/.cookiecutterrc:
without nesting under default_context... tons of unhelpful yaml parse errors (on a valid yaml doc).
default_context:
#... cut out for privacy
add_pyup_badge: y
command_line_interface: "Click"
create_author_file: "y"
open_source_license: "MIT license"
# the names to use here are:
# full_name:
# email:
# github_username:
# project_name:
# project_slug:
# project_short_description:
# pypi_username:
# version:
# use_pytest:
# use_pypi_deployment_with_travis:
# add_pyup_badge:
# command_line_interface:
# create_author_file:
# open_source_license:
I still could not get a combination of ~/.cookiecutterrc and a project-specific config.yaml to work. Too bad that expected configuration format is so lightly documented.
So I will use the .rc but enter the project name, slug and description each time. Oh well, good enough for now.
You are near.
Try this cookiecutter https://github.com/audreyr/cookiecutter-pypackage.git --no-input --config-file config.yaml
The --no-input parameter will suppress the terminal user input, it is optional of course.
The config.yaml file could look like this:
default_context:
full_name: "Audrey Roy"
email: "audreyr#example.com"
github_username: "audreyr"
cookiecutters_dir: "/home/audreyr/my-custom-cookiecutters-dir/"
replay_dir: "/home/audreyr/my-custom-replay-dir/"
abbreviations:
pp: https://github.com/audreyr/cookiecutter-pypackage.git
gh: https://github.com/{0}.git
bb: https://bitbucket.org/{0}
Reference to this example file: https://cookiecutter.readthedocs.io/en/1.7.0/advanced/user_config.html
You probably just need the default_context block since that is where the user input goes.

How can I allow a Python code to open "%temp%" folder for any user?

I have some users on my PC and I try to create a Python code to open %temp% folder, but the problem is that it works under my account only. When I use the same code on a different account it does not work on the same PC.
My folder path >> C:\Users\MyAccount\AppData\Local\Temp <<,
the problem error with this user 'MyAccount'
This is my code:
import webbrowser
webbrowser.open('C:\Users\MyAccount\AppData\Local\Temp')
I need to pass the correct userFolder to my code to work with.
Example:
my account the path >> **C:\Users\MyAccount\AppData\Local\Temp**
on different account >> C:\Users\ **?** \AppData\Local\Temp
**?** = it should be the name of the user.
Could you please advise me?
If pathlib is an option (comes with Python 3.4+) you can use
from pathlib import Path
Path.home() / 'AppData' / 'Local' / 'Temp'
if not, try
from os import path
path.expanduser('~/AppData/Local/Temp')

How to get WKHTMLTOPDF working on Heroku?

I created a website which generates PDF using PDFKIT and I know how to install and setup environment variable path on Window. I managed to deploy my first website on Heroku but now I'm getting error "No wkhtmltopdf executable found: "b''" When trying to generate the PDF.
I have no idea, How to install and setup WKHTMLTOPDF on Heroku because this is first time I'm dealing with Linux.
I really tried everything before asking this but even following this not working for me.
Python 3 flask install wkhtmltopdf on heroku
If possible, please guide me with step by step on how to install and setup this.
I followed all the resource and everything but couldn't make it work. Every time I get the same error.
I'm using Django version 2. Python version 3.7.
This is what I get if I do heroku stack
Available Stacks
cedar-14
container
heroku-16
* heroku-18
Error, I'm getting when generating the PDF.
No wkhtmltopdf executable found: "b''"
If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf
My website works very well on localhost without any problem and as far as I know, I'm sure that I have done something wrong in installing wkhtmltopdf.
Thank you
It's non-trivial. If you want to avoid all of the below's headache, you can just use my service, api2pdf: https://github.com/api2pdf/api2pdf.python. Otherwise, if you want to try and work through it, see below.
1) Add this to your requirements.txt to install a special wkhtmltopdf pack for heroku as well as pdfkit.
git+git://github.com/johnfraney/wkhtmltopdf-pack.git
pdfkit==0.6.1
2) I created a pdf_manager.py in my flask app. In pdf_manager.py I have a method:
def _get_pdfkit_config():
"""wkhtmltopdf lives and functions differently depending on Windows or Linux. We
need to support both since we develop on windows but deploy on Heroku.
Returns:
A pdfkit configuration
"""
if platform.system() == 'Windows':
return pdfkit.configuration(wkhtmltopdf=os.environ.get('WKHTMLTOPDF_BINARY', 'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'))
else:
WKHTMLTOPDF_CMD = subprocess.Popen(['which', os.environ.get('WKHTMLTOPDF_BINARY', 'wkhtmltopdf')], stdout=subprocess.PIPE).communicate()[0].strip()
return pdfkit.configuration(wkhtmltopdf=WKHTMLTOPDF_CMD)
The reason I have the platform statement in there is that I develop on a windows machine and I have the local wkhtmltopdf binary on my PC. But when I deploy to Heroku, it runs in their linux containers so I need to detect first which platform we're on before running the binary.
3) Then I created two more methods - one to convert a url to pdf and another to convert raw html to pdf.
def make_pdf_from_url(url, options=None):
"""Produces a pdf from a website's url.
Args:
url (str): A valid url
options (dict, optional): for specifying pdf parameters like landscape
mode and margins
Returns:
pdf of the website
"""
return pdfkit.from_url(url, False, configuration=_get_pdfkit_config(), options=options)
def make_pdf_from_raw_html(html, options=None):
"""Produces a pdf from raw html.
Args:
html (str): Valid html
options (dict, optional): for specifying pdf parameters like landscape
mode and margins
Returns:
pdf of the supplied html
"""
return pdfkit.from_string(html, False, configuration=_get_pdfkit_config(), options=options)
I use these methods to convert to PDF.
Just follow these steps to Deploy Django app(pdfkit) on Heroku:
Step 1:: Add following packages in requirements.txt file
wkhtmltopdf-pack==0.12.3.0
pdfkit==0.6.0
Step 2: Add below lines in the views.py to add path of binary file
import os, sys, subprocess, platform
if platform.system() == "Windows":
pdfkit_config = pdfkit.configuration(wkhtmltopdf=os.environ.get('WKHTMLTOPDF_BINARY', 'C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe'))
else:
os.environ['PATH'] += os.pathsep + os.path.dirname(sys.executable)
WKHTMLTOPDF_CMD = subprocess.Popen(['which', os.environ.get('WKHTMLTOPDF_BINARY', 'wkhtmltopdf')],
stdout=subprocess.PIPE).communicate()[0].strip()
pdfkit_config = pdfkit.configuration(wkhtmltopdf=WKHTMLTOPDF_CMD)
Step 3: And then pass pdfkit_config as argument as below
pdf = pdfkit.from_string(html,False,options, configuration=pdfkit_config)

openssh - Reading from a file

In the openssh code (openssh-5.9p1/auth2.c) in the function
input_userauth_request(int type, u_int32_t seq, void *ctxt)
I'm trying to read my own file (tried using fopen, fread) but fopen fails with an error saying No such file or directory. The file exists with full permissions. Thanks.
This function is called during in pre-authentication child (before authentication), which is chrooted in /var/empty/sshd/ (Fedora/RHEL). This is the reason why it can not find your file.
If you want it to find that file, you might disable UsePrivilegeSeparation option in sshd_config NOT RECOMMENDED IN PRODUCTION!!!. Read a bit more about privilege separation in openssh.

Resources