PowerShell远程连接主机失败:New-PSSession报错及免密诉求
PowerShell远程连接失败修复及免密方案
一、先解决连接报错问题
1. 修正命令语法错误
你当前的命令存在两个关键语法问题:
- 第一个命令里
a.b.c.d(IP)格式错误,IP需要用引号包裹;另外$host是PowerShell内置变量,别用来存储会话,换用自定义变量名:
$session = New-PSSession -ComputerName "a.b.c.d"
- 第二个命令里
New -PSSession中间多了空格,PowerShell会把New当成单独命令,所以才报“New未被识别”。同时-Credential参数不能直接传用户名和密码字符串,需要用PSCredential对象,修正后命令:
$RemoteServer = "a.b.c.d" $Username = "xyz\abc" $Password = ConvertTo-SecureString "abc" -AsPlainText -Force $cred = New-Object System.Management.Automation.PSCredential ($Username, $Password) $sess = New-PSSession -ComputerName $RemoteServer -Credential $cred
2. 检查目标主机WinRM配置
远程连接依赖WinRM服务,必须确保目标主机开启并配置正确:
- 在目标主机以管理员身份运行:
Enable-PSRemoting -Force
- 本地主机先测试连通性,能正常访问再继续:
Test-WSMan a.b.c.d
二、免密连接的几种方案
1. 域环境下直接免密(最省心)
如果你的电脑和目标主机在同一个AD域中,只要你当前登录的域账号拥有目标主机的远程管理权限,直接运行以下命令即可免密连接:
$sess = New-PSSession -ComputerName "a.b.c.d"
2. 加密存储密码到本地文件
把密码加密存储在本地文件中,之后无需手动输入密码,密码更新时重新生成文件即可:
- 先运行一次生成密码文件(仅需执行一次):
$Username = "xyz\abc" $Password = ConvertTo-SecureString "你的密码" -AsPlainText -Force $Password | ConvertFrom-SecureString | Out-File "C:\Scripts\cred.txt"
- 每次连接时读取文件自动获取密码:
$RemoteServer = "a.b.c.d" $Username = "xyz\abc" $SecurePassword = Get-Content "C:\Scripts\cred.txt" | ConvertTo-SecureString $cred = New-Object System.Management.Automation.PSCredential ($Username, $SecurePassword) $sess = New-PSSession -ComputerName $RemoteServer -Credential $cred
(注:这个加密文件仅能在生成它的用户和主机上使用,安全性有保障)
3. 用SSH实现免密(PowerShell 7+适用)
如果目标主机开启了SSH服务,PowerShell 7及以上版本支持通过SSH远程连接,配置密钥登录即可实现免密:
- 在本地生成SSH密钥对:
ssh-keygen -t rsa
- 将本地生成的公钥(默认路径
C:\Users\你的用户名\.ssh\id_rsa.pub)复制到目标主机的C:\Users\你的用户名\.ssh\authorized_keys文件中 - 之后直接通过SSH连接:
$sess = New-PSSession -ComputerName "a.b.c.d" -SSHTransport
内容的提问来源于stack exchange,提问作者Christina Evans
相关产品推荐
相关产品推荐

