예제 #1
0
def _saveKey(key, options):
    """
    Persist a SSH key on local filesystem.

    @param key: Key which is persisted on local filesystem.
    @type key: C{keys.Key} implementation.

    @param options:
    @type options: L{dict}
    """
    KeyTypeMapping = {'EC': 'ecdsa', 'RSA': 'rsa', 'DSA': 'dsa'}
    keyTypeName = KeyTypeMapping[key.type()]
    if not options['filename']:
        defaultPath = os.path.expanduser(u'~/.ssh/id_%s' % (keyTypeName,))
        newPath = raw_input(
            'Enter file in which to save the key (%s): ' % (defaultPath,))

        options['filename'] = newPath.strip() or defaultPath

    if os.path.exists(options['filename']):
        print('%s already exists.' % (options['filename'],))
        yn = raw_input('Overwrite (y/n)? ')
        if yn[0].lower() != 'y':
            sys.exit()

    if options.get('no-passphrase'):
        options['pass'] = b''
    elif not options['pass']:
        while 1:
            p1 = getpass.getpass(
                'Enter passphrase (empty for no passphrase): ')
            p2 = getpass.getpass('Enter same passphrase again: ')
            if p1 == p2:
                break
            print('Passphrases do not match.  Try again.')
        options['pass'] = p1

    comment = '%s@%s' % (getpass.getuser(), socket.gethostname())

    filepath.FilePath(options['filename']).setContent(
        key.toString(
            'openssh', subtype=options.get('private-key-subtype'),
            passphrase=options['pass']))
    os.chmod(options['filename'], 33152)

    filepath.FilePath(options['filename'] + '.pub').setContent(
        key.public().toString('openssh', comment=comment))
    options = enumrepresentation(options)

    print('Your identification has been saved in %s' % (options['filename'],))
    print('Your public key has been saved in %s.pub' % (options['filename'],))
    print('The key fingerprint in %s is:' % (options['format'],))
    print(key.fingerprint(options['format']))
예제 #2
0
def _saveKey(key, options):
    """
    Persist a SSH key on local filesystem.

    @param key: Key which is persisted on local filesystem.
    @type key: C{keys.Key} implementation.

    @param options:
    @type options: L{dict}
    """
    KeyTypeMapping = {'EC': 'ecdsa', 'RSA': 'rsa', 'DSA': 'dsa'}
    keyTypeName = KeyTypeMapping[key.type()]
    if not options['filename']:
        defaultPath = os.path.expanduser(u'~/.ssh/id_%s' % (keyTypeName,))
        newPath = raw_input(
            'Enter file in which to save the key (%s): ' % (defaultPath,))

        options['filename'] = newPath.strip() or defaultPath

    if os.path.exists(options['filename']):
        print('%s already exists.' % (options['filename'],))
        yn = raw_input('Overwrite (y/n)? ')
        if yn[0].lower() != 'y':
            sys.exit()

    if options.get('no-passphrase'):
        options['pass'] = b''
    elif not options['pass']:
        while 1:
            p1 = getpass.getpass('Enter passphrase (empty for no passphrase): ')
            p2 = getpass.getpass('Enter same passphrase again: ')
            if p1 == p2:
                break
            print('Passphrases do not match.  Try again.')
        options['pass'] = p1

    comment = '%s@%s' % (getpass.getuser(), socket.gethostname())

    filepath.FilePath(options['filename']).setContent(
        key.toString('openssh', options['pass']))
    os.chmod(options['filename'], 33152)

    filepath.FilePath(options['filename'] + '.pub').setContent(
        key.public().toString('openssh', comment))
    options = enumrepresentation(options)

    print('Your identification has been saved in %s' % (options['filename'],))
    print('Your public key has been saved in %s.pub' % (options['filename'],))
    print('The key fingerprint in %s is:' % (options['format'],))
    print(key.fingerprint(options['format']))
예제 #3
0
def displayPublicKey(options):
    if not options['filename']:
        filename = os.path.expanduser('~/.ssh/id_rsa')
        options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename)
    try:
        key = keys.Key.fromFile(options['filename'])
    except keys.EncryptedKeyError:
        if not options.get('pass'):
            options['pass'] = getpass.getpass('Enter passphrase: ')
        key = keys.Key.fromFile(
            options['filename'], passphrase=options['pass'])
    displayKey = key.public().toString('openssh').decode("ascii")
    print(displayKey)
def enter_array():
    num_array = []
    num = raw_input("Enter the number of Aruco_Markers present:")
    int_num = int(num)
    print('Enter numbers one by one: ')

    for i in range(int(int_num)):
        var = raw_input("num :")
        if var == '':
            print('Please enter a valid numbers again..!')
            del num_array
            break
        else:
            n = var
            num_array.append(str(n))

        if i == max(range(int_num)):
            global array_global
            array_global = num_array
            return num_array
    re_enter_array()
    return array_global
예제 #5
0
 def getGenericAnswers(self, name, instruction, prompts):
     responses = []
     with self._replaceStdoutStdin():
         if name:
             print(name.decode("utf-8"))
         if instruction:
             print(instruction.decode("utf-8"))
         for prompt, echo in prompts:
             prompt = prompt.decode("utf-8")
             if echo:
                 responses.append(raw_input(prompt))
             else:
                 responses.append(getpass.getpass(prompt))
     return defer.succeed(responses)
예제 #6
0
 def getGenericAnswers(self, name, instruction, prompts):
     responses = []
     with self._replaceStdoutStdin():
         if name:
             print(name.decode("utf-8"))
         if instruction:
             print(instruction.decode("utf-8"))
         for prompt, echo in prompts:
             prompt = prompt.decode("utf-8")
             if echo:
                 responses.append(raw_input(prompt))
             else:
                 responses.append(getpass.getpass(prompt))
     return defer.succeed(responses)
예제 #7
0
def printFingerprint(options):
    if not options['filename']:
        filename = os.path.expanduser('~/.ssh/id_rsa')
        options['filename'] = raw_input(
            'Enter file in which the key is (%s): ' % filename)
    if os.path.exists(options['filename'] + '.pub'):
        options['filename'] += '.pub'
    options = enumrepresentation(options)
    try:
        key = keys.Key.fromFile(options['filename'])
        print('%s %s %s' % (key.size(), key.fingerprint(
            options['format']), os.path.basename(options['filename'])))
    except keys.BadKeyError:
        sys.exit('bad key')
예제 #8
0
def changePassPhrase(options):
    if not options['filename']:
        filename = os.path.expanduser('~/.ssh/id_rsa')
        options['filename'] = raw_input(
            'Enter file in which the key is (%s): ' % filename)
    try:
        key = keys.Key.fromFile(options['filename'])
    except keys.EncryptedKeyError:
        # Raised if password not supplied for an encrypted key
        if not options.get('pass'):
            options['pass'] = getpass.getpass('Enter old passphrase: ')
        try:
            key = keys.Key.fromFile(options['filename'],
                                    passphrase=options['pass'])
        except keys.BadKeyError:
            sys.exit('Could not change passphrase: old passphrase error')
        except keys.EncryptedKeyError as e:
            sys.exit('Could not change passphrase: %s' % (e, ))
    except keys.BadKeyError as e:
        sys.exit('Could not change passphrase: %s' % (e, ))

    if not options.get('newpass'):
        while 1:
            p1 = getpass.getpass(
                'Enter new passphrase (empty for no passphrase): ')
            p2 = getpass.getpass('Enter same passphrase again: ')
            if p1 == p2:
                break
            print('Passphrases do not match.  Try again.')
        options['newpass'] = p1

    if options.get('private-key-subtype') is None:
        options['private-key-subtype'] = _defaultPrivateKeySubtype(key.type())

    try:
        newkeydata = key.toString('openssh',
                                  subtype=options['private-key-subtype'],
                                  passphrase=options['newpass'])
    except Exception as e:
        sys.exit('Could not change passphrase: %s' % (e, ))

    try:
        keys.Key.fromString(newkeydata, passphrase=options['newpass'])
    except (keys.EncryptedKeyError, keys.BadKeyError) as e:
        sys.exit('Could not change passphrase: %s' % (e, ))

    with open(options['filename'], 'wb') as fd:
        fd.write(newkeydata)

    print('Your identification has been saved with the new passphrase.')
예제 #9
0
def printFingerprint(options):
    if not options['filename']:
        filename = os.path.expanduser('~/.ssh/id_rsa')
        options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename)
    if os.path.exists(options['filename']+'.pub'):
        options['filename'] += '.pub'
    options = enumrepresentation(options)
    try:
        key = keys.Key.fromFile(options['filename'])
        print('%s %s %s' % (
            key.size(),
            key.fingerprint(options['format']),
            os.path.basename(options['filename'])))
    except keys.BadKeyError:
        sys.exit('bad key')
예제 #10
0
    def __init__(self, filename):
        """
        Initializes C{self.filename}.

        If a file with this name already exists, asks if it should be
        overwritten. Terminates with exit status 1, if the user does
        not accept.
        """
        if os.path.isfile(filename):
            response = raw_input(("A file named %s exists. "
                                  "Overwrite it (y/n)? ") % filename)
            if response.lower() != "y":
                print("Performance test cancelled.")
                sys.exit(1)
        self.filename = filename
예제 #11
0
def sh(command, null=True, prompt=False):
    """
    I'll try to execute C{command}, and if C{prompt} is true, I'll
    ask before running it.  If the command returns something other
    than 0, I'll raise C{CommandFailed(command)}.
    """
    print("--$", command)

    if prompt:
        if raw_input("run ?? ").startswith('n'):
            return
    if null:
        command = "%s > /dev/null" % command
    if os.system(command) != 0:
        raise CommandFailed(command)
예제 #12
0
def displayPublicKey(options):
    if not options['filename']:
        filename = os.path.expanduser('~/.ssh/id_rsa')
        options['filename'] = raw_input('Enter file in which the key is (%s): ' % filename)
    try:
        key = keys.Key.fromFile(options['filename'])
    except keys.EncryptedKeyError:
        if not options.get('pass'):
            options['pass'] = getpass.getpass('Enter passphrase: ')
        key = keys.Key.fromFile(
            options['filename'], passphrase = options['pass'])
    displayKey = key.public().toString('openssh')
    if _PY3:
        displayKey = displayKey.decode("ascii")
    print(displayKey)
예제 #13
0
 def parse_before_login(self, response):
     print("parse_before_login")
     captcha_id = response.xpath(
         '//input[@name="captcha-id"]/@value').extract_first()
     captcha_image_url = response.xpath(
         '//img[@id="captcha_image"]/@src').extract_first()
     if captcha_image_url is None:
         print("登录时无验证码")
         form_data = {
             'source': 'movie',
             'redir': 'https://movie.douban.com/',
             'form_email': '*****@*****.**',
             'form_password': '******',
             'remember': 'on',
             'login': '******'
         }
     else:
         print("登录时有验证码")
         # 将图片验证码下载到本地
         urllib.request.urlretrieve(captcha_image_url,
                                    os.getcwd() + '\output\captcha.jpeg')
         # 打开图片,以便我们识别图中验证码
         try:
             im = Image.open(os.getcwd() + '\output\captcha.jpeg')
             im.show()
             captcha_solution = raw_input('根据打开的图片输入验证码:')
             print('您输入的验证码为 : ', captcha_solution)
             form_data = {
                 'source': 'None',
                 'redir': 'https://www.douban.com',
                 'form_email': '*****@*****.**',
                 'form_password': '******',
                 'captcha-solution': captcha_solution,
                 'captcha-id': captcha_id,
                 'remember': 'on',
                 'login': '******'
             }
         except Exception as e:
             print(e.message)
     # 表单需要提交的数据
     return scrapy.FormRequest.from_response(
         response,
         meta={
             "cookiejar": response.meta["cookiejar"]
         },  #表示使用上一次response的cookie,写在FormRequest.from_response()里post授权
         headers=self.headers,
         formdata=form_data,
         callback=self.parse_after_login)
예제 #14
0
def changePassPhrase(options):
    if not options['filename']:
        filename = os.path.expanduser('~/.ssh/id_rsa')
        options['filename'] = raw_input(
            'Enter file in which the key is (%s): ' % filename)
    try:
        key = keys.Key.fromFile(options['filename'])
    except keys.EncryptedKeyError as e:
        # Raised if password not supplied for an encrypted key
        if not options.get('pass'):
            options['pass'] = getpass.getpass('Enter old passphrase: ')
        try:
            key = keys.Key.fromFile(
                options['filename'], passphrase=options['pass'])
        except keys.BadKeyError:
            sys.exit('Could not change passphrase: old passphrase error')
        except keys.EncryptedKeyError as e:
            sys.exit('Could not change passphrase: %s' % (e,))
    except keys.BadKeyError as e:
        sys.exit('Could not change passphrase: %s' % (e,))

    if not options.get('newpass'):
        while 1:
            p1 = getpass.getpass(
                'Enter new passphrase (empty for no passphrase): ')
            p2 = getpass.getpass('Enter same passphrase again: ')
            if p1 == p2:
                break
            print('Passphrases do not match.  Try again.')
        options['newpass'] = p1

    try:
        newkeydata = key.toString('openssh', extra=options['newpass'])
    except Exception as e:
        sys.exit('Could not change passphrase: %s' % (e,))

    try:
        keys.Key.fromString(newkeydata, passphrase=options['newpass'])
    except (keys.EncryptedKeyError, keys.BadKeyError) as e:
        sys.exit('Could not change passphrase: %s' % (e,))

    with open(options['filename'], 'wb') as fd:
        fd.write(newkeydata)

    print('Your identification has been saved with the new passphrase.')
예제 #15
0
    def test_raw_input(self):
        """
        L{twisted.python.compat.raw_input}
        """
        class FakeStdin:
            def readline(self):
                return "User input\n"

        class FakeStdout:
            data = ""
            def write(self, data):
                self.data += data

        self.patch(sys, "stdin", FakeStdin())
        stdout = FakeStdout()
        self.patch(sys, "stdout", stdout)
        self.assertEqual(raw_input("Prompt"), "User input")
        self.assertEqual(stdout.data, "Prompt")
예제 #16
0
파일: main.py 프로젝트: pmAllport/fake_news
    test_location = input(
        "Please enter a target location for the testset. Insert the absolute path \n"
    )
    ## A valid dataset is under (*Project folder*\en).  Remember the absolute path
    print("Processing data...")

    ## This part prepares the data from the test_location
    prep = Preprocessing(test_location)
    seq_dict, test_data, test_values, total_author_list = prep.main()

    train_choice = ''
    while (True):
        if (train_choice == "Y" or train_choice == "N"):
            break
        train_choice = raw_input(
            "Do you wish to retrain the models before testing? (Y/N)  \n")

    if train_choice == 'Y':
        train_target = input(
            "Please insert a training set location. Insert absolute path \n")
        ## A valid dataset is under (*Project folder*\Testset\). Remember the absolute path

        print("Beginning training of Bi-directional lstm")
        ## Trains the Bi_directional model
        Bi_dir = Bi_directional(train_target)
        Bi_dir.main(False)
        print("Finished training of Bi-directional lstm")

        print("Beginning training of LSTM/CNN with frozen weights")
        ## Trains the Freezed weigth LSTM/CNN model
        freezed = Freezed(train_target)
예제 #17
0
def get_data():
    print("initiating")

    try:
        # load config
        config = ConfigParser()
        config.read(CONFIG_PATH)

        # login
        login = config.get('user', 'login')
        if not login:
            login = raw_input('Login: '******'Login: {}'.format(login))

        # password
        password = getpass.getpass('Password: '******'login failed')
            return get_data()
        edt_connexion.rebuild_form_cache()
        print('login success')
        config.set('user', 'login', login)

        # student data
        student_fullname = config.get('user', 'student_fullname')
        if student_fullname:
            print("Student Fullname: {}".format(student_fullname))
        else:
            student_fullname = raw_input('Student Fullname (ex: DUPOND Jean) : ')

        student_id = None
        while not student_id:
            student_id = edt_connexion.get_students().get(student_fullname)
            if student_id is None:
                print("Student not found")
                student_fullname = raw_input('Student Fullname (ex: DUPOND Jean) : ')
        print("Student ID: {}".format(student_id))
        config.set('user', 'student_fullname', student_fullname)

        # get edt data for this week
        week_number = int(raw_input('Week Number : '))
        edt = edt_connexion.get_student_edt(student_id, week_number)
        parsed_edt = parse_edt.get_parsed_edt(edt)

        # get company detail
        company = config.get('user', 'company')
        while not company:
            company = raw_input('Company Name and City (ex: ENIB - Brest) : ')
        config.set('user', 'company', company)

        training_date = config.get('user', 'training_date')
        while not training_date:
            training_date = raw_input('Training Date (ex: DU 05/09/2019 AU 04/09/2020) : ')
        config.set('user', 'training_date', training_date)

        # save config
        with open(CONFIG_PATH, 'w') as configfile:
            config.write(configfile)

        return parsed_edt, week_number
    except KeyboardInterrupt:
        return None
    except Exception as error:
        print('ERROR', error)
        return get_data()