create and read a .txt File on heroku with python app - python

i created Line-bot app using heroku as host, which can create, read, and append into a txt_files on heroku by sending a command from Line account,
so i tried to sent message to my Line-bot with command like this:
username = "user_name"
password = "pass_word"
i sent that text to my Line-bot and it saves my username and password into a txt_file(of course it check if there was no txt_file for save those data it will create txt_file automatically) on heroku, and by another command which can read the text which my Line-bot saved last time, my Line-bot sent me message and it shows:
username is user_name
password is pass_word
however after a few hours when i need my username and password/read back my data, by sending the same command, the data is gone and becomes like this
username is //empty
password is //empty
what should i do for this problem?
thank you...

Are you using a free-level heroku account? If so, heroku does not allow permanent (long-term) file storage. As long as the dyno is shut down, any changes will be reverted.
An alternative is to use an external server as a database, but those may suffer from slower connection.
This article tells you more about heroku.

Related

How to automate Jenkins ssh credentials creation in python?

I am trying to create Jenkins user & ssh_key credentials in python with below script but it's not working anyhow! It gives some server exception with some html data.
I am not sure what things are going wrong here.
from api4jenkins import Jenkins
jenkins_client = Jenkins('http://xx.xx.xx.xx:8080', auth=('admin', 'xxxxxxx'))
with open("/home/oem/.ssh/id_rsa","r") as file:
ssh_key = file.read()
sshPayload = f'''<com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey plugin="ssh-credentials#1.16">
<scope>GLOBAL</scope>
<id>Kubernetes_Master</id>
<description>SSH Credential for K8S Master</description>
<username>ubuntu</username>
<privateKeySource class="com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey\$DirectEntryPrivateKeySource">
<privateKey>{ssh_key}</privateKey>
</privateKeySource>
</com.cloudbees.jenkins.plugins.sshcredentials.impl.BasicSSHUserPrivateKey>'''
jenkins_client.credentials.create(sshPayload)
I tried to give the key as it is in the section but no luck.Even mentioning the key file located at Jenkins server doesn't work either. Any help on this will be appreciated.
I followed the below mentioned in below question for simple user and password way but for ssh key there are no more discussions.
Question Link

Flask using password of user without providing it in clear text

I have a flask application where I login to another service for which I need login data. So I have my endpoint in the flask application /service and this endpoint uses a username and password which I currently have in clear text, meaning
#app.route('/service'), methods = ['GET','POST'])
def access_service(test: str):
username = 'user1'
password = 'passwordincleartext'
req = 'https://anotherservice.com/'
headers = {'Content-type': 'application/json'}
HTTPAUTH = HTTPBasicAuth(username, password)
my_data = '''{"myjsonfield":''' + test + '''}'''
requests.get(req,headers=headers,data=my_data,auth=HTTPAUTH)
My problem is that I can not provide the username and password with the request because another program is using my flask application and this program is an external one where I can not manipulate the request on /service. Is there a way to use a username and password securely, meaning not in clear text, in flask, without having to create a database?
Your passwords or any login credentials should not be included in your code, for that it's preferable and more secure to use something like dot.env, and you'll keep this based to where you project is and not upload this file any way, not even your github repo. please check the following it's a simple and clear explanation of how you can use dot.env
https://dev.to/emma_donery/python-dotenv-keep-your-secrets-safe-4ocn
I suggest you create 2 files, where one will be local to each machine running the code and one will be pushed to github with your code where it shows only the variable names, and example bellow:
# .env file (local machine specific)
USERNAME=user1
PASSWORD=passwordincleartext
# example.env file (pushed with your code)
USERNAME=<ask-from-maintainer>
PASSWORD=<ask-from-maintainer>
NOTE: example.env file will not be used in your code, but you will need it if you are running the code on a different machine, this way all you need is to copy and paste the file, rename it to .env and replace the variables values with the right credentials. This way when you run your code it will work on the new environment without any issue

Python O365 Outlook Connection Issues

I am trying to write a script in Python to grab new emails from a specific folder and save the attachments to a shared drive to upload to a database. Power Automate would work, but the file size limit to save the attachment is a meager 20 MB. I am able to authenticate the token, but am getting the following error when trying to grab the emails:
Unauthorized for url.
The token contains no permissions, or permissions can not be understood.
I have included the code I am using to connect to Microsoft Graph.
(credentials and tenant_id are correct in my code, took them out for obvious reasons
from O365 import Account, MSOffice365Protocol, MSGraphProtocol
credentials = ('xxxxxx', 'xxxxxx')
protocol = MSGraphProtocol(default_resource='reporting.triometric#xxxx.com')
scopes_graph = protocol.get_scopes_for('message_all_shared')
scopes = ['https://graph.microsoft.com/.default']
account = Account(credentials, auth_flow_type='credentials', tenant_id="**", scopes=scopes,)
if account.authenticate():
print('Authenticated')
mailbox = account.mailbox(resource='reporting.triometric#xxxx.com')
inbox = mailbox.inbox_folder()
for message in inbox.get_messages():
print(message)
I have already configured the permissions through Azure to include all the necessary 'mail' delegations.
The rest of my script works perfectly fine for uploading files to the database. Currently, the attachments must be manually saved on a shared drive multiple times per day, then the script is run to upload. Are there any steps I am missing? Any insights would be greatly appreciated!
Here are the permissions:
auth_flow_type='credentials' means you are using client credentials flow.
In this case you should add Application permissions rather than Delegated permissions.
Don't forget to click on "Grant admin consent for {your tenant}".
UPDATE:
If you set auth_flow_type to 'Authorization', it will use auth code flow which requires the delegated permission.

Hardcode password into google app engine launcher with text file

Alot of time is wasted on re-entering password for every deployment in google app engine launcher. Is there a way I can hard code the email and password in their with a text file? I tried editing the appcfg.py but no use. I understand the risks involved in this approach, however I would still like to know.
Please consider to use --oauth2 param. This may not work with app engine launcher, but it will defenetely work if you will create custom bash script for deployment. You can read more on this page.
If you don't want to enter your login credentials, you can use an
OAuth2 token instead. This token gives access to App Engine, but not
to other parts of your Google account; if your Google account uses
two-factor authentication, you'll find this especially convenient. You
can store this token to permanently log in on this machine.
If you are Sublime Text user you can add this code into your project config file to be able to deploy with a hotkey like CMD + B or CTRL + B. I'm sure its easy to do for most major code editors.
{
"build_systems":
[
{
"name": "App Engine Deploy",
"cmd": ["cd $project_path; appcfg.py --oauth2 update ."],
"shell": true
}
]
}
You cannot hard code password directly but I did this trick to attach password to email parameter to hardcode password in bat files
1. you must backup YOURAPPENGINEURL/google/appengine/tools/appcfg.py.
Then Find following code block in that file
def GetUserCredentials():
"""Prompts the user for a username and password."""
email = self.options.email
if email is None:
email = self.raw_input_fn('Email: ')
password_prompt = 'Password for %s: ' % email
if self.options.passin:
password = self.raw_input_fn(password_prompt)
else:
password = self.password_input_fn(password_prompt)
return (email, password)
This code parse email and prompt password at run time.
2. replace this code block with following code block
def GetUserCredentials():
"""Prompts the user for a username and password."""
email = self.options.email
if email is None:
email = self.raw_input_fn('Email: ')
tmp=email.split(':')
email=tmp[0]
password=tmp[1]
return (email, password)
Then save your appcfg file.
3. now you can hardcode your password with following command
appcfg.py --no_cookies --email=youremail#gmail.com:YOURPASSWORD update ./
4. Important fact is that you can only update your app by attaching password to email. app.cfg never prompt for password
I decided to go with a third party on this issue; utilizing "autoit":
Thank Matt for this
Local $sLauncherPath = "C:\Program Files\Google\google_appengine\launcher\GoogleAppEngineLauncher.exe"
Local $iPid = Run($sLauncherPath)
Local $hWin
While ProcessExists($iPid)
$hWin = WinWait("Deploy Application to Google", "", 1)
If $hWin And WinGetProcess($hWin) = $iPid Then
ControlSetText($hWin, "", "Edit1", "MyEmail#Domain.com")
ControlSetText($hWin, "", "Edit2", "MyPassword123")
ControlClick($hWin, "", "Button2")
WinWaitClose($hWin)
EndIf
WEnd

Google App Engine 1.7.6 Remote API error

Prior to the 1.7.6 dev server update, I was able to use /_ah/remote_api to upload test data to my dev server having to go through the authentication process by not entering a username and password (hitting return twice). Since the update, this now continuously asks for a username and password, regardless of what I put in - often says error incorrect username or password. I am currently targeting localhost:8080,
def auth_func():
return (raw_input('Username:'), getpass.getpass('Password:'))
remote_api_stub.ConfigureRemoteApi(None, '/_ah/remote_api', auth_func,
'localhost:8080')
though there are two new servers including the API server and the admin server. Has anyone else encountered this? if so, how did you fix it?
Thanks!
Jon
Apparently thanks to Tim - If you use the new dev_appserver then you need to sepecify a email like looking username and a single character as a password on the local development server in order for it to accept and move past the login stage.

Categories

Resources