使用PowerShell执行mongodump时如何指定MongoDB认证机制?
解决mongodump使用SCRAM-SHA-256认证失败的问题
你的核心问题是没有在mongodump命令中指定SCRAM-SHA-256认证机制参数,虽然你定义了$mechanism变量,但未将其传入命令,导致工具默认使用SCRAM-SHA-1发起认证,与数据库要求不符。
错误信息
mongodump : 2023-01-31T12:11:36.381+0100 Failed: can't create session: could not connect to server: connection() error occurred during connection handshake: auth error: sasl conversation error: unable to authenticate using mechanism "SCRAM-SHA-1": (AuthenticationFailed) Authentication failed.
修改后的PowerShell脚本
<# Set the MongoDB access variables #> $databaseName = "HistoryTest" $username = "..." $password = "..." $mechanism="SCRAM-SHA-256" $mongoDbHost = "localhost:27017" <# Set the folders location and name #> $backupPath = "C:\Mongo_Backup" $currentDate = get-date -format yyyyMMddHHmm $directoryName = "$databaseName-$currentDate" $directoryPath = Join-Path $backupPath $directoryName #endregion #region Backup Process $watch = New-Object System.Diagnostics.StopWatch $watch.Start() Write-Host "Backing up the Database: '$databaseName' to local directory: $backupPath." # Use this command when the database require authorization mongodump -h "$mongoDbHost" ` -d "$databaseName" ` -u "$username" ` -p "$password" ` --authenticationMechanism $mechanism ` -o "$directoryPath" $archiveFileDestinationPath = "$backupPath\$directoryName.gz" mongodump --gzip -h "$mongoDbHost" ` -d "$databaseName" ` -u "$username" ` -p "$password" ` --authenticationMechanism $mechanism ` --archive="$archiveFileDestinationPath" Write-Host "Creating the backup for $databaseName..." $watch.Stop(); Write-Host "MongoDB backup completed in $($watch.Elapsed.ToString())" #endregion
关键修改说明
- 在两个
mongodump命令中均添加了--authenticationMechanism $mechanism参数,明确指定使用SCRAM-SHA-256认证 - 第二个归档备份命令同样需要添加认证参数,否则会重复出现认证失败问题
- 确保
$username和$password变量填写的是数据库的合法认证凭据
内容的提问来源于stack exchange,提问作者Blümchenpeter
相关产品推荐
相关产品推荐

