def get_token(): """ Request a new token to acces an dropbox account. """ auth_flow = dropbox.DropboxOAuth2FlowNoRedirect( APP_KEY, obf(APP_SECRET).decode('ascii')) auth_url = auth_flow.start() webbrowser.open(auth_url) print("1. Go to: %s" % auth_url) print("2. Click \"Allow\" (you might have to log in first).") print("3. Copy the authorization code.") auth_code = input("Enter the authorization code here: ").strip() # noinspection PyBroadException try: oauth_result = auth_flow.finish(auth_code) except Exception: logging.exception("Receiving token failed.") sys.exit(1) else: print("Token received. From now on please start this script with:") print(" --token=%s" % oauth_result.access_token) return oauth_result.access_token
def command_dropbox_connect(args): import dropbox if args.spellbook_name is not None: print('ERR: sync is only for all books') return app_key = 'ow3gosk8pb9bhkr' app_secret = 'w3eqoqx5scb64pd' flow = dropbox.DropboxOAuth2FlowNoRedirect(app_key, app_secret) # Have the user sign in and authorize this token authorize_url = flow.start() print('1. Go to: ' + authorize_url) print('2. Click "Allow" (you might have to log in first)') print('3. Copy the authorization code.') code = collect_str("the authorization code here") # This will fail if the user enters an invalid authorization code access_token, user_id = flow.finish(code) client = dropbox.Dropbox(access_token) print('successfully linked account: ', client.users_get_current_account().name.display_name) with open(DROPBOX_TOKEN_PATH, 'w') as fout: fout.write(access_token)
def _gather_auth(self): import dropbox flow = dropbox.DropboxOAuth2FlowNoRedirect( consumer_key=self.DROPBOX_APP_KEY, consumer_secret=self.DROPBOX_APP_SECRET, token_access_type="offline", ) authorize_url = flow.start() print("Go to the following link in your browser:") print() print(" " + authorize_url) print() code = input("Enter verification code: ").strip() try: auth = flow.finish(code) except dropbox.oauth.NotApprovedException as ex: raise DvcException( "To use Dropbox remote, you need to approve the DVC " "application to access your Dropbox account.\n" "Learn more at {}".format( format_link("https://man.dvc.org/remote/modify") ) ) from ex return { ACCESS_TOKEN: auth.access_token, EXPIRATION: auth.expires_at.isoformat(), REFRESH_TOKEN: auth.refresh_token, }
def main(): #get the DropBox authorization token from file, if it exists auth_token = "" if os.path.exists("user_auth.dat"): with open("user_auth.dat") as auth_file: auth_token = auth_file.read() else: #no DropBox token - user must authorize application #get the app key and secret from file try: with open("my_pi_photo_frame_db.dat") as data_file: lines = data_file.read().splitlines() app_key = lines[0] app_secret = lines[1] except OSError: print "The my_pi_photo_frame_db.dat file is missing or corrupted. Please reinstall the application." raise SystemExit #start the OAuth2 app authoriztion process auth_flow = dropbox.DropboxOAuth2FlowNoRedirect(app_key, app_secret) #get the authorization URL from the API auth_url = auth_flow.start() print "Authorize My Pi Photo Frame in the browser window. Copy the authorization code and paste it below." #open a web browser to allow the user to authorize the app with DropBox webbrowser.open(auth_url) auth_code = raw_input("Enter the authorization code here: ").strip() try: auth_result = auth_flow.finish(auth_code) auth_token = auth_result.access_token except oauth.BadRequestException, e: print "The URL " + auth_url + " was not correct. Error: %s" % (e,) raise SystemExit except oauth.BadStateException, e: #bad state, restart the authorization process print "The application encountered a bad state exception. Restarting the authorization process..." main()
def connect(creds='creds.secret', access='client.secret') -> dropbox.Dropbox: """ Authorises application w/ user and loads client """ parent = Path(__file__).resolve().parent app = loadcreds(parent / creds) access_p = parent / access user = None if access_p.exists(): with open(access_p, 'rb') as token: user = pickle.load(token) if not user: flow = dropbox.DropboxOAuth2FlowNoRedirect(*app) redirect = flow.start() print( f"Redirecting for authorisation: {redirect}\nCtl-C to continue...") wbopen(redirect) token = input("Copy access token here: ").strip() if not token: print("Error: bad input", file=stderr) exit(1) user = flow.finish(token) with open(access_p, 'wb+') as token: pickle.dump(user, token) return dropbox.Dropbox(user.access_token)
def getAuthURL(self): """ Returns authentication URL ued in OAuth """ self.flow = dropbox.DropboxOAuth2FlowNoRedirect( self.APP_KEY, self.APP_SECRET) authorize_url = self.flow.start() return authorize_url
def authorize(): flow = dropbox.DropboxOAuth2FlowNoRedirect(APP_KEY, APP_SECRET) authorize_url = flow.start() print('1. Go to: ' + authorize_url) print('2. Click "Allow" (you might have to log in first)') print('3. Copy the authorization code.') try: input = raw_input except NameError: pass code = input("Enter the authorization code here: ").strip() return flow.finish(code).access_token
def auth(): auth_flow = dropbox.DropboxOAuth2FlowNoRedirect( 'APP_KEY', 'APP_SECRET') #Enter APP_KEY and APP_SECRET authorize_url = auth_flow.start() print("Go to {} and Click Allow".format(authorize_url)) auth_code = input("Enter the authorization code: ").strip() try: oauth_result = auth_flow.finish(auth_code) except Exception as e: print('Error: {}'.format(e)) dbx = dropbox.Dropbox(oauth_result.access_token) print(dbx.users_get_current_account()) return dbx
def authorize_app(APP_KEY, APP_SECRET): auth_flow = dropbox.DropboxOAuth2FlowNoRedirect(APP_KEY, APP_SECRET) authorize_url = auth_flow.start() print("1. Go to: " + authorize_url) print("2. Click \"Allow\" (you might have to log in first).") print("3. Copy the authorization code.") auth_code = input("Enter the authorization code here: ").strip() try: oauth_result = auth_flow.finish(auth_code) except Exception as e: print('Error: %s' % (e, )) dbx = dropbox.Dropbox(oauth_result.access_token) return dbx
def onchange_backup_destination(self): if self.backup_destination == 'ftp': self.ftp_port = 21 if self.backup_destination == 'sftp': self.ftp_port = 22 if no_pysftp: raise exceptions.Warning( _('Missing required pysftp python package\n' 'https://pypi.python.org/pypi/pysftp')) if self.backup_destination == 'dropbox': if no_dropbox: raise exceptions.Warning( _('Missing required dropbox python package\n' 'https://pypi.python.org/pypi/dropbox')) flow = dropbox.DropboxOAuth2FlowNoRedirect('jqurrm8ot7hmvzh', '7u0goz5nmkgr1ot') self.dropbox_authorize_url = flow.start() self.dropbox_authorize_url_rel = self.dropbox_authorize_url self.dropbox_flow = self.env['ir.attachment'].create( dict( datas=base64.b64encode(pickle.dumps(flow)), name='dropbox_flow', # datas_fname='dropbox_flow', description='Automatic Backup File')).id if self.backup_destination == 'google_drive': if no_pydrive: raise exceptions.Warning( _('Missing required PyDrive python package\n' 'https://pypi.python.org/pypi/PyDrive')) secrets_path = os.path.dirname( os.path.realpath(__file__) ) + os.sep + '..' + os.sep + 'data' + os.sep + 'client_secrets.json' GoogleAuth.DEFAULT_SETTINGS['client_config_file'] = secrets_path gauth = GoogleAuth() self.dropbox_authorize_url = gauth.GetAuthUrl() self.dropbox_authorize_url_rel = self.dropbox_authorize_url self.dropbox_flow = self.dropbox_flow = self.env[ 'ir.attachment'].create( dict( datas=base64.b64encode(pickle.dumps(gauth)), name='dropbox_flow', # datas_fname='dropbox_flow', description='Automatic Backup File')).id
def get_access_token(): access_token = keychain.get_password('dropboxv2', app_key) if access_token: return access_token auth_flow = dropbox.DropboxOAuth2FlowNoRedirect(app_key, app_secret) authorize_url = auth_flow.start() print("1. Go to: " + authorize_url) print("2. Click \"Allow\" (you might have to log in first).") print("3. Copy the authorization code.") webbrowser.open(authorize_url, modal=True) auth_code = input("Enter the authorization code here: ").strip() try: access_token, user_id = auth_flow.finish(auth_code) except Exception as e: print('Error: %s' % (e, )) return keychain.set_password('dropboxv2', app_key, access_token) return access_token
def __init__(self, remote_dir, local_dir, cache_file, sleep=600, prg=None): self._logger = logging.getLogger(LOGGER) self.remote_dir = remote_dir.lower() if not self.remote_dir.startswith(dropboxpath.sep): self.remote_dir = dropboxpath.join(dropboxpath.sep, self.remote_dir) if self.remote_dir.endswith(dropboxpath.sep): self.remote_dir, _ = dropboxpath.split(self.remote_dir) self.local_dir = local_dir self.cache_file = cache_file self.sleep = int(sleep) # Can be string if read from conf. self.executable = prg self._tree = {} self._token = None self._cursor = None self._load_state() if self._token is None: key, secret = decode_dropbox_key(APP_KEY) auth_flow = dropbox.DropboxOAuth2FlowNoRedirect(key, secret) auth_url = auth_flow.start() print "1. Go to: " + auth_url print "2. Click \"Allow\" (you might have to log in first)." print "3. Copy the authorization code." auth_code = raw_input( "Enter the authorization code here: ").strip() try: oauth_result = auth_flow.finish(auth_code) except Exception: self._logger.error("Invalid authorization code. Exiting.") sys.exit(1) self._token = oauth_result.access_token try: self.client = dropbox.Dropbox(self._token) except Exception as e: self._logger.exception("Unable to connect to Dropbox.") sys.exit(1)
def authenticate(): app_key = 'x03ls4fvmfws3v5' app_secret = 'w7hn9l5b960f1k0' flow = dropbox.DropboxOAuth2FlowNoRedirect(app_key, app_secret) # Have the user sign in and authorize this token authorize_url = flow.start() print '1. Go to: ' + authorize_url print '2. Click "Allow" (you might have to log in first)' print '3. Copy the authorization code' code = raw_input("\nEnter the authorization code here: ").strip() # This will fail if the user enters an invalid authorization code try: oauth_result = flow.finish(code) except Exception, e: print('Error: %s' % (e,)) return
def link_acc(): app_key = '05edkw3y5uun47z' app_secret = 'orbvhpaj4i7w41w' flow = dropbox.DropboxOAuth2FlowNoRedirect(app_key, app_secret) authorise_url = flow.start() print('1. Go to:' + authorise_url) print('2. Click "Allow" (you might have to log in first)') print('3. Copy the authorisation code') code = input('Enter your code:'.strip()) access_token, user_id = flow.finish(code) client = dropbox.client.DropboxClient(access_token) print('linked account', client.account_info()) print('.....One Pocess Done......') print('\n')
def get_redirect_url(self, *args, **kwargs): dropbox_settings = DropboxSettings.get_solo() auth_flow = dropbox.DropboxOAuth2FlowNoRedirect( # noqa: S106 settings.DSMRREADER_DROPBOX_APP_KEY, use_pkce=True, token_access_type='offline', timeout=settings.DSMRREADER_CLIENT_TIMEOUT) authorize_url = auth_flow.start() # We need the data generated by the SDK (auth challenge) on oauth completion. So we'll serialize it. serialized_auth_flow = pickle.dumps(auth_flow) dropbox_settings.update( serialized_auth_flow=serialized_auth_flow, # Reset all other fields as well. refresh_token=None, one_time_authorization_code=None) return authorize_url
def authorize(): global APP_TOKEN auth_flow = dropbox.DropboxOAuth2FlowNoRedirect(APP_KEY, APP_SECRET) authorize_url = auth_flow.start() print("1. Go to: " + authorize_url) print("2. Click \"Allow\" (you might have to log in first).") print("3. Copy the authorization code.\n") auth_code = input("Enter the authorization code here: ").strip() try: oauth_result = auth_flow.finish(auth_code) except (Exception, e): print('Error: %s' % (e, )) return APP_TOKEN = oauth_result.access_token print("\nYour APP_TOKEN:", APP_TOKEN) print( "Note: don't forget to paste this auth code to the script as APP_TOKEN constant!\n" )
def onchange_backup_destination(self): if self.backup_destination == 'dropbox': if no_dropbox: raise exceptions.Warning( _('Missing required dropbox python package\n' 'https://pypi.python.org/pypi/dropbox')) flow = dropbox.DropboxOAuth2FlowNoRedirect('jqurrm8ot7hmvzh', '7u0goz5nmkgr1ot') self.dropbox_authorize_url = flow.start() self.dropbox_authorize_url_rel = self.dropbox_authorize_url self.dropbox_flow = pickle.dumps(flow) if self.backup_destination == 'google_drive': if no_pydrive: raise exceptions.Warning( _('Missing required PyDrive python package\n' 'https://pypi.python.org/pypi/PyDrive')) secrets_path = os.path.dirname( os.path.realpath(__file__) ) + os.sep + '..' + os.sep + 'data' + os.sep + 'client_secrets.json' GoogleAuth.DEFAULT_SETTINGS['client_config_file'] = secrets_path gauth = GoogleAuth() self.dropbox_authorize_url = gauth.GetAuthUrl() self.dropbox_authorize_url_rel = self.dropbox_authorize_url self.dropbox_flow = pickle.dumps(gauth)
import crypto3 import dropbox import inspect # Get these from the developer dropbox site. APP_KEY = 'sefdetwey2877wd' APP_SECRET = 'vd2blgf607pdx3x' CRYPT_KEY_ACCESS = 'YxRv7LOMT0KiZC9FMz1mc0tY00q' CRYPT_KEY_REFRESH = 'PqUuChmKCFu2hQx6eUe5X45vcDD' #DROPBOX_REDIRECT_URL_FILE = const.DIR_RAMDISK + const.FILE_DBX_AUTH_REDIRECT AUTHFLOW = dropbox.DropboxOAuth2FlowNoRedirect( APP_KEY, consumer_secret=APP_SECRET, token_access_type='offline', scope=[ 'account_info.read', 'files.metadata.write', 'files.metadata.read', 'files.content.write', 'files.content.read', 'file_requests.write', 'file_requests.read' ]) ##################################################### # check to see if the dbx acces token is stil valid # # false the connection is not ok, reauthenticate # # true, all is well # ##################################################### def connection_is_valid(dbx=None, flog=None): try: _user_info = dbx.users_get_current_account() flog.debug(inspect.stack()[0][3] +
# Classify photo files (.jpg) to folders according to location & time taken import dropbox from dropbox.exceptions import ApiError import pathlib import datetime import os from geopy.geocoders import Nominatim import time # OAuth2 authentification auth_flow = dropbox.DropboxOAuth2FlowNoRedirect('APP_KEY', 'APP_SECRET') authorize_url = auth_flow.start() print("Go to {} and Click Allow".format(authorize_url)) auth_code = input("Enter the authorization code: ").strip() try: oauth_result = auth_flow.finish(auth_code) except Exception as e: print('Error: {}'.format(e)) dbx = dropbox.Dropbox(oauth_result.access_token) print(dbx.users_get_current_account()) # Get current file state in a folder def process_folder_entries(current_state, entries): for entry in entries: if isinstance(entry, dropbox.files.FileMetadata): current_state[entry.path_lower] = entry elif isinstance(entry, dropbox.files.DeletedMetadata): current_state.pop(entry.path_lower, None)
def _main(argv=None): if sys.version_info < (3, 5): print( "Error: Your version of Python is too old, 3.5+ is required: %d.%d.%d" % sys.version_info[:3]) return -1 try: check_runtime_requirements() except RuntimeError as e: print("Error: %s" % (e, )) return -1 # Protect access token and potentially encryption keys block_tracing() if argv is None: argv = sys.argv parser = argparse.ArgumentParser() userspacefs.add_cli_arguments(parser) parser.add_argument("-c", "--config-file", help="config file path") parser.add_argument( "-e", "--encrypted-folder", dest='encrypted_folders', type=parse_encrypted_folder_arg, default=[], action='append', help= "relative paths of encrypted folders, can be used multiple times. requires safefs" ) parser.add_argument( "--print-default-config-file", action='store_true', help="print default config file path to standard out and quit") parser.add_argument("mount_point", nargs='?') args = parser.parse_args(argv[1:]) try: version = pkg_resources.require("dbxfs")[0].version except Exception: log.warning("Failed to get version", exc_info=True) version = '' if version: try: with urllib.request.urlopen( "https://pypi.org/pypi/dbxfs/json") as f: rversion = json.load(io.TextIOWrapper(f))['info']['version'] if rversion != version: print( "\033[0;31m\033[1mWarning: dbxfs is out of date (%s vs %s), upgrade with 'pip3 install --upgrade dbxfs'\033[0;0m" % (rversion, version)) except Exception: log.warning("Failed to get most recent version", exc_info=True) config_dir = appdirs.user_config_dir(APP_NAME) if args.config_file is not None: config_file = args.config_file else: config_file = os.path.join(config_dir, "config.json") if args.print_default_config_file: print(config_file) return 0 try: os.makedirs(config_dir, exist_ok=True) except OSError as e: print("Unable to create configuration directory: %s" % (e, )) return -1 config = {} try: f = open(config_file) except IOError as e: if e.errno != errno.ENOENT: raise else: try: with f: config = json.load(f) except ValueError as e: print("Config file %r is not valid json: %s" % (config_file, e)) return -1 mount_point = args.mount_point if mount_point is None: mount_point = config.get("mount_point") if not args.smb_no_mount and mount_point is None: parser.print_usage() print("%s: error: please provide the mount_point argument" % (os.path.basename(argv[0]), )) return 1 encrypted_folders = config.get("encrypted_folders", []) + args.encrypted_folders if safefs_wrap_create_fs is None and encrypted_folders: print( "safefs not installed, can't transparently decrypt encrypted folders" ) return 1 access_token = None save_access_token = False save_config = False access_token_command = config.get("access_token_command", None) if access_token_command is not None: print("Running %r for access token" % (' '.join(access_token_command), )) try: access_token = subprocess.check_output( access_token_command).decode("utf-8") except UnicodeDecodeError: print("Access token command output is not utf-8 encoded") return -1 except TypeError: print("Bad access token command: %r, " % (access_token_command, )) return -1 # NB: access tokens never contain white-space and the access token # command often accidentally appends a newline character. access_token = access_token.strip() if access_token is None: keyring_user = config.get("keyring_user", None) if keyring_user is not None: try: access_token = keyring.get_password(APP_NAME, keyring_user) except KeyringError as e: print("Failed to get access token from keyring: %s" % (e, )) if access_token is None: access_token_privy = config.get("access_token_privy", None) if access_token_privy is not None: passwd = None while True: passwd = getpass.getpass( "Enter access token passphrase (not your Dropbox password) (Ctrl-C to quit): " ) try: access_token = privy.peek(access_token_privy, passwd).decode('utf-8') except ValueError: if not yes_no_input( "Incorrect password, create new access token?"): continue break del passwd try_directly = False while True: if access_token is None: save_access_token = True if (access_token is None and try_directly and yes_no_input( "Want to try entering the access token directly?")): print("Go to https://dropbox.com/developers/apps to " "create an app and generate a personal access token.") while True: access_token = getpass.getpass( "Enter Access token (Ctrl-C to quit): ") if not access_token: print("Access tokens cannot be empty") continue break if access_token is None: auth_flow = dropbox.DropboxOAuth2FlowNoRedirect( APP_KEY, APP_SECRET) authorize_url = auth_flow.start() print("We need an access token. Perform the following steps:") print("1. Go to " + authorize_url) print("2. Click \"Allow\" (you may have to log in first)") print("3. Copy the authorization code.") while True: auth_code = input( "Enter authorization code (Ctrl-C to quit): ") if not auth_code: print("Authorization code cannot be empty") continue break try: oauth_result = auth_flow.finish(auth_code) except Exception as e: print("Authorization code was invalid!") try_directly = True continue access_token = oauth_result.access_token # test out access token try: dropbox.Dropbox(access_token).users_get_current_account() except (dropbox.exceptions.BadInputError, dropbox.exceptions.AuthError, ValueError) as e: print("Error using access token: %s" % (e, )) access_token = None try_directly = True except OSError: if not yes_no_input("Error connecting to Dropbox, Try again?"): return 1 else: break if save_access_token and yes_no_input( "We're all connected. Do you want to save your credentials for future runs?", default_yes=True): keyring_user = ''.join( [random.choice("asdfghjklzxcvbnmqwertyuiop") for _ in range(24)]) try: keyring.set_password(APP_NAME, keyring_user, access_token) except (KeyringError, RuntimeError) as e: print( "We need a passphrase to encrypt your access token before we can save it." ) print( "Warning: Your access token passphrase must contain enough randomness to be resistent to hacking. You can read this for more info: https://blogs.dropbox.com/tech/2012/04/zxcvbn-realistic-password-strength-estimation/" ) while True: pass_ = getpass.getpass("Enter new access token passphrase: ") pass2_ = getpass.getpass( "Enter new access token passphrase (again): ") if pass_ != pass2_: print("Passphrases didn't match, please re-enter") else: del pass2_ break config.pop('keyring_user', None) config['access_token_privy'] = privy.hide( access_token.encode('utf-8'), pass_, server=False) del pass_ save_config = True else: config.pop('access_token_privy', None) config['keyring_user'] = keyring_user save_config = True if not config.get("asked_send_error_reports", False): if yes_no_input( "Would you like to help us improve %s by providing anonymous error reports?" % (APP_NAME, ), default_yes=True): config['send_error_reports'] = True config['asked_send_error_reports'] = True save_config = True if save_access_token and yes_no_input( "Do you want \"%s\" to be the default mount point?" % (mount_point, ), default_yes=True): config['mount_point'] = mount_point save_config = True if save_config: with open(config_file, "w") as f: json.dump(config, f) log.info("Starting %s...", APP_NAME) if config.get('send_error_reports', False): try: sentry_sdk.init( "https://[email protected]/1293235", release='%s@%s' % (APP_NAME, version), with_locals=False) except Exception: log.warning("Failed to initialize sentry", exc_info=True) cache_folder = os.path.join(appdirs.user_cache_dir(APP_NAME), "file_cache") try: os.makedirs(cache_folder, exist_ok=True) except OSError: log.warning( "Failed to create cache folder, running without file cache") cache_folder = None def create_fs(): fs = CachingFileSystem(DropboxFileSystem(access_token), cache_folder=cache_folder) # From a purity standpoint the following layer ideally would # go between the caching fs and dropbox fs, but because the # contract between those two is highly specialized, just put # it on top fs = TranslateIgnoredFilesFileSystem(fs) if sys.platform == 'darwin': fs = DisableQuickLookFileSystem(fs) return fs if safefs_wrap_create_fs is not None: create_fs = safefs_wrap_create_fs(create_fs, encrypted_folders) if not os.path.exists(mount_point): if yes_no_input( "Mount point \"%s\" doesn't exist, do you want to create it?" % (mount_point, ), default_yes=True): try: os.makedirs(mount_point, exist_ok=True) except OSError as e: print("Unable to create mount point: %s" % (e, )) return -1 return userspacefs.simple_main( mount_point, "dbxfs", create_fs, args, on_new_process=None if BLOCK_TRACING_INHERITS else block_tracing)
APP_KEY=get_config( 'Auth', 'app_key' ) APP_SECRET=get_config( 'Auth', 'app_secret' ) if APP_KEY == '': set_config( 'Auth', 'app_key', 'your_app_key', True ) if APP_SECRET == '': set_config( 'Auth', 'app_secret', 'your_app_secret', True ) if APP_KEY == '' or APP_SECRET == '': print 'Please obtain an app key and secret from' print 'https://www.dropbox.com/developers/apps' write_config() sys.exit(0) if len(access_token) == 0: auth_flow = dropbox.DropboxOAuth2FlowNoRedirect(APP_KEY, APP_SECRET) authorize_url = auth_flow.start() print "1. Go to: " + authorize_url print "2. Click \"Allow\" (you might have to log in first)." print "3. Copy the authorization code." auth_code = raw_input("Enter the authorization code here: ").strip() try: oauth_result = auth_flow.finish(auth_code) access_token=oauth_result.access_token set_config( 'Auth', 'access_token', access_token ) except Exception, e: print('Error: %s' % (e,)) if len(access_token) == 0: write_config() sys.exit()
print "********************************************************************************" print "" # Check for latest dropbox sdk. if versiontuple(str(dropbox.__version__)) <= versiontuple('9'): print "Outdated dropbox SDK detected: " + str(dropbox.__version__) print "Please update your dropbox SDK!" print print "sudo pip install --upgrade dropbox" print exit(-1) app_key = raw_input("1.) Enter your 'App key': ").strip() app_secret = raw_input("2.) Enter your 'App secret': ").strip() auth_flow = dropbox.DropboxOAuth2FlowNoRedirect(app_key, app_secret) authorize_url = auth_flow.start() authorize_url = "https://www.dropbox.com/oauth2/authorize?response_type=code&client_id=" + app_key print "3.) Now open this url and confirm the requested permission." print "" print authorize_url print "" auth_code = raw_input("4.) Enter the given access code': ").strip() try: oauth_result = auth_flow.finish(auth_code) except Exception, e: print "Could not finish the Dropbox authorization flow! (" + str(e) + ")\n" sys.exit(-1)
def main(argv=None): # Protect access token and potentially encryption keys block_tracing() if argv is None: argv = sys.argv parser = argparse.ArgumentParser() userspacefs.add_cli_arguments(parser) parser.add_argument("-c", "--config-file", help="config file path") parser.add_argument( "-e", "--encrypted-folder", dest='encrypted_folders', type=parse_encrypted_folder_arg, default=[], action='append', help= "relative paths of encrypted folders, can be used multiple times. requires safefs" ) parser.add_argument( "--print-default-config-file", action='store_true', help="print default config file path to standard out and quit") parser.add_argument("mount_point", nargs='?') args = parser.parse_args(argv[1:]) config_dir = appdirs.user_config_dir(APP_NAME) if args.config_file is not None: config_file = args.config_file else: config_file = os.path.join(config_dir, "config.json") if args.print_default_config_file: print(config_file) return 0 if not args.smb_no_mount and args.mount_point is None: parser.print_usage() print("%s: error: please provide the mount_point argument" % (os.path.basename(argv[0]), )) return 1 os.makedirs(config_dir, exist_ok=True) config = {} try: f = open(config_file) except IOError as e: if e.errno != errno.ENOENT: raise else: try: with f: config = json.load(f) except ValueError as e: print("Config file %r is not valid json: %s" % (config_file, e)) return -1 access_token = None save_access_token = False save_config = False access_token_command = config.get("access_token_command", None) if access_token_command is not None: print("Running %r for access token" % (' '.join(access_token_command), )) try: access_token = subprocess.check_output( access_token_command).decode("utf-8") except TypeError: print("Bad access token command: %r, " % (access_token_command, )) return -1 if access_token is None: keyring_user = config.get("keyring_user", None) if keyring_user is not None: try: access_token = keyring.get_password(APP_NAME, keyring_user) except KeyringError as e: print("Failed to get access token from keyring: %s" % (e, )) if access_token is None: access_token_privy = config.get("access_token_privy", None) if access_token_privy is not None: passwd = None while True: passwd = getpass.getpass( "Enter access token passphrase (not your Dropbox password) (Ctrl-C to quit): " ) try: access_token = privy.peek(access_token_privy, passwd).decode('utf-8') except ValueError: if not yes_no_input( "Incorrect password, create new access token?"): continue break del passwd try_directly = False while True: if access_token is None: save_access_token = True if (access_token is None and try_directly and yes_no_input( "Want to try entering the access token directly?")): print("Go to https://dropbox.com/developers/apps to " "create an app and generate a personal access token.") while True: access_token = getpass.getpass( "Enter Access token (Ctrl-C to quit): ") if not access_token: print("Access tokens cannot be empty") continue break if access_token is None: auth_flow = dropbox.DropboxOAuth2FlowNoRedirect( APP_KEY, APP_SECRET) authorize_url = auth_flow.start() print("We need an access token. Perform the following steps:") print("1. Go to " + authorize_url) print("2. Click \"Allow\" (you may have to log in first)") print("3. Copy the authorization code.") while True: auth_code = input( "Enter authoritization code (Ctrl-C to quit): ") if not auth_code: print("Authorization code cannot be empty") continue break try: oauth_result = auth_flow.finish(auth_code) except Exception as e: print("Authorization code was invalid!") try_directly = True continue access_token = oauth_result.access_token # test out access token try: dropbox.Dropbox(access_token).users_get_current_account() except (dropbox.exceptions.BadInputError, dropbox.exceptions.AuthError) as e: print("Error using access token: %s" % (e, )) access_token = None try_directly = True else: break if save_access_token and yes_no_input( "We're all connected. Do you want to save your credentials for future runs?", default_yes=True): keyring_user = ''.join( [random.choice("asdfghjklzxcvbnmqwertyuiop") for _ in range(24)]) try: keyring.set_password(APP_NAME, keyring_user, access_token) except (KeyringError, RuntimeError) as e: print( "We need a passphrase to encrypt your access token before we can save it." ) print( "Warning: Your access token passphrase must contain enough randomness to be resistent to hacking. You can read this for more info: https://blogs.dropbox.com/tech/2012/04/zxcvbn-realistic-password-strength-estimation/" ) while True: pass_ = getpass.getpass("Enter new access token passphrase: ") pass2_ = getpass.getpass( "Enter new access token passphrase (again): ") if pass_ != pass2_: print("Passphrases didn't match, please re-enter") else: del pass2_ break config.pop('keyring_user', None) config['access_token_privy'] = privy.hide( access_token.encode('utf-8'), pass_, server=False) del pass_ save_config = True else: config.pop('access_token_privy', None) config['keyring_user'] = keyring_user save_config = True if not config.get("asked_send_error_reports", False): if yes_no_input( "Would you like to help us improve %s by providing anonymous error reports?" % (APP_NAME, ), default_yes=True): config['send_error_reports'] = True config['asked_send_error_reports'] = True save_config = True if save_config: with open(config_file, "w") as f: json.dump(config, f) log.info("Starting %s...", APP_NAME) wrap_fs_errors = True if config.get('send_error_reports', False): try: version = pkg_resources.require("dbxfs")[0].version except Exception: log.warning("Failed to get version", exc_info=True) version = '' try: sentry_sdk.init( "https://[email protected]/1293235", release='%s@%s' % (APP_NAME, version), with_locals=False) wrap_fs_errors = True except Exception: log.warning("Failed to initialize sentry", exc_info=True) cache_folder = os.path.join(appdirs.user_cache_dir(APP_NAME), "file_cache") with contextlib.suppress(FileExistsError): os.makedirs(cache_folder) def create_fs(): fs = CachingFileSystem(DropboxFileSystem(access_token), cache_folder=cache_folder) if sys.platform == 'darwin': fs = DisableQuickLookFileSystem(fs) if wrap_fs_errors: fs = WrapErrorsFileSystem(fs) return fs encrypted_folders = config.get("encrypted_folders", []) + args.encrypted_folders create_fs = safefs_wrap_create_fs(create_fs, encrypted_folders) if not os.path.exists(args.mount_point): if yes_no_input( "Mount point \"%s\" doesn't exist, do you want to create it?" % (args.mount_point, ), default_yes=True): os.makedirs(args.mount_point, exist_ok=True) return userspacefs.simple_main(args.mount_point, "dbxfs", create_fs, args)
def download_pdf(self, dirname='/tmp'): '''Download PDF file. Download PDF file and save in the local pc or in the remote server, or in the DropBox Keyword arguments: dirname - The full path for the local saving of PDF files (str) ''' if self.method is None: self.method = method for j in self.manuals: for k, v in j.items(): for i in v: name = '{}-{}.pdf'.format(k, i['name']) if self.verbose is True: print('Getting file: \'{}\', from the website: \'{}\''. format(name, self.url)) req = requests.get(i['link'], stream=True) if self.method == 'dropbox': try: import dropbox except: print( '[Warning!] dropbox module is not found,' 'this method not work, please install module' '`pip install dropbox --user` for use this method' ) sys.exit(-1) if self.credentials['dropbox']['access_token'] is None: app_key = self.credentials['dropbox']['app_key'] app_secret = self.credentials['dropbox'][ 'app_secret'] flow = dropbox.DropboxOAuth2FlowNoRedirect( app_key, app_secret) authorize_url = flow.start() print( '1. Go to: {}\n2. Click "Allow" (you might have to log in first)' .format(authorize_url)) try: code = raw_input( "3. Enter the authorization code here: " ).strip() except: code = input( "3. Enter the authorization code here: " ).strip() self.credentials['dropbox'][ 'access_token'], user_id = flow.finish(code) dbx = dropbox.Dropbox( self.credentials['dropbox']['access_token']) try: dbx.files_upload(req.raw.read(), '/Books/' + name, mute=True) except Exception as e: print('Cannot save file: {} in Dropbox. Error: {}'. format(name, e)) if self.verbose is True: print('Saving a PDF file: \'{}\', on the DropBox'. format(name)) elif self.method == 'scp': try: import paramiko except: print( '[Warning!] paramiko module is not found,' 'this method not work, please install module' '`pip install paramiko --user` for use this method' ) sys.exit(-1) def put_file(dirname, filename, data): ssh = paramiko.SSHClient() ssh.load_host_keys("~/.ssh/known_hosts") ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy()) my_key = paramiko.RSAKey.from_private_key_file( "~/.ssh/id_rsa") try: ssh.connect( hostname=self.credentials['remote_server'] ['ip'], username=self.credentials['remote_server'] ['username'], pkey=my_key) except: ssh.connect( hostname=self.credentials['remote_server'] ['ip'], username=self.credentials['remote_server'] ['username'], password=self.credentials['remote_server'] ['password']) sftp = ssh.open_sftp() try: sftp.mkdir(dirname) except IOError: pass f = sftp.open(dirname + '/' + filename, 'w') f.write(data) f.close() ssh.close() if self.verbose is True: print( 'Saving a PDF file: \'{}\', on the remote server: \'{}\'' .format( name, self.credentials['remote_server']['ip'])) put_file(dirname, name, req.raw.read()) else: if self.verbose is True: print( 'Saving a PDF file: \'{}\', on the local machine' .format(name)) with (open(dirname + '/' + name, 'ab')) as f: for chunk in req.iter_content(chunk_size=1024): if chunk: f.write(chunk)