需求:客户机在普通用户下需要以管理员方式运行 powershell,类似于 runas 命令
如果要以 runas 提权,请参考这里 Win10 Runas 命令 域用户以管理员权限运行_tom.ma的博客-CSDN博客
一、常规方法
1、打开 PowerShell ISE工具
2、运行如下代码,能成功以管理员方式打开 powershell,但在实际环境中都不会允许明文密码的出现
$Username = 'administrator'
$Password = 'xielong.cn'
$Pass = ConvertTo-SecureString $Password -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$Pass
Start-Process powershell.exe -Credential $Credential
二、安全方法
1、创建 AES,保存D盘下面
# 先生成 32 位的 Key 并保存在文件 aes.key
$keyFile = "d:\aes.key"
$key = New-Object Byte[] 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($key)
$key | out-file $keyFile
2、创建密码文件
通过 ConvertFrom-SecureString 命令,我们可以把一个 SecureString 对象转换成一个 Encrypted Standard String(加密后的一个字符串),然后保存到文件中。在创建 Credential 时直接使用前面保存的文件,从而避免明文密码在系统中出现。
# 使用 Key 生成并保存密码文件
Read-Host "Enter Password" -AsSecureString | ConvertFrom-SecureString -key $key | Out-File "d:\pwd.txt"
# 使用密码文件创建和 Key 文件创建 Credential 信息
$userName = "administrator"
$passwdFile = "d:\pwd.txt"
$keyFile = "d:\aes.key"
$key = Get-Content $keyFile
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, (Get-Content $passwdFile | ConvertTo-SecureString -Key $key)
# 以管理员权限启动 powershell
Start-Process powershell.exe -Credential $Credential
3、把 aes.key 跟 pwd.txt 拷到要运行的客户机D盘下面,然后运行下面脚本
$userName = "administrator"
$passwdFile = "d:\pwd.txt"
$keyFile = "d:\aes.key"
$key = Get-Content $keyFile
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $userName, (Get-Content $passwdFile | ConvertTo-SecureString -Key $key)
# 以管理员权限启动 powershell
Start-Process powershell.exe -Credential $Credential