Inject values from python script through console arguments - python

Change code to inject values through console arguments (python script)
In this moment i have adapted the code to inject the value that are defined through a json file which the script load and read, but i need to change this approach to read the value directly by arguments in the console, how can i do this?
Ex: "py login.py username: ' ' password: ' ' "
pyhton script code (login.py):
with open(sys.argv[1]) as json_data:
data = json.load(json_data)
susername = data["log_username"]
spassword = data["log_password"]
log_username=susername
log_password=spassword
json file:
"log_username": "blalala",
"log_password": "blalala",

Related

Python output boolean variable to file (read, check, write)

I am new to python.
Tell me how to implement saving the value of a variable to a file so that you don't receive unnecessary notifications when the program is restarted.
The program pings the servers and sends a message when the status changes. When you restart the program, it does not save the history of its checks. It is very uncomfortable.
I hope I explained the problem correctly?
I need to constantly save the check result to a file and use this data when comparing new checks.
def ping_host(address):
status = ping_url(address.address)
if status != address.status:
send_message(( "! " if status is None else "+ " if status else
"- ") + address.comment)
address.status = status
This function checks the status, if it has changed, then a new message is sent.
If your file does not need to be portable the simplest solution is to use python pickling. The drawback is that you cannot inspect the file manually or modify it for debuging purpose vs text based saving (eg ini files, json or simple txt). The main advantage is the ease of use as you can serialyze this way any python basic type.
Here is a simple example on how to use it:
import pickle
def get_status():
with open('status','rb') as f:
status = pickle.load(f)
return status
def set_status(status:bool):
with open('status','wb') as f:
pickle.dump(status,f)
set_status(True)
s = get_status()
assert s
set_status(False)
s = get_status()
assert not s
You can make a file history.txt, and then on startup open it, and read the last state, and if its different overwrite that state in the file and save.
from what you wrote in comments I would change it to this:
import json
ping_data = dict()
with open('C:\ping_data.json') as file:
data = json.load(file)
def ping_host(address):
status = ping_url(address.address)
if data['address.status'] != status:
ping_data['address.status'] = status
send_message(("! " if status is None else "+ " if status else "- ") + address.comment)
ping_host(youraddress)
with open('C:\ping_data.json', 'w') as file:
json.dump(ping_data, file, indent=2)
the way I would do this is using json library
import json
next thing I would create a dictionary in your script
saved_data = dict()
then whenever I receive an update I would store the value in dictionary
saved_data['info'] = updated_info
and export? it to a json file
with open('saved_data.json', 'w') as file:
json.dump(saved_data, file, indent=2)
now whenever I open the program it would read that file like this
with open('saved_data.json') as file:
data = json.load(file)
and then I would access variable data as a dictionary
for k in data:
for info in data[k]:
if info != updated_info
saved_data['info'] = updated_info

I want to be able to pull login info from a CSV to use as parameters for the redfish object [duplicate]

This question already has answers here:
How do I read and write CSV files with Python?
(7 answers)
Closed 4 years ago.
if __name__ == "__main__":
# When running on the server locally use the following commented values
# iLO_https_url = "blobstore://."
# iLO_account = "None"
# iLO_password = "None"
# When running remotely connect using the iLO secured (https://) address,
# iLO account name, and password to send https requests
# iLO_https_url acceptable examples:
# "https://10.0.0.100"
# "https://f250asha.americas.hpqcorp.net"
iLO_https_url = "https://10.0.0.100"
iLO_account = "admin"
iLO_password = "password"
# Create a REDFISH object
try:
REDFISH_OBJ = RedfishObject(iLO_https_url, iLO_account, iLO_password)
except ServerDownOrUnreachableError as excp:
sys.stderr.write("ERROR: server not reachable or doesn't support " \
"RedFish.\n")
sys.exit()
except Exception as excp:
raise excp
ex4_reset_server(REDFISH_OBJ)
REDFISH_OBJ.redfish_client.logout()
Above is the "login" part of the script im writing. In this part, REDFISH_OBJ = RedfishObject(iLO_https_url, iLO_account, iLO_password), I would like to replace iLO_https_url with a variable whose value would be pulled from a simple CSV file. The CSV would have 3 columns...ip, username,pwd.
I'm trying to execute the other part of the script, not shown here, on every IP in the CSV file. I need to do this in python.
The easiest way is to use the open() function with the split() function.
Try something like this:
with open("data.csv", encoding="utf-8") as csv_file:
iLO_account, iLO_password, iLO_https_url = csv_file.readline().split(",")
If you are separating your entries with new line breaks, simply replace the ",", with a "\n"

TypeError: sequence item 1:expected str instance, bytes found

I want to download tweets from twitter as data sets for sentiment analysis using Python Twitter API ..
I am using SemEval 2016 task 6 dataset ..So I downloaded "Domain corpus for task B" and I found a Readme file that describe the steps ..
I am just a beginner and I do not know much in python ..I installed python 3.4.3 and I already found easy_install.exe and pip.exe in scripts folder ..
I typed in cmd : "easy_install twitter" as it is written in readme file ...then I tried to apply the steps from Readme file , here are the steps:
The first time you run this, it should open up a web browser, have you log into
Twitter, and show a PIN number for you to enter into a prompt generated by the
script.
Login to Twitter with your user name in your default browser.
Run the script like this to download your credentials: python download_tweets_api.py --dist=Donald_Trump.txt -- output=downloaded_Donald_Trump.txt
Download tweets like so: python download_tweets_api.py --dist=Donald_Trump.txt --output=downloaded_Donald_Trump.txt
I finished step 1 , then I typed in cmd "download_tweets_api.py --dist=Donald_Trump.txt --output=downloaded_Donald_Trump.txt" but I got an error in last line of the file
TypeError: sequence item 1:expected str instance, bytes found
Here is the content of the file "download_tweets_api.py"
import sys
import os
import time
import datetime
import argparse
from twitter import *
parser = argparse.ArgumentParser(description="downloads tweets")
parser.add_argument('--partial', dest='partial', default=None, type=argparse.FileType('r'))
parser.add_argument('--dist', dest='dist', default=None, type=argparse.FileType('r'), required=True)
parser.add_argument('--output', dest='output', default=None,type=argparse.FileType('w'), required=True)
args = parser.parse_args()
CONSUMER_KEY='xxxxxxxxxxx'
CONSUMER_SECRET='xxxxxxxxxxxxxxxxx'
MY_TWITTER_CREDS = os.path.expanduser('~/.my_app_credentials')
if not os.path.exists(MY_TWITTER_CREDS):
oauth_dance("Semeval sentiment analysis", CONSUMER_KEY, CONSUMER_SECRET, MY_TWITTER_CREDS)
oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS)
t = Twitter(auth=OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET))
cache = {}
if args.partial != None:
for line in args.partial:
fields = line.strip().split("\t")
text = fields[-1]
sid = fields[0]
cache[sid] = text
for line in args.dist:
fields = line.strip().split('\t')
sid = fields[0]
while not sid in cache:
try:
text = t.statuses.show(_id=sid)['text'].replace('\n', ' ').replace('\r', ' ')
cache[sid] = text.encode('utf-8')
except TwitterError as e:
if e.e.code == 429:
rate = t.application.rate_limit_status()
reset = rate['resources']['statuses']['/statuses/show/:id'] ['reset']
now = datetime.datetime.today()
future = datetime.datetime.fromtimestamp(reset)
seconds = (future-now).seconds+1
if seconds < 10000:
sys.stderr.write("Rate limit exceeded, sleeping for %s seconds until %s\n" % (seconds, future))
time.sleep(seconds)
else:
cache[sid] = 'Not Available'
text = cache[sid]
args.output.write("\t".join(fields + [text]) + '\n')
Note you can find the download_tweets_api.py and readme files in the "domain corpus for task B"
The issue is with the last line of the download_tweets_api.py script. The script was written in Python 2 and would probably run seamlessly in Python 2. The main reason it is not running in Python 3 is that the last line is trying to join strings with bytes. However, in Python 3, bytes are clearly different from strings, in that you cannot join a byte to a string without coercing one into the other. In the case of this script, either the text variable or the fields variable (or even both) is of bytes elements. So, you may have to modify the variables text and fields before applying the string join function on them.
Basically, you will have to replace the last line of the script with the following:
#Create a function that converts the byte elements of the list fields into strings.
def convert(s):
try:
return str(s,encoding='utf8')
except:
return s
text = convert(text)
fields = list(map(lambda x: convert(x), fields))
args.output.write("\t".join(fields + [text]) + '\n')
If you do not want to modify the script, then you may have to run it in Python 2, or use the 2to3 module to convert the code to Python 3.
Hope this helps.

Using CGI in python 3.4 I keep getting "End of script output before headers: measurement.py" error in my error log

The purpose is to have the area method return json serialized data using cgi and restful services. When I run request_area() my console displays 500 internal server error and when I check my error log it says 'End of script output before headers: measurement.py'
Here is measurement.py
#!/usr/bin/python3
__author__ = 'charles'
import json
import logging
import db_utility, db_access
def send_data(data):
logging.debug(str(data))
dataJ = json.dumps(data)
logging.debug("custJ " + str(dataJ))
lng = len(dataJ)
logging.debug("len " + str(lng))
print("Content-Type: application/json; charset=UTF-8")
print("Content-Length: " + str(lng))
print()
print(dataJ)
def area():
areas = db_access.get_all_areas()
# print(areas)
send_data(areas)
And here is request_area()
import requests
r = requests.get("http://localhost/cgi-bin/measurements_rest/measurement.py/area")
print(r.text)
Oh and the function being called in area(), get_all_areas()
def get_all_areas():
"""
Returns a list of dictionaries representing all the rows in the
area table.
"""
cmd = 'select * from area'
crs.execute(cmd)
return crs.fetchall()
I can not figure out what I am doing wrong.
As you are using apache to call your program, apache will place in the
environment several variables with info on the cgi call and the url.
The one of interest to you is PATH_INFO which contains the string remaining
unparsed by apache, ie area. In your python main you need to
os.getenv('PATH_INFO') and recognised the word and call your function.
Alternatively, use a framework like cherrypy which
does this sort of work for you.
Also, you are printing stuff before the Content-type etc headers. Remove
print(areas)

Python newbie - Input strings, return a value to a web page

I've got a program I would like to use to input a password and one or multiple strings from a web page. The program takes the strings and outputs them to a time-datestamped text file, but only if the password matches the set MD5 hash.
The problems I'm having here are that
I don't know how to get this code on the web. I have a server, but is it as easy as throwing pytext.py onto my server?
I don't know how to write a form for the input to this script and how to get the HTML to work with this program. If possible, it would be nice to make it a multi-line input box... but it's not necessary.
I want to return a value to a web page to let the user know if the password authenticated successfully or failed.
dtest
import sys
import time
import getopt
import hashlib
h = hashlib.new('md5')
var = sys.argv[1]
print "Password: ", var
h.update(var)
print h.hexdigest()
trial = h.hexdigest()
check = "86fe2288ac154c500983a8b89dbcf288"
if trial == check:
print "Password success"
time_stamp = time.strftime('%Y-%m-%d_%H-%M-%S', (time.localtime(time.time())))
strFile = "txt_" + str(time_stamp) + ".txt"
print "File created: txt_" + str(time_stamp) + ".txt"
#print 'The command line arguments are:'
#for i in sys.argv:
#print i
text_file = open(strFile, "w")
text_file.write(str(time_stamp) + "\n")
for i in range(2, len(sys.argv)):
text_file.write(sys.argv[i] + "\n")
#print 'Debug to file:', sys.argv[i]
text_file.close()
else:
print "Password failure"
You'll need to read up on mod_python (if you're using Apache) and the Python CGI module.
Take a look at django. It's an excellent web framework that can accomplish exactly what you are asking. It also has an authentication module that handles password hashing and logins for you.

Categories