Pyhton使用pywinrm远程自动安装Zabbix Agent
为实现Zabbix监控添加自动化,使用Python远程安装Zabbix Agent,并开启服务。
1.系统环境
- Python 3.6.1
- pywinrm 0.3.0
2.Windows开启WinRM服务,允许远程连接。开启命令winrm quickconfig
>C:\Users\Administrator>winrm quickconfig
WinRM 服务已在这台电脑上执行。
此电脑上的 WinRM 已设定为可接受远端管理。
3.Python脚本
import winrm
# 远程连接windows执行脚本,window需开通WinRM服务
# WinRM quickconfig
def run_ps_shell(ip, username, password, ps_shell):
try:
# s = winrm.Session(ip, auth=(username, password), transport='ntlm', server_cert_validation='ignore')
s = winrm.Session(ip, auth=(username, password), transport='ntlm') # 建立连接
r = s.run_ps(ps_shell) # 执行powershell命令
# r = s.run_cmd(ps_shell) # 执行cmd命令
print('std_out-->', str(r.std_out, 'big5'))
print('std_err-->', str(r.std_err, 'big5'))
std_out = r.std_out
return std_out
except Exception as e:
print(str(e)) # 打印异常
return None
if __name__ == '__main__':
ip = '' # Windows IP
username = 'administrator'
password = '' # 密码
ps_shell = """
# 创建zabbix相关文件夹
mkdir c:\\zabbix
mkdir c:\\zabbix\\bin
mkdir c:\\zabbix\\conf
mkdir c:\\zabbix\\log
$client = new-object System.Net.WebClient
# 下载的脚本、文件需事先部署到Apache上,其它web服务也可以,以供下载
# 下载zabbix安装脚本bat
$client.DownloadFile("http://weburl/media/zabbix/windows/install_zabbix.bat", "c:\\zabbix\\install_zabbix.bat")
$osarchitecture = (Get-WmiObject Win32_OperatingSystem).osarchitecture
# By操作系统位数下载zabbix agent安装包
if ($osarchitecture -eq "64 位") { # 64位
$client.DownloadFile("http://weburl/media/zabbix/windows/64bit/zabbix_agentd.exe", "c:\\zabbix\\bin\\zabbix_agentd.exe")
}else { # 32位
$client.DownloadFile("http://weburl/media/zabbix/windows/32bit/zabbix_agentd.exe", "c:\\zabbix\\bin\\zabbix_agentd.exe")
}
# 下载zabbix配置文件
$client.DownloadFile("http://weburl/media/zabbix/windows/conf/zabbix.conf", "c:\\zabbix\\conf\\zabbix.conf")
# 执行bat脚本
cmd /c "c:\\zabbix\\install_zabbix.bat"
"""
result = run_ps_shell(ip=ip, username=username, password=password, ps_shell=ps_shell)
print(result)
4.bat脚本内容install_zabbix.bat
Set zabbix_server_ip=0.0.0.0
echo LogFile=c:\zabbix\log\zabbix_agentd.log >> C:\zabbix\conf\zabbix.conf
echo Server=%zabbix_server_ip% >> C:\zabbix\conf\zabbix.conf
echo Hostname=%COMPUTERNAME% >> C:\zabbix\conf\zabbix.conf
echo StartAgents=10 >> C:\zabbix\conf\zabbix.conf
echo Timeout=30 >> C:\zabbix\conf\zabbix.conf
C:\zabbix\bin\zabbix_agentd.exe -i -c C:\zabbix\conf\zabbix.conf
sc config "Zabbix Agent" start=auto
net start "Zabbix Agent"