PowerShell远程连接Windows Server 2012 R2

在之前给Windows服务器配置了SSH连接,但是体验并不好,其实也可以选择使用PowerShell远程连接服务器,因为都是微软自家的东西,所以体验会更好

服务器配置

连接上服务器PowerShell,运行以下命令

允许远程访问

1
Enable-PSRemoting

跳过网络检查

1
Enable-PSRemoting -SkipNetworkProfileCheck -force

设置信任IP,*号代表全部信任,可以自行设置

1
Set-Item WSMan:\localhost\Client\TrustedHosts -Value * -Force 

允许使用脚本

1
set-ExecutionPolicy RemoteSigned

检查WinRm是否正常开启

1
winrm enumerate winrm/config/listener

这里可以看到服务器WinRm开启成功,并且监听5985端口,所以需要开放5985端口

客户端配置

配置信任IP,*代表信任全部

1
winrm set winrm/config/client '@{TrustedHosts="*"}'

如果这一步报错,可能是因为WinRm服务未开启,需要检查服务是否开启

1
Get-Service WinRM

如果未开启,需要开启WinRm服务

1
2
3
Start-Service WinRM
# 或者
net start winrm

服务启动,并配置了信任IP后,可以开始连接服务器

连接

可以选择直接连接

1
Enter-PSSession -ComputerName computerName -Credential userName

验证密码后就连接上远程服务器了

也可以选择创建PSSession

1
New-PSSession -ComputerName computerName -Credential userName

创建PSSession后可以查看现有的PSSession,也可以连接PSSession,或者对PSSession发送远程命令

1
2
3
4
5
# 查看现有PSSession
Get-PSSession
# 连接现有PSSession
Enter-PSSession -Id 6
Enter-PSSession -Name winrm6

发送远程命令

1
2
3
$session=New-PSSession -ComputerName ComputerName -Credential Administrator
Get-PSSession
icm -Session $session {Get-Process}

花括号里的ScriptBlock,就是要在服务器上运行的命令

也可以写脚本自动连接

1
2
3
4
5
$uname=""
$pwd=ConvertTo-SecureString "" -AsPlainText -Force;
$cred=New-Object System.Management.Automation.PSCredential($uname,$pwd);
$servers="";
Enter-PSSession -ComputerName $servers -Credential $cred;

修改信息,保存为ps1文件,用PowerShell打开就可以自动连接

这样子就可以不用远程桌面,仅仅使用PowerShell就可以实现对服务器的操控

使用Get-Help可以查看更多关于PSSession的命令,都可以一个一个去尝试