시놀로지 파일 탐색기에서 공유 링크 생성하기

안녕하세요!

이번에는 시놀로지 NAS에서 File Station에 들어가지 않고도 공유 링크를 생성하는 방법에 대해 다뤄보려고 합니다.

글로는 설명이 힘들기 때문에, 이미지로 예시를 들어보겠습니다.

이런 식으로 파일 탐색기에서 공유 링크를 생성하고자 하는 파일을 우클릭하여
Create Synology Share Link를 클릭하는 것으로

공유 링크를 생성하게 할 수 있습니다.

한글 경로를 지원하긴 하지만, 출력에는 문제가 있습니다.
파일/폴더 무관하게 지원합니다.

구현하고자 하는 기능은 다음과 같습니다.

  1. 파일 탐색기에서 원하는 파일/폴더를 우클릭하여 공유 링크를 생성하기.
  2. 만료일을 n일로 지정하기.
  3. 생성된 공유 링크를 자동으로 클립보드에 붙이기.

매우 긴 코드가 사용되지만, 실제로 수정해야 하는 부분은 얼마 되지 않으므로,
천천히 따라오시기 바랍니다!

시놀로지 드라이브를 사용하는 게 더 직관적이고 간단합니다!

하지만 저는 원시적인 방법을 더 좋아합니다.

PowerShell 코딩

먼저, 작성해야 할 파워셸 스크립트의 완성본은 다음과 같습니다.
시놀로지 API 공식 문서의 75~77page를 참고하여 만든 코드입니다.

# Synology NAS 정보 설정
$nasUrl = "http://input.your.nas.ip:5000"
$username = "yourID"
$password = "yourPW"

# URL 인코딩 함수
function UrlEncode {
    param (
        [string]$string
    )
    return [System.Uri]::EscapeDataString($string)
}

# 비밀번호 및 경로 인코딩
$encodedPassword = UrlEncode $password

# 날짜를 yyyy-mm-dd 형식으로 반환하는 함수
function Get-DateAfterDays {
    param (
        [int]$Days
    )
    $futureDate = (Get-Date).AddDays($Days)
    return $futureDate.ToString("yyyy-MM-dd")
}

# 파일 경로 변환 함수
function Convert-FilePath {
    param (
        [string]$filePath
    )
    # Windows 스타일 경로를 Unix 스타일로 변환
    $unixPath = $filePath -replace '^[A-Z]:', '' -replace '\\', '/'
    return $unixPath
}

# 스크립트가 받을 파일 경로
$filePath = $args[0]  # 파일 경로를 파라미터로 받음
if (-not $filePath) {
    Write-Error "File path not provided."
    exit
}

# 경로 변환
$filePath = $filePath.Trim('"')
$convertedPath = Convert-FilePath $filePath
$encodedPath = UrlEncode($convertedPath)

# 만료일 계산 (값을 수정하여 만료일 지정)
$dateExpired = Get-DateAfterDays 3
$encodedDateExpired = UrlEncode($dateExpired)

# 1단계: 인증 토큰 얻기
try {
    $loginResponse = Invoke-RestMethod -Uri "$nasUrl/webapi/auth.cgi?api=SYNO.API.Auth&version=3&method=login&account=$username&passwd=$encodedPassword&session=FileStation&format=sid" -Method Get
    if ($loginResponse.success -ne $true) {
        Write-Error "Login failed. Error Details: $($loginResponse.error.message)"
        exit
    }
    $sid = $loginResponse.data.sid
} catch {
    Write-Error "An error occurred during login. Error Details: $_.Exception.Message"
    exit
}

# 2단계: 공유 링크 생성
try {
    $createResponse = Invoke-RestMethod -Uri "$nasUrl/webapi/entry.cgi?api=SYNO.FileStation.Sharing&version=3&method=create&path=$encodedPath&date_expired=%22$encodedDateExpired%22&format=sid&_sid=$sid" -Method Get

    if ($createResponse.success -ne $true) {
        Write-Error "Failed to create share link. Error Details: $($createResponse.error.message)"
        exit
    }
    $linkId = $createResponse.data.links[0].id
} catch {
    Write-Error "An error occurred while creating share link. Error Details: $_.Exception.Message"
    exit
}

# 3단계: 링크 정보 확인
try {
    $getInfoResponse = Invoke-RestMethod -Uri "$nasUrl/webapi/entry.cgi?api=SYNO.FileStation.Sharing&version=3&method=getinfo&id=$($linkId)&format=sid&_sid=$sid" -Method Get

    if ($getInfoResponse.success -ne $true) {
        Write-Error "Failed to retrieve share link information. Error Details: $($getInfoResponse.error.message)"
        exit
    }

    # 필요한 공유 링크 정보만 출력
    Write-Output "ID: $($getInfoResponse.data.id)"
    Write-Output "File name: $($getInfoResponse.data.name)"
    Write-Output "File path: $($getInfoResponse.data.path)"
    Write-Output "URL: $($getInfoResponse.data.url)"
    Write-Output "Date Expired: $($getInfoResponse.data.date_expired)"

    # URL을 클립보드에 복사하기 전에 http를 https로, 포트 5000을 5001로 변경
    $shareLinkUrl = $getInfoResponse.data.url
    $modifiedShareLinkUrl = $shareLinkUrl -replace '^http:', 'https:' -replace ':5000', ':5001'

    Set-Clipboard -Value $modifiedShareLinkUrl
    Write-Output "Modified share link URL copied to clipboard: $modifiedShareLinkUrl"
} catch {
    Write-Error "An error occurred while retrieving share link information. Error Details: $_.Exception.Message"
    exit
}

# 4단계: 로그아웃
try {
    Invoke-RestMethod -Uri "$nasUrl/webapi/auth.cgi?api=SYNO.API.Auth&version=3&method=logout&session=FileStation&_sid=$sid" -Method Get
} catch {
    Write-Error "An error occurred during logout. Error Details: $_.Exception.Message"
}

위 스크립트를 메모장에 붙여 넣고, CreateSynologyShareLink.ps1로 저장합니다.

만약 공유 링크에 포트가 붙지 않는다면, 아래 코드를 이렇게 변경하시면 됩니다.

$shareLinkUrl = $getInfoResponse.data.url
$modifiedShareLinkUrl = $shareLinkUrl -replace '^http:', 'https:' -replace ':5000', ':5001'
$shareLinkUrl = $getInfoResponse.data.url
$modifiedShareLinkUrl = $shareLinkUrl -replace '^http:', 'https:' -replace ':\d+', ''

해당 스크립트는, 다음 파트에서 다룰 batch 파일과 같이 사용할 때에만 정상적으로 작동합니다.

이 스크립트는 batch 파일을 실행하여 공유 링크를 생성할 파일/폴더의 경로를 얻은 뒤
다음의 동작을 진행합니다.

  1. NAS에 로그인하여 SID 값을 받아옴.
  2. 공유 링크를 생성할 파일의 주소를 받음.
  3. 해당 주소를 API의 규칙에 맞게 수정함.
    1. 시놀로지의 경로 규칙에 따라, 공유 폴더의 이름으로 시작해야 하므로,
      WebDAV 혹은 SMB가 반드시 Root에 연결돼 있어야 함.
    2. EX)
      변환 전
      “Z:\Archive-Main\test\test.txt”
      변환 후
      /Archive-Main/test/test.txt
  4. 공유 링크를 생성 규칙에 맞게 생성함.
    • 현재 만료일 3일
  5. 생성된 공유 링크의 정보를 출력함.
    • 현재 한글 경로를 출력함에 있어서 버그가 있습니다.
      추후 수정하도록 하겠습니다.
  6. 클립보드에 해당 공유 링크를 가져옴.

위 스크립트의 최상단 부분을 개인의 환경에 맞게 수정하여 CreateSynologyShareLink.ps1으로 저장합니다.

# Synology NAS 정보 설정
$nasUrl = "http://input.your.synology.address:5000"
$username = "Your ID"
$password = "Your PW"

주소에는 IP 형식 혹은 DDNS 형식 모두 가능합니다.

만약 본인이 사용하는 http 포트가 5000이 아닐 경우, 포트를 수정하시기 바랍니다.
그럴 경우 코드 하단에 있는 부분 또한 수정해주셔야 합니다.

# URL을 클립보드에 복사하기 전에 http를 https로, 포트 5000을 5001로 변경
$shareLinkUrl = $getInfoResponse.data.url
$modifiedShareLinkUrl = $shareLinkUrl -replace '^http:', 'https:' -replace ':5000', ':5001'

-replace ‘:5000’, ‘:5001’ 부분을 각각 http, https 포트에 맞게 수정하여 사용하시기 바랍니다.

batch 파일 작성

다음 스크립트를 메모장에 작성합니다.

@echo off
setlocal

:: PowerShell 스크립트 경로 설정
set "SCRIPT_PATH=C:\path\CreateSynologyShareLink.ps1"

:: PowerShell을 통해 스크립트 실행
PowerShell -NoProfile -ExecutionPolicy Bypass -File "%SCRIPT_PATH%" "%~1"

:: 결과 확인을 위해 일시 중지
pause
endlocal

C:\로 시작하는 경로를 위에서 저장한 PowerShell 스크립트의 경로에 맞게 수정합니다.
필자의 경우 C:\users\hinam\CreateSynologyShareLink.ps1 입니다.

작성이 끝났다면, RunSynologyScript.bat으로 저장합니다.

저장 경로는 CreateSynologyShareLink.ps1 파일과 동일한 경로에 저장하시기 바랍니다.

레지스트리 편집으로 컨텍스트 메뉴 등록

파일 컨텍스트 메뉴

먼저 Win + R키를 누르고 regedit을 입력하여 레지스트리 편집기를 실행합니다.

조금 헷갈릴 수 있으므로, 천천히 잘 따라오시기 바랍니다.

다음 경로로 이동합니다.

HKEY_CLASSES_ROOT\*\shell

shell을 마우스 우클릭하여 새로 만들기 > 키를 클릭합니다.

키의 이름을 Create Synology Share Link로 지정합니다.

기본값을 더블 클릭하여, 값 데이터를 Create Synology Share Link로 지정합니다.

Create Synology Share Link를 우클릭하여 새로 만들기 > 키를 클릭합니다.

이름을 command로 지정합니다.

command의 기본값을 더블 클릭하여, 값 데이터를 아래와 같이 작성합니다.

"C:\path\to\RunSynologyScript.bat" "%1"

C:\path\to 부분을 본인의 경로에 맞게 수정합니다.

필자의 경우 C:\users\hinam\RunSynologyScript.bat 입니다.

폴더 컨텍스트 메뉴

마찬가지로 레지스트리 편집기에서 다음 경로로 이동합니다.

HKEY_CLASSES_ROOT\Directory\shell

shell을 우클릭하여 새로 만들기 > 키를 클릭합니다.

이름을 Create Synology Share Link로 지정합니다.

키를 하나 더 생성하여 이름을 command로 지정합니다.

command의 기본값을 더블 클릭하여, 값 데이터를 아래와 같이 작성합니다.

"C:\path\to\RunSynologyScript.bat" "%1"

C:\path\to 부분을 본인의 경로에 맞게 수정합니다.

필자의 경우 C:\users\hinam\RunSynologyScript.bat 입니다.

주의할 점

RaiDrive 혹은 SMB를 반드시 root 경로로 연결해야 합니다.
특정 공유 폴더에 연결할 경우, 공유 링크를 생성하지 못합니다.


수고 많으셨습니다!

사실 저도 이게 뭐 하는 짓인가 싶습니다.
그냥 시놀로지 드라이브나 File Browser로 딸깍 하면 되는 걸, 뭐 하러 이렇게 귀찮은 방법을 사용하는지…

그래도 이 쪽이 더 멋지잖아요?
파일 탐색기에서 바로 된다는 점에서 절차가 생략되기도 하고요.

이제 원하는 파일/폴더를 우클릭하여 컨텍스트 박스에서 Create Synology Share Link를 클릭하는 것으로, 공유 링크를 자동으로 클립보드에 복사할 수 있습니다!

복사되는 공유 링크는 보안을 위해 자동으로 https로 변환되게 해 두었습니다.

만료일과 같은 세세한 설정은 스크립트를 수정하여 충분히 변경할 수 있습니다.
혹은 Chat GPT의 도움을 받아도 쉽게 될 것이라고 생각합니다.

대체 누가 이런 설정을 따라할지 궁금하긴 하지만, 앞으로도 시놀로지와 관련된 포스팅을 계속 할 예정이므로, 많은 관심 부탁드립니다.

감사합니다!

145 thoughts on “시놀로지 파일 탐색기에서 공유 링크 생성하기”

  1. top 10 online casinos in canada, online usa real money is sand hills
    casino open (Scotty) and are there casinos in new united states, or
    united statesn online poker

    응답
  2. canadian online bingo games, no deposit canada casino bonus and real online bay mills casino reviews – Clyde – australia,
    or how to play pokies in canada

    응답
  3. remote gambling usa license, best deposit bonus betting sites new zealand and new no deposit bonus casino 2022 ukraine (Rosalind) deposit
    casino 2021 australia, or nz online casinos that accept paypal

    응답
  4. 200 free spins no deposit usa casinos, yusaon casino review and windsor casino in united states, or free online poker machine gambling types of games, Felisha, australia

    응답
  5. canadian online pokies no minimum deposit, deposit £1 casino bonus usa
    and top online pokies and casinos australian open, or
    the overtones gambling man live (Cassandra) uk poker tournaments

    응답
  6. how much is a gambling license in canada, 100 slots bonus uk and uk online casinos free coins and spins
    for thug life (Dan) play, or roulette online casino australia

    응답
  7. We are a group of volunteers and opening a new scheme in our community.
    Your website offered us with valuable information to work on.
    You have done an impressive job and our entire community will
    be grateful to you.

    my blog post … casino math test (Gail)

    응답
  8. $20 no deposit bonus new zealand, australia casino pokies and uk casino free bonus, or nz online
    casinos that accept paypal

    Also visit my web-site; how to play 2 person blackjack
    (Lanny)

    응답
  9. I got this website from my pal who informed me on the
    topic of this website and now this time I am browsing this site and
    reading very informative articles or reviews at this place.

    Look at my homepage: birthday bonus casinos; Rubin,

    응답
  10. free slot machine games united kingdom, slot machines united states
    for sale and what poker sites are legal in australia, or top online blackjack casinos (Angeles) casino slots
    real money canada

    응답
  11. Thank you for the good writeup. It in fact was a amusement account it.
    Look advanced to far added agreeable from
    you! By the way, how could we communicate?

    Here is my blog post chess pattern roulette (Mason)

    응답
  12. Hello mates, how is everything, and what you would like to say about this post,
    in my view its in fact awesome designed for me.

    응답
  13. free spin no deposit casino australia, united kingdom online casino free chip and casino online jackpot usa 5f bonus, or gambling bonuses co usa

    Also visit my page; do indian casinos check for warrants (Reece)

    응답
  14. 200 free spins no deposit usa casinos, new zealand poker
    players and canadian poker 2 novomatic online, or united statesn roulette wheel numbers add up to (Beatriz) strategy uk

    응답
  15. uptown pokies australia review, best payout online casino
    usa and ept poker chips in usa, or how to play pokies in canada

    my website – roulette helper (Evelyn)

    응답
  16. Hello!
    Unlock travel mysterious destinations with interesting and valuable adventure facts and go where few have gone see on the website for travel guides
    Full information on the link – https://101flow.site
    All the best and development in business!

    응답
  17. Good morning!
    Share peace mysterious treaties with interesting and valuable diplomatic updates and celebrate moments of unity see on the website for treaty texts
    Full information on the link – https://202fliks.site
    All the best and development in business!

    응답

Leave a Comment