标题: [转载代码] [PowerShell每日技巧]导出/导入敏感信息(20140328) [打印本页]
作者: DAIC 时间: 2014-4-4 20:45 标题: [PowerShell每日技巧]导出/导入敏感信息(20140328)
Credential objects contain a username and a password. You can create them using Get-Credential, and then supply this object to any cmdlet that has the -Credential parameter.
However, what do you do if you want your scripts to run without user intervention yet securely? You do not want a credentials dialog to pop up, and you do not want to store the password information inside the script.
Here's a solution: use the function Export-Credential to save the credential to file:- function Export-Credential
- {
- param
- (
- [Parameter(Mandatory=$true)]
- $Path,
-
- [System.Management.Automation.Credential()]
- [Parameter(Mandatory=$true)]
- $Credential
- )
-
- $CredentialCopy = $Credential | Select-Object *
- $CredentialCopy.Password = $CredentialCopy.Password | ConvertFrom-SecureString
- $CredentialCopy | Export-Clixml $Path
- }
复制代码
This would save a credential for the user tobias to a file:- Export-Credential -Path $env:temp\mycred -Credential mycomany\tobias
复制代码
Note that while you do this, the credentials dialog pops up and securely asks for your password. The resulting file contains XML, and the password is encrypted.
Now, when you need the credential, use Import-Credential to get it back from file:- function Import-Credential
- {
- param
- (
- [Parameter(Mandatory=$true)]
- $Path
- )
-
- $CredentialCopy = Import-Clixml $path
- $CredentialCopy.password = $CredentialCopy.Password | ConvertTo-SecureString
- New-Object system.Management.Automation.PSCredential($CredentialCopy.username, $CredentialCopy.password)
- }
复制代码
So use it like this:- $cred = Import-Credential -Path $enc:temp\mycred
- Get-WmiObject -Class Win32_BIOS -ComputerName server1 -Credential $cred
复制代码
The "secret" used for encryption and decryption is your identity, so only you (the user that exported the credential) can import it again. No need to hard-code secrets into your script.
http://powershell.com/cs/blogs/tips/archive/2014/03/28/exporting-and-importing-credentials-in-powershell.aspx
欢迎光临 批处理之家 (http://bbs.bathome.net/) |
Powered by Discuz! 7.2 |