def repair_user_desktop(): password = getpass("Enter the admin password: "******"Make sure the student is logged out before running this repair.\n") fullname, username = user_utils.get_and_confirm_user() if not fullname: return False home_dir = "/nfshome/{}".format(username) # First, make sure their home drive exists. Sometimes home drive creation fails when # creating new users in bulk! if ssh_connection.dir_exists(home_dir): command = "rm -r {}/.cache".format(home_dir) ssh_connection.send_cmd(command, sudo=True) print("I tried to delete their cache. That usually solves the problem...") utils.print_success("Have the student try logging in again.") else: # no home drive! Need to make it utils.print_warning("AH! It appears they don't have a home drive! I gonna try to create one for them now...") command = "bash /nfshome/makehomedirs.sh {}".format(username) ssh_connection.send_cmd(command, sudo=True) utils.print_success("Have the student try logging in again.") ssh_connection.close()
def refresh_slideshow(username=None): if not username: username = utils.input_styled("Enter username: \n") # connects and checks to see if file with the same name already exisits ssh_connection = SSH(TV_FILE_SERVER, TV_FILE_SERVER_USER, TV_FILE_SERVER_PW) print("Updating movie maker script...") copy_movie_maker_to_host(ssh_connection) # Cycle through TV directories to find student folder for tv in range(1, 5): filepath = "{}/tv{}/".format(TV_ROOT, tv) command = 'ls {}'.format(filepath) dir_contents = ssh_connection.send_cmd(command, print_stdout=False).split() if username in dir_contents: utils.print_success("Found art for {} on TV# {}".format( username, tv)) # refresh the video utils.print_warning( "\nGonna regenerate video slideshow now, THIS MIGHT TAKE A WHILE!" ) generate_new_movie_file(ssh_connection, username, tv) return True utils.print_error( "\nSorry, I could find art for {}. Are you sure they have art uploaded to the server?" .format(username)) return None
def get_next_avail_uid(start: int = None) -> int: """Check if {start} is available as a uid, then increase by one untill an available uid is found. If no {start} is provided, then the first number will be the two-digit year followed by three zeros. E.g. in 2022 -> start = 22000 Keyword Arguments: start {int} -- The uid to check first (default: {None}) """ if start is None or start < 1000: # last two digits of current year x 1000, e.g. 2021 -> 21000 start = int(date.today().strftime('%y')) * 1000 if start < 1000: utils.print_warning("uid should be > 1000, using the default instead: {}".format(start)) # get list of all users next_uid = start while True: try: next_uid = pwd.getpwuid(next_uid).pw_uid # print(next_uid) next_uid += 1 except KeyError: # new uid found! break return next_uid
def archive_users(): ssh_connection = SSH(hostname, SERVER_USERNAME) for p in pwd.getpwall(): username = p[0] user_id = pwd.getpwnam(username).pw_uid account_creation_year = int(str(user_id)[:2]) is_not_system_user = 1000 < user_id < 60000 is_older_than_five_years = current_year - account_creation_year >= 5 if is_not_system_user and is_older_than_five_years: utils.print_error( f"Wiping home drive of user {user_id}: {username}\n") confirmation = utils.input_styled( "Are you sure you wish it proceed? [y/N] (q to quit): \n") if confirmation[0].lower() == "y": ssh_connection.send_cmd(f"rm -rf {home_root}{username}/", sudo=True) utils.print_warning(f'deleted {home_root}{username}/') skeleton = f"bash /nfshome/makehomedirs.sh {username}" ssh_connection.send_cmd(skeleton, sudo=True) utils.print_warning( f'place skeleton to {home_root}{username}/') if ssh_connection.dir_exists(f"{home_root}{username}"): utils.print_success( "User was successfully archived, skeleton placed.") else: utils.print_error( "FATAL: Unable to archive user (no home_dir)") elif confirmation == "q": break else: pass
def pip_install(): utils.print_warning( "Checking to see if all necassary pip modules are installed. \n") pipmain(['install', 'paramiko']) pipmain(['install', 'inquirer']) utils.print_success("Everything is installed!") os.system('clear')
def transfer_files(home_dir, dir, connection): if connection.dir_exists(f"{home_dir}.bu/{dir}"): transfer_desk = f"cp -R {home_dir}.bu/{dir} {home_dir}" connection.send_cmd(transfer_desk, sudo=True) utils.print_success(f"✓ Recovered {dir}") else: utils.print_warning(f"✗ {dir} not found")
def guess_tv(username): # First, see if they already have art on a TV tv = get_tv_containing_student(username) # If they don't already have one, then guess based on their last name if tv is None: name = user_utils.get_users_name(username) if name is None: utils.print_error( "I don't recognize the username '{}'. It could be because they don't have an account in the Hackerspace with this username. You can continue anyway tho." .format(username)) return None # Last name A-M = 1, N-Z = 2 # name variable will be fullname, split on spaces and take last element lastname = name.split()[-1] if lastname[0].lower() <= 'M': utils.print_warning( "Suggesting TV 1 because their last name, {}, is A-M".format( lastname)) tv = 1 else: utils.print_warning( "Suggesting TV 2 because their last name, {}, is N-Z".format( lastname)) tv = 2 return tv
def repair_user_desktop(): ssh_connection = SSH(hostname, username) print_warning("Make sure the student is logged out before running this repair.\n") student_number = input_styled("Enter Student Number: \n") command = "rm -r /nfshome/{}/.cache".format(student_number) ssh_connection.send_cmd(command, sudo=True) print_success("Have the student log in again. Their cache should be cleared now.") ssh_connection.close()
def delete_files(location, ssh_connection, name_glob=None, size=None): command = generate_find_command(location, name_glob, size) command += " -delete" # run bash as sudo so wildcards are expanded as sudo and will have permissions to expand into all directories result = ssh_connection.send_cmd(f"bash -c '{command}'", sudo=True) if "No such file or directory" in result: utils.print_warning("Nothing found to delete.") return False else: utils.print_success("Deleted.") return True
def add_user_to_group(username, group, password=None): if not password: password = getpass("Enter the admin password: "******"ldapaddusertogroup {username} {group}" success = ssh_connection.send_cmd(command, sudo=True) if success: utils.print_warning("The user will probably need to log out and back in again before the changes take effect.") return success
def regenerate_all_slideshows(): utils.print_warning( "This takes a LONG time, best to start this after school to let it run for few hours!" ) do_it = utils.confirm( "Are you sure you want to recreate all the slideshow videos?", yes_is_default=False) if not do_it: return # connects and checks to see if file with the same name already exisits ssh_connection = SSH(TV_FILE_SERVER, TV_FILE_SERVER_USER, TV_FILE_SERVER_PW) print("Updating movie maker script...") copy_movie_maker_to_host(ssh_connection) # Cycle through TV directories for tv in range(1, 5): filepath = "{}/tv{}/".format(TV_ROOT, tv) command = 'ls {}'.format(filepath) dir_contents = ssh_connection.send_cmd(command, print_stdout=False).split() for student_number in dir_contents: # TODO: check if it's a directory or not, skip non-directories test_dir_cmd = "test -d {}{}{} || echo nope".format( filepath, os.sep, student_number) not_a_dir = ssh_connection.send_cmd(test_dir_cmd, print_stdout=False) # note this is an empty string if dir exists if not_a_dir: continue # skip to next one utils.print_success("Found art folder for {} on TV# {}".format( student_number, tv)) # refresh the video utils.print_warning( "\nGonna regenerate video slideshow now, THIS MIGHT TAKE A WHILE!" ) generate_new_movie_file(ssh_connection, student_number, tv, silent=True) utils.print_success("\nFinished TV #{}\n".format(tv)) utils.print_success("Done!")
def setup_stormLauncher(): utils.print_warning( "\nSTORMLAUNCHER has not been installed on this profile yet. I'm gonna install it for you now...\n" ) os.chdir(STORM_LAUNCHER_LOCATION) os.mkdir(STORM_LAUNCHER_DIR) os.chdir(STORM_LAUNCHER_DIR) subprocess.run( "git clone https://github.com/timberline-secondary/stormLauncher.git", shell=True, check=True) os.chdir(CODE_DIR) print(os.getcwd()) # create virtual environment and install dependancies to it so launch script works subprocess.run("bash setup.sh", shell=True, check=True) utils.print_warning("\n...Install complete. LETS DO THIS!\n")
def quick_puppet_run(auto_fix_certificates=False, computer_number=None): password = getpass("Enter the admin password: "******"Enter the computer numbers, seperated by spaces \n" "(where # is from hostname tbl-h10-#-s e.g: 2 15 30)\n" " or 'all' to run on all computers: ") num_list = numbers.split() if num_list[0] == "all": num_list = [ f"{i}" for i in range(0, 32) ] # list of strings. 0 will cause problem if int instead of str for num in num_list: utils.print_warning("Trying computer #{}...".format(num)) puppet_run(num, password, auto_fix_certificates=True)
def puppet_clear_certificates(hostname=None, password=None): if password is None: password = getpass("Enter the admin password: "******"Which computer? (e.g. 'tbl-h10-12', or '192.168.3.125' or [q]uit) ") if hostname == 'q': print("Quitting this.") return None remove_server_cert_cmd = "/opt/puppetlabs/bin/puppetserver ca clean --certname {}.hackerspace.tbl".format(hostname) ssh_connection_puppet = SSH(puppet_host, username, password) ssh_connection_puppet.send_cmd(remove_server_cert_cmd, sudo=True) ssh_connection_puppet.close() utils.print_warning("Ok, I tried to remov the old certificates from the puppet server.")
def get_and_confirm_user(username=None): """ Ask for a username (if not provided) and checks if it exists. If it does, returns a tuple of (fullname, username), if it does not, will return None, username """ if not username: username = utils.input_styled("Enter username: "******"I couldn't find an account for user {}.".format(username)) return None, username else: utils.print_success("Found {}: {}.".format(username, fullname)) is_correct_user = utils.confirm("Is this the correct student?", yes_is_default=False) if is_correct_user: return fullname, username else: return None, username
def check_for_disconnected_pis(password=None): # if password is None: # password = getpass("Enter the admin password: "******"nmap", "-sn", "192.168.43.0/24"] output = subprocess.run(cmd, capture_output=True, text=True).stdout # run twice, cus the pis seem to get sleepy and don't show up the first time, sometimes?! output = subprocess.run(cmd, capture_output=True, text=True).stdout found_at_least_one = False for pi in PI_LIST: if pi not in output: utils.print_warning( f"Pi named '{pi}' was not found connected to the network.") found_at_least_one = True if not found_at_least_one: utils.print_success(f"All the pis were found on the network:") print(f"\t{str(PI_LIST)}")
def reinstall_graphics_drivers(): password = getpass("Enter the admin password: "******"Enter the computer numbers, seperated by spaces (where # is from hostname tbl-h10-#-s e.g: 2 15 30): " ) num_list = numbers.split() for num in num_list: utils.print_warning("Trying computer #{}...".format(num)) good_host = False computer_host = "tbl-h10-{}-s".format(num) good_host = utils.host_exists(computer_host) if not good_host: # this computer # doesn't exist or can't connect utils.print_error( "Host not found. Does that computer exist? Is it on?") continue # now that we know we have a good host, ssh into it and try to run puppet ssh_connection = SSH(computer_host, username, password) nvidia_cmd = "bash /opt/NVIDIA-Linux-x86_64-430.50.run --disable-nouveau --run-nvidia-xconfig --no-x-check --silent" utils.print_warning = "Running command: {}".format(nvidia_cmd) utils.print_warning = "This may take a minute..." output = ssh_connection.send_cmd(nvidia_cmd, sudo=True) if "ERROR" in output: utils.print_error("It looks like something went wrong. Sorry!") print(output) else: utils.print_success( "It looks like it worked. Don't worry about those warnings. I'm going to try to restart computer #{}" .format(num)) output = ssh_connection.send_cmd("/sbin/shutdown -r now", sudo=True) utils.print_success("\nComplete\n\n") ssh_connection.close()
def get_new_username() -> str: """Asks for a new username and checks if it already exists or not Returns: str -- the username if it's new, or {None} if it already exists or bad username """ username = utils.input_styled( "What is the new username? (must start with a letter, then any combo of letters, numbers, or _-.) ") username = username.lower().strip() # make sure it's valid if not re.match(r'^[a-zA-Z][\w\-._]+$', username): utils.print_error("Invalid username {}".format(username)) return None # does user exist already? if utils.user_exists(username): fullname = get_users_name(username) utils.print_warning("The username {} already exists for {}.".format(username, fullname)) return None else: return username
def change_username(current_username=None, new_username=None, auto=False, password=None): utils.print_warning( "\nMake sure the student is logged out before making this change!\n") if not current_username: fullname, current_username = user_utils.get_and_confirm_user() if not fullname: return False if not new_username: new_username = user_utils.get_new_username() if not new_username: return False if not auto: if not utils.confirm( f"Confirm you want to change {current_username} to {new_username}?", yes_is_default=False): print("Bailing...") return False if not password: password = getpass("Enter the admin password: "******"sudo ldaprenameuser {} {}".format(current_username, new_username) ssh_connection.send_cmd(command, sudo=True) ssh_connection.close() utils.print_warning( "Now gonna change the name of their home directory to match the new username" ) ssh_connection = SSH(file_hostname, username, password) command = "mv /nfshome/{} /nfshome/{}".format(current_username, new_username) ssh_connection.send_cmd(command, sudo=True) ssh_connection.close() utils.print_success("Done!") utils.print_warning("Now gonna tell LDAP where the new home directory is") user_utils.modify_user(new_username, {'homeDirectory': f'/home/{new_username}'}, password) return True
def count_files(location, ssh_connection, name_glob=None, size=None): command = generate_find_command(location, name_glob, size) command += " | wc -l" utils.print_warning(f"Searching for files with: {command}") # use double quotes as command may have single quotes within result = ssh_connection.send_cmd(f'bash -c "{command}"', sudo=True) # strip newlines from end of resulting output num = re.search( r'\d+$', result.strip()).group() # get the number at the end of the output if num == '0': # e.g. find: ‘/home/username/Downloads/*’: No such file or directory\n0 utils.print_warning("No files found, skipping.") else: utils.print_warning(f"Found {num} files and directories to delete.") return int(num)
def add_new_users_csv_import(): utils.print_warning(""" Importing new users in bulk requires a csv file with at least these two fields (extra fields are ok): Name, Email1 "Bloggins, Jimmy", "*****@*****.**" ...etc There should be no headings row, just students. Usernames can include @stu.sd72.bc.ca or not. If it is included, it will be removed and only firstname.lastname will be used for their username """) print("""To get this list from MyEd: 1. Go to the Students tab 2. Click the filter and choose Students in My Classes 3. Select the grid icon beside the filter and choose EMAIL STUDENT SD72... 4. Click the print icon and choose CSV 5. Save the file to your Downloads as StudentList.csv """) # Get a CSV file and read it: while True: utils.print_warning( "If the csv file is not in the default location you'll have to tell me where it is, and what it's called, e.g:") utils.print_warning('"/home/myusername/Documents/students.csv"') student_csv_file = utils.input_plus('Where can I find the csv file?', default_csv_location) if student_csv_file == 'q': return if os.path.isfile(student_csv_file): # good, carry on with script break else: utils.print_error("I couldn't find this file: {} ".format(student_csv_file)) password = getpass("Enter the admin password: "******"" name_heading = "Name" email_heading = "Email1" ssh_connection = ssh.SSH(hostname, server_username, password) with open(student_csv_file) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') name_column = None email_column = None for row in csv_reader: if name_column is None: # then this is the header row try: name_column = row.index(name_heading) email_column = row.index(email_heading) except ValueError: # column doesn't exist ssh_connection.close() return False else: try: username = parse_username_from_email(row[email_column]) except IndexError: # Probably blank lines at the end of the list, or missing data? Even missing data should be a blank string print("Skipping line. Blank line at end of list or missing student email field.") continue # Check if user already exists or not if utils.user_exists(username): utils.print_warning("This user already exists: {}".format(username)) continue # go to next user # Name column is in format: "Lastname, Firstname" first_name = row[name_column].split(",")[1] last_name = row[name_column].split(",")[0] add_new_user( username, first_name=first_name, last_name=last_name, password=password, ssh_connection=ssh_connection, bulk_creation=True, ) # next_uid = get_next_avail_uid() # ldif_entry += generate_ldif_entry(username, first_name, last_name, next_uid) + "\n" # success = create_users_from_ldif(ldif_entry, password=password) # create home dir for new user # if success: # return create_home_dirs([username], password) ssh_connection.close() print("All done!")
def add_new_user(): created = False while not created: student_number = utils.input_styled("Enter Student Number: \n") password = getpass("Enter the admin password: "******"An account for {}, {}, already exists. Try resetting their password." .format(student_number, student)) else: first_name = utils.input_styled("First Name: \n").upper() last_name = utils.input_styled("Last Name: \n").upper() create = utils.input_styled( "Create account for {} {} {}? y/[n] \n".format( student_number, first_name, last_name)) if create == 'y': ssh_connection = SSH(hostname, username, password) main_command = 'bash hs-ldapadduser.sh "{}" "{}" "{}"'.format( student_number, first_name, last_name) command_response_list = [ ("cd hs-ldap/", ":~/hs-ldap$", None), (main_command, "[sudo] password for hackerspace_admin: ", None), (password, "Enter LDAP Password: "******"hackerspace_admin@tyrell's password: "******"[sudo] password for hackerspace_admin: ", None), (password, ":~/hs-ldap$", "Set owner on: /nfshome/{}".format(student_number)), ] success = ssh_connection.send_interactive_commands( command_response_list) ssh_connection.close() if success: utils.print_success( 'Successfully created account for {} {} {}'.format( student_number, first_name, last_name)) utils.print_success( 'Their default password will be "wolf"') created = True else: utils.print_error( "Something went wrong there, hopefully useful info is printed above...let's try again\n" ) else: print("Aborted that one. \n") if utils.input_styled("Try again? [y]/n: ") == 'n': return input("\nHit enter to continue...\n")
def add_new_media(username=None, tv=None): media_url = True while media_url: # gets and checks the url of the file media_url, name_without_ext, extension = get_media_url() if media_url is None: return # collects information to name the file, and as to which tv to send it to username_input = utils.input_styled( "Enter username (default = {}): \n".format(username)) if not username_input: pass else: username = username_input tv = guess_tv(username) tv_input = utils.input_styled( "What TV # are you sending this to? (default = {}): ".format(tv)) if not tv_input: pass else: tv = tv_input image_name = None name_good = utils.input_styled( "What is the name of this image? (default = {}): ".format( name_without_ext)) if not name_good: image_name = name_without_ext else: image_name = name_good filename = username + ".z." + image_name + extension # Save videos directly in the tv's rtoot directory. if is_video(extension.lower()): filepath = "{}/tv{}/".format(TV_ROOT, tv) # Save images into a subfolder, which will be used to generate a slideshow video else: filepath = "{}/tv{}/{}/".format(TV_ROOT, tv, username) utils.print_warning( "Sending {} to hightower to see if file exists already with that name." .format(filename)) # connects and checks to see if file with the same name already exisits ssh_connection = SSH(TV_FILE_SERVER, TV_FILE_SERVER_USER, TV_FILE_SERVER_PW) already_exists = ssh_connection.file_exists(filepath, filename) # if it does exist, asks user if they want to overwrite it while already_exists and not utils.confirm( "There is a file that already exists with that name. Do you want to overwrite it?", yes_is_default=False): # don't want to overwrite, so get a new name: image_name = utils.input_styled( "Provide a different name for the image: ") filename = username + ".z." + image_name + extension # check again already_exists = ssh_connection.file_exists(filepath, filename) command = "wget -O {}{} '{}' && exit".format(filepath, filename, media_url) # make sure the directory exists, if not create it: if not ssh_connection.file_exists(filepath): ssh_connection.send_cmd('mkdir {}'.format(filepath)) success = ssh_connection.send_cmd(command) if success: utils.print_success( "{} was succesfully sent over to pi-tv{}".format(filename, tv)) else: utils.print_error( "Something went wrong. Check the filename, is it wonky with weird characters?" ) # asks user if they want to add another image if utils.confirm("Would you like to add another image?"): media_url = True else: break ssh_connection.close() if utils.confirm( "Do you want to generate a new video slideshow of this student's art?" ): refresh_slideshow(username=username)
def refresh_user(): utils.print_warning( "This will refresh a user's account by removing all their customizations and settings. However their files/documents will remain. This can be used if the user is experiences UI issues or having other weird problems with their account." ) password = getpass("Enter the admin password: "******"ENSURE THE USER IS LOGGED OUT BEFORE PERFORMING THIS ACTION!\n") fullname, username = user_utils.get_and_confirm_user() if not fullname: return False home_dir = f"/nfshome/{username}" # First, make sure their home drive exists. Sometimes home drive creation fails when # creating new users in bulk! if ssh_connection.dir_exists(home_dir): move = f"mv {home_dir} {home_dir}.bu" ssh_connection.send_cmd(move, sudo=True) utils.print_success(f"✓ Backing up home drive") skeleton = f"bash /nfshome/makehomedirs.sh {username}" ssh_connection.send_cmd(skeleton, sudo=True) utils.print_success(f"✓ Created skeleton") for dir in dirs: transfer_files(home_dir, dir, ssh_connection) if ssh_connection.dir_exists(home_dir): utils.print_success(f"✓ All files have been recovered") remove_backup = f"rm -rf {home_dir}.bu" ssh_connection.send_cmd(remove_backup, sudo=True) utils.print_success(f"✓ Removing old backup") change_ownership = f"chown -R '{username}:students' '{home_dir}'" ssh_connection.send_cmd(change_ownership, sudo=True) utils.print_success(f"✓ Changed ownership root → {username}") utils.print_success( "Operation complete, please have the user log back in.") else: utils.print_error( f"✗ New home directory does not exist, reverting to backup.") revert_to_backup = f"mv {home_dir}.bu {home_dir}" ssh_connection.send_cmd(revert_to_backup, sudo=True) if ssh_connection.dir_exists(home_dir): utils.print_error( "Reverted to backup successfully (No changes).") else: utils.print_error( "FATAL (PANIC): Error while creating new home directory, could not revert to backup. (No home directory exists)" ) panic = f"bash /nfshome/makehomedirs.sh {username}" ssh_connection.send_cmd(panic, sudo=True) if ssh_connection.dir_exists(home_dir): utils.print_success( "A New home directory was able to be made.") else: utils.print_error( "FATAL (PANIC): COULD NOT CREATE NEW HOME DIRECTORY FOR USER." ) else: # no home drive! Need to make it utils.print_warning( "No home drive detected, creating new home drive...") command = f"bash /nfshome/makehomedirs.sh {username}" ssh_connection.send_cmd(command, sudo=True) utils.print_success( "Operation complete, please have the user log back in.") ssh_connection.close()
def clean_user_files(): who_to_clean = utils.input_styled("Enter a username or all? ") if who_to_clean == 'all': search_root = "/nfshome/*" else: fullname, username = user_utils.get_and_confirm_user( username=who_to_clean) if not fullname: return False # utils.print_warning("Make sure the student is logged out before running this repair.\n") search_root = f"/nfshome/{username}" ssh_connection = SSH(HOSTNAME, SERVER_USERNAME) print("Available space on the file server BEFORE:") print("Filesystem Size Used Avail Use% Mounted on") ssh_connection.send_cmd("df -h | grep nfshome") # empty Downloads directory location = f"{search_root}/Downloads/*" num = count_files(location, ssh_connection) if num > 0: utils.print_warning(f"Emptying Downloads directory: {location}") utils.input_styled("Enter to continue...") delete_files(location, ssh_connection) # remove .cache directory and contents location = f"{search_root}/.cache/*" num = count_files(location, ssh_connection) if num > 0: utils.print_warning(f"Emptying .cache directory: {location}") utils.input_styled("Enter to continue...") delete_files(location, ssh_connection) # empty trash location = f"{search_root}/.local/share/Trash/files/*" num = count_files(location, ssh_connection) if num > 0: utils.print_warning(f"Emptying Trash: {location}") utils.input_styled("Enter to continue...") delete_files(location, ssh_connection) # CR2 Files (raw images...massive sizes) location = f"{search_root}" file_glob = '*.CR2' # all files num = count_files(location, ssh_connection, file_glob) if num > 0: print( "Finding and deleting all CR2 files (raw images that are massive)..." ) # delete_files(location, file_glob, ssh_connection) # # delete any tmp directory contents # location = f"{search_root}" # num = count_files(location, ssh_connection) # if num > 0: # utils.print_warning(f"Emptying .cache directory: {location}") # utils.input_styled("Enter to continue...") # delete_files(location, ssh_connection) # large files location = f"{search_root}" size = '2G' utils.print_warning("This search can take a while, please be patient...") num = count_files(location, ssh_connection, size=size) if num > 0: utils.print_warning(f"Removing files larger than: {size}") utils.input_styled("Enter to continue...") delete_files(location, ssh_connection, size=size) print("Available space on the file server AFTER:") print("Filesystem Size Used Avail Use% Mounted on") ssh_connection.send_cmd("df -h | grep nfshome") ssh_connection.close()
def remove_media(username=None, tv=None): ssh_connection = SSH(TV_FILE_SERVER, TV_FILE_SERVER_USER, TV_FILE_SERVER_PW) username = utils.input_plus("Enter username", default=username) if username == "q": return False while True: tv = get_tv_containing_student(username) if tv is None: utils.print_error("No art found for {}".format(username)) return False # get of list of the student's art and display the list filepath = "{}/tv{}/{}/".format(TV_ROOT, tv, username) command = 'ls {}'.format(filepath) dir_contents = ssh_connection.send_cmd(command, print_stdout=False).split() media_list = [ inquirer.List( 'art', message= "Which file do you want to delete? I'll display it first so you can confirm.", choices=dir_contents, ), ] art_file = inquirer.prompt(media_list)["art"] art_file_full_path = filepath + art_file # Show the image with Pillow # Transfer locally local_copy = "/tmp/" + art_file ssh_connection.get_file(art_file_full_path, local_copy) try: img = Image.open(local_copy) except IOError: utils.print_error("File not found") ssh_connection.close() return False w, h = img.size aspect_ratio = w / h thumb = img.resize((400, int(400 / aspect_ratio))) thumb.show() delete_file = utils.confirm( "Are you sure you want to delete {}? Hopefully it popped up for you" .format(art_file), yes_is_default=False) if delete_file: cmd = "rm {}".format(art_file_full_path) ssh_connection.send_cmd(cmd, print_stdout=True) # confirm it's gone: if ssh_connection.file_exists(art_file_full_path): utils.print_error( "\nNot sure what happened there, but the file didn't get deleted. Sorry!" ) else: utils.print_success("\nThe file was successfully deleted.") # Keep deleting files ina loop if they want to keep_going = utils.confirm("Remove another file for this student?") if not keep_going: ssh_connection.close() utils.print_warning( "\nDon't forget to refresh the user's video slideshow!\n") return True
def puppet_run(computer_number=None, password=None, auto_fix_certificates=False): if password is None: password = getpass("Enter the admin password: "******"\nComputer is online, but cant' connect. Maybe it's mining?\n") return False puppet_command = '/usr/bin/puppet agent -t' while not success: utils.print_warning( "\nRunning puppet on {}. This may take a while. The ouput will appear when it's done for you to inspect...\n" .format(computer_host)) output_puppet_run = ssh_connection.send_cmd(puppet_command, sudo=True) if "Error: Could not request certificate: The certificate retrieved from the master does not match the agent's private key." in output_puppet_run: pass elif "alert certificate unknown" in output_puppet_run: pass elif "unable to get local issuer certificate" in output_puppet_run: pass elif "Notice: Run of Puppet configuration client already in progress" in output_puppet_run: if remove_puppet_lock(ssh_connection, password): pass else: utils.print_warning( "\nIt appears that puppet is already running on {}. Give it a few minutes and try again.\n" .format(computer_host)) break elif "command not found" in output_puppet_run: utils.print_warning( "\nCouldn't find puppet.... why not? Try the other spot...") break else: utils.print_success("\n\nSeems like everything worked ok!\n\n") break # out of the while loop, all done # ## Handle certificate problem ### # Error: Could not request certificate: The certificate retrieved from the master does not match the agent's private key. # Certificate fingerprint: 26:DD:EC:AC:15:95:7C:4B:7C:DB:0C:C6:30:C8:1A:7D:FF:C1:7B:C8:A5:56:53:77:94:2A:C3:F2:98:B7:D6:6A # To fix this, remove the certificate from both the master and the agent and then start a puppet run, which will automatically regenerate a certificate. # On the master: # puppet cert clean tbl-hackerspace-2-s.hackerspace.tbl # On the agent: # 1a. On most platforms: find /etc/puppetlabs/puppet/ssl -name tbl-hackerspace-2-s.hackerspace.tbl.pem -delete # 1b. On Windows: del "\etc\puppetlabs\puppet\ssl\certs\tbl-hackerspace-2-s.hackerspace.tbl.pem" /f # 2. puppet agent -t # # Exiting; failed to retrieve certificate and waitforcert is disabled if not auto_fix_certificates: try_to_fix = utils.input_styled( "Looks like there was a certificate problem. Usually this happens when a computer is re-imaged. Want me to try to fix it? [y]/n " ) if try_to_fix == 'n': break # first, remove certificate from agent: if "find /etc/puppetlabs/puppet/ssl" in output_puppet_run: # old 16.04 installations remove_agent_cert_cmd = "find /etc/puppetlabs/puppet/ssl -name {}.hackerspace.tbl.pem -delete".format( computer_host) else: remove_agent_cert_cmd = "rm -rf /var/lib/puppet/ssl" # just delete them all ssh_connection.send_cmd(remove_agent_cert_cmd, sudo=True) # now remove certificate from puppet server: puppet_clear_certificates(computer_host, password) # command_response_list = [ # ("sudo passwd {}".format(student_number), "[sudo] password for {}:".format(username), None), # (password, "New password: "******"wolf", "Re-enter new password: "******"wolf", prompt_string, "password updated successfully"), # ] # success = ssh_connection.send_interactive_commands(command_response_list) ssh_connection.close()