I have a program that runs through a list of names in 'serverlist.txt'.
The user selects the database they want to search in by choosing option 1 or option 2.
The program will run through all names in the list and provide the id tied to each name.
Name: Jupiter ID: 23
Name: Mars ID: 26
Name: Mercury ID: 27
This works fine but it doesn't stop. When the list is complete, it loops through everything all over again.
How do I stop it from going through the list more than once?
import pypyodbc
import os
def replaceid(connection, servername):
try:
cursor = connection.cursor()
SQLCommand = ("SELECT Name, Location_ID "
"FROM dbo.Server_ID " # table name
"with (nolock)"
"WHERE Name = ?")
Values = [servername]
cursor.execute(SQLCommand,Values)
results = cursor.fetchone()
if results:
print (" Name: " + results[0] + " ID: " + str(results[1]))
print (" ")
locationid(results, connection, servername)
else:
print (" ID for " + servername + " does not exist.")
print (" ")
connection.close()
except:
print("Database is down or you are not connected to network.")
exit()
def start1():
os.system('cls' if os.name == 'nt' else 'clear')
array = []
local = input('\n\n Type option 1 or 2: ')
while True:
with open("serverlist.txt", "r") as f:
for servername in f:
try:
if local in ['1']:
connection = pypyodbc.connect('Driver={SQL Server};Server=db1;Database=WinOasis;Trusted_Connection=yes;')
elif local in ['2']:
connection = pypyodbc.connect('Driver={SQL Server};Server=db2;Database=WinOasis;Trusted_Connection=yes;')
else:
return
except pypyodbc.Error as ex:
sqlstate = ex.args[0]
if sqlstate == '28000':
print ("You do not have access.")
replaceid(connection, servername.strip())
return
start1()
I think your return statement on the third to last line needs to be indented one level. Otherwise your while loop will run forever, because True will always be true!
You might want to add a break statement after you call replaceid(connection, servername.strip()) in start1()
You might also want a break statement after the exception clause ends.
Related
I'm new to python and I'm working on the following code. Of course this is not the best code but it's currently what I know. Overall, the class Database contains a method called log_in() where we have a variable called login_code. When the user logs in using that method, login_code stores the code that the user enters, after this, the class Logged gets executed and when it runs I want to see what user is logged in from a method called who(). Thank you
class Database:
def clear_console(self):
os.system('cls' if os.name == 'nt' else 'clear')
return self
def txt_menu(self):
self.clear_console()
terms_conditions()
checking = input("> Proceed? ")
if checking == "a":
self.clear_console()
self.user_menu()
else:
self.txt_menu()
def loading_bar(self):
for _ in tqdm(range(101), "> Loading. . .", ncols=75):
time.sleep(0.01)
print("> Complete. . .")
time.sleep(1)
os.system('cls' if os.name == 'nt' else 'clear')
return self
def user_menu(self):
print("")
process = input("> Are you registered y/n? Or forgot details 'f': ")
if process == "y":
self.log_in()
elif process == "n":
self.user_registration()
elif process == "f":
self.forgot_details()
else:
print("Try again! ")
self.user_menu()
def user_registration(self):
global registration_code
cursor = conn.cursor()
print("> To register enter the details below: \n")
registration_username = input("> Username: ")
registration_email = input("> Email: ")
registration_password = input("> Password: ")
for pwd in range(1):
registration_code = ""
for c in range(5):
registration_code += random.choice(chars)
cursor.execute("INSERT INTO tst (username, email, password, code) values (?, ?, ?, ?)",
registration_username, registration_email, registration_password, registration_code)
print("> Your code is: ", registration_code)
print("> Successful registration")
print("")
print("> Welcome", registration_username)
conn.commit()
return
def log_in(self):
cursor = conn.cursor()
login_code = input("Enter the code: ")
cursor.execute("SELECT * FROM tst WHERE code = ?", login_code)
data = cursor.fetchall()
if not data:
print('> Not found')
self.log_in()
else:
cursor.execute("SELECT username FROM tst WHERE code = ?", login_code)
data = cursor.fetchall()
reducing_string = str(data)[1:-1]
last_cut = str(reducing_string)[1:-1]
print("")
print("Welcome", last_cut)
return login_code
def forgot_details(self):
cursor = conn.cursor()
login_username = input("> Username: ")
login_password = input("> Password: ")
cursor.execute("SELECT code FROM tst WHERE username = ? AND password = ?", login_username, login_password)
data = cursor.fetchall()
if not data:
self.forgot_details()
else:
reduction = str(data)[1:-1]
self.loading_bar()
print("> Your details are: ", str(reduction)[1:-1])
print("> To log in enter the code below: ")
self.log_in()
conn.commit()
class Logged:
def who(self):
cursor = conn.cursor()
cursor.execute("SELECT username FROM tst WHERE code = ?", #NOT SURE WHAT TO WRITE HERE)
data = cursor.fetchall()
print("Welcome user called: "data)
conn.commit()
def login_menu(self):
print("")
print("> Choose one of the following: ")
print("> 1: One \n"
"> 2: Two \n"
"> 3: Three \n"
"> 4: Four")
user_ask = input("> : ")
if user_ask == "1":
print("One")
elif user_ask == "2":
print("Two")
elif user_ask == "3":
print("Three")
elif user_ask == "4":
print("Four")
else:
self.login_menu()
First issue:
def log_in(self):
cursor = conn.cursor()
login_code = input("Enter the code: ")
This does not store the login_code variable to be retrieved later. login_code is only available during the execution of log_in(). To save it for later, you need to explicitly make login_code a member of some object (or make it an object in its own right in a higher scope). This might mean using self.login_code, or it might mean making login_code a member of some other object that is a member of the Database object.
If you want login_code to be a member of the Database class, you must explicitly refer to it as self.login_code. Python doesn't automatically include the object's member variables in the scope of methods like C++ (and Java?) do.
after this, the class Logged gets executed and when it runs I want to see what user is logged in from a method called who().
You could
Make login_code a global variable and use its value in the Logged.who() method. This is probably a bad idea.
Make login_code a member of the Database class and make the database instance a member of Logged so it can be fetched.
Make login_code a member of Logged and give the Database class a way to set it when executing the log_in method.
Make login_code a member of some other object that is passed as an argument to Database.log_in() and Logger.who() so that it can be accessed from both methods.
I am trying to query a database based upon user input, if the data exist then print the data, otherwise prompt entering new data. Upon query, the code only returns one time.
I've tried to use the while True: statement, it queries the data based upon the original input repeatedly.
I would like to query based on input, return a result, then reset query based on new user input. Can't seem to figure this one out. Any help would be appreciated.
user_input = input("Scan ID: ")
def read_from_db():
try:
c.execute("SELECT * FROM users WHERE barcode LIKE %s", ("%" + user_input + "%",))
result = c.fetchall()
if result is not None:
print ('Name:' , result[0][1], '| barcode: ' , result[0][3], ' | crew position: ' , result[0][4])
except:
print ("Register new user")
def main():
read_from_db()
if __name__ == '__main__':
try:
db = MySQLdb.connect("localhost","user","pw","database")
c= db.cursor()
except:
print ("not working...")
This did the trick -
while True:
user_input = input("Scan ID: ")
read_from_db = c.execute("SELECT * FROM users WHERE barcode LIKE %s", ("%" + user_input + "%",))
result = c.fetchall()
#print (result)
today = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print (today)
if len(result) == 1:
print ('Name:' , result[0][1], '| barcode: ' , result[0][3], ' | crew position: ' , result[0][4])
c.execute("INSERT INTO Data (first_name,last_init,crew,time) VALUES (%s,%s,%s,%s)", (result[0][1],result[0][2][:1],result[0][4],today,))
db.commit()
else:
print ("Register new user")
fn = input("First Name: ")
ln = input("Last Name: ")
bc = input("Scan ID: ")
cp = input("IP or Student: ")
c.execute("INSERT INTO users (first_name,last_name,barcode,crew_position) VALUES (%s,%s,%s,%s)", (fn,ln,bc,cp,))
db.commit()
SELECT *
FROM users
WHERE barcode
LIKE CONCAT('%',user_input,'%');
Apologies, as I am new to the Programming world for asking novice question.
When I try to run the below code first time it is running fine, I can perform all the 3 operations perfectly, but when I try to run the same code again, I am getting an error as "list index out of range".
Any help and suggestions would be highly appreciated.
# To create a new file
ob=open(r'C:\Python27\avi_file_handling\cred_assgn.txt','w')
ob.write("Number" + "-" + "Username" + ":" + "Password" + '\n')
i=0
for x in range(5):
uid=raw_input("Please enter your username to login\n")
pswd=raw_input("Please enter your password {} to login\n".format(uid))
ob.write(str(i) + " " "-" " " + uid + " : " + pswd + '\n')
i=i+1
ob.close()
After creating the new file from the above code ,I ran the below code to call these operations.
import re
# function to validate the userId and password for the customers present in a text file
def validate_user():
T=0
global uid,pswd,T,c1,f1
f1=open(r'C:\Python27\avi_file_handling\cred_assgn.txt','r+')
f1.seek(0)
print f1.tell()
uid=raw_input("Please enter your username to validate\n")
print f1.tell()
pswd=raw_input("Please enter your password {} to validate\n".format(uid))
print f1.tell()
for line in f1:
c1=re.split(r'(-|:+|)',line.replace(' ','').strip())
if((uid==c1[2]) and (pswd==c1[4])):
print("welcome sir ",uid,"you are a valid user\n")
print f1.tell()
T+=1
return
else:
print("Sir",uid, "Please enter the correct Username and Password")
#Function to add a new user
def AddNew_User():
with open(r'C:\Python27\avi_file_handling\cred_assgn.txt','r+') as ob1:
uid=raw_input("Please enter username to Register\n")
ob1.seek(0,0)
z=0
print ob1.tell()
for line in ob1:
z=z+1
x=z
#z=sum(1 for _ in ob1)
c1=re.split(r'(-|:+|)',line.replace(' ','').strip())
if uid==c1[2]:
print "Sorry sir {},you are already registered, we cannot register you again".format(uid)
break
else:
pswd=raw_input("Please enter your password for userid {} to register\n".format(uid))
print ob1.tell()
if uid==pswd:
print "Sorry {} sir you cannot have same username and password".format(uid)
return
pswd2=raw_input("Please confirm your password once again for userid {} to register\n".format(uid))
print ob1.tell()
if pswd!=pswd2:
print "You have entered incorrect confrim password"
return
print ob1.tell()
print "Hello {} you have successful registered to us".format(uid)
print ob1.tell()
ob1.write(str(x) + " " "-" " " + uid + " : " + pswd + '\n')
print ob1.tell()
ob1.close()
#Function to update the password of an Existing user
def Update_password():
#print "up" ,f1.tell()
#global f1
validate_user()
#print "up" ,f1.tell()
print "previous one",c1
if T>0:
#print "up" ,f1.tell()
pswd3=raw_input("Hello {} Please entrer your new password")
#print "-up" ,f1.tell()
pswd4=raw_input("Hello {} once agin password")
print "1--up" ,f1.tell()
print pswd,pswd4,pswd3,uid
if pswd==pswd3:
print "Please enter the new password and do not repeat"
elif pswd3==pswd4:
#print "---up" ,f1.tell()
print c1[4]
print "11--up" ,f1.tell()
f1.seek(0)
ch=f1.read().replace(c1[4],pswd4)
print "2----up" ,f1.tell()
print ch
print "3----wup" ,f1.tell()
#ob.seek(2)
print "4----qup" ,f1.tell()
f1.seek(2)
f1.write(ch)
print "5----qup" ,f1.tell()
#contents = f.read().replace('Total: __00__', total)
#print "up" ,f1.tell()
print "poassower matcg"
#ob.seek(0,0)
f1.close()
#Main function calling
while(True):
Inputs=input("Please select the operation you would like to perform sir\n 1) Valudate user\n 2) Add new user \n 3) Update password \n5)Exit from the program")
if Inputs==1:
validate_user()
elif Inputs==2:
AddNew_User()
elif Inputs==3:
Update_password()
elif Inputs==5:
break
I'm doing a code where the program ask for personal informations of someone, then he reads those infomations and send to the database. So I have the option to register and to consult. I don't know if the program is with more problems because I need to fix it first.
When I try to register the person It's give me the error "Is not possible to register." and I can't find why.
import sqlite3
conn = sqlite3.connect('database.db')
c = conn.cursor()
def criardb():
c.execute('CREATE TABLE IF NOT EXISTS pessoas(id INTEGER PRIMARY KEY
AUTOINCREMENT,nome VARCHAR, idade INT, tel VARCHAR, pais VARCHAR)')
conn.commit()
def insertdata(nome,idade,tel,pais):
c.execute = ('INSERT INTO pessoas VALUES (?,?,?,?)',
(nome,idade,tel,pais))
conn.commit()
def consultdata():
sql = c.execute('SELECT * FROM pessoas')
for row in sql:
print("Nome: {}".format(row[0]))
def consultdataind(esc):
sql = c.execute('SELECT * FROM pessoas WHERE id = ?')
for row in sql(sql,(esc)):
print("Nome: {} Idade: {} Telefone: {} País:
{}".format(row[0],int(row[1]),row[2],row[3]))
try:
print("Creating database...")
criardb()
except:
print("ERRO: It was not possible to create the database.")
else:
print("Database successfully created.")
while True:
print("Welcome to the register system, choose a option:")
op = int(input("| 1 - Register | 2 - Consult | 3 - Exit | "))
if op == 1:
n = input("Nome: ")
i = int(input("Idade: "))
t = input("Telefone: ")
p = input("País: ")
try:
insertdata(n,i,t,p)
except:
print("ERRO: It's not possible to register")
else:
print("Successfully registered.")
elif op == 2:
print("List of registered users:")
try:
consultdata()
except:
print("It was not possible to load the list.")
print("Write the person ID to individual consult.")
esc = int(input(">> "))
consultdataind(esc)
elif op == 3:
break
else:
print("Invalid command.")
I need to send all the information to the database and return the consult, first it will show all the registered person then the user can write the respective ID of someone in the list and it will show all the details about this person
Replace your insertdata with this and everything should work fine.
def insertdata(nome,idade,tel,pais):
c.execute('INSERT INTO pessoas (nome,idade,tel,pais) VALUES (?,?,?,?)', [nome,idade,tel,pais])
conn.commit()
You need to call the execute method of the cursor here.
And on the side note, never use except directly without specifying an exception. It hides the simplest of error messages which will make your code very hard to debug. As of now it was AttributeError that was causing this problem as you were trying to assign value to Cursor which is ReadOnly
I need help terminating my SSH session after my sendShell object runs through list commandfactory[].
I have a Python script where I use paramiko to connect to a cisco lab router via ssh; execute all commands in commandfactory[]; and output the results to the standard out. Everything seems to work except, I can't seem to get the SSH session to close after all my commands are ran. The session simply stays open until I terminate my script.
import threading, paramiko, re, os
class ssh:
shell = None
client = None
transport = None
def __init__(self, address, username, password):
print("Connecting to server on ip", str(address) + ".")
self.client = paramiko.client.SSHClient()
self.client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
self.client.connect(address, username=username, password=password, look_for_keys=False)
self.transport = paramiko.Transport((address, 22))
self.transport.connect(username=username, password=password)
thread = threading.Thread(target=self.process)
thread.daemon = True
thread.start()
def closeConnection(self):
if(self.client != None):
self.client.close()
self.transport.close()
def openShell(self):
self.shell = self.client.invoke_shell()
def sendShell(self):
self.commandfactory = []
print("\nWelcome to Command Factory. Enter Commands you want to execute.\nType \"done\" when you are finished:")
while not re.search(r"done.*", str(self.commandfactory)):
self.commandfactory.append(input(":"))
if self.commandfactory[-1] == "done":
del self.commandfactory[-1]
break
print ("Here are the commands you're going to execute:\n" + str(self.commandfactory))
if(self.shell):
self.shell.send("enable" + "\n")
self.shell.send("ilovebeer" + "\n")
self.shell.send("term len 0" + "\n")
for cmdcnt in range(0,len(self.commandfactory)):
self.shell.send(self.commandfactory[cmdcnt] + "\n")
self.shell.send("exit" + "\n")
self.shell.send("\n")
else:
print("Shell not opened.")
def process(self):
global connection
while True:
# Print data when available
if self.shell != None and self.shell.recv_ready():
alldata = self.shell.recv(1024)
while self.shell.recv_ready():
alldata += self.shell.recv(1024)
strdata = str(alldata, "utf8")
strdata.strip()
print(strdata, end = "")
sshUsername = "adrian"
sshPassword = "ilovebeer"
sshServer = "10.10.254.129"
connection = ssh(sshServer, sshUsername, sshPassword)
connection.openShell()
while True:
connection.sendShell()
I would like the SSH session terminate once all the commands in my commandfactory list has been ran (CODE BELOW).
def sendShell(self):
self.commandfactory = []
print("\nWelcome to Command Factory. Enter Commands you want to execute.\nType \"done\" when you are finished:")
while not re.search(r"done.*", str(self.commandfactory)):
self.commandfactory.append(input(":"))
if self.commandfactory[-1] == "done":
del self.commandfactory[-1]
break
print ("Here are the commands you're going to execute:\n" + str(self.commandfactory))
if(self.shell):
self.shell.send("enable" + "\n")
self.shell.send("ilovebeer" + "\n")
self.shell.send("term len 0" + "\n")
for cmdcnt in range(0,len(self.commandfactory)):
self.shell.send(self.commandfactory[cmdcnt] + "\n")
self.shell.send("exit" + "\n")
self.shell.send("\n")
My code was mainly taken from https://daanlenaerts.com/blog/2016/07/01/python-and-ssh-paramiko-shell/. Much thanks to Daan Lenaerts for a good blog. I did make my own changes to fit my needs.
End the sendShell function with self.transport.close(), see http://docs.paramiko.org/en/2.0/api/transport.html
Was able to solve by adding self.shell.transport.close() after my iterator.
def sendShell(self):
self.commandfactory = []
print("\nWelcome to Command Factory. Enter Commands you want to execute.\nType \"done\" when you are finished:")
while not re.search(r"done.*", str(self.commandfactory)):
self.commandfactory.append(input(":"))
if self.commandfactory[-1] == "done":
del self.commandfactory[-1]
break
print ("Here are the commands you're going to execute:\n" + str(self.commandfactory))
if(self.shell):
self.shell.send("enable" + "\n")
self.shell.send("ilovebeer" + "\n")
self.shell.send("term len 0" + "\n")
for cmdcnt in range(0,len(self.commandfactory)):
self.shell.send(self.commandfactory[cmdcnt] + "\n")
self.shell.send("exit" + "\n")
self.shell.transport.close()