ARM 虚拟机默认只有 RDP 的远程连接方式,我们可以在机器创建好后,手动为虚拟机配置 Powershell 的侦听。
这里只是使用 Azure ARM 虚拟机进行一个简单的演示,对于Windows Server下面的方法其实是通用的。
首先我们创建一台 Windows Server 2012 R2 的虚拟机,可以在防火墙中添加 TCP 5985 和 TCP5986 端口的放行规则,5985 是 HTTPListener 的侦听端口,5986 是 HTTPSListener(启用SSL) 的侦听端口。
1) 我们先进行HTTP Listener的配置:
登陆虚拟机,打开 Powershell,执行Enable-PSRemoting -Force;
执行成功后,使用 netstat -ano | findstr 查看是否有 5985 端口的侦听:
接着我们需要在本地需要连接的客户端机器上添加信任,使用管理员权限打开Powershell,执行下面两条命令:
winrmquickconfig
Set-itemwsman:localhost\client\trustedhosts -value 139.219.109.64
注意:上面命令中标黄的部分替换成虚拟机的公网IP地址。
配置好之后,使用下面的命令连接到虚拟机的 5985 端口:
Enter-Pssession-ComputerName 139.219.109.64-port 5985 -Authentication Negotiate -Credential daniel -SessionOption (New-PSSessionOption-SkipCACheck -SkipCNCheck)
2) 我们接着配置 HTTPS Listener,在虚拟机中打开 Powershell,使用下面的命令创建一个自签名证书:
New-SelfSignedCertificate-DnsName dan2012r2.chinanorth.cloudapp.chinacloudapi.cn-CertStoreLocation Cert:\LocalMachine\My
注意:上面高亮的部分是这台虚拟机公网 IP 对应的 DNS 名称,如果没有 DNS,直接换成虚拟机的公网 IP 地址就可以了。
创建好之后,可以看到下面生成了一个证书指纹(Thumbprint),打开 mmc:
添加 Certificates(Computeraccount):
可以看到刚刚生成的自签名证书:
核对一下证书指纹:
使用管理员权限打开cmd,执行下面的命令添加 HTTPSListener(替换一下域名或者公网 IP,以及证书指纹):
winrm createwinrm/config/Listener?Address=*+Transport=HTTPS @{Hostname="dan2012r2.chinanorth.cloudapp.chinacloudapi.cn";CertificateThumbprint="A52FFC1ACC8606E8A7750217599742699E42A27A"}
核实一下 HTTPS 的侦听:
netstat-ano | findstr 5986
创建成功后,就可以在客户端使用-UseSSL 参数来进行连接了:
Enter-Pssession-ComputerName 139.219.109.64-port 5986 -Authentication Negotiate -Credential daniel -UseSSL -SessionOption (New-PSSessionOption -SkipCACheck-SkipCNCheck)
注:HTTPS 的连接不需要再客户端进行winrm 的任何配置。
上面的步骤可以用于解决下面这个问题:
对于经典 Azure 虚拟机,默认虚拟机创建好之后 Powershell 的 SSL 就配置好了,可以直接访问虚拟机的 5986 端口。如果不小心把 Personal 下的自签名证书删除了该怎么办?
很简单,删除了自签名证书,可以使用管理员权限运行 cmd,执行下面的命令将原来的HTTPS Listener 删除掉:
winrmdelete winrm/config/Listener?Address=*+Transport=HTTPS
删除后,再使用上面配置 HTTPS Listener 的方法做一遍就好了。