winrm的全称是Windows Remote Management,就是windows的远程管理,通俗理解就是通过网络http请求在对windows进行管理,所以当远程操作时使用python的pywinrm模块来实现对windows的远程访问
winrm这个模块windows是自带的。 一般使用winrm模块向远程主机执行命令行命令
winrm是要求将网络设置为专有网络
以管理员方式打开Powershell,执行如下命令:
- Get-NetConnectionProfile #查看当前网络配置详情
- Set-NetConnectionProfile -InterfaceAlias LAN1 -NetworkCategory Private #根据名称设置网络为Private
winrm这个模块虽然是windows是自带的,仍需要执行powerShell命令打开此功能
以管理员方式打开Powershell,执行如下命令:
-
winrm enumerate winrm/config/listener #查看侦听器
-
winrm quickconfig #winrm快速设置,网络要求为专有网络
-
winrm configSDDL default # 配置winrm各账号的控制权限,将账号加入并给完全控制权限
-
reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f #禁用 UAC 远程限制
-
winrm set winrm/config/service/auth ‘@{Basic=“true”}’ #启用基本身份验证(明文)
-
winrm set winrm/config/service @{AllowUnencrypted=“true”} #允许非加密方式
-
winrm set winrm/config/client ‘@{TrustedHosts=“*”}’ #信任所有客户端
-
如打开防火墙的情况下,在出入站规则中请允许端口5985及5986通过防火墙,或直接关闭防火墙功能。
-
使用python+winrm,远程创建目录
import winrm
class windows_ssh():
def __init__(self, ip, username, password):
self.ip = ip
self.username = username
self.password = password
def win_command(self, shell):
try:
wintest = winrm.Session('http://' + self.ip + ':5985/wsman', auth=(self.username, self.password))
ret = wintest.run_cmd(shell)
ret = ret.std_out.decode()
return {'code':200, 'msg': '执行命令成功', 'data': ret}
except Exception as e:
return {'code': 500, 'msg': '执行命令失败! 错误信息: %s' % e}
def test(self):
result = self.win_command('mkdir D:\\winrm_Dir')
return result
if __name__ == '__main__':
ssh = windows_ssh("ip", "username", "password")
print(ssh.test()) # 验证是否能连接
tips:
如按照上述步骤出现:{‘code’: 500, ‘msg’: '执行命令失败! 错误信息: the specified credentials were rejected by the server’};按照如下处理:
-
使用compmgmt.msc打开计算机管理器、将使用winrm服务的账号计入adminstrator组
-
使用secpol.msc,打开本地安全策略、设置远程服务账号
-
使用secpol.msc,打开本地安全策略、设置远程服务账号
-
如果PC有多个账号A开启WINRM服务,使用B账号去访问时也可能会出现reject情况,如因多账号问题出现被服务器拒绝,A账号中关闭WINRM服务(或直接删除A账号),在B账号从新设置WINRM即可