Winrm+python远程连接windows执行命令


WinRM(Windows Remote Management)windows远程管理,这个是基于[powershell](https://baike.baidu.com/item/Windows PowerShell ISE)的功能,一个形象的类比就是ssh之于linux。

winrm可以远程连接windows并执行cmd命令(使用python语言)

WinRM端口是5985和5986(HTTPS)

1、开启服务端winrm的服务

在window服务器上,要打开winrm服务。下面是操作流程:

第一步:用管理员权限打开windows powershell
第二步:首先查看winrm service的运行状态,默认情况是没有开启的;执行命令为空是没有启动。

winrm enumerate winrm/config/listener


第三步:对winrm service进行配置

winrm quickconfig


第四步:为winrm service 配置auth:

winrm set winrm/config/service/auth @{Basic="true"}
# winrm set winrm/config/service/auth '@{CredSSP="true"}' #凭据安全支持提供程序协议 (CredSSP)可以开启加密凭据的传输

第五步:为winrm service 配置加密方式为允许非加密:

winrm set winrm/config/service  @{AllowUnencrypted="true"}

检验是否配置成功

winrm get winrm/config/service/auth

2、python代码

python环境中安装依赖包

pip install isodate
pip install xmlwitch

安装pywinrm

pip install pywinrm

使用session方法

 import winrm
 win = winrm.Session('http://windowsip:5985/wsman',auth=('windows管理员账户','windows管理员密码'))
 r = win.run_cmd('history')  #执行cmd命令 这里cmd中没有history的命令
 print(str(r.std_out,encoding='gbk'))  # 打印获取到的信息
 print(str(r.std_err,encoding='gbk')) #打印错误信息

 import winrm
 win = winrm.Session('http://windowsip:5985/wsman',auth=('windows管理员账户','windows管理员密码'))
 r = win.run_ps('history')  #执行powershell命令 可以执行一些cmd没有的命令,
 print(str(r.std_out,encoding='gbk'))  # 打印获取到的信息
 print(str(r.std_err,encoding='gbk')) #打印错误信息#因为cmd默认使用gbk编码,而python默认使用utf-8,所以要用gbk进行解码


使用Protocol方法

import winrm
conn = winrm.Protocol(endpoint='http://10.10.60.14:5985/wsman', transport='plaintext', username='administrator', password='password')

shell_id=conn.open_shell()

com=conn.run_command(shell_id,"dir") 

stdout, stderr, return_code = conn.get_command_output(shell_id, com) 

print "STDOUT: %s" % (stdout)
print "STDERR: %s" % (stderr)

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值