Hide credential in Python script - python-3.x

What is the best method to hide credential in a Python script?
I would like to avoid storing it in clear text.
import paramiko
# how to avoid clear text ?
my_server='myserver'
my_password='mysecret'
ssh = paramiko.client.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(my_server, username='root', password=my_password)
except paramiko.SSHException:
print("Connection Failed")
quit()
If I create an myscript.exe with pyInstaller, is it possible to retrieve the clear text (my_server and my_password) "disassembling" the .exe?
Thanks

It doesn't matter if it's stored in clear text or not, if the script needs the password, everyone who has the script also has the password.
Store the credentials in a separate file (yaml comes to mind) and load that at runtime. Don't add the credentials file to the repository if every user uses their own credentials.

Related

Beginner Python Project - My function is skipping, what is causing this?

as the title says I'm a beginner with Python. I have started to work on what I thought first was a simple enough script for scanning a folder and printing the names of each subdirectory to a CMD prompt.
However, I've run into an issue where the function in the code below does not execute. I suspect it's to do with Windows permissions which is why I've added in the is_admin(): function.
My question is, what is it that is causing the function to skip? and what is the proper way to achieve what it is I am trying to do?
Any and all help is appreciated and if anyone could point me in the direction for learning more about Python and the Windows OS technical side for programmers would be doing me a huge favor.
Thanks in advance :)
import os, sys, ctypes
def is_admin():
try:
return ctypes.windll.shell32.IsUserAnAdmin()
except:
return False
if is_admin():
rootdir = 'C:/Windows'
def listdirs(rootdir):
for file in os.listdir(rootdir):
d = os.path.join(rootdir, file)
if os.path.isdir(d):
print(d)
listdirs(d)
listdirs(rootdir)
else:
ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, " ".join(sys.argv\[1:\]), None, 1)
input('Press any key to continue...')
Expecting the program to:
Produce an output of all the subdirectories of a folder printed to a CMD prompt window and have the window stay open when the program has finished executing each line of code. The Window should remain open until the user is finished with it. The Windows UAC should prompt asking the user if they wish to run as admin, if the user is already an admin then it should skip this and proceed to run the program.

Integrating python-decouple with PRAW?

I've been trying to see if I can use python-decouple to place my bot credentials on a separate .env file.
Auth method is basically right off the praw doc:
reddit = praw.Reddit(
client_id=config('CLIENT_ID'),
client_secret=config('CLIENT_SECRET'),
password=config('PASSWORD'),
user_agent=config('USER_AGENT'),
username=config('USERNAME')
)
However, whenever I try it, it seems to return an 403 auth error. I work my way back, replacing the decouple configs with strings of the actual details, but it doesn't seem to follow through, and the errors that occur seem random depending on what and when things I take out.
Is this a problem with how decouple functions?
Thanks.
I've been trying to see if I can use python-decouple to place my bot credentials on a separate .env file.
Why not use a praw.ini file? This is documented here in PRAW documentation. It's a format for storing Reddit credentials in a separate file from your code. For example, a praw.ini file may look like:
[bot1]
client_id=Y4PJOclpDQy3xZ
client_secret=UkGLTe6oqsMk5nHCJTHLrwgvHpr
password=pni9ubeht4wd50gk
username=fakebot1
[bot2]
client_id=6abrJJdcIqbclb
client_secret=Kcn6Bj8CClyu4FjVO77MYlTynfj
password=mi1ky2qzpiq8s59j
username=fakebot2
You then use specific credentials in your code like so:
import praw
reddit = praw.Reddit('bot2', user_agent='myBot v0.1')
print('Logged in as', reddit.user.me())
I think this is the best solution for working with PRAW credentials.
However, if you really want to do it with python-decouple, here's a working example:
Contents of file .env:
username=k8IA
password=REDACTED
client_id=REDACTED
client_secret=REDACTED
Contents of file connect.py:
import praw
from decouple import config
reddit = praw.Reddit(username=config('username'),
password=config('password'),
client_id=config('client_id'),
client_secret=config('client_secret'),
user_agent='myBot v0.1')
print('Logged in as', reddit.user.me())
Output when running python3 connect.py:
Logged in as k8IA

Windows Registry access for Python script

I'm working on a Python 3.7 script that eventually will be a CLI program like reg.exe is. I'm aiming to include the ability to add, delete and query keys and subkeys. At this point, I can create a new Key and iterate through all keys within the specific path however; once I try to write a value to the new key I made, I get a WinError 5 - Access denied.
Is there a way I can include in the script a way to have access to write to the registry?
I'm still a beginner with Python and programming, I've had a look at documents but I cant figure this one out.
Any help will be greatly appreciated. My code soo far:
import winreg
reg_connection = winreg.ConnectRegistry(None, winreg.HKEY_CURRENT_USER)
reg_key = winreg.OpenKey(reg_connection, r"SOFTWARE\Microsoft\\")
winreg.CreateKey(reg_key, "New Key")
for key in range(3000):
try:
show_sub_keys = winreg.EnumKey(reg_key, key)
print(show_sub_keys)
except WindosError:
break
new_key_value = winreg.OpenKey(reg_connection, r"SOFTWARE\Microsoft\New Key")
winreg.SetValueEx(new_key_value, "New Value",0,winreg.REG_SZ, "This Value")
winreg.CloseKey(new_key_value)
new_key_value = winreg.OpenKey(reg_connection, r"SOFTWARE\Microsoft\New Key")
Here you do not specify an argument for the optional access parameter, so the call passes the default value of KEY_READ. Hence you can only read from the key, but not write.
You should pass an argument for the access parameter, that specifies the permissions you need:
new_key_value = winreg.OpenKey(reg_connection, r"SOFTWARE\Microsoft\New Key", 0,
winreg.KEY_SET_VALUE)
For further details, see the winreg reference.

Importing a variable, which is user inputted, from another file

I am looking for help.
For the purpose of the question, i have created a small test program. I am trying to find a way to import an input that is saved in a variable from one Python file, into another file. I am able to pass a standard variable, but not one that has been inputted by a user.
When i try to do this it runs the file from the start again, which is not what i want See below
I want to Run test.py first
test.py
password = input ("Please enter your password")
import test2
test2.py
from test import password
print (password)
output below
Please enter your password:Fred
Please enter your password Fred
Fred
What i am trying to do is to pass an input without it running the file again. I hope this makes sense.
I basically want the second file to display the input

Executing python against a script stored in database

db: mysql
lang: python
framework:
django
Operating System: Linux (ubuntu)
Hello,
Is there a way to execute a python against a content of a script that is stored in a database? For example, a content of a file is stored in a db column text. Would the only solution be to create a temporary file, dump the content from the db into the file and then run python os command against it? I'm assuming the content of the executed script will need to be stored such that it escapes quotes etc.
I'm open to suggestions on what database to use to accomplish my goal. MySQL will require additional wrappers before storage of the file content and possibly apply others to reply qoutes/datetime/etc.
Please advise if additional information necessary, but in essence i'm looking to store python script content in a db, retrieve it and run it against the python interpreter.
Thank you in advance for any advise.
You can use the compile built in function.
s = """def f(x):
return x + x
print(f(22))
"""
code = compile(s, "string", "exec")
exec(code)
# OUT: 44
Although I'm wondering if you couldn't just store a data structure and use that with some pre-defined code. Executing arbitrary code in this way could be dangerous, and a security risk.
This seems very similar to SO post here:
Dynamically loading Python application code from database under Google App Engine
Here is information on exec
http://docs.python.org/release/2.5.2/ref/exec.html
Python Wiki page for Python+MySQL
http://wiki.python.org/moin/MySQL

Resources