コード例 #1
0
def login():
        
        # Getting the user input
        username = input("Username: "******"Password: "******"{username}"')
        db_username = C.fetchone()

        # Getting the password associated to the username that was entered
        C.execute(f'SELECT password FROM usernameAndPasswords WHERE username = "******"')
        db_password = C.fetchone()

        try:
            # Assigning the results to a variable and converting the data from a tuple to a string
            db_username = ''.join(db_username)
            db_password = ''.join(db_password)

            # If statement to determine if they got the correct username and password
            if username == db_username and password == db_password:
                print("You are logged in!")
                close_program()

            else:
                print("Username or password is not correct.\n")
                close_program()
        except TypeError:
            print("Username not found, please try again.\n")
            close_program()
        except Exception:
            print("Unknown error occcured.\n")
            close_program()
コード例 #2
0
def sendMail(recommendationList):
    sender_email = "*****@*****.**"
    #receiver_email = "*****@*****.**", "*****@*****.**", "*****@*****.**"
    receiver_email = "*****@*****.**"
    print("Type your password and press enter:")
    password = stdiomask.getpass(mask='X')
    message = MIMEMultipart("alternative")
    message[
        "Subject"] = "Hi Reader ! Recommendation for you from CMPE 256 : Team 5"
    message["From"] = "*****@*****.**"
    message["To"] = ", ".join(receiver_email)

    print("================== Composing the mail ================== ")
    # Create the plain-text and HTML version of your message
    html = """\
    <html>
        <head></head>
        <body>
            {0}
        </body>
    </html>
    """.format(recommendationList.to_html())

    # Turn these into plain/html MIMEText objects
    part1 = MIMEText(html, 'html')

    # Add HTML/plain-text parts to MIMEMultipart message
    # The email client will try to render the last part first
    message.attach(part1)

    # Create secure connection with server and send email
    context = ssl.create_default_context()
    with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
        server.login(sender_email, password)
        server.sendmail(sender_email, receiver_email, message.as_string())

    print("==================   Main sent ================== ")
コード例 #3
0
def login_interface():
    """
    Called to display menus and options for logging in
    """
    print("\nPlease enter your Docket Alarm username and press ENTER.\n")
    input_username = input()
    menus.clear()
    print(
        "\nPlease enter your Docket Alarm password and press ENTER\n(This will be stored securely on your local machine)\n"
    )
    input_password = stdiomask.getpass(mask="*", prompt="")
    menus.clear()
    # This is the endpoint for logging in to Docket Alarm from the API.
    login_url = "https://www.docketalarm.com/api/v1/login/"
    # The data we will send to the endpoint with our post request will be
    # our Docket Alarm username and password.
    data = {
        'username': input_username,
        'password': input_password,
    }
    # We save the response to a variable. The response is a json object containing
    # our authentication key iside the json key named 'login_token'
    result = requests.post(login_url, data=data)
    # Calling the .json() method on the result turns it into a python dictionary we
    # can work with natively.
    result_json = result.json()
    # Checks to see if the login was a success...
    if result_json['success'] != True:
        # If it was not a sucess, we let the user know...
        print(result_json['error'])
        input()
        # And prompt the user to log in again.
        login_interface()
    else:
        # If the login is a success, we store the user info in a pickle file to be accessed later.
        # That way, the program can log in automatically every time the script is run afterwards.
        store_user_info_locally(input_username, input_password)
コード例 #4
0
ファイル: login.py プロジェクト: rupansh/reddit-cli
def authenticate():
    """A function to authenticate the user and return the reddit instance."""
    if cred_check() != True:
        print("""credentials.json does not exist.""")
        print("""refer to instructions and create it""")
        os.sys.exit()
    try:
        with open("credentials.json") as creds:
            credentials = json.load(creds)

        reddit = praw.Reddit(
            client_id=credentials["client_id"],
            client_secret=credentials["client_secret"],
            user_agent=credentials["user_agent"],
            username=input("Enter your reddit username: "******"Enter your reddit password: "******"Welcome /u/%s!\n\n" % (reddit.user.me()))
        return reddit
    except:
        print("Incorrect username/password. Try again...")
        os.sys.exit()
コード例 #5
0
ファイル: bankingDefs.py プロジェクト: zonkia/atm-banking
    def sign_in(self):

        credentialsFile = Encryption.decrypt_dict(
            self, FileSupport.read_file(self, "credentials"))
        while True:
            try:
                login = str(input("Please enter your UserID: "))
            except:
                print("Wrong ID, please try again")
                continue
            if login not in credentialsFile:
                print("Wrong ID, please try again")
                continue
            password = stdiomask.getpass(prompt="Please enter your password: "******"*")
            if password != credentialsFile[login]:
                print("Wrong password, please try again")
                continue
            else:
                accountsFile = Encryption.decrypt_dict(
                    self, FileSupport.read_file(self, "Accounts"))
                accountBalance = accountsFile[login]
                self.user = BankAccount(accountBalance, login)
            break
コード例 #6
0
def update_entry():
    """ used to update password and username of a existing website
    """
    print("Enter the website you want to update into\n")
    w = get_input()

    record = get_data(w)
    if record is None:
        print("Website name doesn't exits!")
        val = int(input("Press 1 to enter the website else 0: "))
        if (val == 1):
            terminal_entry()
    else:
        print("Enter the Username and New Password")
        u = input("Username: "******"\nUpdated entry!\n")
        display_data(0, w)
    except:
        print("Website doesn't exist in db")
コード例 #7
0
 def get_passphrase(self) -> None:
     """ Use the stdiomask library to mask the user input (hide the password). """
     self.passphrase = stdiomask.getpass(prompt='Enter passphrase: ', mask='*')
コード例 #8
0
clear = lambda: os.system('cls')


def deleteContent(pfile):
    pfile.seek(0)
    pfile.truncate()


# If account is public you can query Instagram without auth
instagram = Instagram()
while True:
    file = open('cred.txt', "r+")
    up = file.read().splitlines()
    if len(up) < 2 or (not up[0] or not up[1]):
        username = input('username: '******'pass: ')
    else:
        username = up[0]
        password = up[1]
    print("try to login...")
    try:
        instagram.with_credentials(username, password)
        instagram.login()
        deleteContent(file)
        file.write(f"{username}\n{password}")
        file.close()
        break
    except Exception as e:
        deleteContent(file)
        file.close()
        print(e)
コード例 #9
0
from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from termcolor import colored
import stdiomask

ID = input('[+] Enter username:\n')
PASSWORD = stdiomask.getpass(prompt='[+] Enter password:\n')
frequency = 3


def add(hour, val):
    return str(int(hour) + val)


def ryt_now():
    cur_time = time.localtime()
    cur_time = time.strftime("%H:%M:%S", cur_time)
    return cur_time


def get_time():
    cur_time = ryt_now()
    hour, mn, sec = cur_time.split(':')
    if int(mn) >= 40:
        hour = str((int(hour) + 1))
    return hour
コード例 #10
0
def hashPasswordInput(message):
    password = stdiomask.getpass(message)
    return password
コード例 #11
0
def del_act():
    print("Do you know your username?\n1) Yes\n2) No")
    print("--------------------------")

    # Input validation and seeing if they need to quit the program
    know_username = input("Your selection: ")
    if know_username.upper() == QUIT:
        close_program()
    while validateInput(know_username) == False or int(know_username) < YES or int(know_username) > NO:
            print("Please enter a valid selection.")
            user_selection = str(input("Your selection: "))
            if user_selection.upper() == QUIT:
                close_program()
    
    print()
    # Converting input to an integer for the selection below
    know_username = int(know_username)

    # Empty variable to hold the users username
    username = ''

    # If they do not know the username
    if know_username == NO:
        email = input("What is the email associated to this email? ")
        if email.upper() == QUIT:
                close_program()

        # Testing to see if the email is in the database.
        try:  
            C.execute(f'SELECT email FROM usernameAndPasswords WHERE email = "{email}"')
            test_email = C.fetchone() # Getting the results of the cursor and assigning it to a variable
            test_email = ''.join(test_email) # converting the results from a tuple to a string
            if email == test_email: # if user email and db email matches..
                print("We found a username associated to that email.")
                C.execute(f'SELECT username FROM usernameAndPasswords WHERE email = "{email}"') # Getting the username associated to the email
                db_username = C.fetchone()
                db_username = ''.join(db_username) # Converting it to the string format from the db
                print(f"This is your username: {db_username}\n")  # Printing off the username to the host
                username = db_username # assigning the db username to the empty username variable above

        except Exception:
            print ("Specified email was not found in the system.")
            print("Please try again")
            close_program()
    
    elif know_username == YES:
        uk_username = input("What is your username? ").lower()  # "Unknown user name" variable from input
        if uk_username.upper() == QUIT:
                close_program()

        # trying to get the username in the database based on the user input
        try:  
            C.execute(f'SELECT username FROM usernameAndPasswords WHERE username = "******"')
            test_username = C.fetchone() # Getting the results of the cursor and assigning it to a variable
            test_username = ''.join(test_username) # converting the results from a tuple to a string
            if uk_username == test_username:

                print("We found a matching username\n")
                username = uk_username
        except Exception:
            print ("We were not able to find the specified username, please try again.")
            close_program()

    # Getting the password, security questions and answers from the database
    C.execute(f'SELECT password FROM usernameAndPasswords WHERE username = "******"') 
    password = C.fetchone()
    password = ''.join(password)

    C.execute(f'SELECT question1 FROM usernameAndPasswords WHERE username = "******"') 
    question1 = C.fetchone()
    question1 = ''.join(question1)
    C.execute(f'SELECT answer1 FROM usernameAndPasswords WHERE username = "******"') 
    answer1 = C.fetchone()
    answer1 = ''.join(answer1)

    C.execute(f'SELECT question2 FROM usernameAndPasswords WHERE username = "******"') 
    question2 = C.fetchone()
    question2 = ''.join(question2)
    C.execute(f'SELECT answer2 FROM usernameAndPasswords WHERE username = "******"') 
    answer2 = C.fetchone()
    answer2 = ''.join(answer2)

    # Getting the hosts information on the account to compare with the database entry
    user_password = stdiomask.getpass("What is the password associated to this account? ")
    if user_password.upper() == QUIT:
                close_program()
    user_answer1 = input(f"{question1} ").lower()
    if user_answer1.upper() == QUIT:
                close_program()
    user_answer2 = input(f"{question2} ").lower()   
    if user_answer2.upper() == QUIT:
                close_program()

    # If the user got the password and security questions correct
    if password == user_password and answer1 == user_answer1 and answer2 == user_answer2:
        print("\nAre you sure you want to delete this account? This cannot be undone.")
        print("1) Yes\n2) No")
        print("--------------------------")

        # Input validation and seeing if they need to quit the program
        del_act = input("Your selection: ")
        if del_act.upper() == QUIT:
            close_program()

        while validateInput(del_act) == False or int(del_act) < YES or int(del_act) > NO:
                print("Please enter a valid selection.")
                del_act = str(input("Your selection: "))
                if del_act.upper() == QUIT:
                    close_program()
        
        # Converting input to an integer for the selection below
        del_act = int(del_act)   

        if del_act == YES:
            C.execute(f'DELETE FROM usernameAndPasswords WHERE username = "******"')
            CONN.commit()
            print()
            print("Account has been deleted")
            close_program()
        else:
            close_program()
    
    else:
        print()
        print("Either the password or one of the security questions did not match, please try again.")
        close_program()


    print("")
コード例 #12
0
def savefile(name, data):
    with open(name + ".json", 'w') as json_file:
        json.dump(data, json_file)


link = r'https://api.github.com/user/repos'
header = {
    'User-Agent':
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 /'
    '(KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}

login = input("Введите логин пользователя GitHub: ")
# password = input("Введите пароль пользователя GitHub: ")
password = stdiomask.getpass(prompt="Введите пароль пользователя GitHub: ",
                             mask='*')  # маскирует только в терминале,
# в PyCharm показывает в открытом виде

response = requests.get(link, auth=HTTPBasicAuth(login, password))
data = json.loads(response.text)
for repo in data:
    try:
        print("Название репозитория: " + repo["name"])
        print("Язык программирования: " + str(repo["language"]))
        print("Описание репозитория: " + str(repo["description"]))
        print("Лицензия репозитория: " + str(repo["license"]["name"]))
    except:
        pass
    finally:
        print("URL репозитория:" + repo["url"])
        print('\n')
コード例 #13
0
def connect_ratings_table():
    conn = None

    host = input('Enter Host for database: ')
    database = input('Enter database name: ')
    user = input('Enter user for database: ')
    password = stdiomask.getpass("Enter password: "******"""For ratings table: 
            Enter 1 to insert
            Enter 2 to update
            Enter 3 to delete...
            """))

            if user_selection == 1:

                sql_insert = "INSERT INTO ratings (rating, movie_id, reviewer_id) VALUES (%s,%s,%s);"
                val = []
                numberOfEntries = int(
                    input("How many records do you want to enter?: "))

                for i in range(numberOfEntries):
                    rating = input("Enter movie rating: ")
                    movie_id = (input("Enter movie id: "))
                    reviewer_id = input("Enter reviewer id: ")

                    print()

                    val.append((rating, movie_id, reviewer_id))

                db_cursor.executemany(sql_insert, val)

                conn.commit()

                print(db_cursor.rowcount, 'record(s) was inserted')

            if user_selection == 2:
                numberOfEntries = int(
                    input("How many fields do you want to update?: "))

                for i in range(numberOfEntries):
                    movie_id = (input("Enter movie id: "))
                    reviewer_id = input("Enter reviewer id: ")
                    updated_rating = input("Enter new rating: ")

                    sql_update = "UPDATE ratings SET rating = \'" + updated_rating + "\' WHERE movie_id = \'" + movie_id + "\' and reviewer_id = \'" + reviewer_id + "\'"
                    db_cursor.execute(sql_update)
                    conn.commit()
                    print(db_cursor.rowcount, 'field(s) was updated')

            if user_selection == 3:
                numberOfEntries = int(
                    input("How many records do you want to delete?: "))
                for i in range(numberOfEntries):
                    movie_id = input("Enter movie id: ")
                    reviewer_id = input("Enter reviewer id: ")

                    sql_delete = "DELETE from ratings WHERE movie_id = \'" + movie_id + "\' and reviewer_id = \'" + reviewer_id + "\'"
                    print()

                db_cursor.execute(sql_delete)

                conn.commit()

                print(db_cursor.rowcount, 'record(s) are deleted')

            else:
                print("Invalid selection")
                connect_ratings_table()

            db_cursor.close

    except Error as e:
        print('Connection failed due to the following:', e)
    finally:
        if conn is not None and conn.is_connected():
            conn.close()
            print('Disconnected from the database')
コード例 #14
0
    # if operation == '':
    #     operation = 0
    #     break
    try:
        operation = int(operation)
    except:
        print('您的输入不是有效数字,请重新输入')
        continue
    if operation < 0 or operation > 1:
        print('您输入的序号不在有效范围内,请重新输入')
        continue
    break
print('\n\n\n======================第三步==========================\n')
print('接下来需要输入保险库的密码\n')
print('注意,无论密码是否正确,都能打开保险库,但只有当“输入的密码”与“存入文件前输入的密码”一致时,才能正确读取保险库里的文件!!!\n')
passwd = stdiomask.getpass('现在请输入保险库密码:')

typeVar, typeValue = f'RCLONE_CONFIG_{vault.innerName}_TYPE', 'crypt'
remoteVar, remoteValue = f'RCLONE_CONFIG_{vault.innerName}_REMOTE', vault.remote
passVar, passValue = f'RCLONE_CONFIG_{vault.innerName}_PASSWORD', encrypt(
    passwd)
os.environ[typeVar] = typeValue
os.environ[remoteVar] = remoteValue
os.environ[passVar] = passValue

print('\n\n\n======================第四步==========================\n')

if operation == 0:
    print(f'开始映射,此次映射的保险库是“{vault.name}”,其实际存储路径为 {vault.remote}\n')
    if vault.serverType == 'webdav' or vault.serverType == 'http':
        print(
コード例 #15
0
        if input_string[i] not in normalChars:
            specialChar = True

    # Strength of password
    print("Strength of password:-", end="")
    if (hasLower and hasUpper and hasDigit and specialChar and n >= 8):
        print("Strong")

    elif (hasLower and hasUpper and hasDigit or specialChar and n > 6):
        print("Moderate")

    else:
        print("Weak")


input_string = stdiomask.getpass("Enter your password: "******"Do you want me to create a password for you?\nPlease enter Yes or No: "
).lower()

if answer == "yes":

    length = int(
        input("Enter the number of letters the password should have: "))
    password_characters = string.ascii_letters + string.digits  # + string.punctuation
    password = ''.join(
        random.choice(password_characters) for i in range(length))
    print("Your Password will be: ", password)
    print("Thank You")
コード例 #16
0
    def modify_entry(self):
        entries = json.loads(
            decryptor.get_decrypted_content(self.password, self.db_path))
        if len(entries.keys()) == 0:
            print("No entries yet! Go create some.")
            input("\nEnter to continue")
            return
        while True:
            print(
                "You will now be listed all entries of your database. Select one and copy it below to modify it. Type in 'quit' to get back to the menu"
            )
            self.real_show_all_entries()
            entry_to_modify = input("Entry to modify: ")
            if entry_to_modify in ['q', 'quit']:
                break
            if entry_to_modify:
                try:
                    entry_to_modify_entry = entries[entry_to_modify]
                    print(
                        "\nIf you want to change something, write it. If not just press enter\n"
                    )
                    print("Old entry:\n")
                    print(f"Title: {entry_to_modify}")
                    print(f"Username: {entry_to_modify_entry['username']}")
                    print(
                        f"Description: {entry_to_modify_entry['description']}")
                    print(
                        f"Password: {len(entry_to_modify_entry['password'])*'*'}"
                    )
                    print("\nNew Entry:\n")
                    new_title = input(f"New title: ")
                    new_username = input(f"New username: "******"New description: ")
                    new_password = getpass("New password: "******""
                    if new_password:
                        confirm_new_password = getpass(
                            "Confirm new password: "******"The passwords don't match. Do you want to re-enter both? y/n: "
                        )
                        check = confirm(check)
                        if isinstance(check, bool):
                            if check is False:
                                new_password = ""
                                print("Ignoring new password")
                            else:
                                new_password = getpass("New password: "******"Confirm new password: "******"Passwords match")

                    title_gets_updated = False

                    if new_title:
                        check = None
                        while check is None:
                            check = input(
                                "Are you sure to update the title? y/n: ")
                            check = confirm(check)
                        if check is True:
                            title_gets_updated = True
                            entries[new_title] = entries[entry_to_modify]
                            del entries[entry_to_modify]
                            print("Title got updated")
                        else:
                            print("Did not update title")
                        print()

                    if new_username:
                        check = None
                        while check is None:
                            check = input(
                                "Are you sure to update the username? y/n: ")
                            check = confirm(check)
                        if check is True:
                            if not title_gets_updated:
                                entry_to_modify_entry[
                                    'username'] = new_username
                            else:
                                entries[new_title]['username'] = new_username
                            print("Updated username")
                        else:
                            print("Did not update username")
                        print()

                    if new_description:
                        check = None
                        while check is None:
                            check = input(
                                "Are you sure to update the description? y/n: "
                            )
                            check = confirm(check)
                        if check is True:
                            if not title_gets_updated:
                                entry_to_modify_entry[
                                    'description'] = new_description
                            else:
                                entries[new_title][
                                    'description'] = new_description
                            print("Updated description")
                        else:
                            print("Did not update description")
                        print()

                    if new_password:
                        check = None
                        while check is None:
                            check = input(
                                "Are you sure to update the password? y/n: ")
                            check = confirm(check)
                        if check is True:
                            if not title_gets_updated:
                                entry_to_modify_entry[
                                    'password'] = new_password
                            else:
                                entries[new_title]['password'] = new_password
                            print("Updated password")
                        else:
                            print("Did not update password")
                        print()

                    self.__save_file__(entries)
                    print(f"\nUpdated entry: {entry_to_modify}\n")

                except KeyError:
                    print("You don't have a entry titled like that!")

                input("\nEnter to continue")
                clear_screen()
コード例 #17
0
ファイル: pdf_encrypter.py プロジェクト: amzorn1/python
ftypes = [('PDF Files', '*.pdf')]

print("\n\n\n\nPython File Encrypter")
print("Created by Alex Zorn\n")
print("Select a PDF file you want to encrypt\n")
in_file = filedialog.askopenfilename(title='Select a PDF file',
                                     filetypes=ftypes)
# Create reader and writer object
pdfReader = PyPDF2.PdfFileReader(in_file)
pdfWriter = PyPDF2.PdfFileWriter()
# Add all pages to writer (accepted answer results into blank pages)
for pageNum in range(pdfReader.numPages):
    pdfWriter.addPage(pdfReader.getPage(pageNum))
# Encrypt with your password
print("Enter a password with which to encrypt your PDF file:   \n")
password = pw.getpass()
pdfWriter.encrypt(password, use_128bit=True)

print("\nSelect an output directory to save your encrypted PDF\n\n")
currdir = os.getcwd()
tempdir = filedialog.askdirectory(parent=root,
                                  initialdir=currdir,
                                  title='Select a directory')

# Write it to an output file. (you can delete unencrypted version now)
resultPdf = open(tempdir + "/" + 'encrypted_output.pdf', 'wb')
pdfWriter.write(resultPdf)
resultPdf.close()
print("PDF File has been protected using 128-bit encryption.")
print("\nFile location: " + tempdir + "/" + "encrypted_output.pdf")
input("\nPress any key to exit....\n\n")
コード例 #18
0
#	this is primarily a local utility used to initialize the flaskapp database
#######################################################################################

import sqlite3
import stdiomask
import bcrypt

# delete db if exists, create new one
conn = sqlite3.connect('flaskapp.db')
cur = conn.cursor()
cur.execute("""DROP TABLE IF EXISTS flaskapp""")
cur.execute("""CREATE TABLE flaskapp
    (username text, password text, firstname text, lastname text, email text)"""
            )

# create admin account on init of db
print 'Enter your admin password here'
admin_pass = stdiomask.getpass(mask='*')

# store salt into a file locally (DO NOT LOSE IT!!!)
salt = bcrypt.gensalt()
with open('salt.txt', 'wc') as f:
    f.write(salt)
hashed = bcrypt.hashpw(admin_pass, salt)

# add the admin account and commit db changes
cur.execute("""INSERT INTO flaskapp VALUES (?,?,?,?,?)""",
            ('admin', hashed, 'admin', 'account', '*****@*****.**'))
conn.commit()
conn.close()
コード例 #19
0
def forgot_pwd():
    # Asking if they know their username
    print("Do you know your username?\n1) Yes\n2) No")
    print("--------------------------")

    # Input validation and seeing if they need to quit the program
    know_username = input("Your selection: ")
    if know_username.upper() == QUIT:
        close_program()
    while validateInput(know_username) == False or int(know_username) < YES or int(know_username) > NO:
            print("Please enter a valid selection.")
            user_selection = str(input("Your selection: "))
            if user_selection.upper() == QUIT:
                close_program()
    
    # Converting input to an integer for the selection below
    know_username = int(know_username)
    
    # Empty variable to hold the username based on the if / elif statements below
    username = ''
    
    # If the user knows their username....
    if know_username == YES:
        print()
        uk_username = input("What is your username? ").lower()  # "Unknown user name" variable from input
        if uk_username.upper() == QUIT:
                close_program()

        # trying to get the username in the database based on the user input
        try:  
            C.execute(f'SELECT username FROM usernameAndPasswords WHERE username = "******"')
            test_username = C.fetchone() # Getting the results of the cursor and assigning it to a variable
            test_username = ''.join(test_username) # converting the results from a tuple to a string
            if uk_username == test_username:

                print("We found a matching username")
                username = uk_username
                print()
        except Exception:
            print ("We were not able to find the specified username, please try again.")
            close_program()

    # If the user DOES NOT know their username...
    elif know_username == NO:
        print()
        email = input("What is the email associated to this email? ")
        if email.upper() == QUIT:
                close_program()

        # Testing to see if the email is in the database.
        try:  
            C.execute(f'SELECT email FROM usernameAndPasswords WHERE email = "{email}"')
            test_email = C.fetchone() # Getting the results of the cursor and assigning it to a variable
            test_email = ''.join(test_email) # converting the results from a tuple to a string
            if email == test_email: # if user email and db email matches..
                print("We found a username associated to that email.")
                C.execute(f'SELECT username FROM usernameAndPasswords WHERE email = "{email}"') # Getting the username associated to the email
                db_username = C.fetchone()
                db_username = ''.join(db_username) # Converting it to the string format from the db
                print(f"This is your username: {db_username}\n")  # Printing off the username to the host
                username = db_username # assigning the db username to the empty username variable above

        except Exception:
            print ("Specified email was not found in the system.")
            print("Please try again")
            close_program()
    

    # Getting the security questions and answers from the database
    C.execute(f'SELECT question1 FROM usernameAndPasswords WHERE username = "******"') 
    question1 = C.fetchone()
    question1 = ''.join(question1)
    C.execute(f'SELECT answer1 FROM usernameAndPasswords WHERE username = "******"') 
    answer1 = C.fetchone()
    answer1 = ''.join(answer1)

    C.execute(f'SELECT question2 FROM usernameAndPasswords WHERE username = "******"') 
    question2 = C.fetchone()
    question2 = ''.join(question2)
    C.execute(f'SELECT answer2 FROM usernameAndPasswords WHERE username = "******"') 
    answer2 = C.fetchone()
    answer2 = ''.join(answer2)
    
    # Asking the security questions to the user and storing their answer in a variable to compare with
    user_answer1 = input(f"{question1} ").lower()
    if user_answer1.upper() == QUIT:
                close_program()
    user_answer2 = input(f"{question2} ").lower()   
    if user_answer2.upper() == QUIT:
                close_program()

    # If the user got the security questions correct
    if answer1 == user_answer1 and answer2 == user_answer2:
        new_password = stdiomask.getpass("Please enter a new password: "******"Confirm the new password: "******"Passwords did not match.")
            new_password = stdiomask.getpass("Please enter a new password: "******"Confirm the new password: "******"{new_password}" WHERE username = "******"')
        CONN.commit()
        print("\nPassword has been updated!\n")
        close_program()
        

    # If they did not get the security questions correct
    else: 
        print("Sorry, the security questions were incorrect, please try again")
        close_program()
コード例 #20
0
def connect_reviewer_table():
    conn = None

    host = input('Enter Host for database: ')
    database = input('Enter database name: ')
    user = input('Enter user for database: ')
    password = stdiomask.getpass("Enter password: "******"""For reviewers table: 
            Enter 1 to insert
            Enter 2 to update
            Enter 3 to delete...
            """))

            if user_selection == 1:
                sql_insert= "INSERT INTO reviewers (first_name, last_name) VALUES (%s, %s);"

                val = []
                numberOfEntries = int(input("How many records do you want to enter?: "))

                for i in range(numberOfEntries):
                    first_name = input("Enter first name: ")
                    last_name = input("Enter last name: ")
                    
                    print()

                    val.append((first_name, last_name))
                db_cursor.executemany(sql_insert, val)

                conn.commit()

                print(db_cursor.rowcount, 'record(s) are inserted')

            if user_selection == 2:
                numberOfEntries = int(input("How many fields do you want to update?: "))

                for i in range(numberOfEntries):
                    column_name = input("Enter column name: ")
                    updated_value = input("Enter new value: ")
                    reviewer_id = int(input("Enter reviewer id: "))
                    update = column_name + "=" + updated_value
                    # val.append((first_name, last_name))
                    sql_update = "UPDATE reviewers SET " + column_name + "=" + "\'" + updated_value + "\' WHERE reviewer_id = " + str(reviewer_id)
                    # values = (first_name, reviewer_id)
                    db_cursor.execute(sql_update)
                    conn.commit()
                    print(db_cursor.rowcount, 'field(s) are updated')

            if user_selection == 3:
                numberOfEntries = int(input("How many records do you want to delete?: ")) 
                for i in range(numberOfEntries):
                    value = input("Enter the value of the row: ")
                    column_name = input("Enter column name: ")
                    # reviewer_id = int(input("Enter reviewer id: "))
                    
                    sql_delete = "DELETE from reviewers WHERE " + column_name + "=" + "\'" + value + "\'"
                    print()

                    # val.append((first_name, last_name))
            
                db_cursor.execute(sql_delete)

                conn.commit()

                print(db_cursor.rowcount, 'record(s) are deleted')
             
            else:
                print("Invalid selection")
                connect_reviewer_table()

            db_cursor.close

    except Error as e:
        print('Connection failed due to the following:', e)
    finally:
        if conn is not None and conn.is_connected():
            conn.close()
            print('Disconnected from the database')
コード例 #21
0
import mysql.connector
import stdiomask
from mysql.connector import Error
import os

username_str = input("Enter your db username: "******"Enter db name ")

conn = None


def initialize_connection():
    try:
        global conn
        conn = mysql.connector.connect(
            host='localhost',
            user=username_str,
            password=password_str
        )
        print('connection successful')
        if conn.is_connected():
            sql = f'CREATE DATABASE IF NOT EXISTS {db_name}'
            conn.cursor().execute(sql)
            print(f"{db_name} created successfully")
            return conn
    except Error as connection_error:
        print("Connection failed due to ", connection_error)

コード例 #22
0
import stdiomask
print("WELCOME TO MONEYHEIST")

name = ""
print("Enter credentials: \n")
credentials = {"Nikita": "Nikit@1232", "parth": "Krishna", "admin": "password"}

var1, var2 = 1, 3
while var1 == 1:
    name = input("Enter the username :"******"Enter the password : "******"LOGGED IN")
            else:
                var2 -= 1
                print("You have ", var2, " attempts remaining")
                if var2 == 0:
                    print("Now calling 911!!!")
    else:
        print("Enter correct Details!!!  \n")

# For the transactions and stuff
'''

total_amt = 5000
コード例 #23
0
ファイル: run.py プロジェクト: 1010011-1010010/reddit_scraper
    resp = requests.get(data["url"])
    with open(os.path.join(save_folder, data["name"] + "." + image_type),
              "wb") as f:
        f.write(resp.content)


def process_video(data: dict):
    resp = requests.get(
        data["preview"]["reddit_video_preview"]["fallback_url"])
    with open(os.path.join(save_folder, data["name"] + ".mp4"), "wb") as f:
        f.write(resp.content)


if __name__ == "__main__":
    reddit_user_name = input("reddit_user_name: ")
    reddit_password = stdiomask.getpass("reddit_password: "******"latest_saved_post.txt"):
        with open("latest_saved_post.txt", "r") as f:
            before_post = f.read()

    if before_post:
        while True:
            posts = get_saved_posts(authenticate_user,
                                    before=before_post,
                                    posts_limit=posts_limit)
            for post in posts["data"]["children"]:
                print(post["data"]["name"])
                post_hint = post["data"].get("post_hint")
コード例 #24
0
def get_env_data():
    trakt.core.CONFIG_PATH = pytrakt_file
    print("")
    #plex_needed = util.input_yesno("Are you logged into hawke.one with your Plex account? (almost certainly yes)")
    plex_needed = 1
    if plex_needed:
        username = input("    Please enter your Plex username: "******"    Please enter your Plex password: "******"\nNext we will need your server name:\n\n    The server name is displayed top left (under the library title) when viewing a library on that server:\n    https://app.plex.tv/desktop \n\n    For Hawke.one your server name will most likely be one of the following:"
        )
        print("     1) plex1.hawke.one (usually for Golden Company)")
        print("     2) plex2.hawke.one (usually for Nightswatch)")
        print("     3) plex3.hawke.one (usually for Kings Guard")
        print("     4) plex4.hawke.one (usually for Nightswatch)")
        servername = input(
            "\n    Please select you server (1-4), or enter your custom server name: "
        )
        if servername == "1": servername = "plex1.hawke.one"
        if servername == "2": servername = "plex2.hawke.one"
        if servername == "3": servername = "plex3.hawke.one"
        if servername == "4": servername = "plex4.hawke.one"
        print("    Verifying server...")
        account = MyPlexAccount(username, password)
        plex = account.resource(
            servername).connect()  # returns a PlexServer instance
        token = plex._token
        users = account.users()
        if users:
            print("\n    The following managed Plex user(s) were found:")
            for user in users:
                if user.friend is True:
                    print("     * " + user.title)
            print(" ")
            name = input(
                "    To use your " + username +
                " account, press enter (else enter the name of a managed user): "
            )
            while name:
                try:
                    useraccount = account.user(name)
                except:
                    if name != "_wrong":
                        print("Unknown username!")
                    name = input(
                        "Please enter a managed username (or just press enter to use your main account): "
                    )
                    if not name:
                        print("Ok, continuing with your account " + username)
                        break
                    continue
                try:
                    token = account.user(name).get_token(
                        plex.machineIdentifier)
                    username = name
                    break
                except:
                    print("    Impossible to find the managed user \'" + name +
                          "\' on this server!")
                    name = "_wrong"
        CONFIG["PLEX_USERNAME"] = username
        CONFIG["PLEX_TOKEN"] = token
        CONFIG["PLEX_BASEURL"] = plex._baseurl
        CONFIG["PLEX_FALLBACKURL"] = "http://localhost:32400"

        print("    User {} configured successfully.".format(username))
        # print("PLEX_TOKEN={}".format(token))
        # print("PLEX_BASEURL={}".format(plex._baseurl))
    else:
        CONFIG["PLEX_USERNAME"] = "******"
        CONFIG["PLEX_TOKEN"] = "-"
        CONFIG["PLEX_BASEURL"] = "http://localhost:32400"

    trakt.core.AUTH_METHOD = trakt.core.DEVICE_AUTH
    print("\n\n")
    print("Now we'll setup the Trakt part of things:")
    print(" ")
    print(
        "    Create the required Trakt client ID and secret by completing the following steps:"
    )

    if platform.system() == "Windows":
        print(
            "      1 - Press enter below to open http://trakt.tv/oauth/applications"
        )
        print("      2 - Login to your Trakt account")
        print("      3 - Press the NEW APPLICATION button")
        print(
            "      4 - Set the NAME field = hawke.one (or something else meaningful)"
        )
        import pyperclip
        pyperclip.copy("urn:ietf:wg:oauth:2.0:oob")
        print(
            "      5 - Set the REDIRECT URL field = urn:ietf:wg:oauth:2.0:oob (This has been copied to your clipboard for you)"
        )
        input(
            "\n    Press Enter to open http://trakt.tv/oauth/applications and complete steps 1-6: "
        )
        webbrowser.open('http://trakt.tv/oauth/applications')
    else:
        print(
            "      1 - Open http://trakt.tv/oauth/applications on any computer"
        )
        print("      2 - Login to your Trakt account")
        print("      3 - Press the NEW APPLICATION button")
        print("      4 - Set the NAME field = hawke.one")
        print(
            "      5 - Set the REDIRECT URL field = urn:ietf:wg:oauth:2.0:oob")

    print("      6 - Press the SAVE APP button")

    print(
        "\n    Once steps 1-6 are completed, please proceed to steps 7-8 below:\n"
    )

    #client_id, client_secret = trakt.core._get_client_info()
    client_id = input("      7 - Copy and paste the displayed Client ID: ")
    client_secret = input(
        "      8 - Copy and paste the displayed Client secret: ")

    if platform.system() == "Windows":
        input(
            "\n    We will now generate a user code and open https://trakt.tv/activate for you to authenticate the app.\n    Press Enter to continue..."
        )
        webbrowser.open('https://trakt.tv/activate')
        print("\n")

    trakt.init(client_id=client_id, client_secret=client_secret, store=True)
    trakt_user = trakt.users.User('me')
    CONFIG["TRAKT_USERNAME"] = trakt_user.username

    print("\n\n")
    print("You're all done!\n")
    print(
        "Plex / Trakt accounts may be altered by re-running setup, or deleting the .env and .pytrakt.json files."
    )
    print("Expert settings may also be altered within the config.json file.")
    print(" ")
    print(" ")

    CONFIG.save()
コード例 #25
0
ファイル: main.py プロジェクト: 7000WORDS/GUI-password
from tkinter import *
import tkinter as tk
from tkinter import messagebox
import webbrowser
import stdiomask

username = input("set your username: "******"set your password: "******"*")


def Ok():

    uname = e1.get()
    pword = e2.get()

    if (uname == "" and pword == ""):
        messagebox.showinfo("", "Blank Not allowed")

    elif (uname == username and pword == password):

        messagebox.showinfo("", "Login Success")
        ruut = Tk()
        ruut.title("Understandable")
        root.destroy()

    else:
        messagebox.showinfo("", "Incorrent Username and Password")


def callback(url):
コード例 #26
0
    
    encoded_list[up]  = chr(ord(encoded_list[up])%26 + ord('A')).upper()
    encoded_list[num] = str(ord(encoded_list[num]) % 10)
    encoded_list[spc] = chr(special_chars[ord(encoded_list[spc])%26])
    
    encoded_text = "".join(encoded_list)
    
    return encoded_text



print("\n\tAll input should be in lower case\n")
print("\tEnter the name of the site you want a password for.\n\tFor www.facebook.com enter only facebook\n")
site  = input("Enter site name: ")
email = input("Enter your email: ")
print('''\n\tNow you have to enter a secrete code.\n\tThis can be same for all of your password.\n\tMost importantly you must enter the same secrete code for same site everytime.\n''')
    
while(True):    
    key   = secret.getpass("Enter a secrete code: ")
    print("\n\tPlease retype your secrete code")
    repkey   = secret.getpass("Re-type: ")

    if(key == repkey):
        print("Your Password is : {}".format(encrypt(site,email,key)))
        break
    else:
        print("\n\tSecret Code doesn't match.\n\t Try again")



コード例 #27
0
def storageinfo():
    global URL
    env = input(
        "Please select the env you want to query? [QA, Stage, or Prod]: "
    ).upper()
    if env in ['QA', 'STAGE', 'PROD']:

        user = input("Please enter a " + f'{env}' + " username: "******"Please enter " + f'{env}' +
                                     ' password for user ' + f'{user}: ')

        if env == 'PROD':
            site = input(
                'Please enter a site location to query [SJC, RTP-SAT, RTP-DR, GPK, BGL, NTN]: '
            ).lower()
            if site == 'rtp-dr':
                site = 'rtp'
                URL = f'http://{site}-wapl-localhost.com:6090'
            elif site == 'sjc':
                URL = f'http://{site}-wapl-localhost.com:6090'
            elif site == 'rtp-sat':
                site = 'rtp'
                URL = f'http://{site}-wapl-localhosts4.com:6090'
            elif site == 'ntn':
                URL = f'http://{site}-wapl-localhost2.com:6090'
            elif site == 'gpk' or site == 'bgl':
                URL = f'http://{site}-wapl-localhost3.com:6090'
            else:
                print(
                    'Please re-run script and select one of the following PROD sites [SJC, RTP-SAT, RTP-DR, GPK, BGL, NTN]'
                )

        elif env == 'STAGE':
            site = input(
                'Please enter a site location to query [SJC, RTP-DR, GPK]: '
            ).lower()
            if site == 'rtp-dr':
                site = 'rtp'
                URL = f'http://{site}-stg-localhost1.com:6090'
            elif site == 'sjc' or site == 'gpk':
                URL = f'http://{site}-stg-localhost1.com:6090'
            else:
                print(
                    'Please re-run script and select one of the following STAGE sites [SJC, RTP-DR, GPK,]'
                )

        elif env == 'QA':
            site = input(
                'Please enter a site location to query [SJC, RTP-DR,GPK]: '
            ).lower()
            if site == 'rtp-dr':
                site = 'rtp'
                URL = f'http://{site}-qa-localhost1.com:6090'
            elif site == 'sjc' or site == 'gpk':
                URL = f'http://{site}-qa-localhost1.com:6090'
            else:
                print(
                    'Please re-run script and select one of the following QA sites [SJC, RTP-DR, GPK,]'
                )
        else:
            print(
                'Please re-run script and select one of the following env [QA, Stage, or Prod]'
            )
        try:

            print(
                f'Querying API endpoint, please wait while I fetch the data.........'
            )
            session = requests.Session()

            r = session.get(url=f'{URL}/localhost/api/storageinfo',
                            auth=(user, password),
                            timeout=None)

            if r.status_code != 200:
                print('Script failed due to the following status code  ===>',
                      r.status_code)
                exit(1)

            dataJson = r.json()
            data = dataJson['storageSummary']['repositoriesSummaryList']
            df = pandas.DataFrame(data=data)

            print('Done, Saving the file ' +
                  f'localhost_{env}_{site.upper()}_Storage_Quota_report.csv' +
                  ' to current working directory')
            df.to_csv(
                f'./localhost_{env}_{site.upper()}_Storage_Quota_report.csv',
                index=False)

        # catch all the exceptions
        except requests.exceptions.RequestException as e:
            print('ERROR: Request failed due to the following error =====>', e)

    else:
        print('Please only enter, [QA, Stage, or Prod]')
コード例 #28
0
def main():
    # clear the screen
    clear()

    # access to global variables
    global enter
    global pressed
    global serverMessage
    global upToDateServer
    global upToDate
    global serverOwner
    global filesList
    global selectedFile

    # internal flags to determin the state of the program
    # to save if the program should be running or not
    running = True
    # to save if the user is logged in or not
    loggedIn = False
    # to save if the user is logged in a server or not
    serverLoggedIn = False

    # link the keyboard api to the function that handles inputs
    keyboard.on_press(keyboardEventHandler)

    # try to login through cookie
    if loginWithoutCredentials():
        loggedIn = True

    # MAIN LOOP
    while running:
        # print the server message (errors, info etc...)
        if (serverMessage != ""):
            print(colored(serverMessage + "\n", 'yellow'))

        # LOGIN
        if not loggedIn:
            # print the login commands (login, login with cookie, register, delete, close)
            printLoginCommands()

            # keyboard event polling
            while not pressed and not enter:
                pass
            pressed = False

            # login
            if selectedLoginCommand == 0 and enter == True:
                # clean the previous server message
                serverMessage = ""
                # flush the inputs buffer before getting user inputs
                flushInput()
                # get the username from the user
                usernameL = input("\nUsername: "******""
                # flush the inputs buffer before getting user inputs
                flushInput()
                # get the username from the user
                usernameL = input("\nUsername: "******""
                # flush the inputs buffer before getting user inputs
                flushInput()
                # get the username from the user
                usernameL = input("\nUsername: "******""
                # flush the inputs buffer before getting user inputs
                flushInput()
                # get the username from the user
                usernameL = input("\nUsername: "******"User: "******""

                # New server
                if selectedServer == 0:
                    # clean the input buffer before a user input
                    flushInput()
                    # get the new server name from the user
                    serverName = input("\nServer Name: ")
                    # transform the server name into lower case (to match with the minio bucket, which only accepts lower case names)
                    serverName = serverName.lower()
                    print()
                    # get the new server password from the user without showing it
                    serverPassword = stdiomask.getpass(mask='*')
                    # check if the new server was created correctly
                    if createServer(serverName, serverPassword):
                        # notify that the user is not logged in to the newly created server
                        serverLoggedIn = True
                        # notify to recheck the server list, now that a new server has been created
                        upToDateServer = False
                        # set the files list to "null" to notify that when entering the server, the file list should be redownloaded
                        filesList = ["null"]
                        # notify that the file list needs to be updated
                        upToDate = False
                        # sets the selected file to 0 to set it to the beginning, since there won't be any files to begin with
                        selectedFile = 0
                    # sets enter to false to listen for a new command
                    enter = False

                # Logout
                elif selectedServer == len(serverList) + 1:
                    # sets enter to false to listen for a new command
                    enter = False
                    # notify that the user is no longer logged in into any account
                    loggedIn = False
                    # notify that the user isn't the server owner anymore
                    serverOwner = False

                    # try to remove the cookie.txt file if it exists
                    try:
                        os.remove("cookie.txt")
                    except IOError:
                        print("No cookie to remove")

                # Login server
                else:
                    # clean the input buffer before a user input
                    flushInput()
                    print()
                    # get the server password from the user without showing it
                    serverPassword = stdiomask.getpass(mask='*')
                    # set enter to false to listen for new commands
                    enter = False
                    # check if the server login was succesful
                    if loginServer(serverPassword):
                        # notify that the user is logged into a server
                        serverLoggedIn = True
                        # set the fileslist to "null" to make it update
                        filesList = ["null"]
                        # notify that the files list needs to be updated
                        upToDate = False
                        # set the selected file to the first one
                        selectedFile = 0

            # clear the screen
            clear()

        # FILE MANAGEMENT
        else:
            # if the user is the server owner
            if serverOwner:
                # print the user in blue color
                print("User:"******"User: "******"\nServer: " + serverCurrent)

            # print all the files within the current server
            printFiles()

            print()

            # print all the available commands inside a server
            printCommands()

            # keyboard event polling
            while not pressed and not enter:
                pass
            pressed = False

            # upload file
            if selectedCommand == 0 and enter == True:
                # wipe the server message
                serverMessage = ""
                # set enter to false to listen for a new input
                enter = False
                # try to open a file to upload
                try:
                    # get the file path
                    path = askopenfilename()
                    # upload it to the server
                    uploadFile(path)
                # if there's no file uploaded or any IOError
                except IOError:
                    # notify the user of the error
                    serverMessage = "No file selected"

            # download file
            elif selectedCommand == 1 and enter == True:
                # check if the file list isn't empty
                if len(filesList) == 0:
                    # notify that there isn't any file to download
                    serverMessage = "No file to download!"
                    # set enter to false to listen for a new input
                    enter = False
                else:
                    # wipe the server message
                    serverMessage = ""
                    # set enter to false to listen for a new input
                    enter = False
                    # download the file specified
                    downloadFile(filesList[selectedFile])

            # delete file
            elif selectedCommand == 2 and enter == True:
                # check if the file list isn't empty before deleting a file
                if len(filesList) == 0:
                    # if the list of files is empty, notify the user that there's no file to delete
                    serverMessage = "No file to delete!"
                    # set enter to false to listen for a new input
                    enter = False
                else:
                    # wipe the server message
                    serverMessage = ""
                    # clean the input buffer
                    flushInput()
                    # ask the user if they are sure about the choice
                    choice = input("Are you sure? [Yes/No]: ")
                    # set enter to false to listen for a new input
                    enter = False
                    # if the user choice was positive
                    if choice == "Yes" or choice == "yes" or choice == "ye" or choice == "y":
                        # delete the selected file
                        deleteFile(filesList[selectedFile])

            # change server
            elif selectedCommand == 3 and enter == True:
                # wipe the server message
                serverMessage = ""
                # set enter to false to listen for a new input
                enter = False
                # logout from the server
                serverLoggedIn = False
                # set the server owner to false, since we're not inside any server anymore
                serverOwner = False

            # delete server
            elif selectedCommand == 4 and enter == True:
                # wipe the server message
                serverMessage = ""
                # clean the input buffer
                flushInput()
                # ask the user if they are sure about the choice
                choice = input("Are you sure? [Yes/No]: ")
                # set enter to false to listen for a new input
                enter = False
                # if the user choice was positive
                if choice == "Yes" or choice == "yes" or choice == "ye" or choice == "y":
                    # delete the server
                    if deleteServer():
                        # logout of the server
                        serverLoggedIn = False
                        # set the server owner to false since there's no server anymore
                        serverOwner = False
                        # notify that the server list needs to be updated
                        upToDateServer = False

            # logout
            elif selectedCommand == 5 and enter == True:
                # wipe the server message
                serverMessage = ""
                # set enter to false to listen for new inputs
                enter = False
                # logout of the account
                loggedIn = False
                # logout of the server
                serverLoggedIn = False
                # set the server owner to false, since we're not logged in to a server anymore
                serverOwner = False
                # try to remove the cookie file in case it's there
                try:
                    os.remove("cookie.txt")
                except IOError:
                    print("No cookie to remove")

            # close
            elif selectedCommand == 6 and enter == True:
                # set enter to false to listen for new inputs
                enter = False
                # stops the program from running
                running = False
                # clear the inputs before closing
                flushInput()

            # clean the screen
            clear()
コード例 #29
0
ファイル: set-category.py プロジェクト: vcdgibbs/scripts
        # código para dict de una sola VM
        myVarItem = { 
            "vm_name" : pars['vm'],
            "category_name" : pars['category'],
            "value_name" : pars['value']
        }
        myListVMs = { "vm1" : myVarItem }
    else:
        printError("Please provide the VM with Category and Value information or CSV file")

# Enter password:
#Password = stdiomask.getpass()
if "password" in pars:
    Password = pars["password"]
else:
    Password = stdiomask.getpass()


# Variables
API_Server_End_Point="https://" + PC_IP + ":9440/api/nutanix/v3/"
PrismCreds = {
    "User" : User,
    "Password" : Password
    }
#headers = {'ContentType':'application/json','cache-control': 'no-cache','Accept':'application/json'}
headers = {'ContentType':'application/json','Accept':'application/json'}

###################################################################################
# API Calls to Prism Central
# https://httpstatuses.com/ is a good page to know the HTTP status codes
###################################################################################
コード例 #30
0
from email import encoders  #for encode payloads
from email.mime.multipart import MIMEMultipart  #to create multipart message object
from email.mime.text import MIMEText  #to create the plain text attachments
from email.mime.base import MIMEBase  #to create base to other subclasses
import getpass
import stdiomask

print("----------------------")
print("SEND EMAIL WITH PYTHON")
print("----------------------")

#LOGIN
print("Sign in to your Gmail account")
sender_address = input("Enter your email               : ")
while True:
    sender_pass = stdiomask.getpass("Enter your password            : "******"\nLOGIN SUCCESS")
        break
    except smtplib.SMTPAuthenticationError:  #SMTP exception
        print("Wrong Username/Password.")

print("\nCompose New Message")

r = open("receiver_list.txt", "r")

receiver_list = []