def readFromFile(): timeNow = datetime.today() timeStamp = timeNow.strftime("%Y%m%d%H%M%S") USBPath = findUSBMountPoint(USBDir, labelMatch, verbose) if not USBPath: LCDMessage = "No USB inserted" if verbose: print "\n*** Printing to LCD: \n %s" % LCDMessage displayOnLCD("", LCDMessage, verbose) onError(4, "No matching USB mounted") else: displayOnLCD("", "Reading files...", verbose) if verbose: print "\n*** Searching for files in %s ..." % USBDir foundFiles = [] for f in os.listdir(USBPath): if f.startswith("piSchoolBellDb-") and f.endswith(".csv"): foundFiles.append(os.path.join(USBPath, f)) if foundFiles: if verbose: print " %s files found:" % len(foundFiles) for f in foundFiles: print " %s" % f foundFiles = sorted(foundFiles, reverse=True) inFile = foundFiles[0] if verbose: print "\n*** %s\n is the latest" % inFile rowsInserted, rowsUpdated = importToDb( inFile, verbose) # import from file to database if rowsInserted: if verbose: print "\n*** %s rows inserted" % rowsInserted else: if verbose: print "\n*** Nothing inserted" if rowsUpdated: if verbose: print "\n*** %s rows updated" % rowsUpdated else: if verbose: print "\n*** Nothing updated" displayOnLCD("", "%s rows inserted" % rowsInserted, verbose) else: if verbose: print "*** No file found" displayOnLCD("", "No file found", verbose) sys.exit(0)
def commitToDB(con, verbose): if verbose: print("\n--- Committing changes to database") try: con.commit() except: onError(7, "Could not commit changes to database") else: return True
def sshCreateKey(verbose): if verbose: print("\n--- Checking if there is a key at " + rsaPublicKey) if os.path.isfile(rsaPublicKey): if verbose: print(" OK") keyFile = rsaPublicKey else: keyDir = os.path.dirname(rsaPublicKey) print( "\nCould not find key file at " + rsaPublicKey + "\n\nIf file is at other location, state full path, \nor leave empty to create key pair in\n" + rsaPublicKey) keyFile = input(" ? ") if keyFile: if not os.path.isfile(keyFile): keyDir = os.path.dirname(keyFile) keyFile = os.path.splitext(keyFile)[0] print( "\nCould not find that file either\nDo you want to create key pair at " + keyFile + "?") answer = input("n/Y") if answer.lower() != "n": print("\nWill create key pair at " + keyFile + "\n\n----------") else: keyFile = rsaPublicKey keyFile = os.path.splitext(keyFile)[0] print("\nWill create key pair at " + keyFile + "\n\n----------") keyDir = os.path.dirname(keyFile) if keyDir == "": keyDir = "./" if not os.path.isdir(keyDir): try: os.makedirs(keyDir, exist_ok=False) except: onError(6, ("Could not create directory " + keyDir)) cmd = "ssh-keygen -f " + keyFile runSubprocess(cmd, verbose) return keyFile
def dbConnect(dbHost, dbName, dbUser, dbPass, verbose): if verbose: print("\n--- Connecting ...\n host: " + dbHost + "\n database: " + dbName + "\n user: "******"\n using password " + dbPass) try: con = mdb.connect(host=dbHost, user=dbUser, passwd=dbPass, db=dbName) except mdb.Error as e: print("\nError %d: %s" % (e.args[0], e.args[1])) onError(3, "Could not connect to database") except: onError(4, "Could not connnect to database") return con
def findMedia(post, keepGoing, verbose): mediaList = [] if verbose: print "Post:" print post if "photos" in post: for line in post["photos"]: print "Original size url: \n%s" % line["original_size"]["url"] if verbose: print "Width x height: %s x %s" % (line["original_size"]["width"], line["original_size"]["height"]) mediaList.append(line["original_size"]["url"]) elif "video_url" in post: print "Video url: \n %s" % post["video_url"] mediaList.append(post["video_url"]) else: if not keepGoing: onError(5, "Did not find photos or video") return mediaList
def findMedia(post, keepGoing, verbose): mediaList = [] if verbose: print "Post:" print post if "photos" in post: for line in post["photos"]: print "Original size url: \n%s" % line["original_size"]["url"] if verbose: print "Width x height: %s x %s" % ( line["original_size"]["width"], line["original_size"]["height"]) mediaList.append(line["original_size"]["url"]) elif "video_url" in post: print "Video url: \n %s" % post["video_url"] mediaList.append(post["video_url"]) else: if not keepGoing: onError(5, "Did not find photos or video") return mediaList
def dumpToFile(): filesWritten = 0 timeNow = datetime.today() timeStamp = timeNow.strftime("%Y%m%d%H%M%S") USBPath = findUSBMountPoint(USBDir, labelMatch, verbose) if not USBPath: LCDMessage = "No USB inserted" if verbose: print("\n*** Printing to LCD: \n %s" % LCDMessage) displayOnLCD("", LCDMessage, verbose) onError(5, "No matching USB mounted") else: displayOnLCD("", "Writing files...", verbose) # database outFilePath = os.path.join(tempDir, "piSchoolBellDb-%s.csv" % timeStamp) if verbose: print("\n*** Creating file %s ..." % outFilePath) outFile = open(outFilePath, "a") # connect to database cnx = db_connect(verbose) # create cursor cursor = db_create_cursor(cnx, verbose) for table in ("breaks", "ringTimes", "ringPatterns", "days"): if verbose: print("\n*** Reading table %s..." % table) selection = tableSelection(table, verbose) query = "SELECT " + selection + " FROM " + table + " " result, rowCount = db_query(cursor, query, verbose) # run query if rowCount: if verbose: print("\n*** Table: %s" % table) columnNames = selection.replace(", ", ";") outFile.write("%s;%s\n" % (table, columnNames)) selection = selection.replace(" ", "").split(",") for row in result: i = 0 values = "" for columnName in selection: column = row[i] values = "%s;%s" % (values, column) if verbose: print(" %s: %s" % (columnName, column)) i += 1 outFile.write("%s\n" % values) if verbose: print() if verbose: print("\n*** Closing file %s ..." % outFilePath) outFile.close() if verbose: print("\n*** Moving file \n %s \n to \n %s" % (outFilePath, USBPath)) copy(outFilePath, USBPath) filesWritten += 1 # log files dirName, fileName, extension = splitPath(logFile, verbose) logFileName = os.path.join(USBPath, "%s-%s.%s" % (fileName, timeStamp, extension)) if verbose: print("\n*** Copying \n %s \n to \n %s ..." % (logFile, logFileName)) copyfile(logFile, logFileName) filesWritten += 1 if verbose: print(" %s" % gpioWatchLog) dirName, fileName, extension = splitPath(gpioWatchLog, verbose) gpioWatchLogName = os.path.join( USBPath, "%s-%s.%s" % (fileName, timeStamp, extension) ) if verbose: print( "\n*** Copying \n %s \n to \n %s ..." % ( gpioWatchLog, gpioWatchLogName, ) ) copyfile(gpioWatchLog, gpioWatchLogName) filesWritten += 1 # close cursor db_close_cursor(cnx, cursor, verbose) # close db db_disconnect(cnx, verbose) LCDMessage = "%s files written" % filesWritten if verbose: print("\n*** Printing to LCD: \n %s" % LCDMessage) displayOnLCD("", LCDMessage, verbose)
logFile, gpioWatchLog, splitPath, displayOnLCD, tableSelection, onError, usage, ) try: myopts, args = getopt.getopt( sys.argv[1:], "dr" "vh", ["dump", "read", "verbose", "help"] ) except getopt.GetoptError as e: onError(1, str(e)) # if len(sys.argv) == 1: # no options passed # onError(2, 2) dump = False read = False verbose = False for option, argument in myopts: if option in ("-d", "--dump"): # first line of LCD dump = True elif option in ("-r", "--read"): # verbose output read = True elif option in ("-v", "--verbose"): # verbose output verbose = True
logFile, internetAccess, testAddress, drygUri, drygPath) import getopt, sys, json, MySQLdb from datetime import date from dateutil.relativedelta import relativedelta from urlparse import urljoin from urllib2 import urlopen try: myopts, args = getopt.getopt(sys.argv[1:], 'm:' 'c' 'vh', ['months=', 'cron', 'verbose', 'help']) except getopt.GetoptError as e: onError(1, str(e)) if len(sys.argv) == 1: # no options passed onError(2, 2) addedDays = 0 updatedDays = 0 months = 12 logging = False verbose = False for option, argument in myopts: if option in ('-m', '--months'): try: months = int(argument) except:
writeToFile, ) import getopt, sys, MySQLdb from datetime import date from dateutil.relativedelta import relativedelta from urlparse import urljoin from urllib2 import urlopen try: myopts, args = getopt.getopt(sys.argv[1:], 'pc' 'vh', ['pretend', 'cron', 'verbose', 'help']) except getopt.GetoptError as e: onError(1, str(e)) if len(sys.argv) == 1: # no options passed onError(2, 2) logging = False purge = False verbose = False for option, argument in myopts: if option in ('-p', '--purge'): purge = True if option in ('-c', '--cron'): logging = True purge = True elif option in ('-v', '--verbose'):
# import modules from file modules.py from modules import (devicePath, rdserialCmd, deviceOn, deviceOff, setVolt, setAmps, useGroup, groupSettings, runSubprocess, onError, usage) # handle options and arguments passed to script try: myopts, args = getopt.getopt(sys.argv[1:], '10ls' 'V:A:g:' 'vh', [ 'on', 'off', 'load', 'status', 'volt=', 'ampere=', 'group=', 'verbose', 'help' ]) except getopt.GetoptError as e: onError(1, str(e)) # if no options passed, then exit if len(sys.argv) == 1: # no options passed onError(2, "No options given") on = False off = False loadGroup = False status = False group = 0 volt = 0 ampere = 0
import sys, getopt, os # import modules from file modules.py from modules import (onError, usage, outFile, videoTypes, audioTypes, checkOutFilePath, inDirCheck, findFiles, createPlaylist) # handle options and arguments passed to script try: myopts, args = getopt.getopt(sys.argv[1:], 'o:i:e:msravh', [ 'out=', 'indir=', 'extension=', 'movies', 'sound', 'recursive', 'absolute' 'verbose', 'help' ]) except getopt.GetoptError as e: onError(1, str(e)) # if no options passed, then exit #if len(sys.argv) == 1: # no options passed # onError(2, 2) outDir = os.getcwd() outFilePath = os.path.abspath(os.path.join(outDir, outFile)) inDir = outFilePath = os.path.abspath(os.getcwd()) checkInDir = False recursive = False findVideo = False findAudio = False
import sys, getopt from modules import onError, usage, checkDirectories, defaultDownloadDir, subDir, gifDir, videoDir from tumblr import authenticateClient, getPosts try: myopts, args = getopt.getopt(sys.argv[1:], 'b:' 'k' 'l' 'vh', ['blog:', 'keepgoing', 'log', 'verbose', 'help']) except getopt.GetoptError as e: onError(1, str(e)) if len(sys.argv) == 1: # no options passed onError(2, 2) verbose = False keepGoing = False writeLog = False for option, argument in myopts: if option in ('-b', '--blog'): blog = argument elif option in ('-k', '--keepgoing'): keepGoing = True elif option in ('-l', '--log'): writeLog = True
show = False connect = False edit = False verbose = False selections = 0 # handle options and arguments passed to script try: myopts, args = getopt.getopt( sys.argv[1:], "apscevh", ["add", "print", "show", "connect", "edit", "verbose", "help"], ) except getopt.GetoptError as e: onError(1, str(e)) # if no options passed, then connect if len(sys.argv) == 1: # no options passed print("Automatically selecting to connect") connect = True # onError(2, 2) # interpret options and arguments for option, argument in myopts: if option in ("-a", "--add"): # add connections create = True selections += 1 elif option in ("-p", "--print"): # print connections view = True selections += 1
def paramikoRunCmd(f_key, ip, port, username, cryptPasswd, cmd, verbose): import paramiko, base64 outputList = [] errorList = [] if verbose: print("\n--- Connecting with paramiko ...") rsaKeyFile = rsaPublicKey.strip(".pub") if verbose: print(" Using keyfile at " + rsaKeyFile) if verbose: print(" Generating host keys ...") host_key = paramiko.RSAKey.from_private_key_file(rsaKeyFile) public_host_key = paramiko.RSAKey(data=host_key.asbytes()) if verbose: print(" Setting up client ...") client = paramiko.SSHClient() # if verbose: # print(" Adding host keys ...") # client.get_host_keys().add(ip, "ssh-rsa", public_host_key) if verbose: print(" Setting missing host key policy ...") client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) if verbose: print(" Loading known hosts from " + knownHostsFile + " ...") client.load_host_keys(knownHostsFile) if verbose: print(" Connecting ...") try: client.connect( ip, port=int(port), username=username, password=decryptPassword(f_key, cryptPasswd, verbose), ) except paramiko.ssh_exception.SSHException as e: onError(7, str(e)) stdout = "" stderr = "" else: if verbose: print(" Running command ...") stdin, stdout, stderr = client.exec_command(cmd) if verbose: print("\n--- Output:") for line in stdout: outputList.append(line) if verbose: print(" " + line.strip("\n")) if verbose: print("\n--- Error:") for line in stderr: errorList.append(line) if verbose: print(" " + line.strip("\n")) if verbose: print("\n--- Closing client ...") client.close() return outputList, errorList
print("\n--- Table '" + tableName + "' does not exist") return False if __name__ == "__main__": setupDB = False con = False verbose = False # handle options and arguments passed to script try: myopts, args = getopt.getopt(sys.argv[1:], 'svh', ['setup', 'verbose', 'help']) except getopt.GetoptError as e: onError(1, str(e)) # if no options passed, then exit if len(sys.argv) == 1: # no options passed onError(2, 2) # interpret options and arguments for option, argument in myopts: if option in ('-s', '--setup'): # add connections setupDB = True elif option in ('-v', '--verbose'): # verbose output verbose = True elif option in ('-h', '--help'): # display help text usage(0) if setupDB:
# import modules from file modules.py from modules import (onError, usage, videoTypes, file_size, findVideos, printVideoInfo, findVideoBitrate) # handle options and arguments passed to script try: myopts, args = getopt.getopt(sys.argv[1:], 'fri' 'p:' 'vh', ['find', 'recursive', 'info', 'vbr=', 'path=', 'verbose', 'help']) # handle module errors except getopt.GetoptError as e: onError(1, str(e)) # if no options passed, then exit if len(sys.argv) == 1: # no options passed onError(2, "No options given") # initialize variables find = False recursive = False info = False videoBitrate = False path = False verbose = False # interpret options and arguments for option, argument in myopts:
# Encoding: UTF-8 import sys, getopt, os, ConfigParser from modules import onError, usage, findFiles, doRename from genericpath import isfile try: myopts, args = getopt.getopt(sys.argv[1:], 'c:p:ro:n:e:yvh', ['configfile=', 'path=', 'recursive', 'oldpattern=', 'newpattern=', 'extensions=', 'yes', 'verbose', 'help']) except getopt.GetoptError as e: onError(1, str(e)) #if len(sys.argv) == 1: # no options passed # onError(2, 2) configFileName = "" searchPath = os.path.abspath(os.getcwd()) recursive = False oldPattern = "" newPattern = "" extensions = "*Files" yesToQuestions = False verbose = False for option, argument in myopts: if option in ('-c', '--configfile'):
db_connect, db_create_cursor, db_close_cursor, db_disconnect, db_query, bellRelayGpio, onError, ) try: myopts, args = getopt.getopt( sys.argv[1:], "d:" "t:" "vh", ["date=", "time=", "verbose", "help"] ) except getopt.GetoptError as e: onError(1, str(e)) # if len(sys.argv) == 1: # no options passed # onError(2, 2) dateNow = "" timeNow = "" verbose = False for option, argument in myopts: if option in ("-d", "--date"): dateNow = argument if option in ("-t", "--time"): timeNow = argument elif option in ("-v", "--verbose"): # verbose output verbose = True
from modules import (db_connect, db_create_cursor, db_close_cursor, db_disconnect, db_query, initialize_lcd, print_to_LCD, remove_leading_zero, random_chars, active_schedules, active_devices, process_schedules, onError, usage) try: myopts, args = getopt.getopt(sys.argv[1:], 'l' '1:2:' 'g:' 'vh', ['line1=', 'line2=', 'gpio=', 'light', 'verbose', 'help']) except getopt.GetoptError as e: onError(1, str(e)) if len(sys.argv) == 1: # no options passed onError(2, 2) light = False line_1 = "" line_2 = "" gpio = False toggleMode = False toggleTimer = False stopModeTimer = False verbose = False for option, argument in myopts: if option in ('-l', '--light'): # turn backlight on
def changeValue(ip, option, oldValue, connectionFile, show, verbose): if verbose: print("\n--- Changing value for " + option.lower() + " \n in section [" + ip + "]") if verbose: print("\n--- Reading config file ...") config = configparser.ConfigParser() config.read(connectionFile) # read config file print("\nOld " + option.lower() + ": " + oldValue) if option.lower() == "hostname": if verbose: print("\n--- Asking " + ip + " for hostname ...") try: hostname = socket.gethostbyaddr(ip)[0] except: hostname = "" onError(4, "Could not get hostname") else: if verbose: print(" OK\n Got " + hostname) while True: # input host name if hostname: print("\nHost name") newValue = input("[" + hostname + "] ? ") if not newValue: # if no value stated newValue = hostname else: print("\nHost name") newValue = input("[" + oldValue + "] ? ") if not newValue: newValue = oldValue if newValue == oldValue: newValue = oldValue print("\nYou've entered the same " + option.lower() + " again\nKeep old " + option.lower() + "?") correct = input("(Y/n) ? ") if correct.lower() != "n": # if anything but 'n' was stated print("\nKeeping old " + option.lower()) break else: if ( not newValue and not hostname ): # if no host name stated and we could not probe a hostname print("\nYou must state a hostname\nTry again") elif (not newValue and hostname ): # if no hostname stated and we could probe a hostname newValue = hostname break elif newValue: break else: newValue = oldValue break # break out of while loop elif option.lower() == "port": while True: # input port print("\nRemote port") newValue = input("[" + oldValue + "] ? ") if not newValue: # if no port stated use old port newValue = oldValue if newValue == oldValue: newValue = oldValue print("\nYou've entered the same " + option.lower() + " again\nKeep old " + option.lower() + "?") correct = input("(Y/n) ? ") if correct.lower() != "n": # if anything but 'n' was stated print("\nKeeping old " + option.lower()) break else: try: newValue = int( newValue ) # raises an exception if port is not an integer except: print("\n" + str(newValue) + "is not an integer\nTry again") else: if verbose: print("\n--- Checking if port is valid ...") if (newValue >= 0 and newValue <= 65535): # port must be between 0 and 65535 if verbose: print(" OK") newValue = str(newValue) break # break out of while loop else: print("\n" + str(newValue) + " is outside the range 0-65535\nTry again") if oldValue != newValue: print("\nChanging " + option.lower() + " from " + oldValue + " to " + newValue) if verbose: print("\n--- Writing new value ...") config.set(ip, option, newValue) if verbose: print(" Writing to config file ...") with open(connectionFile, "w") as configfile: config.write(configfile) # write everything to config file else: print("\nNo changes made")
def createConnection(f_key, connectionFile, show, verbose): print("\nCreate new connection\n----------") defaultIP = get_ip() # this computers IP hostname = "" defaultPort = "22" defaultUser = getuser() # user running this script defaultPasswd = "xxxxx" newSection = False sectionNo = 1 if verbose: print("\n--- Reading config file ...") config = configparser.ConfigParser() config.read(connectionFile) # read config file oldSections = config.sections() print("\n1: Add new") for oldIP in oldSections: sectionNo += 1 oldPort = config.get(oldIP, "port") oldHostname = config.get(oldIP, "hostname") print(str(sectionNo) + ": " + oldIP + ", " + oldHostname) print("\nEnter number:") while True: selection = input("(1) ? ") if not selection: selection = 1 break else: try: selection = int(selection) except: print("\nOnly integers allowed\nTry again:") else: if selection <= 0 or selection > sectionNo: print("Number must be 1-" + str(sectionNo)) else: break if selection == 1: newSection = True else: ip = oldIP hostname = oldHostname port = oldPort print("\nHostname: " + hostname) print("Port: " + str(port)) while True: # section loop, run until all users are added if newSection: # if select new section, continue here while True: # ip loop, run until all users are added print("\nRemote IP") ip = input("[" + defaultIP + "] ? ") if not ip: # if no IP stated, accept default IP ip = defaultIP ipValid = False isURL = False if verbose: print("\n--- Checking if " + ip + " is a valid IPv4 ...") if not validators.ip_address.ipv4(ip): if verbose: print(" Not a valid IPv4") else: if verbose: print(" OK\n Is a valid IPv4") ipValid = True if not ipValid: if verbose: print("\n--- Checking if " + ip + " is a valid IPv6 ...") if not validators.ip_address.ipv6(ip): if verbose: print(" Not a valid IPv6") else: if verbose: print(" OK\n Is a valid IPv6") ipValid = True if not ipValid: if verbose: print("\n--- Checking if " + ip + " is a valid domain ...") if not validators.domain(ip): if verbose: print(" Not a domain") else: if verbose: print(" OK\n Is a valid domain") isURL = True ipValid = True if not ipValid: if verbose: print("\n--- Checking if " + ip + " is a valid URL ...") if not validators.url("http://" + ip): if verbose: print(" Not a URL") else: if verbose: print(" OK\n Is a valid URL") isURL = True ipValid = True if ipValid: if verbose: print("\n--- Checking if " + ip + " is already in sections ...") for existingIP in oldSections: if existingIP == ip: if verbose: print(" Found matching ip") else: print( "\n" + ip + " is already added\nUsing old hostname and port" ) oldPort = config.get(oldIP, "port") oldHostname = config.get(oldIP, "hostname") if verbose: print(" Using old hostname " + oldHostname + " and port " + oldPort) newSection = False break # break out of ip loop else: print( "\n" + ip + "is not\n a valid IPv4 address,\n a valid IPv6 address,\n a valid domain name,\n a valid URL" ) print("Try again") if verbose: print("\n--- Asking " + ip + " for hostname ...") if isURL: if verbose: print("\n--- Trying to resolve " + ip + " ...") try: domain, data, domainIP = socket.gethostbyname_ex(ip) except: print("\nCould not get hostname") else: probeIP = domainIP[0] if verbose: print(" OK\n Got IP " + probeIP) else: probeIP = ip try: hostname = socket.gethostbyaddr(probeIP)[ 0] # probe for hostname except: hostname = "" onError(4, "Could not get hostname") else: if verbose: print(" OK\n Got " + hostname) if newSection: while True: # hostname loop, input host name if hostname: # if hostname could be probed print("\nHost name") newHostname = input("[" + hostname + "] ? ") else: print("\nHost name") newHostname = input(" ? ") if (not newHostname and not hostname ): # if no hostname stated and no hostname could be probed print("\nYou must state a hostname\nTry again") elif (not newHostname and hostname ): # if no hostname stated but hostname was probed break else: hostname = newHostname break # break out of hostname loop if newSection: while True: # port loop, input port print("\nRemote port") port = input("[" + defaultPort + "] ? ") if not port: # if no port stated use default port port = defaultPort try: port = int( port) # raises an exception if port is not an integer except: print("\n" + str(port) + "is not an integer\nTry again") else: if verbose: print("\n--- Checking if port is valid ...") if port >= 0 and port <= 65535: # port must be between 0 and 65535 if verbose: print(" OK") break # break out of port loop else: print("\n" + str(port) + " is outside the range 0-65535\nTry again") userNo = 0 # stores number of users to be added userList = [] # stores user names to be added passwdList = [] # stores passwords to be added cryptPasswdList = [] # stores the encrypted passwords to be added while True: # user-pass loop, add users and passwords userNo += 1 # count up number of users to be added jumpToAdd = False while True: # username loop, input username print("\nUsername " + str(userNo)) username = input("(" + defaultUser + ")/q ? ") if not username: # if no username given accept the default one username = defaultUser elif username.lower() == "q": jumpToAdd = True break # break out of username loop else: defaultUser = username isNewUser = True if verbose: print("\n--- Checking if " + username + " is already in add-list ...") if (username in userList ): # if the username is already given in this session isNewUser = False print("\nUsername already in list\nTry again") else: if verbose: print(" OK\n User not in list") if verbose: print("\n--- Checking if " + username + " is already in connections ...") print(" Trying to read usernames from connections") try: options = config.options(ip) except: if verbose: print(" No section for ip " + ip) # break # this username not added in this session and ip not in connections else: for option in options: if option.startswith("username"): if config.get(ip, option) == username: isNewUser = False if verbose: print(" Username " + username + " already in connections") else: if verbose: print( " No matches found in connections" ) if isNewUser: if verbose: print(" Adding " + username + " to add-list") userList.append(username) # append username to list break # break out of while loop else: print("\nUsername already exists for this IP\nTry again") if jumpToAdd: break # break out of user-pass loop else: while True: # password loop, input password print("\nPassword " + str(userNo)) if show: passwd1 = input("[" + defaultPasswd + "] ? ") # enter password invisible else: passwd1 = getpass("[" + defaultPasswd + "] ? ") # enter password visibly if not passwd1: # if no password is given accept the default one passwd1 = defaultPasswd print("\nEnter password " + str(userNo) + " again") if show: passwd2 = input("[" + defaultPasswd + "] ? ") # enter password invisible else: passwd2 = getpass("[" + defaultPasswd + "] ? ") # enter password visibly if not passwd2: # if no password is given accept the default one passwd2 = defaultPasswd if (passwd1 == passwd2 ): # check if the same password was given both times passwdList.append(passwd1) # append password to list break # break out of password loop else: print("\nPasswords do not match\nTry again") print("\nDo you like to add another user") # add another user? addUser = input("(y/N) ? ") if addUser.lower() != "y": # if anything but 'y' was given break # break out of user-pass loop else: # reset variables username = "" passwd1 = "" passwd2 = "" if newSection or len(userList) >= 1: # encrypt passwords if verbose: print("\n--- Encrypting passwords ...") for i in range(0, len(userList)): cryptPasswdList.append( encryptPassword(f_key, passwdList[i], show, verbose)) # cryptPasswdList.append(f_key.encrypt(passwdList[i].encode())) # encrypt password and append to encrypted password as bytes # display all values and ask if correct print("\nNew connection:\n----------") print("IP: " + ip) print("Host name: " + hostname) print("Port: " + str(port)) for i in range(0, len(userList)): if show: print("\nUser " + str(i + 1) + ": " + userList[i]) print("Pass " + str(i + 1) + ": " + passwdList[i]) else: print("\nUser " + str(i + 1) + ": " + userList[i]) print("Pass " + str(i + 1) + ": " + cryptPasswdList[i]) print("\nIs this correct") correct = input("(Y/n/q) ? ") if correct.lower() == "q": # if 'q' then exit print("\nExiting ...") sys.exit(0) elif correct.lower() == "n": # if anything but 'n' was stated break # break out of loop else: for i in range(0, len(userList)): # encrypt passwords cryptPasswd = cryptPasswdList[i] # encrypted password if verbose: print("\n--- Encrypted password " + str(i + 1) + ": " + cryptPasswd) if show: print("\n--- Plain text password " + str(i + 1) + ": " + decryptPassword(f_key, cryptPasswd, verbose)) print("\nAdding new connection ...") writeConnections( f_key, connectionFile, ip, hostname, port, userList, cryptPasswdList, show, verbose, ) break else: print("\nNothing to add\n\nNo changes made") break # break out of section loop