def reset_password():
    # student_number = utils.input_styled(
    #     'Enter the student number of the student whose password you want to reset to "{}": '.format(default_pw))

    password = getpass("Enter the admin password: "******"Who's password do you want to reset?")

    student_number = get_and_confirm_user(password)

    ssh_connection = SSH(hostname, username, password)

    prompt_string = "{}@{}:~$".format(username, hostname)
    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)

    if success:
        utils.print_success("Password for {} successfully reset to {}".format(
            student_number, default_pw))

    ssh_connection.close()
Exemple #2
0
def create_home_dirs(username_list: list, password: str = None):
    """Sends the list of users to the file server and runs a script on that server to generate new home directories

    Arguments:
        username_list {list} -- list of usernames to generate home directories for

    Keyword Arguments:
        password {str} -- file server password (default: {None})
    """
    username_list_as_string = " ".join(username_list)

    make_home_dirs_cmd = 'ssh -t hackerspace_admin@tyrell "sudo /nfshome/makehomedirs.sh {}"'.format(username_list_as_string)

    command_response_list = [
        (make_home_dirs_cmd, "hackerspace_admin@tyrell's password: "******"[sudo] password for hackerspace_admin: ", None),
        (password, "$", None),
    ]

    if not password:
        password = getpass("Enter the admin password: "******"Looks like it worked!  Unless you see some nasty errors above...")
        return success
    else:
        utils.print_error("Something went wrong but I'm not smart enough to know what...")
        return False
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
Exemple #4
0
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")
Exemple #5
0
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')
Exemple #7
0
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 generate_new_movie_file(ssh_connection, username, tv, silent=False):

    output = '/tmp/slideshow.mp4'
    # remove existing file
    ssh_connection.send_cmd(
        'rm {}'.format(output),
        print_stdout=False)  # don't care about error if it doesn't exists

    # create video in defaul location
    cmd = 'python3 movie_maker.py --images tv{}/{} --output {}'.format(
        tv, username, output)
    ssh_connection.send_cmd(cmd)

    # move the file into the proper location
    success = ssh_connection.send_cmd('cp {} {}/tv{}/{}.a.mp4'.format(
        output, TV_ROOT, tv, username))

    if success == '':
        if not silent:
            # copy so still avail for tv 4 move
            utils.print_success(f"Video created and placed on tv {tv}.")

        # also place on tv4
        if tv != 4:
            success = ssh_connection.send_cmd('cp {} {}/tv4/{}.a.mp4'.format(
                output, TV_ROOT, username))
            if success == '':
                if not silent:
                    utils.print_success("Also placed on tv 4.")
            else:
                utils.print_error("Something went wrong sending to tv 4.")

    else:
        utils.print_error(f"Something went wrong sending to tv {tv}.")
def reset_password():
    print("Who's password do you want to reset?")

    fullname, student_number = get_and_confirm_user()
    if not fullname:
        return

    password = getpass("Enter the admin password: "******"{}@{}:~$".format(username, hostname)
    command_response_list = [
        ("sudo passwd {}".format(student_number),
         "[sudo] password for {}:".format(username), None),
        (password, "LDAP administrator password: "******"New password: "******"wolf", "Retype new password: "******"wolf", prompt_string, "password updated successfully"),
    ]
    success = ssh_connection.send_interactive_commands(command_response_list)

    if success:
        utils.print_success("Password for {} successfully reset to {}".format(
            student_number, default_pw))
    else:
        utils.print_error("Something went wrong...")

    ssh_connection.close()
Exemple #10
0
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()
Exemple #11
0
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
Exemple #12
0
def check_for_disconnected_computers(password=None):
    # if password is None:
    #     password = getpass("Enter the admin password: "******"{hostname} found.")
        else:
            utils.print_error(f"{hostname} missing.")
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 get_tv_containing_student(student_number):
    """ Search all pi-slideshow TV directories until directory with same number is found, return the TV # """
    ssh_connection = SSH(TV_FILE_SERVER, TV_FILE_SERVER_USER,
                         TV_FILE_SERVER_PW)

    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 student_number in dir_contents:
            utils.print_success("Found art for {} on TV# {}".format(
                student_number, tv))
            ssh_connection.close()
            return tv

    ssh_connection.close()
    return None
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)}")
Exemple #16
0
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
Exemple #17
0
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()
Exemple #18
0
def modify_user(username, ldif_changes_dict, password=None):
    """[summary]

    Args:
        username: ldap username
        ldif_changes_dict: a dictionary of ldif keys and their new values, e.g {'sn': 'COUTURE', 'givenName': 'TYLERE'}
        password: admin password
    """
    if not password:
        password = getpass("Enter the admin password: "******"sudo ldapmodifyuser {}".format(username)
    EOF = '\x04'  # Ctrl + D

    command_response_list = []

    first = True
    for key, value in ldif_changes_dict.items():
        if first:
            command_response_list.append((main_command, "[sudo] password for hackerspace_admin: ", None))
            command_response_list.append((password, "dc=tbl", None))
            first = False
        else:
            command_response_list.append((main_command, "dc=tbl", None))

        change_tuple = (f"replace: {key}\n{key}: {value}\n{EOF}", '$', None)
        command_response_list.append(change_tuple)

    success = ssh_connection.send_interactive_commands(command_response_list)

    if success:
        utils.print_success("Looks like it worked to me?")
        return True

    else:
        utils.print_error("Something appears to have gone wrong. Hopefully there's a useful error message somewhere up there.")
        return False
Exemple #19
0
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!")
Exemple #20
0
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()
Exemple #21
0
def add_new_title():

    #gets info of the student who made the art
    first_name = utils.input_styled("First name: \n")
    last_name = utils.input_styled("Last name: \n")
    grad_year = utils.input_styled("Grad Year: \n")
    student_number = utils.input_styled("Student number: \n")

    #https://pypi.org/project/inquirer/

    subject_list = [
        inquirer.List(
            'subject',
            message="What subject is the student in?",
            choices=[
                'Digital Art', 'Digital Photography',
                '3D Modelling & Animation', 'Custom subject:'
            ],
        ),
    ]

    choose_subject = inquirer.prompt(subject_list)["subject"]

    #gets user to input a custom subject if they so choose
    if choose_subject == "Custom subject:":
        custom_subject = utils.input_styled("Well then what are they in? \n")
        choose_subject = custom_subject

    default_tv = '1' if last_name.upper()[0] <= 'M' else '2'

    tv = utils.input_styled(
        "Which TV # are you sending this to (1 for lastname A-M, 2 for N-Z)? [Enter] = {}: \n"
        .format(default_tv))

    if not tv:
        tv = default_tv

    filename = student_number + ".a." + first_name + last_name
    template = "_template.svg"
    source_file = "scripts/TVs/{}".format(template)
    temp_filepath_svg = "{}{}.svg".format(temp_dir, filename)
    filename_png = filename + ".png"
    temp_filepath_png = temp_dir + filename_png

    #creates copy of template with the filename it will use
    os.system("cp {} {}".format(source_file, temp_filepath_svg))

    # writes the student information into the copy of the svg template
    os.system('sed -i -e "s/FIRSTNAME LASTNAME/{} {}/g" {}'.format(
        first_name, last_name, temp_filepath_svg))
    os.system('sed -i -e "s/YYYY/{}/g" {}'.format(grad_year,
                                                  temp_filepath_svg))
    os.system('sed -i -e "s/SUBJECT/{}/g" {}'.format(choose_subject,
                                                     temp_filepath_svg))

    # creates a png image from the svg
    os.system('inkscape -z -e {} -w 1920 -h 1080 {}'.format(
        temp_filepath_png, temp_filepath_svg))

    filepath_pi = "/home/pi-slideshow/tv{}/{}/".format(tv, student_number)

    # make a folder for a new student when title card is made
    os.system('sshpass -p "{}" ssh {}@{} && mkdir {}'.format(
        pi.password, username, hostname, filepath_pi))

    #scps into the tv photo directory
    command = 'sshpass -p "{}" scp {} {}@{}:{}'.format(pi.password,
                                                       temp_filepath_png,
                                                       username, hostname,
                                                       filepath_pi)
    os.system(command)

    #removes all files it created
    os.system('rm {}'.format(temp_filepath_png))
    os.system('rm {}'.format(temp_filepath_svg))
    #os.system('rm {}.png'.format(filename))

    ssh_connection = SSH(hostname, username, pi.password)
    title_exists = ssh_connection.file_exists(filepath_pi, filename_png)

    if title_exists:
        utils.print_success("{} was successfully sent over to TV {}".format(
            filename_png, tv))
        add_images = utils.input_styled(
            utils.ByteStyle.Y_N,
            "Would you like to add images to {}'s new shrine? ([y]/n)\n".
            format(first_name))
        if not add_images or add_images.lower()[0] == "y":
            add_new_media.add_new_media(student_number, tv)
    else:
        utils.print_error(
            "The title image '{}' was not added. Is sshpass installed?".format(
                filename_png))
Exemple #22
0
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
Exemple #23
0
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 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)
Exemple #26
0
def add_new_title():

    fullname, username = user_utils.get_and_confirm_user()

    fullname = fullname.title()

    # gets info of the student who made the art
    fullname_entered = utils.input_plus("Full name", fullname)
    if fullname_entered:
        fullname = fullname_entered

    grad_year = utils.input_styled("Grad Year: \n")

    last_name = username.split(".")[-1].title(
    )  # get the last word if the username tyere.couture will get couture

    # https://pypi.org/project/inquirer/

    subject_list = [
        inquirer.List(
            'subject',
            message="What subject is the student in?",
            choices=[
                'Digital Art', 'Digital Photography',
                '3D Modelling & Animation', 'Custom subject:'
            ],
        ),
    ]

    choose_subject = inquirer.prompt(subject_list)["subject"]

    # gets user to input a custom subject if they so choose
    if choose_subject == "Custom subject:":
        custom_subject = utils.input_styled("Well then what are they in? \n")
        choose_subject = custom_subject

    default_tv = '1' if last_name.upper()[0] <= 'M' else '2'

    tv = utils.input_plus(
        "Which TV # are you sending this to (1 for lastname A-M, 2 for N-Z, 3 for Grads)?",
        default_tv)

    if not tv:
        tv = default_tv

    filename = username + ".a.title"
    template = "_template.svg"
    source_file = "scripts/TVs/{}".format(template)
    temp_filepath_svg = "{}{}.svg".format(temp_dir, filename)
    filename_png = filename + ".png"
    temp_filepath_png = temp_dir + filename_png

    # creates copy of template with the filename it will use
    os.system("cp {} {}".format(source_file, temp_filepath_svg))

    # writes the student information into the copy of the svg template
    os.system('sed -i -e "s/FIRSTNAME LASTNAME/{}/g" {}'.format(
        fullname, temp_filepath_svg))

    os.system('sed -i -e "s/YYYY/{}/g" {}'.format(grad_year,
                                                  temp_filepath_svg))

    # need to escape the ampersand character in "3D Modelling & Animation"
    os.system('sed -i -e "s/SUBJECT/{}/g" {}'.format(
        choose_subject.replace('&', '\&amp;'), temp_filepath_svg))

    # creates a png image from the svg
    os.system('inkscape -z -e {} -w 1920 -h 1080 {}'.format(
        temp_filepath_png, temp_filepath_svg))

    server_filepath = "tv{}/{}/".format(tv, username)

    # setup a connect so we can makesure the directory exists
    ssh_connection = SSH(hostname, SERVER_USERNAME, pi.password)
    # make sure the directory exists, if not create it:
    if not ssh_connection.file_exists(server_filepath):
        ssh_connection.send_cmd('mkdir {}'.format(server_filepath))

    # move image onto the server with scp (this will fail if they've never connected to hightower before, hence warning at bottom)
    command = 'sshpass -p "{}" scp {} {}@{}:{}'.format(pi.password,
                                                       temp_filepath_png,
                                                       SERVER_USERNAME,
                                                       hostname,
                                                       server_filepath)

    os.system(command)

    # removes all temp files we created
    os.system('rm {}'.format(temp_filepath_png))
    os.system('rm {}'.format(temp_filepath_svg))

    # Check if file now exists on the server
    title_exists = ssh_connection.file_exists(server_filepath, filename_png)

    if title_exists:
        utils.print_success(
            f"{filename_png} was successfully sent over to TV {tv}")
        add_images = utils.confirm(
            f"Would you like to add images to {fullname}'s new shrine?")
        if add_images:
            add_new_media(username, tv)
        else:
            gen_video = utils.confirm(
                "Would you like to regenerate the video file?")
            if gen_video:
                refresh_slideshow(username=username)
    else:
        utils.print_error(
            f"The title image '{filename_png}' was not added. Maybe inkscape isn't installed? Or it's possible you've never connected to this server before. \n\n"
            "Try connecting once first by typing `ssh hightower` into a terminal, then answering yes."
        )