I wrote a program which gets username and password from the user and creates a table in an SQLite DB then sends those data through a connection to DB.
It was working fine until I added the shebang in my code, then I made it executable(chmod +x) and after all, I put that file into /usr/bin so that I could use it anywhere in the terminal. now it runs but it doesn't work (it doesn't add data to DB).
here is my code:
#!/usr/bin/python3
__author__ = "Taha Jalili"
__license__ = "GPL"
__version__ = "1.0.0"
__email__ = "tahajalili#gmail.com"
import sys
import sqlite3
from sqlite3 import *
import inquirer
SQL_CREATE_STATEMENT = '''CREATE TABLE password
(id integer PRIMARY KEY NOT NULL,username text, password text, source text)'''
SQL_INSERT_STATEMENT = '''INSERT INTO password (username, password, source)VALUES(?,?,?)'''
DATABASE_PATH = '/home/taha/lessons/projects/passStorage/passDB.db'
def create_connection(db_file):
try:
conn = sqlite3.connect(db_file)
return conn
print('Connection created.')
except Error as e:
return e
# def create_table(connection, sql_commands):
# c = connection.cursor()
# c.execute(sql_commands)
# print('=> Table created.')
def get_input():
USERNAME = input('username: ')
PASSWORD = input('password: ')
SOURCE = input('source: ')
return USERNAME,PASSWORD,SOURCE
def insert_date(connection,data):
try:
c = connection.cursor()
c.execute(SQL_INSERT_STATEMENT, data)
print('=> Data insertion done.')
except Error as e:
return e
def show_info(connection):
c = connection.cursor()
info = c.execute('SELECT * FROM password ORDER BY id')
print('YOUR PASSWORDS'.center(45,'-'))
print('(id, username, password, source)')
for row in info:
print(row,'')
print('\n')
def ask_again():
user_choice = input("Wish to continue? Y/N ")
if user_choice == 'y' or user_choice == 'Y':
main()
elif user_choice == 'n' or user_choice == 'N':
print("==> BYE <==")
sys.exit(0)
def main():
conn = create_connection(DATABASE_PATH)
# create_table(conn, SQL_CREATE_STATEMENT)
questions = [
inquirer.List(
'job',
message = 'What should I do?',
choices=['Add data','Show saved data.']
),
]
answers = inquirer.prompt(questions)
if answers['job'] == 'Add data':
conn2 = create_connection(DATABASE_PATH)
insert_date(conn2,get_input())
elif answers['job'] == 'Show saved data.':
show_info(conn)
ask_again()
conn.commit()
conn.close()
if __name__ == '__main__':
main()
Related
I'm writing code for an assignment where I can't change the main. The way I have it written, it prints like in the screenshot below:
Here is my code:
import csv
class Customer:
def __init__(self, cust_id, name, lastName, companyName, address, city, state, cust_zip):
self.cust_id = cust_id
self.first_name = name
self.last_name = lastName
self.company_name = companyName
self.address = address
self.city = city
self.state = state
self.zip = cust_zip
def getFullName(self):
return(self.first_name, self.last_name)
def getFullAddress(self):
return(self.getFullName(), self.company_name, self.address, self.city, self.state, self.zip)
def get_customers():
myList = []
counter = 0
with open("customers.csv", "r") as csv_file:
reader = csv.reader(csv_file, delimiter = ",")
for row in reader:
if counter!=0:
customer1 = Customer(row[0],row[1],row[2],row[3],row[4],row[5],row[6],row[7])
myList.append(customer1)
counter+=1
return myList
def find_customer_by_id(customers, cust_id):
for i in range(len(customers)):
if cust_id == customers[i].cust_id:
return customers[i]
return None
def main():
#main is fully implemented with no modification expected
print("Customer Viewer")
print()
customers = get_customers()
while True:
cust_id = input("Enter customer ID: ").strip()
print()
customer = find_customer_by_id(customers, cust_id)
if customer == None:
print("No customer with that ID.")
print()
else:
print(customer.getFullAddress())
print()
again = input("Continue? (y/n): ").lower()
print()
if again != "y":
break
print("Bye!")
if __name__ == "__main__":
main()
Why are there parenthesis and, can you get rid of them?
I tried to different approaches but nothing changed the output in the intended way
I am having a issue with my frame switching after I click a button for my results. My button is hooked up to for inserting the fields into a database and it does do that but after it does it pulls the login screen back to the toplevel of the screen and just stay on the same screen how can I prevent this from happening? I am thinking its happening once the db closes. I don't get any errors.
if self.first == "":
ms.showerror('Please enter a first name')
elif self.last == "":
ms.showerror('Please enter a last name')
elif self.date == "":
ms.showerror('Please enter a username')
elif self.addr == "":
ms.showerror('Please enter a password')
elif self.phoneNum == "":
ms.showerror('Please enter a password')
else:
findSql = 'SELECT firstname, lastname FROM client WHERE firstname =? and
lastname=? '
c.execute(findSql, [(self.first),(self.last)])
f = c.fetchall()
if f:
ms.showerror('User already exist')
else:
ms.showinfo('Account has been created')
self.insert = 'INSERT INTO client(firstname, lastname, birthdate,
address, phone, symptom1, symptom2, symptom3, symptom4, symptom5)
VALUES(?,?,?,?,?,?,?,?,?,?)'
c.execute(self.insert,[self.first, self.last, self.date, self.addr,
self.phoneNum, self.sym1, self.sym2, self.sym3, self.sym4, self.sym5])
db.commit()
db.close()
# runs calculation accuracy for random forest
a = Algo()
a.randomForest(self.master,self.Symptom1, self.Symptom2, self.Symptom3, self.Symptom4,self.Symptom5)
I recently had an interview and was asked to write a code that logs into 3 routers and reloads each, one at a time - checks that BGP is established and the interfaces are up before moving to reload the next device. We have been provided an imported module that can SSH into the router and reload it. Thoughts anyone? I'm new to Python
Though a module was provided for SSH, I started by coding it out and here is what I tired; just to give an idea of how the router works and what I am checking for:
import socket
import paramiko
def run_ssh_command(username, password, host, command):
"""
Using paramiko to SSH into remote locations and run commands
"""
port = 22
s = paramiko.SSHClient()
s.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
s.connect(host, port, username, password, look_for_keys=False, timeout=5.0)
except paramiko.AuthenticationException as e:
print("authentication failed: ", e)
s.close()
return
except socket.timeout as e:
print("socket timeout: ", e)
s.close()
return
except paramiko.SSHException as e:
print("SSH Exception: ", e)
s.close()
return
except socket.error as e:
print("socket error: ", e)
s.close()
return
(stdin, stdout, stderr) = s.exec_command(command)
print ("ran command ", command)
# for line in stdout.readlines():
# print(line)
s.close()
if __name__ == "__main__":
while True:
run_ssh_command("CompRouter", "backbonedevice", "10.10.10.25", "show ip bgp summary")
So my line of thought is to SSH to the device, issue a "show ip bgp summary" command - this is what the table typically looks like:
Neighbor V AS MsgRcvd MsgSent TblVer InQ OutQ Up/Down Statd
10.10.10.2 4 65536 7 7 1 0 0 00:03:04 0
The idea is to check that the InQ/OutQ values are zero or non of the BGP neighbor are "Down", then and only then do I move to reload the next router.
This is particularly where I am stuck. Given a table like this, how to I check the entire InQ/OutQ column (there might be more than one neighbor) and then take the necessary action?
Opted to use napalm and netmiko - works like a charm:
from simplecrypt import encrypt, decrypt
from pprint import pprint
from netmiko import ConnectHandler
from napalm import get_network_driver
import json
#from time import time
import time
def read_device_data(devices_filename):
devices = {} #Create a dictionary for each IP's unique info
with open(devices_filename) as device_info:
for lines in device_info:
this_dev = lines.strip().split(',')
dev = {'ipaddr': this_dev[0],
'type': this_dev[1],
'name': this_dev[2]}
devices[dev['ipaddr']] = dev
print('Displaying info for all devices below: ')
pprint(devices)
return devices
#Create a function to decrypt and read file containing credentials encrypted in the format ip,username,password
def read_device_creds(device_cred_filename, key):
print('\n Decoding encrypted device credentials....')
with open(device_cred_filename, 'rb') as device_creds_file:
device_creds_decry = decrypt(key, device_creds_file.read())
device_creds_list = json.loads(device_creds_decry.decode('utf-8'))
pprint(device_creds_list)
print('\n Displaying device credentials in dictionary format:')
"""
Convert device_creds_list to dictionary using list comprehension
"""
device_creds_dict = {this_dev[0]: this_dev for this_dev in device_creds_list}
print(device_creds_dict)
return device_creds_dict
def check_BGP(net_device, cred):
print(f"Connecting to {net_device['ipaddr']} right now to check BGP status.....")
while True:
try:
driver = get_network_driver('ios')
iosv = driver(net_device['ipaddr'], cred[1], cred[2])
iosv.open()
except:
print('Waiting to establish a socket...')
else:
time.sleep(30)
ios_output = iosv.get_bgp_neighbors()
for k,v in ios_output.items():
for y in v.values():
if type(y) == dict:
for z in y.values():
print(f"BGP peer is up? {z['is_up']}")
return z['is_up'] == True
def reload(creds):
iosv_device = {
'device_type': 'cisco_ios',
'ip': creds[0],
'username': creds[1],
'password': creds[2]
}
net_connect = ConnectHandler(**iosv_device)
output = net_connect.send_command_timing('wr mem')
time.sleep(10)
output += net_connect.send_command_timing('reload')
output += net_connect.send_command_timing('y')
print(output)
def is_alive(alive_dev, alive_cred): #check if device is back online after reload
while True:
try:
driver = get_network_driver('ios')
iosvl2 = driver(alive_dev['ipaddr'], alive_cred[1], alive_cred[2])
iosvl2.open()
except:
print(f"Attempting to reconnect to {alive_cred[0]}")
else:
alive_output = iosvl2.is_alive()
print(alive_output)
return alive_output['is_alive'] == True
break
if __name__ == '__main__':
net_devices = read_device_data('devices_data')
net_creds = read_device_creds('encrypted_device_creds', 'cisco')
# starting_time = time()
for ipadd, device_info in net_devices.items():
print(net_devices.items())
while True:
print (f'Connecting to: {ipadd}')
if check_BGP(device_info, net_creds[ipadd]) == True:
print(f'Reloading {ipadd} now')
reload(net_creds[ipadd])
else:
print(f'Re-checking BGP on {ipadd}')
if is_alive(device_info, net_creds[ipadd]) == True and check_BGP(device_info, net_creds[ipadd]) == True:
print(f'{ipadd} back online and BGP OK!')
break
else:
print('Router down or BGP failed to reconverged; exiting script')
break
# print ('\n---- End get config sequential, elapsed time=', time() - starting_time)
In the example below, I wrote a code that detects BGP route limits. Its purpose is to calculate the route limit rate by learning the information under the Interfaces. In this regard, I recommend the TTP module, where you can create your own templates.
from netmiko import ConnectHandler
from getpass import getpass
from pprint import pprint
from ttp import ttp
from genie.testbed import load
from pprint import pprint
import json
import time
from multiprocessing.dummy import Pool as ThreadPool
from netmiko import Netmiko
#**************************************************************************************************************************
with open("user_pass.txt", "r") as f5:
user_pass = f5.readlines()
for list_user_pass in user_pass:
if "username" in list_user_pass:
username = list_user_pass.split(":")[1].strip()
if "password" in list_user_pass:
password = list_user_pass.split(":")[1].strip()
def _ssh_(nodeip):
try:
huawei = {
'device_type': 'huawei', 'ip': nodeip, 'username':
username, 'password': password, }
con = Netmiko(**huawei)
print(nodeip.strip() + " " + "basarili giris")
except Exception as e:
print(e)
f_3.write(nodeip.strip() + "\n")
return
#**************************************************************************************************************************
data_to_parse_0 = con.send_command_timing('display ip vpn-instance | ignore-case i Customer_A')
print(data_to_parse_0)
ttp_template_0 ="""
{{Customer_Name}} {{nodeip}} {{IPV4}}
"""
parser_0 = ttp(data=data_to_parse_0, template=ttp_template_0)
parser_0.parse()
#print result in JSON format
results_0 = parser_0.result(format='json')[0]
print(results_0)
#str to list **convert with json.loads
result_0 = json.loads(results_0)
print(result_0[0]["Customer_Name"])
#**************************************************************************************************************************
data_to_parse = con.send_command_timing("display current-configuration configuration vpn-instance {}".format(result_0[0]["Customer_Name"]))
print(data_to_parse)
ttp_template ="""
{{routing-table}} limit {{ total_number | DIGIT }} {{total_number2}}
"""
parser = ttp(data=data_to_parse, template=ttp_template)
parser.parse()
#print result in JSON format
results = parser.result(format='json')[0]
print(results)
#str to list **convert with json.loads
result = json.loads(results)
print(result)
#**************************************************************************************************************************
data_to_parse_2 = con.send_command_timing('dis ip routing-table vpn-instance' + " " + result_0[0]["Customer_Name"] + " " + " statistics | i Summary Prefixes")
print(data_to_parse_2)
ttp_template_2 ="""
Summary Prefixes : {{ used_number | DIGIT }}
"""
parser2 = ttp(data=data_to_parse_2, template=ttp_template_2)
parser2.parse()
#print result in JSON format
results2 = parser2.result(format='json')[0]
print(results2)
#str to list **convert with json.loads
result2 = json.loads(results2)
print(result2[0]["used_number"])
#**************************************************************************************************************************
result3 = (int(result2[0]["used_number"]) / int(result[0]["total_number"])) * 100
print(int(result3))
with open("vrf_limit_result.txt", "a") as f:
f.write("Customer_Result" +"_" + nodeip +"==>" + str(result3)+ "\n")
f.close()
#**************************************************************************************************************************
f_2 = open("ip_list.txt", "r")
ip_list = f_2.readlines()
f_2.close()
f_3 = open("Ssh_unconnected_2.txt", "w")
# Therading method
myPool = ThreadPool(100)
result = myPool.map(_ssh_, ip_list)
I'm trying to save and load files by player name, but it errors when I try to call PlayerIG.name for the path. I've declared global PlayerIG higher up.
Basically I use the PlayerIG to load and then overwrite the values as the name remains the same anyway. The player doesn't have to know and I couldn't find an easier way to do this
class Player:
def __init__(self, name):
self.name = name
self.maxhealth = 100
self.health = self.maxhealth
self.base_attack = 10
self.gold = 10
self.pots = 1
self.weap = ["Rusty Sword"]
self.curweap = self.weap
#property
def attack(self):
attack = self.base_attack
if self.curweap == "Rusty Sword":
attack += 5
if self.curweap == "Great Sword":
attack += 12
return attack
def attack_damage(self, attack):
damage = random.randint(attack / 2, attack)
return damage
def start():
os.system('clear')
print ("Hello, what is your name?")
options = input("--> ")
global PlayerIG
PlayerIG = Player(options)
name = "Your name is: " + PlayerIG.name
send_status(name)
main()
def main():
os.system('clear')
menutext = "Welcome to text RPG!\n 1.) Start\n 2.) Load\n 3.) Exit\n"
print (menutext)
options = input("-> ")
if options == "1":
Menu()
elif options == "2":
if os.path.exists(PlayerIG.name == True:
os.system('clear')
with open(PlayerIG.name, 'rb') as f:
PlayerIG = pickle.load(f)
loaded = "You loaded your save"
print (loaded)
send_status(loaded)
time.sleep(2)
Menu()
else:
noload = "You have no save file for this game."
print (noload)
time.sleep(2)
main()
elif options == "3":
sys.exit()
else:
main()
After so many hours I still can't figure out how to check if the name and password user input exist in my data. For example, when I ask Please input customer name: and they input Sam than I ask again Please input customer password: and the input is janos i want customer_menu() function to be called. thanks
customers_list = []
class BankSystem(object):
def __init__(self):
self.customers_list = []
self.load_bank_data()
def load_bank_data(self):
customer_1 = Customer("Sam", "janos", ["14", "Wilcot Street", "Bath", "B5 5RT"])
account_no = 1234
account_1 = Account(5000.00, account_no)
customer_1.open_account(account_1)
self.customers_list.append(customer_1)
def customer_login(self, name, password):
if name in customers_list and password in customers_list:
self.name = name
self.password = password
self.customer_menu()
else:
print("sorry %s, it doesn't look like you are a customer"%name)
exit()
def main_menu(self):
print ("1) Customer login")
print (" ")
option = int(input ("Choose your option: "))
return option
def run_main_option(self):
loop = 1
while loop == 1:
choice = self.main_menu()
if choice == 1:
name = input ("\nPlease input customer name: ")
password = input ("\nPlease input customer password: ")
msg = self.customer_login(name, password)
print(msg)
person.py
class Person(object):
def __init__(self, name, password, address = [None, None, None, None]):
self.name = name
self.password = password
self.address = address
def get_address(self):
return self.address
def update_name(self, name):
self.name = name
def get_name(self):
return self.name
def print_details(self):
print("Name %s:" %self.name)
print("Address: %s" %self.address[0])
print(" %s" %self.address[1])
print(" %s" %self.address[2])
print(" %s" %self.address[3])
print(" ")
def check_password(self, password):
if self.password == password:
return True
return False
def profile_settings_menu(self):
#print the options you have
print (" ")
print ("Your Profile Settings Options Are:")
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print ("1) Update name")
print ("2) Print details")
print ("3) Back")
print (" ")
option = int(input ("Choose your option: "))
return option
def run_profile_options(self):
loop = 1
while loop == 1:
choice = self.profile_settings_menu()
if choice == 1:
name=input("\n Please enter new name\n: ")
self.update_name(name)
elif choice == 2:
self.print_details()
elif choice == 3:
loop = 0
customer.py
from person import Person
class Customer(Person):
def __init__(self, name, password, address = [None, None, None, None]):
super().__init__(name, password, address)
def open_account(self, account):
self.account = account
def get_account(self):
return self.account
def print_details(self):
super().print_details()
bal = self.account.get_balance()
print('Account balance: %.2f' %bal)
print(" ")
for customer in customers_list:
if customer.name == name:
if customer.password == password:
...