기본 콘텐츠로 건너뛰기

라즈베리파이를 이용해서 Google drive와 sync하기






연구실에서는 보통 라즈베리파이와 라즈베리파이 카메라를 이용해서 연구를 진행하는 편인데, 실험 결과를 매번 ftp와 filezilla를 이용하였다. 근데 어차피 노트북으로 작업하던걸 데스크탑으로 옮기는 과정에서 구글 드라이브를 사용하는데 이런 과정을 거칠 필요 없이 그냥 라즈베리파이에서 업로드를 하는 시스템을 구성하기로 하였다.
구성하기 전에 이리저리 구글에 검색을 해봤는데 윈도우나 맥에서는 자체 프로그램이 제공되지만 리눅스는 지원하지 않아 먼저 개인 NAS를 돌리고 있는 동기 형에게 백업 프로그램을 물어봤다. 그렇게 Rclone을 알게되었고 라즈베리파이의 경우는 ARM코어라 x86에만 구동하는 것들은 안 돌아가는 경우도 있었기 때문에 검색한 결과 상관없이 잘 작동한다는 것을 알게 되었다.
그리고 역시 친절한 개발자들은 설치 스크립트까지 github(https://github.com/pageauc/rclone4pi)에 올려두었다. 그래서 이를 이용하여 잘 활용하여 세팅하였다.

1. 라즈베리파이 패키지 업데이트


모든 작업을 하기전에는 패키지 업데이트를 진행하자.
$ sudo apt-get update
$ sudo apt-get upgrade -y

2. 설치 스크립트 다운 및 설치하기


업데이트가 완료 되면 설치 스크립트를 받아야 하는데 제작자가 친절하게 Readme에 코드를 복사하여 넣으라고 한다. 개발자의 말을 잘 듣는 착한 학생이 되어야하니 시키는 대로 하자.
cd를 이용해 원하는 폴더로 이동한 후
$ curl -L https://raw.github.com/pageauc/rclone4pi/master/rclone-install.sh | bash
bash ver 1.6 written by Claude Pageau
-------------------------------------------------------------------------------
--2019-04-29 16:00:53--  https://downloads.rclone.org/rclone-current-linux-arm.zip
...
...
...
...
rclone installed at /usr/bin/rclone
-------------------------------------------------------------------------------
                 INSTRUCTIONS Google Drive Example

1 You will be required to have a login account on the remote storage service
  Open putty SSH login session to RPI and execute command below

  rclone config

  Follow rclone prompts. For more Details See
  https://github.com/pageauc/rclone4pi/wiki/Home
2 At name> prompt specify a reference name  eg gdmedia
3 At storage> prompt Enter a remote storage number from List
4 Select Auto Config, At Link: prompt, left click
  and highlight rclone url link (do not hit enter)
5 on computer web browser url bar right click paste and go.
6 On computer web browser security page, Confirm access.
7 Copy web browser access security token and paste
  into RPI SSH session rclone prompt. Enter to accept
8 To test remote service access. Execute the following where
  gdmedia is the name you gave your remote service

  rclone ls gdmedia:/

Example sync command make source identical to destination

rclone sync -v /home/pi/rpi-sync gdmedia:/rpi-sync

To upgrade

  cd rpi-sync
  ./rclone-install.sh upgrade

For more Details See https://github.com/pageauc/rclone4pi/wiki/Home
Bye
Rclone 설치가 완료되었다는 정보와 이것저것 tip을 적어두셨다. 현재 할려고 하는게 예제와 같으므로 저 순서대로 진행해보자.

3. Rclone 설정


먼저 Rlone을 설정해야한다.(사실 이게 이 포스트의 목적이다) 명령창에 다음 명령어를 입력한다.
$ rclone config
2019/04/29 16:21:29 NOTICE: Config file "/home/pi/.config/rclone/rclone.conf" not found - using defaults
No remotes found - make a new one
n) New remote
s) Set configuration password
q) Quit config
n/s/q> n
rclone.conf가 없다고 알려주는데 만든 적이 없으니 있는 것이 이상하다. 무시하자.
새로운 remote를 만들어야하므로 n을 입력하고 enter를 치면 어마어마하게 설정을 해야한다. 설정창을 살펴보면
name> drive
원하는 이름을 설정한다. 이는 rclone에서 고유의 이름으로 설정이나 다른 설정을 구별할 때 사용한다.
Type of storage to configure.
Enter a string value. Press Enter for the default ("").
Choose a number from below, or type in your own value
 1 / A stackable unification remote, which can appear to merge the contents of several remotes
   \ "union"
 2 / Alias for a existing remote
   \ "alias"
 3 / Amazon Drive
   \ "amazon cloud drive"
 4 / Amazon S3 Compliant Storage Provider (AWS, Alibaba, Ceph, Digital Ocean, Dreamhost, IBM COS, Minio, etc)
   \ "s3"
 5 / Backblaze B2
   \ "b2"
 6 / Box
   \ "box"
 7 / Cache a remote
   \ "cache"
 8 / Dropbox
   \ "dropbox"
 9 / Encrypt/Decrypt a remote
   \ "crypt"
10 / FTP Connection
   \ "ftp"
11 / Google Cloud Storage (this is not Google Drive)
   \ "google cloud storage"
12 / Google Drive
   \ "drive"
13 / Hubic
   \ "hubic"
14 / JottaCloud
   \ "jottacloud"
15 / Koofr
   \ "koofr"
16 / Local Disk
   \ "local"
17 / Mega
   \ "mega"
18 / Microsoft Azure Blob Storage
   \ "azureblob"
19 / Microsoft OneDrive
   \ "onedrive"
20 / OpenDrive
   \ "opendrive"
21 / Openstack Swift (Rackspace Cloud Files, Memset Memstore, OVH)
   \ "swift"
22 / Pcloud
   \ "pcloud"
23 / QingCloud Object Storage
   \ "qingstor"
24 / SSH/SFTP Connection
   \ "sftp"
25 / Webdav
   \ "webdav"
26 / Yandex Disk
   \ "yandex"
27 / http Connection
   \ "http"
Storage> 12
원하는 드라이브의 숫자를 입력한다. 자세히 살펴보면 꽤나 많은 드라이브들이 지원된다. 12번이 google drive이다.
Google Application Client Id
Setting your own is recommended.
See https://rclone.org/drive/#making-your-own-client-id for how to create your own.
If you leave this blank, it will use an internal key which is low performance.
Enter a string value. Press Enter for the default ("").
client_id>
Google Application Client Secret
Setting your own is recommended.
Enter a string value. Press Enter for the default ("").
client_secret>
구글 드라이브용으로 클라이언트 id를 따로 생성하는 것인데 이를 이용해서 전송 속도를 좀 더 높일 수 있다. 굳이 필요하지 않아서 설정하지 않았다.
Scope that rclone should use when requesting access from drive.
Enter a string value. Press Enter for the default ("").
Choose a number from below, or type in your own value
 1 / Full access all files, excluding Application Data Folder.
   \ "drive"
 2 / Read-only access to file metadata and file contents.
   \ "drive.readonly"
   / Access to files created by rclone only.
 3 | These are visible in the drive website.
   | File authorization is revoked when the user deauthorizes the app.
   \ "drive.file"
   / Allows read and write access to the Application Data folder.
 4 | This is not visible in the drive website.
   \ "drive.appfolder"
   / Allows read-only access to file metadata but
 5 | does not allow any access to read or download file content.
   \ "drive.metadata.readonly"
scope> 1
rclone의 권한을 설정한다. 각각을 보면
  1. Application Data folder를 제외한 모든 파일에 대해 access 가능
  2. 파일 내용을 읽기만 가능
  3. Rclone에서만 만들어진 파일만 access 가능
  4. Application Data folder access 가능
  5. 오직 파일의 metadata만 접근 가능(다운로드나 읽기 불가)
그래서 무난히 1번을 설정하였다.
ID of the root folder
Leave blank normally.
Fill in to access "Computers" folders. (see docs).
Enter a string value. Press Enter for the default ("").
root_folder_id> 1Sb6*********************
구글 드라이브에서의 root폴더를 설정한다. 아무것도 설정하지 않으면 전체 드라이브를 공유할 수 있다. 이때 folder의 id는 구글 드라이브 링크의 뒷자리 숫자들이다.
Ex) drive.google.com/drive/u/0/folders/1Sb6****************
Service Account Credentials JSON file path
Leave blank normally.
Needed only if you want use SA instead of interactive login.
Enter a string value. Press Enter for the default ("").
service_account_file>
무엇인지 자세히는 알아보지 않았지만 잘 모르겠으면 기본으로 설정하는 것이 대부분 맞다.
Edit advanced config? (y/n)
y/n> n
Use auto config?
y/n> n
그 외에 추가적인 설정은 진행하지 않았다.
설정이 완료되고 나면 구글 계정 인증을 요구한다. 링크를 복사하여 사용할 계정을 로그인하고 권한을 동의한 다음 나타나는 키를 복사하여 넣어주자.
If your browser doesn't open automatically go to the following link: https://accounts.google.com/o/oauth2/auth?/*****************************
Enter verification code> 4/**************************
마지막으로 팀 드라이브를 사용할 것인지 묻는다. 현재 연구실은 팀 드라이브를 이용하여 데이터를 공유하고 있으니 y를 선택해주자.(사용하지 않을거면 n을 누르면 된다.) 그러면 팀 드라이브 목록이 나타나고 사용한 팀 드라이브를 번호를 입력하면 된다.
Configure this as a team drive?
y) Yes
n) No
y/n> y
Fetching team drive list...
Choose a number from below, or type in your own value
 1 / "팀드라이브 이름"
   \ "0A****************"
Enter a Team Drive ID> 1
--------------------
# 설정한 rclone 정보
--------------------
y) Yes this is OK
e) Edit this remote
d) Delete this remote
y/e/d> y
Current remotes:

Name                 Type
====                 ====
"드라이브 이름"       drive
최종적으로 정보가 맞는지 확인한 다음, 최종 체크를 해준다. 만약 여기서 설정을 잘못하여 수정하고 싶으면 rclone config를 이용해 e를 선택하여 수정하면 된다. 그럼 위 설정창이 설명 없이 그대로 한번 더 나온다.
$ rclone config
Current remotes:

Name                 Type
====                 ====
gdrive               drive

e) Edit existing remote
n) New remote
d) Delete remote
r) Rename remote
c) Copy remote
s) Set configuration password
q) Quit config
e/n/d/r/c/s/q> e
Choose a number from below, or type in an existing value
 1 > gdrive
remote> 1
자 이러면 이제 설치와 설정이 완료 된 것이다.
아래 명령어를 입력했을때 파일 리스트가 잘 보이면 성공적으로 설정이 된 것이다.
rclone ls "rclone name":

4. 라즈베리파이와 동기화하기


동기화는 간단하게 명령어를 통해서 진행할 수 있다. 명령어는 크게 3가지가 있는데
  1. sync : 원격 폴더와 로컬 폴더를 동일하게 만든다.(쌍방향)
  2. copy : 로컬 폴더의 내용을 원격폴더에 복사한다. 이미 복사 된 것은 넘어간다.
  3. move : 로컬 폴더의 내용을 원격폴더에 이동한다.
$ rclone copy(move or sync) source:sourcepath dest:destpath
하지만 매번 명령어를 입력하기는 귀찮지 않은가? 하지만 내가 스크립트를 만들기 이전에 이미 만들어져 있다. 설치파일 폴더로 가면 rclone-sync.sh가 있다.
#  Customize rclone sync variables Below
# ---------------------------------------

lockFileCheck=false      # true= Checks for pi-timolo.sync file. false = No Check (case sensitive)
rcloneName="gdrive"     # Name of Remote Storage Service
syncRoot="/home/pi/"      # Root Folder to Start
localDir="gdrive"      # Source Folder on Local
remoteDir=""     # Destination Folder on Remote
rcloneParam="copy"       # rclone option to perform  Eg  sync, copy, move
                         # IMPORTANT: sync will make remoteDir identical to localDir
                         # so remoteDir Files that do not exist on localDir will be Deleted.
# ---------------------------------------
13번째 줄을 보면 수정하라는 부분이 있다. 이를 각 주석에 맞춰 자기 취향에 맞게 수정한다.
수정을 완료한 후 이를 돌리면,
$ ./rclone-sync.sh
rclone-sync.sh 10.00  written by Claude Pageau
----------- SETTINGS -------------

lockFileCheck : false
rcloneName    : gdrive
syncRoot      : /home/pi/
localDir      : gdrive
remoteDir     :
rcloneParam   : copy   (Options are sync, copy or move)

---------------------------------
rclone v1.47.0
- os/arch: linux/arm
- go version: go1.12.4
gdrive:
INFO  : /usr/bin/rclone copy -v gdrive gdrive:
        One Moment Please ...
2019/04/29 17:02:48 INFO  : Google drive root '': Waiting for checks to finish
2019/04/29 17:02:48 INFO  : Google drive root '': Waiting for transfers to finish
2019/04/29 17:02:52 INFO  : 2019-04-30/test.txt: Copied (new)
2019/04/29 17:02:52 INFO  :
Transferred:            40 / 40 Bytes, 100%, 7 Bytes/s, ETA 0s
Errors:                 0
Checks:                 0 / 0, -
Transferred:            1 / 1, 100%
Elapsed time:        5.1s

INFO  : rclone copy Successful ...
---------------------------------------------------
Exiting rclone-sync.sh ver 10.00
Bye ...
설정값을 띄워주면서 업로드를 성공했다는 것을 알 수 있다.

5. 자동 동기화


이제 자동으로 이 스크립트가 동작하게만 하면 된다. 방법은 간단하다. crontab을 이용하면 된다. crontab의 문법은 여기서 설명하기는 너무 많은 양이므로 관련 링크만 아래에 남겨두겠다.
시간은 적당히 원하는 간격으로 설정하면 된다. 다만 파일이 크면 파일이 올라가는 시간을 고려하여 그 이후에 실행하게 하도록 하는 것이 좋다.
$ sudo crontab -e
*/5 * * * * su pi -c "/home/pi/rpi-sync/rclone-sync.sh" > /dev/null 2>&1

6. 관련 링크

댓글

이 블로그의 인기 게시물

[라즈베리파이] Openssl 설치 1.0.1

OpenPose를 이용한 사람의 움직임 감지(Human Pose Estimation)

라즈베리파이-QT5 설치