从.ps1
脚本在远程计算机( Win 2008 Server )上创建网络共享,并提供username
和password
。
这适用于当前用户具有足够权限的地方
$share = Get-WmiObject Win32_Share -List -ComputerName 10.0.0.1
$share.create("C:\dir","foo", 0)
当targetServer
是我的用户没有足够权限的计算机时,我需要一种方法来提供username
和password
答案 0 :(得分:1)
Get-WmiObject
有一个参数-Credential
,因此您可以使用Get-Credential
提示用户输入凭据并按以下方式传递:
$cred = Get-Credential
$share = Get-WmiObject Win32_Share -List -Computer 10.0.0.1 -Credential $cred
$share.Create('C:\dir', 'foo', 0)
如果您想完全自动化凭证处理,您可以自己构建凭据对象:
$username = 'DOMAIN\user'
$password = 'password'
$pw = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object Management.Automation.PSCredential $username, $pw
$share = Get-WmiObject Win32_Share -List -Computer 10.0.0.1 -Credential $cred
$share.Create('C:\dir', 'foo', 0)
在脚本中存储明文密码不是一个好习惯,因此您可能希望将加密密码存储在单独的文件中(确保对该文件设置限制性权限):
PS C:\> Read-Host 'Enter password' -AsSecureString |
>> ConvertFrom-SecureString | Out-File 'C:\password.txt'
>>
Enter password: ******
PS C:\> Get-Content 'C:\password.txt'
01000000d08c9ddf0115d1118c7a00c04fc297eb01000000a04a09e406c93741865ab010ed072699
0000000002000000000003660000c00000001000000028b14f21c501cdf629b94cea2837e8520000
000004800000a0000000100000002db774b0a8612917224e7dbfd69055340800000043f449c82f47
3e78140000007de59fcec57a1dc9b6b62272eff517b8bf5291e5
然后可以像这样读取和解密加密的密码:
$username = 'DOMAIN\user'
$pw = Get-Content 'C:\password.txt' | ConvertTo-SecureString
$cred = New-Object Management.Automation.PSCredential $username, $pw
$share = Get-WmiObject Win32_Share -List -Computer 10.0.0.1 -Credential $cred
$share.Create('C:\dir', 'foo', 0)
但请注意,ConvertTo-SecureString
使用运行该命令的用户(我认为主机)加密/解密密码。如果您需要将密码加密为一个用户并将其作为另一个用户(或另一个主机)解密,则必须在这些用户/主机之间共享密钥。可以像这样生成随机密钥:
PS C:\> $numchars = 24 # 192 Bit
PS C:\> $charmap = [char]'A'..[char]'Z' +
>> [char]'a'..[char]'z' +
>> [char]'0'..[char]'9'
>>
PS C:\> [char[]]($charmap | sort {Get-Random})[1..$numchars] -join ''
b69cGXKpJaI5tLrj4lHEPN3e
使用共享密钥创建密码文件,如下所示:
PS C:\> $key = [char[]]($charmap | sort {Get-Random})[1..$numchars] -join ''
PS C:\> $pw = Read-Host 'Enter password' -AsSecureString |
>> ConvertFrom-SecureString -Key ([byte[]][char[]]$key)
>>
Enter password: ******
PS C:\> @"
>> Key = $key
>> Pass = $pw
>> "@ | Out-File 'C:\password.txt'
>>
并阅读加密密码,如下所示:
$username = 'DOMAIN\user'
$pass = Get-Content 'C:\password.txt' | Out-String | ConvertFrom-StringData
$pw = ConvertTo-SecureString $pass.Pass -Key ([byte[]][char[]]$pass.Key)
$cred = New-Object Management.Automation.PSCredential $username, $pw
$share = Get-WmiObject Win32_Share -List -Computer 10.0.0.1 -Credential $cred
$share.Create('C:\dir', 'foo', 0)