Home > Sci-Tech
Use Python to remotely control the Windows server, so easy to use!
2022-05-15 06:02:11 5 ℃在很多企业会使用闲置的 Windows 机器作为临时服务器,有时候我们想远程调用里面的程序或查看日志文件
Windows 内置的服务「 winrm」可以满足我们的需求
它是一种基于标准简单对象访问协议( SOAP )的防火墙友好协议,允许来自不同供应商的硬件和操作系统进行互操作
官网:
1. 被控端 windows
这里以 Windows 10 系统机器为例
具体操作步骤如下:
1-1 启动 winrm 服务
以管理员权限打开 CMD 命令窗口,输入下面命令启动 winrm 服务
# 启动winrm服务
如果运行报错,提示网络类型设置异常
可以快捷键 win+i 进入到网络和 Internet,更改网络配置文件,由公用切换为专用
1-2 检查 winrm 服务监听状态
继续在命令行输入下面命令,查看 winrm 服务的状态
PS: 注意这里的端口号 Port 值后面连接会用到
# 查看winrm服务的状态
winrme winrm/config/listener
# result
Listener
Address = *
Transport = HTTP
Port = 5985
Hostname
Enabled = true
URLPrefix = wsman
CertificateThumbprint
ListeningOn = **
1-3 查看 winrm 配置信息(可选)
通过以下命令可以查看 winrm 全部配置信息、client 客户端配置信息、service 服务端配置信息
# all
winrm getwinrm/config
# Client
winrm getwinrm/config/client
# Service
winrm getwinrm/config/service
1-4 配置 winrm client
# 配置winrm client
winrm setwinrm/config/ [email protected]{AllowUnencrypted= "true"}
winrm setwinrm/config/ [email protected]{TrustedHosts= "*"}
winrm setwinrm/config/ client/auth @{Basic= "true"}
1-5 配置 winrm service
在配置完 winrm service 和 winrm client 后,我们通过通过步骤 1-3 查看配置文件,确保配置文件已生效
# 配置winrm service
winrm setwinrm/config/service @{AllowUnencrypted= "true"}
winrm setwinrm/config/service/auth @{Basic= "true"}
2. 控制端
在控制端,比如:Mac OSX、Linux,我们只需要安装「 pywinrm」依赖包即可
# 控制端安装依赖包
pip3install pywinrm
3. 实战一下
做为以上准备后,我们就可以编写代码对 Windows 进行控制了
首先,我们需要 ip 地址、端口号、用户名、密码连接 Windows 被控端
# 连接windows
import winrm
Em
# ip地址:端口号
# winrm server端口号
# auth:用户名和密码
self.session = winrm.Session( "192.168.**.**:5985", auth=( 'username', 'password'), transport= 'ntlm')
Em
这样,我们就可以通过对象的「 run_cmd」和「 run_ps」函数模拟 CMD、PowerShell 输入命令了
这里以查看 Windows 某个硬盘目录下的日志文件为例
# 连接windows
importwinrm
importcodecs
Em
defexec_cmd(self, cmd):
"""
执行cmd命令,获取返回值
: Param CMD :: Return:
"" "
# Cmd
result = self.Session.run_cmd (cmd)
# Powershell
# result = self.session.run_ps (cmd)
# Return code
# code is 0 for the call successful call
code = result.status_code
# According to the return code, get the response content (bytes)
content = result.std_out ifCode == 0LSeresult.std_err
#Profinned to string (try to decod on UTF8 and GBK)
# result = content.decode ("UTF8")
# result = codecs.decode (content, 'utf-8')
try:
result = Content.decode ("UTF8")
Except:
result = content.decode ("gbk")
Print (Result)
ReturnResult
Em
# D: /py/log/trade.log
# Windows use Type command to view file content
Result = Self.exec_cmd ('D: & CD Pylog & Trade.log')
# View Results
Print (Result)
4. Summary
In addition to remotely viewing Windows files, you can also perform BAT batch files, or simulate the input of the command line, and perform other show operations according to the return value
Getting Started: The most comprehensive zero -basic learning Python question | Python that has been learned for 8 months | practical project | Learning python is this shortcut
Dry goods: Climbing Douban Short Review, the movie "Later Us" | 38 years of NBA Best Player Analysis | From the expectations to word of mouth! Tang Tan 3 is disappointing | Laugh, see Xin Yi Tian Tu Long Ji | Lantern Ilie answer king | Use Python to make a massive lady sketch | Mission Impossible is so hot, I use machine learning to make a mini recommendation system movie movie
Fun: Better Ball Game | Jiugongge | Beautiful Flowers | Two Erotic Python "Tiantian Cool Run" game!
AI: Robot that can make poetry | Give the picture color | Forecast income | Mission Impossible is so hot, I use machine learning to make a mini recommendation system movie
Annual explosive copy
1). PDF to Word with Python easily! 2). Learn python so fragrant! I made a website with 100 lines of code, helping people PS travel pictures, earning a chicken leg to eat 3). The first broadcast of more than 100 million, hot network, I analyzed "The Sister of the Wind and Broken Waves", discovered these secrets 4). 80 line code code. Intersection Use python to make a dream division 5). You must master the 20 Python code, short and intensive, useless 6). 30 python kinky skills collection 7). .pdf ", all dry goods 8). Goodbye Python! I want to learn GO! 2500 words in depth analysis! 9). Discover a dog's benefits! This Python reptile artifact is too cool, download girls automatically
Guess you like
- 2022-05-16What is the difference between the "localization" service of Kuaishou?
- 2022-05-16The cost accounting form of the 29 -year -old female accounting preparation of Shanghai is popular due to automatic analysis.
- 2022-05-16Electrical foundation 60-TT equal potential potential
- 2022-05-16Samsung GALAXYS23 mobile phone exposure: The new machine will use 200 million pixels
- 2022-05-16Without 400 billion yuan, Sun Piaosheng couldn't retire
- 2022-05-15Bilibili Windows version is here!
- 2022-05-15Foreign media: Huawei is "agreed"
- 2022-05-15I have a fire at home and office. I have a business. One month's income has passed three months
- 2022-05-15In the third quarter, the Siteeweed PICC Regulatory Image Sensor
- 2022-05-15How do novices rely on self -media to support their families?Recommend 2 creative directions to make you quickly make money
- [Wide -loved cross -border selection material] Sunflower pattern full of warmth and fresh vitality
- 900 days of survival of practitioners from the country: selling houses, fortune tellers, and making emotions
- The official announcement of the Chinese Academy of Sciences!Foreign media: ASML "show good" is useless
- [News Weekly] Paying the giant?
- Daily copywriting of friends
- Musk revealed that he was unique to 5%of the "robot", which was warned that he was leaked, causing criticism of experts!
- Hold the chassis!To realize the dual -screen office dream to buy another display screen is enough
- Essentials for water treatment practitioners: 20 different resins use full analysis
- Computer configuration purchase guide in May 2022: 1300-8000 price DIY assembly machine solution
- Whether the welding seam of the water pipe flexible waterproof sleeve is standard