Micromegas
Micromegas

Reputation: 1689

Downloading files from nextcloud with python script with 2-factor authentication enabled

I set up a nextcloud instance and I would like to download files from there using a python script. My nextcloud instance enforces 2-factor authentication for all users and I want it to remain that way.

My dream scenario would be to use the requests library, so following the docs here https://docs.nextcloud.com/server/15/developer_manual/client_apis/WebDAV/basic.html , I tried to do something like this:

from requests.auth import HTTPBasicAuth

r = requests.request(
    method='get',
    url='https://mycloudinstance/index.php/apps/files/?dir=/Test&fileid=431',
    auth=('username', 'pass')
)
print(r.status_code)
print(r.text)

That gives me an 401 error saying {"message":"Current user is not logged in"}.

When I change the above URL to https://remote.php/dav/myinstance/index.php/apps/files/?dir=/Test&fileid=431 I get

ConnectionError(': Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known'))

As an alternative I was trying to use trying to use this library https://github.com/owncloud/pyocclient just to see if I can create a testfolder with it (it is from owncloud but should work with nextcloud too):

import owncloud
oc = owncloud.Client('https://mycloudinstance')
oc.login('username', 'pass')
oc.mkdir('cooldir')

This throws me an owncloud.owncloud.HTTPResponseError: HTTP error: 401 error. I think that might either be because I just use it incorrectly or because of 2-factor auth.

I am not sure how to use the webdav protocol combined with the python requests library and also I am not sure how to get two-factor authorization to work with it. Has anyone ever done this?

Help is very much appreciated, thanks so much in advance.

Upvotes: 2

Views: 6968

Answers (1)

lsterzinger
lsterzinger

Reputation: 717

You can bypass the 2-factor authentication by generating a secure password for a single application.

In next cloud, go to: Settings -> Personal -> Security -> Create New App Password

The password will be shown to you once (and only once), use it in place of your normal password in your script.

Upvotes: 4

Related Questions