Why is request module closing after giving an input? - python

I am working on a project that finds if a user is available or not on Instagram, (Basically that's only one of the functions.)
To do that I use this code from requests:
def start():
clear() # Clears the previous input through the OS module
print(inp + cut + "Stress them is booting...") # Inp + Cut are optional strings
use = input("Who do you want to attack? Enter here: >> ") # We take the input from here (Specifically the user)
response = requests.get("https://www.instagram.com/"+xuse+"/") # Check if the user exists, this does not work if you put # in the beginning.
if response.status_code == 404 :
PrintFatalError("User could not be found, try again.") # The user wasn't found
# Here the program stops and returns to the main program / input where I ask the user for a command.
elif response.status_code == 200 :
PrintFatalError("User " + use + " has been detected ! Proceed with the tool? ") # The user was found
f = input(" ") # This is the point
if f in "y":
print ("Beginning")
else:
print("Not a valid option, aborting.") # I abort since I don't want a loop in this phase.
Some other info that might help:
The program is fully CLI, I don't use a GUI.
This program uses while loops instead of for loops, for many reasons.
NOTE: PrintFatalError is a variable I created to display messages in red / green color. It still does not work with the classic print("string") way through.

Related

How to re-execute same python file [duplicate]

This question already has answers here:
How to make a script automatically restart itself?
(5 answers)
Closed last year.
I've been looking for a way to re-run my program when it reaches the end, it will normally close the file and I need to re-run it manually. I've been trying to replicate making a programming language with my own modules and files because it's had to understand sly,ply and it has alot of functions and every fix I've seen on other stackoverflow pages don't have my fix.
Here is my code:
# main.py
# if program crashes with error code 164 that means it crashed because of invalid syntax or unexpected error in the input you made. contact a developer if you don't know what you did wrong.
import sys
from util.sys import log4javi
from util.sys import *
# Code
print("Running javi build "+build+" ["+lang+"]")
print()
codej = input("Run >> ")
try:
if codej == "":
javi("Null crash", True)
except:
print("excepted null crash")
codej = input("Run >> ")
if codej == "-version":
print(codej)
elif codej == "L":
print("how dare u L me?? >:(")
elif codej == "ඞ":
print("sussy moogus 69420")
print(moogus)
log4javi("Sussy moogus never trust 69420", True)
codej = input("Run >> ")
def sum(num1, num2):
print(num1 + num2)
codej = input("Run >> ")
# The official print statement
def sys_println(printarg):
print(printarg)
codej = input("Run >> ")
try:
exec(codej)
except:
print()
if anyone can give me some help on re-executing it when it reaches the end i will try it.
Python version 3.8.12 64-bit on Ubuntu
I also have alot of functions so I don't know if I can store functions on functions
Actually, it has a simple answer: infinite loops
Just add a while True (or condition with a counter) in your code.
Example:
# imports....
# defs....
while True:
# your code for re-run
# break at some condition; or it can run forever.

Wondering why my error message pops up through every name read in a file?

I'm making a program in Python for a class that involves logging in to get to the main GUI. Currently, this file has 3 sets of usernames and passwords. My intention was for when the user clicks a button, the program reads through all account username and password combinations from a txt file, and if it does not find a match, an error message shows up. Right now it is giving that error message after it reads each set of names. So if I try to sign in with the last account's information in the file, it will give me the error 2 times, then proceed to log in. If anyone has any advice to help fix my logic, I'd greatly appreciate it.
def verify_login(login):
user = login.login_window.username_entry.get()
password = login.login_window.password_entry.get()
accounts = open("accounts.txt",'r')
for line in accounts.readlines():
login_info = line.split()
if (user == login_info[0] and password == login_info[1]):
print("Account found. Logging in...")
###
### take to main gui
###
else:
tk.messagebox.showerror("Error", "Account not found. Try again.")
login.login_window.username_entry.delete(0,END)
login.login_window.password_entry.delete(0,END)
Like this:
def verify_login(login):
user = login.login_window.username_entry.get()
password = login.login_window.password_entry.get()
accounts = open("accounts.txt",'r')
found = False
for line in accounts.readlines():
login_info = line.split()
if (user == login_info[0] and password == login_info[1]):
print("Account found. Logging in...")
found = True
break
###
### take to main gui
###
if not found:
tk.messagebox.showerror("Error", "Account not found. Try again.")
login.login_window.username_entry.delete(0,END)
login.login_window.password_entry.delete(0,END)
If you return during the "success" processing, then you don't need the found flag. Once you exit the loop, you know you have a failure.

Python problem with if-elif-else and/or string comparison problem

I'm new to Python (and stackoverflow :D) and in school we got the task to create (normal users and with sudo rights) and delete users on a linux system (Ubuntu 18.04 in my case). I'm using Pycharm for coding and Python 3.7 as interpreter.
I have already searched for an answer but couldn't find one.
So I'm not sure what exactly causes this problems so sorry for the may confusing title.
I'll try to explain it as good as possible.
I want to ask a question if the user wants to create or delete an user..
def useradministration():
parameters.question_user ##input("User add (a) or delete (d)?: ").strip()
...followed by:
#a for adding an user
if parameters.question_user == 'a':
def usercreate():
parameters.question_role ##input("Role for the user: administrator (a) or normal user (n)? ").strip()
# n for normal user - creating via useradd
if parameters.question_role == 'n':
.....
# a for administrator - same as a but with usermod for sudo
elif parameters.question_role == 'a':
.....
#error if its neither n or a
else:
print("Error: wrong specification for role.")
usercreate()
#d for deleting an user
elif parameters.question_user == 'd':
def userdelete():
........
#error if its neither a or d
else:
print("Error: wrong specification for user.")
First question.
An example output:
User add (a) or delete (d)?: r
Role for the user: administrator (a) or normal user (n)? u
Select username:g
Error: wrong specification for user.
It gives the right output with "Error: wrong specification for user." - but why is it still going through all the questions if the first if isn't true? Is it a problem with my script or is the input comparison not working, or something else?
User add (a) or delete (d)?: r
Error: wrong specification for user.
That would be the output I've hoped for.
Another question for the deleting part. We have to log everything into a file. My userdelete looks like this:
def userdelete():
parameters.username ##username = input("Select username:")
#try to delete if it exists, print and log it
try:
os.system("sudo userdel -r " + parameters.username)
print("User " + parameters.username + " deleted.")
logging.info("User " + parameters.username + " deleted.")
#exception for when user doesn't exist, just printing and logging it
except OSError:
print("User " + parameters.username + " doesnt exist.")
logging.critical("User " + parameters.username + " doesnt exist.")
pass
userdelete()
An example output:
User add (a) or delete (d)?: d
Role for the user: administrator (a) or normal user (n)? o
Select username:abc
User abc deleted.
userdel: user 'abc' does not exist
The script is actually deleting the user if it exists.
But why is it asking the Role question and why isn't it using the except statement if the user doesn't exist (because abc doesn't exist)? Am I using it wrong in this case?
I hope someone can help me.
Thanks.
EDIT
parameters.question_user is from another .py file called parameters.py (I've imported it in the main.py file) and just contains
question_user = input("User add (a) or delete (d)?: ").strip()
question_role = input("Role for the user: administrator (a) or normal user (n)? ").strip()
username = input("Select username:")

transcrypt connectionpool error

I am very new to coding and web development. I am a Systems Engineer and looking to get into the Web Development side of things. I took some python tutorials and pieced together a (probably very) rough python application. I would now like to take that application and put it on a website I have created so that I can allow others in the office to use the utility as well.
To that end, I installed transcrypt with the goal of converting the python code to javascript. When running transcrypt I get the following output:
Error while compiling (offending file last):
File 'c:/Scripting/Transcrypt/Meraki.py', line 1, at import of:
File 'c:/users/dab404/appdata/local/programs/python/python36/lib/site-packages/requests/init.py', line 43, at import of:
File 'c:/users/dab404/appdata/local/programs/python/python36/lib/site-packages/urllib3/init.py', line 8, namely:
Attempt to import module: connectionpool
Can't find any of:
c:/Scripting/Transcrypt/connectionpool.py
c:/Scripting/Transcrypt/javascript/connectionpool.mod.js
The error goes on to list about 10 other files that it needs to run. I am not sure how to fix this issue and would appreciate any help anyone can give me.
Here is my code:
import requests
import json
from meraki import meraki
base_url = "https://dashboard.meraki.com/api/v0/"
def List_Orgs(apikey): #A FUNCTION FOR LISTING ORGANIZATION ADMINS
myOrgs = meraki.myorgaccess(apikey)
for orgs in myOrgs:
print(orgs)
def List_Admins(URL_admin, headers):
x = requests.get(URL_admin, headers = headers)
myAdmins = x.json()
for admins in myAdmins:
print(admins)
def Add_Admin(URL, admin_data, headers): #FUNCTION FOR ADDING NEW ADMIN
TO AN ORGANIZATION
r = requests.request("POST", URL, data = admin_data, headers = headers)
print(r.status_code)
if (r.status_code) == 201:
print()
print()
print("Administrator successfully added!")
print()
else:
print()
print("Administrator was NOT successfully added. Please try again!")
print()
def Del_Admin(URL_del, headers): #FUNCTION FOR DELETING AN ADMIN FROM AN
ORGANIZATION
r = requests.request("DELETE", URL_del, headers = headers)
print(r.status_code)
if (r.status_code) == 204:
print()
print()
print("Administrator successfully deleted!")
print()
else:
print()
print("Administrator was NOT successfully deleted. Please try again!")
print()
apikey = input("What is your Meraki API key? ")
print()
print("******************************************")
print()
print("Here is a list of your Organizations. You will need the ID to answer
the next set of questions.")
print()
print()
List_Orgs(apikey)
print()
print()
headers = {
'X-Cisco-Meraki-API-Key': apikey,
'Content-Type': "application/json"
}
add_or_del = input("Would you like to add or delete an admin? ")
if add_or_del == ("add" or "Add" or "ADD"):
orgid = input("Which Organization would you like to add an admin to? ")
admin_name = input("What is the new Admin's First and Last name? ")
admin_email = input("What is " + admin_name + "'s email address? ")
admin_access = input("What level of access would you like " + admin_name +
" to have? (full or read-only) ")
admin_data = '{\n\t\"name\":\"' + admin_name + '\",\n\t\"email\":\"' +
admin_email + '\",\n\t\"orgAccess\":\"' + admin_access + '\"}'
URL = (base_url + 'organizations/' + orgid + '/admins')
Add_Admin(URL, admin_data, headers)
elif add_or_del == ("delete" or "Delete" or "DELETE"):
orgid = input("Which Organization would you like to delete an admin from?
")
URL_admin = (base_url + 'organizations/' + orgid + '/admins/')
print()
print("Here is a list of Admins in this Organization. You will need to
admin ID to answer the next question.")
print()
print()
List_Admins(URL_admin, headers)
print()
print()
adminid = input ("What is the admin's Meraki portal ID? ")
URL_del = (base_url + 'organizations/' + orgid + '/admins/' + adminid)
Del_Admin(URL_del, headers)
else:
print("Please type add or delete and try again.")'
Thanks!
David
The problem lies with the imports:
import requests
import json
from meraki import meraki
A module like requests is a standard Python module that isn't supported by Transcrypt, since it uses code written in C, that doesn't run in a browser.
For json there's a JavaScript counterpart that can be used directly from Transcrypt without problems.
Module meraki I don't know, so can't judge about.
Although a growing number of standard modules is supplied in the Transcrypt distribution, in general it makes use of JavaScript modules, since these are specially geared toward functionality that makes sense in a browser.
E.g. local file access is generally prohibited in a browser, so any module using that cannot do it's 'thing'.
See also:
http://www.transcrypt.org/docs/html/what_why.html#the-ecosystem-different-batteries
So in Transcrypt you program in Python, but the libs you use are mainly JavaScript. The exception are very common libs like math, cmath, random (partially), time, datetime, itertools, re etc.
To get an impression of how to use JavaScript libs from Transcrypt, take a look at:
http://www.transcrypt.org/examples
and also at:
http://www.transcrypt.org/docs/html/integration_javascript.html#mixed-examples
[EDIT]
I've taken another good look at your application, and I notice that it's a typical console application, using things like input and print. While these are supported in Transcrypt in a limited way, see
http://www.transcrypt.org/docs/html/integration_javascript.html#example-using-input-and-print-in-a-dom-terminal-element-in-your-browser
in general web applications work somewhat differently.
In general they are event driven, meaning that a number of GUI elements are pieced together, sometimes in HTML, sometimes in a script. These GUI elements then trigger events, that in turn trigger certain pieces of code (event handlers) to be run.
So a good next step may be to study this way of working. A nice, simple example in Transcrypt, of HTML/DOM and a script cooperating in this way is this one:
http://www.transcrypt.org/docs/html/installation_use.html#your-first-transcrypt-program
In many cases with a web application there's also interaction with a webserver, so part of the processing is done on the server.
You can e.g. use Bottle or Django for that, as is demoed at:
https://github.com/Michael-F-Ellis/NearlyPurePythonWebAppDemo

How to create a python dictionary that will store the username and password for multiple accounts

The problem I have right now is that for my dictionary that uses a key:value to store username:password is that every time I rerun the program, the current key:value is reset and the dictionary is set to empty again. The goal of my program is to have a person log in with a username and password and be able to store notes and passwords (I did this with python .txt files). Then the next person can come along, create an account and do the same. Here is my code (I have commented every line of code pertaining to my problem):
def userPass():
checkAccount = input("Do you have an account (Y or N)?")
if (checkAccount == 'N' or checkAccount == 'n'):
userName = input("Please Set Your New Username: ")
password = input("Please Set Your New Password: ")
// if (userName in dictAcc):
print("Username is taken")
userPass()
else:
// dictAcc[userName] = password
print("Congratulations! You have succesfully created an account!")
time.sleep(1.5)
dataInput()
elif(checkAccount == 'Y' or checkAccount == 'y'):
login()
else:
print("Invalid answer, try again")
userPass()
def login():
global userName
global password
global tries
loginUserName = input("Type in your Username: ")
loginPass = input("Type in your Password: ")
if (tries < 3):
// for key in dictAcc:
// if (loginUserName == key and loginPass == dictAcc[key]):
// print("You have successfully logged in!")
dataInput()
else:
print("Please try again")
tries += 1
login()
if (tries >= 3):
print("You have attempted to login too many times. Try again later.")
time.sleep(300)
login()
userPass()
As others have mentioned, you need to have your dictionary saved into a file and load it when you restart your program. I adjusted your code to work for me and created two functions, one to save the dictionary (savedict) and another to load it (loaddict). The except IOError part is just so that it creates a new file if it doesn't exist.
Note that in general, storing passwords in a text file is a very bad idea. You can clearly see the reason why if you try to open the "dictAcc.txt" file (it will have all passwords there).
import pickle
import time
def loaddict():
try:
with open("dictAcc.txt", "rb") as pkf:
return pickle.load(pkf)
except IOError:
with open("dictAcc.txt", "w+") as pkf:
pickle.dump(dict(), pkf)
return dict()
def savedict(dictAcc):
with open("dictAcc.txt", "wb") as pkf:
pickle.dump(dictAcc, pkf)
def userPass():
dictAcc = loaddict() #Load the dict
checkAccount = raw_input("Do you have an account (Y or N)?")
if (checkAccount == 'N' or checkAccount == 'n'):
userName = raw_input("Please Set Your New Username: ")
password = raw_input("Please Set Your New Password: ")
if (userName in dictAcc):
print("Username is taken")
userPass()
else:
dictAcc[userName] = password
print("Congratulations! You have succesfully created an account!")
savedict(dictAcc) #Save the dict
time.sleep(1.5)
# dataInput() Code ends
elif(checkAccount == 'Y' or checkAccount == 'y'):
login()
else:
print("Invalid answer, try again")
userPass()
def login():
global userName
global password
global tries
loginUserName = raw_input("Type in your Username: ")
loginPass = raw_input("Type in your Password: ")
dictAcc = loaddict() #Load the dict
if (tries < 3):
for key in dictAcc:
if (loginUserName == key and loginPass == dictAcc[key]):
print("You have successfully logged in!")
# dataInput() Code ends
else:
print("Please try again")
tries += 1
login()
if (tries >= 3):
print("You have attempted to login too many times. Try again later.")
time.sleep(3)
tries=1 #To restart the tries counter
login()
global tries
tries=1
userPass()
There are different ways to do this. I'll mention two.
As you noticed, all variables created by your program are erased when the program finishes executing.
One way to keep those variables alive is to keep the program running indefinately; something like a background process. This could be achieved very simply by running the script within a while loop while True:, although there are more effective ways to do it too. Then, it's variables can continue to exist because the program never terminates.
However that is only useful in occasions when you want to have something running all the time, such as a user interface waiting for input. Most of the time, you want your script to run and be able to complete.
You can therefore output your needed data to a text file. Then, when you start your program, read that text file and organize the info into your dictionary. This will make use of open("Your_username_file") and reading that file's data. If you need help on how to do that, there are many tutorials about how to read information from files in Python.
How you will store it doesn't matter too much in your case, so it's better to keep things simple and store it in something like a text file. In anycase, you don't want to store the accounts in memory, because you will need to keep it running forever.
Since this is also running locally, no matter how you choose to store your passwords, it'll be accessible to anyone who uses it. So User_a can check User_b's account and password.
So you'll need to encrypt the password before storing them. It's not as hard as it sound. Actually, Python has built-in libraries to deal with it.
A quick google search returned a simple tutorial explaning all this step by step, check it out. You'll probably be able to implement it into your code very quickly.

Categories