Python学习之九_winrm执行远程机器的cmd命令

济南小老虎 / 2023-05-14 / 原文

Python学习之九_winrm执行远程机器的cmd命令


winrm

# 注意如下命令需要按照顺序执行.
# 打开powershell的管理员模式进行如下的操作. 
set-executionpolicy remotesigned
winrm quickconfig
winrm set winrm/config/service/auth '@{Basic="true"}'
winrm set winrm/config/service '@{AllowUnencrypted="true"}'

Python的使用方式为

import winrm
def win_cmd(cmd: str):
    """远程调用 windows 执行命令"""
    hostname = '10.110.xxx.xxx'
    username = 'administrator'
    password = 'xxxx'
    wintest = winrm.Session('http://' + hostname + ':5985/wsman', auth=(username, password))
    res = wintest.run_cmd(cmd)
    return str(res.std_out.decode())

zhaobsh = win_cmd('ipconfig')
print(zhaobsh)

对应的调用python的程序就简单了-被调用方

在Windows机器上面安装一下python
然后安装一下 psutil获取内存信息
pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple
python.exe -m pip install --upgrade pip
pip install psutil

编写简单脚本为:
import psutil
def getfree() :
    free = str(round(psutil.virtual_memory().free / (1024.0 * 1024.0 * 1024.0), 2))+'GB'
    total = str(round(psutil.virtual_memory().total / (1024.0 * 1024.0 * 1024.0), 2))+'GB'
    memory_use_percent = str(psutil.virtual_memory().percent)+' %'
    return free

free = getfree()
print (str(free))

将文件放到 c:\winenv.py中去

远程调用方


import winrm
def win_cmd(cmd: str):
    """远程调用 windows 执行命令"""
    hostname = '10.110.xxx.xxx'
    username = 'administrator'
    password = 'xxxxx'
    wintest = winrm.Session('http://' + hostname + ':5985/wsman', auth=(username, password))
    res = wintest.run_cmd(cmd)
    return str(res.std_out.decode())

zhaobsh = win_cmd('python c:/winenv.py')
print(zhaobsh)

验证执行结果

C:\Users\zhaobsh\AppData\Local\Programs\Python\Python39\python.exe F:\00GSCloud2211\updatecompare\win_winrmpy.py 
12.67GB

cmd 命令的结果为:
C:\Users\zhaobsh\AppData\Local\Programs\Python\Python39\python.exe F:\00GSCloud2211\updatecompare\win_winrm.py 

Windows IP Configuration


Ethernet adapter Ethernet0 2:

   Connection-specific DNS Suffix  . : 
   Link-local IPv6 Address . . . . . : fe80::6c47:603c:580d:8f%13