Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in
Deleted user
0 / 0 points
Next:
badges earned

Your Points Tracker
Challenges
Leaderboard
  • Global
  • Feed

Badge for your thoughts?

You're enrolled in our new beta rewards program. Join our group to get the inside scoop and share your feedback.

Join group
Recognition
Give the gift of kudos
You have 0 kudos available to give
Who do you want to recognize?
Why do you want to recognize them?
Kudos
Great job appreciating your peers!
Check back soon to give more kudos.

Past Kudos Given
No kudos given
You haven't given any kudos yet. Share the love above and you'll see it here.

It's not the same without you

Join the community to find out what other Atlassian users are discussing, debating and creating.

Atlassian Community Hero Image Collage

Having issue with JIRA backup via powershell

Hello,

 

Having issue with JIRA back via Powershell, Could someone help on this?

Invoke-RestMethod : The remote server returned an error: (401) Unauthorized.
At E:\Scripts\JIRA.ps1:37 char:1
+ Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://$hostna ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-R
estMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRest
MethodCommand

VERBOSE: POST https://xxxxxx.atlassian.net/rest/backup/1/export/runbackup with -1-byte payload
{"message":"Client must be authenticated to access this resource.","status-code":401}

2 answers

0 votes

It means what it says - your call is being made from code that does not authenticate the session first.  Your code needs to "log in" correctly as a user and get tokens that say it has access and then provide them when making calls to the system.

Hello Nic,

Thank you very much for the reply. We can log on to the system without any issues via the browser. But when we try to run the script with same credentials that used in site this issue popup.

This is full powershell script that we are using to backup. Appreciate if you could look

 

param([string]$attachments='false') #Must be the first statement in your script
$account     = 'xxxx' # Atlassian subdomain i.e. whateverproceeds.atlassian.net
$username    = 'XXXX' # username without domain
$password    = 'XXX'
$destination = 'R:\Camsolean' # Location on server where script is run to dump the backup zip file.
#$attachments = $false # Tells the script whether or not to pull down the attachments as well

$hostname    = "$account.atlassian.net"
$today       = Get-Date -format yyyyMMdd-hhmmss
$credential  = New-Object System.Management.Automation.PSCredential($username, (ConvertTo-SecureString $password -AsPlainText -Force))
$string = "cbAttachments:true, exportToCloud:true"
#$stringbinary = [system.Text.Encoding]::Default.GetBytes($String) | %{[System.Convert]::ToString($_,2).PadLeft(8,'0') }
$running_backup_file = "E:\running_incomplete_logs\camsolean-jira-$today.log"
$previous_day=get-date -date(get-date).adddays(-1) -format MM/dd/yyyy

function Get-TimeStamp {
   
    return "[{0:MM/dd/yy} {0:HH:mm:ss}]" -f (Get-Date)
   
}

if ($PSVersionTable.PSVersion.Major -lt 4) {
    throw "Script requires at least PowerShell version 4. Get it here: https://www.microsoft.com/en-us/download/details.aspx?id=40855"
}

$body = @{
          cbAttachments=$attachments
          exportToCloud='true'
         }
$bodyjson = $body | ConvertTo-Json

Write-Output "$(Get-TimeStamp) --Starting--$account--Backup---" | Out-file $running_backup_file -append
Write-Output "$(Get-TimeStamp) $bodyjson" | Out-file $running_backup_file -append


# New session
Invoke-RestMethod -UseBasicParsing -Method Post -Uri "https://$hostname/rest/auth/1/session" -SessionVariable session -Body (@{username = $username; password = $password} | convertTo-Json -Compress) -ContentType 'application/json'

# Request backup
try {
        $InitiateBackup = Invoke-RestMethod -Method Post -Headers @{"Accept"="application/json"} -Uri "https://$hostname/rest/backup/1/export/runbackup" -WebSession $session -ContentType 'application/json' -Body $bodyjson -Verbose | ConvertTo-Json -Compress | Out-Null
} catch {
        $InitiateBackup = $_.Exception.Response.GetResponseStream()
        $reader = New-Object System.IO.StreamReader($InitiateBackup)
        $reader.BaseStream.Position = 0
        $reader.DiscardBufferedData()
        $responseBody = $reader.ReadToEnd();
}

$responseBody

Write-Output "$(Get-TimeStamp) Response:$responseBody" | Out-file $running_backup_file -append

$GetBackupID = Invoke-WebRequest -Method Get -WebSession $session https://$hostname/rest/backup/1/export/lastTaskId

$LatestBackupID = $GetBackupID.content

Write-Output "$(Get-TimeStamp) LatestBackupID:$LatestBackupID" | Out-file $running_backup_file -append

# Wait for backup to finish
do {
    $status = Invoke-RestMethod -Method Get -Headers @{"Accept"="application/json"} -Uri "https://$hostname/rest/backup/1/export/getProgress?taskId=$LatestBackupID" -WebSession $session
    $statusoutput = $status.result
    $separator = ","
    $option = [System.StringSplitOptions]::None
    $s
 
    if ($status.progress -match "(\d+)") {
        $percentage = $Matches[1]
        if ([int]$percentage -gt 100) {
            $percentage = "100"
        }
        Write-Progress -Activity 'Creating backup' -Status $status.progress -PercentComplete $percentage
  Write-Output "$(Get-TimeStamp) Progress:$percentage% " | Out-file $running_backup_file -append
    }
    Start-Sleep -Seconds 5
} while($status.status -ne 'Success')

Write-Output "$(Get-TimeStamp) Summary:$status.status  " | Out-file $running_backup_file -append

# Download
if ([bool]($status.PSObject.Properties.Name -match "failedMessage")) {
throw $status.failedMessage
}

Write-Output "$(Get-TimeStamp) Description:$status  " | Out-file $running_backup_file -append

$BackupDetails = $status.result

$BackupURI = "https://$hostname/plugins/servlet/$BackupDetails"

Write-Output "$(Get-TimeStamp) $BackupURI  " | Out-file $running_backup_file -append

if ($attachments -eq 'false') {
Invoke-WebRequest -Method Get -Headers @{"Accept"="*/*"} -WebSession $session -Uri $BackupURI -OutFile (Join-Path -Path $destination -ChildPath "JIRA-backup-$today.zip")
}
else {
Invoke-WebRequest -Method Get -Headers @{"Accept"="*/*"} -WebSession $session -Uri $BackupURI -OutFile (Join-Path -Path $destination -ChildPath "JIRA-backup-full-$today.zip")
}


Write-Output "$(Get-TimeStamp) Moving logs from E:\running_incomplete_logs to E:\Backups_logs  " | Out-file $running_backup_file -append

mv $running_backup_file E:\Backup_logs

Write-Output "$(Get-TimeStamp) --Log purge--  " | Out-file E:\Backup_logs\camsolean-jira-$today.log -append

forfiles /p "E:\Backup_logs" /m camsolean-jira-*.log /d -$previous_day /c "cmd /c move @path E:\Backup_logs\Old_Logs&echo @path" >> E:\Backup_logs\camsolean-jira-$today.log

forfiles /p "E:\Backup_logs\Old_Logs" /m camsolean-jira-*.log /d -14 /c "cmd /c del @path&echo @path" >> E:\Backup_logs\camsolean-jira-$today.log

forfiles /p "R:\Camsolean" /m *.zip /d -14 /c "cmd /c del @path&echo @path" >> E:\Backup_logs\camsolean-jira-$today.log

Write-Output "$(Get-TimeStamp) --Backup--$account--Completed--  " | Out-file E:\Backup_logs\camsolean-jira-$today.log -append

I don't use powershell, I can't tell you what is wrong with the code, other than it is not presenting the right authorisation data to Jira.  Check what your script is doing against https://developer.atlassian.com/cloud/jira/platform/jira-rest-api-basic-authentication/

@IT Infrastructure  is your script backup host JIRA Cloud site include attachments ? 

Suggest an answer

Log in or Sign up to answer
TAGS

Community Events

Connect with like-minded Atlassian users at free events near you!

Find an event

Connect with like-minded Atlassian users at free events near you!

Unfortunately there are no Community Events near you at the moment.

Host an event

You're one step closer to meeting fellow Atlassian users at your local event. Learn more about Community Events

Events near you