如何在连接字符串中用*替换密码字符?



我没有得到关于这个问题的正确帮助

所以我在这里发布我想到的另一个选择:

我有以下脚本可以更改级别 1100 和 1400 多维数据集/数据库的连接字符串

$newConnectionString = "Connection Timeout=120;User Id=UID1;Data Source=datasource.com;Password=password123553;Persist Security Info=True;Session Character Set=UTF8"
$AS = New-Object Microsoft.AnalysisServices.Server  
$AS.connect("$Server")
$cubeName = $Analysis_Server.Databases.FindByName($Cube)
$compatibility_lvl = $cubeName.CompatibilityLevel
if ($compatibility_lvl -lt 1200) #1103
{
$cubeName.DataSources[0].ConnectionString = $newConnectionString
$cubeName.DataSources[0].Update()
$lt1200 = $($cubeName.DataSources[0].ConnectionString)
Write-Host "$lt1200`r`n" -Fore yellow
}
else
{
$TAS = new-Object Microsoft.AnalysisServices.Tabular.Server
$TAS.Connect("$Server")
$TAS.Databases[$Cube].model.datasources[0].ConnectionString = $newConnectionString
$TAS.Databases[$Cube].Update([Microsoft.AnalysisServices.UpdateOptions]::ExpandFull)    
$gt1200 = $($TAS.Databases[$Cube].model.datasources[0].ConnectionString)
Write-Host "$gt1200`r`n" -Fore yellow
}

从这些陈述中:

$lt1200 = $($cubeName.DataSources[0].ConnectionString)
Write-Host "$lt1200`r`n" -Fore yellow
$gt1200 = $($TAS.Databases[$Cube].model.datasources[0].ConnectionString)
Write-Host "$gt1200`r`n" -Fore yellow

这是我得到的输出

连接超时 = 120;用户 ID = UID1;数据 源=数据源.com;密码=密码123553;保留安全信息 = 真;会话字符集 = UTF8

我应该只将其作为输出返回:

连接超时 = 120;用户 ID = UID1;数据源=数据源.com;保留安全信息 = 真;会话字符集 = UTF8

由于我找不到刷新数据源的方法,除非重新连接到服务器并打印出没有密码的连接字符串,因此我希望正则表达式将密码替换为以下方案:

  1. 将密码值替换为所有星号

连接超时 = 120;用户 ID = UID1;数据 源=数据源.com;密码=********;保留安全信息 = 真;会话字符集 = UTF8

  1. 保留密码值的第一个和最后一个字符,但将中间替换为所有星号

连接超时 = 120;用户 ID = UID1;数据 源=数据源.com;密码=p*******3;保留安全信息 = 真;会话字符集 = UTF8

  1. 保留密码的第一个 3 个值,并将其余部分替换为星号

连接超时 = 120;用户 ID = UID1;数据 源=数据源.com;密码=pas********;保留安全信息 = 真;会话字符集 = UTF8

我知道它会是这样的,但我不确定上述情况下的正则表达式是什么:

$lt1200 = $($cubeName.DataSources[0].ConnectionString) -Replace($_ "Password=*?;", "Password=********");

您可能应该查看 .net 类SqlConnectionStringBuilder。 它可以分析连接字符串并将其转换为对象。 您不需要正则表达式即可找到密码,并且可以轻松地将密码替换为所需的任何密码。

$builder = [System.Data.SqlClient.SqlConnectionStringBuilder]::New('Connection Timeout=120;User Id=UID1;Data Source=datasource.com;Password=password123553;')
$builder.Password

替换为与密码相同的长度。 不是很优雅,但它有效

function Hide-ConnectionStringPassword {
param(
[string]$ConnectionString
)
$re = [regex]::new("Password=(.*);")
$match = $re.Match($ConnectionString)
[string]$password = $match.Groups[1].Value
[string]$stars = "*" * $password.Length
return $ConnectionString -replace 'Password=.*;', "Password=$stars;"
}
Hide-ConnectionStringPassword "Source=datasource.com;Password=password123553;"

输出:

Source=datasource.com;Password=**************;

最新更新