I wanted to ask how I can concatenate a string and a variable in a .conf file.
Example:
In the settings.conf file:
# The credential is in another, separate passphrase.conf file, declared as 'password'
credential = passphrase/${password}
url = "XYZ.${credential}XYZ.com"
If i do it as shown in my example, I get an error that I have the wrong password, so somehow it is not concatenating correctly.
Check this
import configparser
config = configparser.ConfigParser()
config.read('passphrase.conf')
pass=config['__REPLACE WITH CONFIG SECTION__']['password']
url = "XYZ"+pass+"XYZ.com"
Here is simple way how to concat string and variable.
password_var = 123456
new_string = f"This is my password: {password_var}"
Output:
This is my password: 1234
Related
I want to save a variable (user input fo mail) in pc. Because I don't want it to ask to login again and again. So please help me with how to store email variable in pc and also how to access it. Thank you.
I'm not sure what you want exactly.
If you just wanna save a text(I mean, string) in variable, then write it to a file like this.
f = open("some_file_to_save.txt", 'w')
f.write(your_variable)
f.close()
Or if you want data to be loaded as python variable again, then you can utilize pickle
May be you need config to your program?
So for this use the configparser
import configparser
You need 2 functions, first to Save:
def save_config(email):
config = configparser.ConfigParser()
config['DEFAULT'] = {
'Email': email
}
with open('config.ini', 'w') as configfile:
config.write(configfile)
And second to read saved data:
def read_config():
config = configparser.ConfigParser()
config.read('config.ini')
return config['DEFAULT']['Email']
Then add it to your code or use this example:
try:
email = read_config()
except:
print("Config doest contain email, type it:")
email = input()
print(f"My email is {email}")
save_config(email)
I have an API scan of a large URL file, read that URL and get the result in JSON
I get the kind of url and domain like
google.com
http://c.wer.cn/311/369_0.jpg
How to change file format name using url name ".format (url_scan, dates)"
If I use manual name and it successfully creates a file, but I want to use it to read all URL names from the URL text file used for file name
The domain name is used for json file name and created successfully without errors
dates = yesterday.strftime('%y%m%d')
savefile = Directory + "HTTP_{}_{}.json".format(url_scan,dates)
out = subprocess.check_output("python3 {}/pa.py -K {} "
"--sam '{}' > {}"
.format(SCRIPT_DIRECTORY, API_KEY_URL, json.dumps(payload),savefile ), shell=True).decode('UTF-8')
result_json = json.loads(out)
with open(RES_DIRECTORY + 'HTTP-aut-20{}.csv'.format(dates), 'a') as f:
import csv
writer = csv.writer(f)
for hits in result_json['hits']:
writer.writerow([url_scan, hits['_date'])
print('{},{},{}'.format(url_scan, hits['_date']))
Only the error displayed when the http url name is used to write the json file name
So the directory is not a problem
Every / shown is interpreted by the system as a directory
[Errno 2] No such file or directory: '/Users/tes/HTTP_http://c.wer.cn/311/369_0.jpg_190709.json'
Most, if not all, operating systems disallow the characters : and / from being used in filenames as they have special meaning in URL strings. So that's why it's giving you an error.
You could replace those characters like this, for example:
filename = 'http://c.wer.cn/311/369_0.jpg.json google.com.json'
filename = filename.replace(':', '-').replace('/', '_')
I ma using csv file to fetch some data for automatic login. In my first file, lets call it core.py, i am defining it as function.Here is my code :
import csv
def csvTodict():
dir = os.path.dirname(__file__)
filename = os.path.join(dir, './testdata/InputData.csv')
with open(filename) as f:
logins = dict(filter(None, csv.reader(f)))
return logins
and in another file, i am calling the values for username and password : Its my modules.py
from core import *
fnsignin()
def fnsignin():
try:
myDict=csvTodict()
fnLogin(myDict["Username"],myDict["Password"]
But when i run, I am getting error " not all arguments converted during string formatting". I am not sure where I am doing wrong. Please help
I am use python fabric with all configuration in one .fab file.
How can I put sensitive data as password to separate file and then import/load to fab main file?
Define a simple function within your fabfile.py to read your passwords out of a separate file. Something along the lines of:
def new_getpass(username):
with open("/etc/passwd", "r") as f:
for entry in [l.split(":") for l in f.readlines()]:
if entry[0] == username:
return entry
return None
This will return None in the event that the username cannot be found and the entire user's record as a list in the event the user is found.
Obviously my example is getting its data from /etc/passwd but you can easily adapt this basic functionality to your own file:
credentials.dat
database1|abcd1234
database2|zyxw0987
And then the above code modified to use this file like this, with the slight variation to return only the password (since we know the database name):
def getpass(database):
with open("credentials.dat", "r") as f:
for entry in [l.split("|") for l in f.readlines()]:
if entry[0] == username:
return entry[1]
return None
While not as simple as an import, it provides you flexibility to be able to use plaintext files to store your credentials in.
Guest = {}
with open('LogIn.txt') as f:
credentials = [x.strip().split(':') for x in f.readlines()]
for username,password in credentials:
Guest[username] = password
def DelUser():
DB = open('LogIn.txt',"r+")
username = DB.read()
delete = raw_input("Input username to delete: ")
if delete in username:
<insert code to remove line containing username:password combination>
So, I have a LogIn.txt file with the following username:password combinations:
chris:test
char:coal
yeah:men
test:test
harhar:lololol
I want to delete the username:password combination that I want to in the object "delete"
But the problem is, if I use the
if delete in username:
argument, it'll have to consider the password as well. and example, what if I have two accounts with the same password? Or like the one above. What path can I take for this one? Or am I missing something here?
According to your current DelUser function, you can read the file, remove the line that start with the user to delete, and write a new one:
def DelUser():
# read the current files, and get one line per user/password
with open('LogIn.txt',"r+") as fd:
lines = fd.readlines()
# ask the user which one he want to delete
delete = raw_input("Input username to delete: ")
# filter the lines without the line starting by the "user:"
lines = [x for x in lines if not x.startswith('%s:' % delete)]
# write the final file
with open('LogIn.txt', 'w') as fd:
fd.writelines(lines)
Use
if delete in Guest:
to test if delete is a key in Guest. Since the keys of Guest represent usernames, if delete in Guest tests if delete is a username.
You could use the fileinput module to rewrite the file "inplace":
import fileinput
import sys
def DelUser(Guest):
delete = raw_input("Input username to delete: ")
for line in fileinput.input(['LogIn.txt'], inplace = True, backup = '.bak'):
if delete not in Guest:
sys.stdout.write(line)