python远程控制windows机器

1,进入cmd,输入winrm quickconfig -q,如果出现下图报错,把电脑公网设置为专网

 

 

 设置专网步骤:win+i,网络和internet,状态,属性

 

 

2,检查 winrm 服务监听状态;进入cmd,输入winrm e winrm/config/listener;记录端口号 Port 值,后面会用到

 

 

 

 

 3,查看 winrm 配置信息(可选)

通过以下命令可以查看 winrm 全部配置信息、client 客户端配置信息、service 服务端配置信息

# 全部

winrm get winrm/config

# Client

winrm get winrm/config/client

# Service

winrm get winrm/config/service

 

4,配置 winrm client

# 配置winrm client
winrm set winrm/config/client @{AllowUnencrypted="true"}

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

winrm set winrm/config/client/auth @{Basic="true"}


5,配置 winrm service

在配置完 winrm service 和 winrm client 后,我们通过通过步骤 3 查看配置文件,确保配置文件已生效

# 配置winrm service

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

winrm set winrm/config/service/auth @{Basic="true"}

 

6,进入cmd安装pywinrm依赖包

 

7,写python代码,输入 ip 地址、端口号、用户名、密码连接 Windows 

# 连接windows
import winrm


self.session = winrm.Session("192.168.**.**:5985", auth=('username', 'password'), transport='ntlm')

# 发起连接windows请求

wintest = winrm.Session('http://192.168.**.**/wsman',auth= ('username', 'password'), transport='ntlm')

 
# 获取被远程windows的ip
ret = wintest .run_ps("ipconfig")
print(ret)
 
#打印结果为0,说明远程连接windows成功
print(ret.std_out.decode())
#打印错误信息,说明连接windows失败
print(ret.std_err.decode())

 

8,通过对象的「 run_cmd 」和「 run_ps 」函数模拟 CMD、PowerShell 输入命令了

# 连接windows
import winrm
import codecs
...
def exec_cmd(self, cmd):
"""
执行cmd命令,获取返回值
:param cmd:
:return:
"""
# CMD
result = self.session.run_cmd(cmd)
# powerShell
# result = self.session.run_ps(cmd)
# 返回码
# code为0代表调用成功
code = result.status_code

# 根据返回码,获取响应内容(bytes)
content = result.std_out if code == 0 else result.std_err

# 转为字符串(尝试通过UTF8、GBK进行解码)
# result = content.decode("utf8")
# result = codecs.decode(content,'UTF-8')
try:
result = content.decode("utf8")
except:
result = content.decode("GBK")

print(result)
return result
...
# 打开文件D:/py/log/trade.log
# windows使用type命令,查看文件内容
result = self.exec_cmd('D: &cd py\\log &type trade.log')

# 查看结果
print(result)

 

 7,

if __name__ ==__name__:
#username需要本地用户,域用户可能需要先加到修改策略加到本地用户组中,本人未试过
win = winrm.Session('http://192.168.1.112/wsman',auth= ('ds900726','window3!'), transport='ntlm')
#run_ps运行PowerShell命令
r = win.run_ps("ipconfig")
#run_cmd运行cmd命令
s = win.run_cmd("ipconfig")
ip = str(r.std_out,encoding='gbk')
IP = str(r.std_out,encoding='gbk')
print(ip)
print(str(r.std_out,encoding='gbk')) # 打印获取到的信息
print(("----------------------------------world line-------------------------------------------"))
print(str(r.std_err,encoding='gbk')) #打印错误信息
posted @ 2023-04-07 23:15  liuweipaul123  阅读(596)  评论(0编辑  收藏  举报