python连接Windows执行doc命令---winrm
最近做项目用Windows电脑起服务,因为不是自己电脑,所以每次都得远程操作拉取代码,重新启动服务等操作,所以想有什么工具可以直接连Windows执行doc命令呢,首先想到了Jenkins,但是为了执行一些命令,直接使用Jenkins有点重,所以就看了python的winrm实现远程执行,接下来我们一起学习下吧,希望对你有所帮助。
一、开启winrm服务
1、查看是否开启winrm服务
winrm e winrm/config/listener
如果报错说明没有开启,应该更改powershell执行策略为remotesigned,执行以下命令,选择Y:
set-executionpolicy remotesigned
PS C:\Windows\system32> set-executionpolicy remotesigned
执行策略更改
执行策略可帮助你防止执行不信任的脚本。更改执行策略可能会产生安全风险,如 https:/go.microsoft.com/fwlink/?LinkID=135170
中的 about_Execution_Policies 帮助主题所述。是否要更改执行策略?
[Y] 是(Y) [A] 全是(A) [N] 否(N) [L] 全否(L) [S] 暂停(S) [?] 帮助 (默认值为“N”): y
2、开启服务
要在管理员模式下,使用POWERSEHLL模式执行命令:
winrm quickconfig
执行命令后会有2个确认问题,直接都输入“Y”即可
3、winrm服务设置auth
winrm set winrm/config/service/auth '@{Basic="true"}'
4、为winrm服务配置加密方式为允许非加密(必须配置,否则远程连接会出错)
winrm set winrm/config/service '@{AllowUnencrypted="true"}'
5、查看winrm配置
winrm get winrm/config
6、查看http服务是否开启
netsh http show servicestate
图片中框选的为访问地址,应该是:http://ip:5985/WSMAN/,当前电脑还需要配置用户名和密码,后面使用python连接时使用。
二、python连接winrm服务
1、安装pywinrm模版
pip install pywinrm
2、编写代码链接Windows
http_url='http://192.168.31.43:5985/wsman'
user_name = "username"
pass_wd = "password"
session = winrm.Session(http_url,auth=(user_name,pass_wd),transport='ntlm')
res = session.run_cmd('ipconfig')
print(res.status_code)
print(res.std_out.decode('gbk'))
简单封装一下:
class ConnectWinServer:
def __init__(self, ip: str, username: str, password: str, port: str = "5985", http_type: str = "http"):
self.http_url = f"{http_type}://{ip}:{port}/wsman"
self.session = winrm.Session(self.http_url, auth=(username, password), transport='ntlm')
def run_cmd(self, command: str, args=()):
res = self.session.run_cmd(command=command, args=args)
return res
因为每次调用run_cmd方法执行命令后,再次调用执行命令时,不会接着上一次执行,而是重新开一个cmd任务执行,所有想要执行多条命令必须在一个窗口执行,使用2个&符号分割命令,例如:我先到一个目录下,执行git命令,然后再执行打包命令
command = """
E: && cd /data/code && mvn package
"""
大家在使用过程中有问题,欢迎评论区留言!博文尽可能帮忙解决哦。