def handle(self, options, global_options, *args): from uliweb import functions import getpass self.get_application(global_options) password = getpass.getpass('Input your password(Blank will quit):') if not password: return password1 = getpass.getpass('Enter your password twice:') if password != password1: print("Your password is not matched, please run the command again") else: print(functions.encrypt_password(password))
def handle(self, options, global_options, *args): from uliweb import functions from uliweb.core.SimpleFrame import get_settings, __global__ import getpass settings = get_settings(global_options.project, settings_file=global_options.settings, local_settings_file=global_options.local_settings) __global__.settings = settings password = getpass.getpass('Input your password(Blank will quit):') if not password: return password1 = getpass.getpass('Enter your password twice:') if password != password1: print "Your password is not matched, please run the command again" else: print functions.encrypt_password(password)
def Get_Authentication(): USR = input("Username: ") PSW = getpass.getpass(prompt='Password: ', stream=None) Authentication = list() Authentication.append(USR) Authentication.append(PSW) return Authentication
def handle(self, options, global_options, *args): from uliweb import functions from uliweb.core.SimpleFrame import get_settings, __global__ import getpass settings = get_settings( global_options.project, settings_file=global_options.settings, local_settings_file=global_options.local_settings) __global__.settings = settings password = getpass.getpass('Input your password(Blank will quit):') if not password: return password1 = getpass.getpass('Enter your password twice:') if password != password1: print "Your password is not matched, please run the command again" else: print functions.encrypt_password(password)
def commissioning(self): # mise en service qui lira les contenus de 2 clefs usb pour recomposer la clef et l'écrira dans notre ram temporaire (ramdisk) subdirs = [] files = [] for root, subdir, file in os.walk(Server.plugged_path): subdirs += subdir files += file if len(subdirs) < 2 and len(files) < 2: raise Exception( "Vous devez ou moins avoir deux clefs usb connectés") print("Mise en service du serveur...") try: os.remove(Server.clear_key_path) except FileNotFoundError: pass try: with open(Server.plugged_path + subdirs[0] + "/" + files[0], "rb") as f: ciphertext = f.read() key1 = decrypt(getpass.getpass( prompt='Veuillez taper le mot de passe pour déverrouiller %s : ' % subdirs[0]), ciphertext).decode("utf-8") key1 = self.check_user_type(key1) with open(Server.plugged_path + subdirs[1] + "/" + files[1], "rb") as f: ciphertext = f.read() key2 = decrypt(getpass.getpass( prompt='Veuillez taper le mot de passe pour déverrouiller %s : ' % subdirs[1]), ciphertext).decode("utf-8") key2 = self.check_user_type(key2) if Server.is_judicial_officer == -1 or Server.is_technical_officer == -1: raise Exception("la Combinaison de la clef n'est pas bonne") with open(Server.clear_key_path, "w") as f: f.write(self.sxor(key1, key2)) Server.is_commissioning = True except DecryptionException: raise DecryptionException("Mauvais mot de passe")
def example(): username = input('Python login: '******'x' or cryptedpasswd == '*': raise ValueError('no support for shadow passwords') cleartext = getpass.getpass() return compare_hash(crypt.crypt(cleartext, cryptedpasswd), cryptedpasswd) else: return True
def encrypt(api_key, api_secret, export=True, export_fn='secrets.json'): cipher = AES.new( getpass.getpass('Input encryption password (string will not show)')) api_key_n = cipher.encrypt(api_key) api_secret_n = cipher.encrypt(api_secret) api = {'key': str(api_key_n), 'secret': str(api_secret_n)} if export: with open(export_fn, 'w') as outfile: json.dump(api, outfile) return api
def reset_password(username): code = input('Enter your code: ') if code == get_code(username): new_password = getpass.getpass() password = get_crypted(new_password) select_query = 'UPDATE clients SET password = (?) WHERE username = (?)' cursor.execute(select_query, (password, username)) conn.commit() return 'successfully change your password' else: return 'the code is incorrect'
def signup(): name=input("\nenter your name").lower() password=getpass.getpass() bal=int(input("enter the initial balance")) acc=bank['acc'][-1]+1 bank['name'].append(name) bank['password'].append(password) bank['bal'].append(bal) bank['acc'].append(acc) print("\nyour account succesfully created") print("\nplease note down your new account number{}".format(acc)) time.sleep(2)
def decrypt(self): if encrypted: cipher = AES.new( getpass.getpass('Input decryption password (string will not show)')) try: self.api_key = ast.literal_eval(self.api_key) if type( self.api_key) == str else self.api_key self.api_secret = ast.literal_eval(self.api_secret) if type( self.api_secret) == str else self.api_secret except: pass self.api_key = cipher.decrypt(self.api_key).decode() self.api_secret = cipher.decrypt(self.api_secret).decode() else: raise ImportError('"pycrypto" module has to be installed')
def login(username=None, password=None): """Return a logged in session.""" s = requests.session() if os.path.isfile(SESSION_CACHE): logging.debug("session cache found") with open(SESSION_CACHE, 'rb') as cache: return pickle.load(cache) if not (username and password): if os.path.isfile(CRED_FILE): logging.debug("credentials found") with open(CRED_FILE, 'r') as credentials: # TODO: less silly login = credentials.readline()[:-1] username, password = login.split(' ') else: logging.debug("credentials not found") username = input('Username: '******'http://www.neopets.com/login.phtml', data={ 'destination': "%2F", 'username': username, 'password': password }) # DEBUG #with open('/tmp/login.html', 'w') as fp: # fp.write(response.content.decode('utf-8')) # TODO: better validation if response.status_code != 200: logging.error("login unsuccessful") return None with open(SESSION_CACHE, 'wb') as cache: pickle.dump(s, cache) logging.debug("session cached") return s
def __init__(self, admin=False): """ Initialize TopoLens service with user authentication """ self.endpoint = "http://141.142.170.7:63830/rest/v1/" if admin: self.endpoint += "admin/" self.user = raw_input('User name ') self.token = requests.post( 'https://sandbox.cigi.illinois.edu/rest/token', data={ 'username': self.user, 'password': getpass.getpass('Password') }, verify=False).json()['result']['token'] self.headers = { 'x-user-name': self.user, 'x-auth-token': self.token, 'Content-Type': 'text/plain;charset=utf-8' }
def main(): global thread_exit global url print("Enter Match ID") url = url % input() print("Enter feed username") uname = input() print("Enter feed password") pwd = getpass.getpass() # Connect to ExternalExtensions' websocket print("Connecting to ExternalExtensions...",) try: ws = create_connection("ws://127.0.0.1:%s" % websockets_port) except ConnectionRefusedError: print("Connection to ExternalExtensions refused.") finally: print("Connection failed. Exiting") exit(1) print("Connected.") t = threading.Thread(target=send_events, args=ws) t.start() last_event = None while True: req = requests.get(url, auth=(uname, pwd)) if req.status_code == 401: print("Wrong Username and/or password") thread_exit = True exit(1) js = json.load(req.text) if last_event is None: last_event = add_events(js, 0) else: last_event = add_events(js, js.index(last_event) + 1)
def create_courses_file(): #TODO - this function is incomplete - needs to ask user if they want to create #TODO - give option to do this or choose existing #TODO - enrollment_term filter """Creates a file to work with get_courses_df from subaccount_id parameters: subaccount_id (Int): the subaccount to run in returns: df (Dataframe): dataframe with course ids and current course information """ account_id = getpass.getpass('Enter subaccount_id: ').strip() account = settings.CANVAS.get_account(account_id) courses = account.get_courses() course_info = [] for c in courses: course_dict = { 'course_id': c.id, 'course_name': c.name, 'term': c.enrollment_term_id, 'course_subaccount': c.account_id, 'course_subaccount_name': account.name, 'start_at': c.start_at, 'end_at': c.end_at, 'timezone': c.time_zone } course_info.append(course_dict) df = pd.DataFrame(course_info) df.to_csv( f'{settings.ROOT_PATH}/data/output/{account_id}-course information.csv' )
def write_usb4(self, clear_key, mask): ciphertext = encrypt(getpass.getpass( prompt='Configurez le mot de passe de usb4 (représentant juridique) : '), self.sxor(clear_key, mask)) with open(Server.plugged_path + Server.usb4_path, "wb") as f: f.write(ciphertext)
def write_usb3(self, mask): ciphertext = encrypt(getpass.getpass( prompt='Configurez le mot de passe de usb3 (représentant technique) : '), mask) with open(Server.plugged_path + Server.usb3_path, "wb") as f: f.write(ciphertext)
def rights_revocation(self): subdirs = [] files = [] for root, subdir, file in os.walk(Server.plugged_path): subdirs += subdir files += file if len(subdirs) < 3 and len(files) < 3: raise Exception( "Vous devez ou moins avoir 3 clefs usb connectées") try: with open(Server.plugged_path + subdirs[0] + "/" + files[0], "rb") as f: ciphertext = f.read() key1 = decrypt(getpass.getpass( prompt='Veuillez taper le mot de passe pour déverrouiller %s : ' % subdirs[0]), ciphertext).decode("utf-8") key1 = self.check_user_type(key1) with open(Server.plugged_path + subdirs[1] + "/" + files[1], "rb") as f: ciphertext = f.read() key2 = decrypt(getpass.getpass( prompt='Veuillez taper le mot de passe pour déverrouiller %s : ' % subdirs[1]), ciphertext).decode("utf-8") key2 = self.check_user_type(key2) secondKey = None # condition pour récupérer la bonne deuxième clef if Server.is_judicial_officer > -1 and Server.is_judicial_officer < 2 and Server.is_technical_officer > -1 and Server.is_judicial_officer < 2: secondKey = key2 with open(Server.plugged_path + subdirs[2] + "/" + files[2], "rb") as f: ciphertext = f.read() key3 = decrypt(getpass.getpass( prompt='Veuillez taper le mot de passe pour déverrouiller %s : ' % subdirs[2]), ciphertext).decode("utf-8") key3 = self.check_user_type(key3) # condition pour récupérer la bonne deuxième clef if Server.is_judicial_officer > -1 and Server.is_judicial_officer < 2 and Server.is_technical_officer > -1 and Server.is_judicial_officer < 2: secondKey = key3 if Server.is_judicial_officer == -1 or Server.is_technical_officer == -1: raise Exception("la combinaison de la clef n'est pas bonne") clear_key = self.sxor(key1, secondKey) with open(Server.clear_key_path, "w") as f: f.write(clear_key) # Pour voir nous à qui nous essayons de révoquer les droits repudiated_person = None if Server.is_judicial_officer == 1: repudiated_person = "REPRESENTANT JUDICIAIRE" elif Server.is_judicial_officer == 0: repudiated_person = "RESPONSABLE JUDICIAIRE" elif Server.is_technical_officer == 1: repudiated_person = "REPRESENTANT TECHNIQUE" elif Server.is_technical_officer == 0: repudiated_person = "RESPONSABLE TECHNIQUE" print( "Commencement de la procédure de révocation de droit du " + repudiated_person + "...") clear_line = [] with open(self.card, "rb") as f: lines = f.read().split('///---'.encode('utf-8')) for i in range(len(lines) - 1): clear_line.append(decrypt(clear_key, lines[i]).decode("utf-8")) clear_key = None print( "Récupération du contenu des paires carte/nom avec l'ancienne clef de cryptage/decryptage : DONE") subdirs = [] while(len(subdirs) < 4): for root, subdir, file in os.walk(Server.plugged_path): subdirs += subdir print("Veuillez vérifier que quatres clefs usb sont branchées pour définir la nouvelle clef de cryptage et les 4 responsables/représentants") input( "Appuyez sur une touche une fois que les quatres clefs usb sont branchées...") self.init(clear_line) except DecryptionException: raise DecryptionException("Mauvais mot de passe")
from mastodon import Mastodon from getpass import getpass def prompt(p, d=""): ret = input(p + " (" + d + ") ") ins = prompt("Instance: ", d="https://botsin.space") Mastodon.create_app(input("Title: "), api_base_url=ins, to_file='clientcred.txt') sgc = Mastodon(client_id="clientcred.txt", api_base_url=ins) sgc.log_in(input("Email: "), getpass.getpass("Password: "******"accesscred.txt")
from netmiko import ConnectHandler from getpass import getpass import getpass import re import openpyxl #######*****####### Device_LIST = open('inventory.txt') user1 = input("Enter Username: "******"Enter Password: "******"Enter Password: "******"Logging_info" rowdata = [ "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD" ] Logg = "logging" cmd1 = "show run | sec logging" i = 2 for Host in Device_LIST: print("Reading Device info of " + Host.strip() + "")
def _set_password(service): from keyring import set_password from getpass import getpass set_password(service, input("Username: "), getpass.getpass())
from netmiko import ConnectHandler from getpass import getpass import os with open("commands.txt","r") as file: cmds = (line.rstrip() for line in file) cmds = list(cmd for cmd in cmds if cmd) cmds_len = len(cmds) if not os.path.exists('logs'): os.makedirs('logs') host = input('hostname:') username = input('username:'******'password:'******'host': host, 'username': host, 'password': password, 'device_type': 'cisco_xr', } try: net_connect = ConnectHandler(**my_device) f1 = open('logs/' + host + '.txt', "w+") f1.write('\n') for cmd in cmds: print(cmd.strip('\n')) output = net_connect.send_command(cmd,delay_factor=10,max_loops=100)
tn.write(b"end\n") tn.write(b"wr\n") tn.write(b"exit\n") print(tn.read_all().decode('ascii')) """ Program 3: Backup switches configs """ import getpass import telnetlib user = input('Enter your telnet username: '******'myswitches') for IP in f: IP=IP.strip() print ('Get running config from Switch ' + (IP)) HOST = IP tn = telnetlib.Telnet(HOST) tn.read_until(b'Username: '******'ascii') + b'\n') if password: tn.read_until(b'Password: '******'ascii') + b'\n') tn.write(b"terminal length 0\n") tn.write(b"show run\n")
import os import sys from getpass import getpass module = os.path.dirname(os.path.dirname(__file__)) sys.path.append(module) from Utils.KMS.DocServer import DocServer user = input("user:"******"document id:") ds = DocServer() ds.login(user, pw) doc = ds.read_doc_by_id(doc_id) view_links = doc.get_view_link() file_links = doc.get_files_link() for file in file_links: if file_links[file_links] is None: ds.download_view_url(view_links[file]) continue ds.download_file_url(file, file_links[file])
connection_dict = {} for vpn in vpns: neighbor = '' for tag in vpn.getchildren(): connection_details_dict = {} if tag.tag == 'neighbor-address': neighbor = tag.text if tag.tag == 'connection': for child in tag.getchildren(): if child.tag == 'local-interface': ifce = child.find('interface-name').text connection_details_dict.update({'interface': ifce}) else: if child.tag == 'connection-id': cid = child.text else: connection_details_dict.update({child.tag: child.text}) connection_details_dict.update({'neighbor': neighbor}) if connection_dict.get(cid): connection_dict.get(cid).append(connection_details_dict) else: connection_dict.update({cid: [connection_details_dict]}) return connection_dict if __name__ == '__main__': host = 'router.example.com' username = raw_input('Give the username for %s: ' % host) password = getpass.getpass('Give the password: ') response = connect(host, username, p)
# Python 3.6 # Made to run on Windows at command prompt # the main function runs it all and calls the other functions from netmiko import ConnectHandler from netmiko.ssh_exception import NetMikoTimeoutException from netmiko.ssh_exception import NetMikoAuthenticationException from getpass import getpass import re platform = 'cisco_wlc' fopen = open('ap_host.txt', 'r') hosts = fopen.read().splitlines() username = '******' #####Edit this for your username########## password = getpass.getpass("Please enter the password for the WLCs: " ) def main(): for i in hosts: net_connect = connect_to_host(i) # connect to host aps = get_aps(net_connect) get_count(aps) def get_count(ap_list): sites=[] #dictionary to store the aps in ap_dict={} out_csv = 'ap_count.csv' #get the ap list and just get the three digit site codes from it for i in ap_list:
connection_details_dict = {} if tag.tag == 'neighbor-address': neighbor = tag.text if tag.tag == 'connection': for child in tag.getchildren(): if child.tag == 'local-interface': ifce = child.find('interface-name').text connection_details_dict.update({'interface': ifce}) else: if child.tag == 'connection-id': cid = child.text else: connection_details_dict.update( {child.tag: child.text}) connection_details_dict.update({'neighbor': neighbor}) if connection_dict.get(cid): connection_dict.get(cid).append( connection_details_dict) else: connection_dict.update( {cid: [connection_details_dict]}) return connection_dict if __name__ == '__main__': host = 'router.example.com' username = raw_input('Give the username for %s: ' % host) password = getpass.getpass('Give the password: ') response = connect(host, username, p)
import xml.etree.ElementTree as ET from getpass import getpass env = input("Enter the environment(SIT,QA,UAT or PROD) : ") env = env.upper() if env == "PROD": verify = input("\nYou entered PROD Y/N : ") if verify != "Y": print("Process is exiting as environment is not verified. \n") exit(1) reason = input("Reason for resend message(INC, JIRA or ALM) : ") url = input("Enter URL : ") username = input("Enter username : "******"Process is starting for " + env + "\n") def parse(ANSWER): print("\nANSWER ", ANSWER) try: tree = ET.fromstring(ANSWER) result = {} for item in tree.getiterator(): result[item.tag] = item.text resp1 = result print("\nRESPONSE ", resp1) except Exception:
#Importation des modules nécessaires. from netmiko import ConnectHandler from netmiko.ssh_exception import NetMikoTimeoutException from getpass import getpass from datetime import datetime import getpass import calendar import time import os import errno import sys #Récupération des informations d'identifications print("Entrez vos informations de connexion: ") username = input("Username: \n") password = getpass.getpass("Password: \n") #Fonction destinée à propulser un fichier de configuration vers les équipements. def configuration(): start_time = datetime.now() #Ouverture du fichier de configuration et du fichier contenant les IP des commutateurs. with open('CONFIGURATION_L2') as f: lines_l2 = f.read().splitlines() with open('switch.list') as f: ip_sw = f.read().splitlines() #Boucle autant de fois qu'il y a de ligne dans le fichier 'switch.list'. for ip in ip_sw: device = {