找回密码
 注册
搜索
[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
查看: 15031|回复: 0

[转载代码] [PowerShell每日技巧]导出/导入敏感信息(20140328)

[复制链接]
发表于 2014-4-4 20:45:07 | 显示全部楼层 |阅读模式
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:
  1. function Export-Credential
  2. {
  3.    param
  4.    (
  5.      [Parameter(Mandatory=$true)]
  6.      $Path,

  7.      [System.Management.Automation.Credential()]
  8.      [Parameter(Mandatory=$true)]
  9.      $Credential
  10.    )

  11.   $CredentialCopy = $Credential | Select-Object *
  12.   $CredentialCopy.Password = $CredentialCopy.Password | ConvertFrom-SecureString
  13.   $CredentialCopy | Export-Clixml $Path
  14. }
复制代码
This would save a credential for the user tobias to a file:
  1. 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:
  1. function Import-Credential
  2. {
  3.    param
  4.    (
  5.      [Parameter(Mandatory=$true)]
  6.      $Path
  7.    )

  8.   $CredentialCopy = Import-Clixml $path
  9.   $CredentialCopy.password = $CredentialCopy.Password | ConvertTo-SecureString
  10.   New-Object system.Management.Automation.PSCredential($CredentialCopy.username, $CredentialCopy.password)
  11. }
复制代码
So use it like this:
  1. $cred = Import-Credential -Path $enc:temp\mycred
  2. 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
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|批处理之家 ( 渝ICP备10000708号 )

GMT+8, 2026-3-17 05:13 , Processed in 0.013802 second(s), 8 queries , File On.

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表