说明
远程连接windows系统,查询信息并返回结果
前提
安装第三方库pywinrm,windows系统开启winrm并配置,实测开启winrm不配置部分系统可以正常操作
第三方库安装
python -m pip install paramiko
windows的winrm配置
winrm quickconfig
winrm e winrm/config/listener
winrm set winrm/config/service/auth @{Basic="true"}
winrm set winrm/config/service @{AllowUnencrypted="true"}
winrm get winrm/config
代码
# -*- coding: UTF-8 -*-
import winrm
import os
import sys
import time
import source.readfile as rf
# 巡检的windows端需要开通winrm服务并配置
# winrm quickconfig
# winrm e winrm/config/listener
# winrm set winrm/config/service/auth @{Basic="true"}
# winrm set winrm/config/service @{AllowUnencrypted="true"}
# winrm get winrm/config
def strout(st):
lst1 = []
num = st.count(r'\r\r\n')
for t in range(1, num):
lst1.append(st.split(r'\r\r\n')[t-1])
return lst1
# 操作系统列表配置文件
b_path = os.getcwd()
osfilename = r'.\config\winoslist'
oslist = rf.osreadlist(osfilename)
ctime = time.localtime()
# linux系统报告存储目录
r_path = r'.\report'
os.chdir(r_path)
# 判断目录是否存在,若不存在则创建
if 'chkreport' not in os.listdir():
os.mkdir('chkreport')
dr_path = os.getcwd() + r'\chkreport'
# 根据系统列表查询数据
for osc in oslist:
osname = 'Win_' + osc.split(',')[0]
machine = osc.split(',')[0]
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ' INFO:' + osname + ' 信息开始收集!')
# 初始化系统连接
url = 'http://' + osc.split(',')[0] + r':5985/wsman'
try:
ssh = winrm.Session(url, auth=(osc.split(',')[2], osc.split(',')[3]), transport='ntlm')
# 生成报告
os.chdir(dr_path)
if machine not in os.listdir():
os.mkdir(machine)
os.chdir(dr_path + '\\' + machine)
dbrf = osname + '_' + time.strftime("%Y%m%d-%H%M%S", ctime) + '.txt'
dbr = open(dbrf, 'w+')
dbr.write(osc.split(',')[0] + ':\n')
# 磁盘信息
dbr.write('\n磁盘信息:\n')
rep = ssh.run_cmd('wmic logicaldisk')
rep1 = str(rep.std_out)
lst = strout(rep1)
for l in lst:
if l.count('b\'') == 1:
dbr.write(l.split('\'')[1] + '\n')
else:
dbr.write(l + '\n')
# 系统信息
dbr.write('系统信息:\n')
rep = ssh.run_cmd('systeminfo')
dbr.write(str(rep.std_out, 'big5'))
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ' INFO:' + osname + ' 信息收集完成!')
except winrm.exceptions.InvalidCredentialsError as err:
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ' ERROR:' + osname +
' 连接失败!错误信息为:' + str(err))
os.chdir(b_path)