Мониторинг сервера 1С с помощью powershell и Icinga2
28 Sep 2017
Скрипт проверки состояния сервера 1С для системы мониторинга Icinga2:
<#
icinga2scripts
Version 1.0
Description: Скрипт для Icinga 2 - состояние сервера 1С
Pavel Satin (c) 2017
pslater.ru@gmail.com
#>
#[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$returnStateOK = 0
$returnStateWarning = 1
$returnStateCritical = 2
$returnStateUnknown = 3
#$ErrorActionPreference = "SilentlyContinue"
#В дальнейшем это будут аргументы передоваемые скрипту
$platform1c_obj = "V83.COMConnector"
$service1c_name = "1C:Enterprise 8.3 Server Agent*"
$agent1c_connection = "tcp://localhost"
$checkServices = $true
#Замер времени исполнения скрипта
$watch = [System.Diagnostics.Stopwatch]::StartNew()
$watch.Start() #Запуск таймера
#$output += "Status of the 1C Server:<br>"
$output += "<div class='plsatin-ps-style'>"
if ($checkServices) {
$output += "<table>"
#Проверяем запущены ли необходимые службы, если нет, запускаем.
$mssqlsrv = Get-Service "MSSQLSERVER"
if ($mssqlsrv.Status -ne "Running") {
$output += "<tr><td class='IconErrorEncoded'></td>
<td>The MS SQL Server service was not started</td></tr>"
$output += "<tr><td class='IconInfoEncoded'></td>
<td>Start MS SQL Server service ...</td></tr>"
Start-Service $mssqlsrv
if ($mssqlsrv.Status -ne "Running") {
Write-Host $mssqlsrv
Write-Host $output
[System.Environment]::Exit($returnStateCritical)
} else {
$output += "<tr><td class='IconSuccessEncoded'></td>
<td>The MS SQL Server service is started</td></tr>"
}
} else {
$output += "<tr><td class='IconSuccessEncoded'></td>
<td>The MS SQL Server service is running</td></tr>"
}
$1cagent = Get-Service $service1c_name
if ($1cagent.Status -ne "Running") {
$output += "<tr><td class='IconErrorEncoded'></td>
<td>The 1C Server Agent service was not started</td></tr>"
$output += "<tr><td class='IconInfoEncoded'></td>
<td>Start the service of the 1C Server Agent ...</td></tr>"
Start-Service $1cagent
if ($1cagent.Status -ne "Running") {
Write-Host $1cagent
Write-Host $output
[System.Environment]::Exit($returnStateCritical)
} else {
$output += "<tr><td class='IconSuccessEncoded'></td>
<td>1C Server Agent service is started</td></tr>"
}
} else {
$output += "<tr><td class='IconSuccessEncoded'></td>
<td>The 1C Server Agent service is running</td></tr>"
}
$output += "</table>"
}
#Создаем COM объект 1С
$comobj1c = New-Object -ComObject $platform1c_obj
#Подключаемя к агенту сервера 1С
$connect1c = $comobj1c.ConnectAgent($agent1c_connection)
#Получаем доступные кластеры на данном сервере
$cluster1c = $connect1c.GetClusters()
#Подключаемся к кластеру
#При условии что кластер только один, тоесть выбираем первый - [0]
$connect1c.Authenticate($cluster1c[0],"","")
#Получаем список сессий
$sessions1c = $connect1c.GetSessions($cluster1c[0])
$output += "1C application sessions: "
$output += $sessions1c | Select-Object SessionID, Host, userName, dbProcTook, StartedAt, LastActiveAt | ConvertTo-Html -Fragment
$output += "</div>"
$sessionsCount = $sessions1c.Count
$watch.Stop() #Остановка таймера
#$output += $watch.Elapsed #Время выполнения
#$output += "<br>Date time: " + (Get-Date) + "<br>"
Write-Host $output
Write-Host " |1c_sessions=$sessionsCount;;;;"
[System.Environment]::Exit($returnStateOK)
Мониторинг
Подключаем к системе мониторинга Icinga2:
apply Service "1c-status" {
max_check_attempts = 2
check_interval = 15m
retry_interval = 3m
enable_perfdata = true
assign where host.name == "ts02.domain.local"
ignore where host.vars.os_family == "Linux" || host.vars.bypass == true
check_command = "powershell"
vars.ps_command = "c:\\ProgramData\\icinga2\\scripts\\icinga2\\check_1c_status.ps1"
//vars.ps_args = ""
command_endpoint = host.vars.client_endpoint
}
Дополнительно
Вот что еще можно выудить из GetSessions
:
PS C:\Windows\system32> $connect.GetSessions($cluster[0])
infoBase : System.__ComObject
SessionID : 1
StartedAt : 28.09.2017 18:39:08
LastActiveAt : 28.09.2017 19:17:49
Host : TS02
AppID : 1CV8
userName : Администратор
Locale : ru_RU
process : System.__ComObject
connection : System.__ComObject
dbProcInfo :
dbProcTookAt : 01.01.0100 0:00:00
dbProcTook : 0
blockedByDBMS : 0
blockedByLS : 0
durationCurrentDBMS : 0
durationLast5MinDBMS : 0
durationAllDBMS : 22624
dbmsBytesLast5Min : 220
dbmsBytesAll : 5198698
durationCurrent : 0
durationLast5Min : 0
durationAll : 26283
callsLast5Min : 118
callsAll : 2347
bytesLast5Min : 16206
bytesAll : 460688
MemoryCurrent : 0
MemoryLast5Min : 37401
MemoryAll : 17179518
InBytesCurrent : 0
InBytesLast5Min : 1962
InBytesAll : 18850640
OutBytesCurrent : 0
OutBytesLast5Min : 0
OutBytesAll : 18060346
License : System.__ComObject
Hibernate : False
PassiveSessionHibernateTime : 1200
HibernateSessionTerminateTime : 86400
Работа с COM объектом 1С:
```powershell
$com1c = New-Object -ComObject V83.COMConnector
<#
PS C:\Windows\system32> $com1c
PoolCapacity : 0
PoolTimeout : 0
MaxConnections : 0
RAgentPortDefault : 1540
RMngrPortDefault : 1541
LowBoundDefault : 1560
HighBoundDefault : 1591
PS C:\Windows\system32> $com1c | Get-Member
TypeName: System.__ComObject#{2ff2245e-c604-45bd-ac16-19b1f64bd9a4}
Name MemberType Definition
---- ---------- ----------
Connect Method IDispatch Connect (string)
ConnectAgent Method IServerAgentConnection ConnectAgent (string)
ConnectWorkingProcess Method IWorkingProcessConnection ConnectWorkingProcess (string)
HighBoundDefault Property int HighBoundDefault () {get}
LowBoundDefault Property int LowBoundDefault () {get}
MaxConnections Property uint MaxConnections () {get} {set}
PoolCapacity Property uint PoolCapacity () {get} {set}
PoolTimeout Property uint PoolTimeout () {get} {set}
RAgentPortDefault Property int RAgentPortDefault () {get}
RMngrPortDefault Property int RMngrPortDefault () {get}
#>
$connect = $com1c.ConnectAgent("tcp://localhost")
<#
PS C:\Windows\system32> $cluster = $connect.GetClusters
PS C:\Windows\system32> $cluster | Get-Member
TypeName: System.Management.Automation.PSMethod
Name MemberType Definition
---- ---------- ----------
Copy Method System.Management.Automation.PSMemberInfo Copy()
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
Invoke Method System.Object Invoke(Params System.Object[] arguments)
ToString Method string ToString()
IsInstance Property bool IsInstance {get;}
MemberType Property System.Management.Automation.PSMemberTypes MemberType {get;}
Name Property string Name {get;}
OverloadDefinitions Property System.Collections.ObjectModel.Collection[string] OverloadDefinitions {get;}
TypeNameOfValue Property string TypeNameOfValue {get;}
Value Property System.Object Value {get;set;}
PS C:\Windows\system32> $cluster = $connect.GetClusters()
PS C:\Windows\system32> $cluster
ClusterName : Локальный кластер
HostName : TS02
MainPort : 1541
MultiProcess : True
SecurityLevel : 0
LifeTimeLimit : 0
ExpirationTimeout : 0
MaxMemorySize : 0
MaxMemoryTimeLimit : 0
SessionFaultToleranceLevel : 0
LoadBalancingMode : 0
PS C:\Windows\system32> $connect | Get-Member
TypeName: System.__ComObject#{0433d6e5-c99a-4fbc-aaa6-7b20add134d0}
Name MemberType Definition
---- ---------- ----------
ApplyAssignmentRules Method void ApplyAssignmentRules (IClusterInfo, int)
Authenticate Method void Authenticate (IClusterInfo, string, string)
AuthenticateAgent Method void AuthenticateAgent (string, string)
CreateAssignmentRule Method IAssignmentRuleInfo CreateAssignmentRule ()
CreateClusterAdminInfo Method IRegUserInfo CreateClusterAdminInfo ()
CreateClusterInfo Method IClusterInfo CreateClusterInfo ()
CreateSecurityProfile Method ISecurityProfile CreateSecurityProfile ()
CreateSecurityProfileAddIn Method ISecurityProfileAddIn CreateSecurityProfileAddIn ()
CreateSecurityProfileApplication Method ISecurityProfileApplication CreateSecurityProfileApplication ()
CreateSecurityProfileCOMClass Method ISecurityProfileCOMClass CreateSecurityProfileCOMClass ()
CreateSecurityProfileInternetResource Method ISecurityProfileInternetResource CreateSecurityProfileInternetR...
CreateSecurityProfileUnSafeExternalModule Method ISecurityProfileExternalModule CreateSecurityProfileUnSafeExter...
CreateSecurityProfileVirtualDirectory Method ISecurityProfileVirtualDirectory CreateSecurityProfileVirtualDi...
CreateWorkingServerInfo Method IWorkingServerInfo CreateWorkingServerInfo ()
GetAgentAdmins Method SAFEARRAY(Variant) GetAgentAdmins ()
GetAssignmentRules Method SAFEARRAY(Variant) GetAssignmentRules (IClusterInfo, IWorkingSe...
GetClusterAdmins Method SAFEARRAY(Variant) GetClusterAdmins (IClusterInfo)
GetClusterManagers Method SAFEARRAY(Variant) GetClusterManagers (IClusterInfo)
GetClusters Method SAFEARRAY(Variant) GetClusters ()
GetClusterServices Method SAFEARRAY(Variant) GetClusterServices (IClusterInfo)
GetConnectionLocks Method SAFEARRAY(Variant) GetConnectionLocks (IClusterInfo, IConnectio...
GetConnections Method SAFEARRAY(Variant) GetConnections (IClusterInfo)
GetInfoBaseConnections Method SAFEARRAY(Variant) GetInfoBaseConnections (IClusterInfo, IInfoB...
GetInfoBaseLocks Method SAFEARRAY(Variant) GetInfoBaseLocks (IClusterInfo, IInfoBaseShort)
GetInfoBases Method SAFEARRAY(Variant) GetInfoBases (IClusterInfo)
GetInfoBaseSessions Method SAFEARRAY(Variant) GetInfoBaseSessions (IClusterInfo, IInfoBase...
GetLocks Method SAFEARRAY(Variant) GetLocks (IClusterInfo)
GetSecurityProfileAddIns Method SAFEARRAY(Variant) GetSecurityProfileAddIns (IClusterInfo, string)
GetSecurityProfileApplications Method SAFEARRAY(Variant) GetSecurityProfileApplications (IClusterInfo...
GetSecurityProfileCOMClasses Method SAFEARRAY(Variant) GetSecurityProfileCOMClasses (IClusterInfo, ...
GetSecurityProfileInternetResources Method SAFEARRAY(Variant) GetSecurityProfileInternetResources (ICluste...
GetSecurityProfiles Method SAFEARRAY(Variant) GetSecurityProfiles (IClusterInfo)
GetSecurityProfileUnSafeExternalModules Method SAFEARRAY(Variant) GetSecurityProfileUnSafeExternalModules (ICl...
GetSecurityProfileVirtualDirectories Method SAFEARRAY(Variant) GetSecurityProfileVirtualDirectories (IClust...
GetServerWorkingProcesses Method SAFEARRAY(Variant) GetServerWorkingProcesses (IClusterInfo, IWo...
GetSessionLocks Method SAFEARRAY(Variant) GetSessionLocks (IClusterInfo, ISessionInfo)
GetSessions Method SAFEARRAY(Variant) GetSessions (IClusterInfo)
GetWorkingProcesses Method SAFEARRAY(Variant) GetWorkingProcesses (IClusterInfo)
GetWorkingServers Method SAFEARRAY(Variant) GetWorkingServers (IClusterInfo)
RegAgentAdmin Method void RegAgentAdmin (IRegUserInfo)
RegAssignmentRule Method void RegAssignmentRule (IClusterInfo, IWorkingServerInfo, IAssi...
RegCluster Method void RegCluster (IClusterInfo)
RegClusterAdmin Method void RegClusterAdmin (IClusterInfo, IRegUserInfo)
RegSecurityProfile Method void RegSecurityProfile (IClusterInfo, ISecurityProfile)
RegSecurityProfileAddIn Method void RegSecurityProfileAddIn (IClusterInfo, string, ISecurityPr...
RegSecurityProfileApplication Method void RegSecurityProfileApplication (IClusterInfo, string, ISecu...
RegSecurityProfileCOMClass Method void RegSecurityProfileCOMClass (IClusterInfo, string, ISecurit...
RegSecurityProfileInternetResource Method void RegSecurityProfileInternetResource (IClusterInfo, string, ...
RegSecurityProfileUnSafeExternalModule Method void RegSecurityProfileUnSafeExternalModule (IClusterInfo, stri...
RegSecurityProfileVirtualDirectory Method void RegSecurityProfileVirtualDirectory (IClusterInfo, string, ...
RegWorkingServer Method void RegWorkingServer (IClusterInfo, IWorkingServerInfo)
SetClusterDescription Method void SetClusterDescription (IClusterInfo, string)
SetClusterMultiProcess Method void SetClusterMultiProcess (IClusterInfo, bool)
SetClusterRecycling Method void SetClusterRecycling (IClusterInfo, int, int)
SetClusterRecyclingByMemory Method void SetClusterRecyclingByMemory (IClusterInfo, int, int)
SetClusterRecyclingByTime Method void SetClusterRecyclingByTime (IClusterInfo, int)
SetClusterRecyclingErrorsCountThreshold Method void SetClusterRecyclingErrorsCountThreshold (IClusterInfo, int)
SetClusterRecyclingExpirationTimeout Method void SetClusterRecyclingExpirationTimeout (IClusterInfo, int)
SetClusterRecyclingKillProblemProcesses Method void SetClusterRecyclingKillProblemProcesses (IClusterInfo, bool)
SetClusterSecurityLevel Method void SetClusterSecurityLevel (IClusterInfo, int)
TerminateSession Method void TerminateSession (IClusterInfo, ISessionInfo)
UnregAgentAdmin Method void UnregAgentAdmin (string)
UnregAssignmentRule Method void UnregAssignmentRule (IClusterInfo, IWorkingServerInfo, IAs...
UnregCluster Method void UnregCluster (IClusterInfo)
UnregClusterAdmin Method void UnregClusterAdmin (IClusterInfo, string)
UnregSecurityProfile Method void UnregSecurityProfile (IClusterInfo, string)
UnregSecurityProfileAddIn Method void UnregSecurityProfileAddIn (IClusterInfo, string, string)
UnregSecurityProfileApplication Method void UnregSecurityProfileApplication (IClusterInfo, string, str...
UnregSecurityProfileCOMClass Method void UnregSecurityProfileCOMClass (IClusterInfo, string, string)
UnregSecurityProfileInternetResource Method void UnregSecurityProfileInternetResource (IClusterInfo, string...
UnregSecurityProfileUnSafeExternalModule Method void UnregSecurityProfileUnSafeExternalModule (IClusterInfo, st...
UnregSecurityProfileVirtualDirectory Method void UnregSecurityProfileVirtualDirectory (IClusterInfo, string...
UnregWorkingServer Method void UnregWorkingServer (IClusterInfo, IWorkingServerInfo)
UpdateInfoBase Method void UpdateInfoBase (IClusterInfo, IInfoBaseShort)
UpdateWorkingServer Method void UpdateWorkingServer (IClusterInfo, IWorkingServerInfo)
ConnectionString Property string ConnectionString () {get}
#>
$connect.Authenticate($cluster[0],"","")
$connect.GetSessions($cluster[0])
<#
PS C:\Windows\system32> $connect.GetSessions($cluster[0])
infoBase : System.__ComObject
SessionID : 1
StartedAt : 28.09.2017 18:39:08
LastActiveAt : 28.09.2017 19:17:49
Host : TS02
AppID : 1CV8
userName : Администратор
Locale : ru_RU
process : System.__ComObject
connection : System.__ComObject
dbProcInfo :
dbProcTookAt : 01.01.0100 0:00:00
dbProcTook : 0
blockedByDBMS : 0
blockedByLS : 0
durationCurrentDBMS : 0
durationLast5MinDBMS : 0
durationAllDBMS : 22624
dbmsBytesLast5Min : 220
dbmsBytesAll : 5198698
durationCurrent : 0
durationLast5Min : 0
durationAll : 26283
callsLast5Min : 118
callsAll : 2347
bytesLast5Min : 16206
bytesAll : 460688
MemoryCurrent : 0
MemoryLast5Min : 37401
MemoryAll : 17179518
InBytesCurrent : 0
InBytesLast5Min : 1962
InBytesAll : 18850640
OutBytesCurrent : 0
OutBytesLast5Min : 0
OutBytesAll : 18060346
License : System.__ComObject
Hibernate : False
PassiveSessionHibernateTime : 1200
HibernateSessionTerminateTime : 86400
PS C:\Windows\system32> $connect.GetSessions($cluster[0]) | ft
infoBase SessionID StartedAt LastActiveA Host AppID userName Locale process connection
t
-------- --------- --------- ----------- ---- ----- -------- ------ ------- ----------
System._... 2 28.09.20... 28.09.20... TS02 1CV8 ru_RU System._... System._...
System._... 1 28.09.20... 28.09.20... TS02 1CV8 Админист... ru_RU System._... System._...
PS C:\Windows\system32> $connect.GetSessions($cluster[0]).License | ft
IssuedBySer RMngrAddres RMngrPort RMngrPID LicenseType Series Net MaxUsersCur MaxUsersAll FileName
ver s
----------- ----------- --------- -------- ----------- ------ --- ----------- ----------- --------
True TS02 1541 3440 1 ORGL8 True 50 50
True TS02 1541 3440 1 ORGL8 True 50 50
PS C:\Windows\system32> $connect.GetSessions($cluster[0]).connection | ft
infoBase process Host Application ConnID ConnectedAt blockedByLM SessionID blockedByLS
-------- ------- ---- ----------- ------ ----------- ----------- --------- -----------
System.__C... System.__C... TS02 1CV8 37 28.09.201... 0 2 0
System.__C... System.__C... TS02 1CV8 4 28.09.201... 0 1 0
PS C:\Windows\system32> $connect.GetSessions($cluster[0]).infoBase | ft
Name Descr
---- -----
ut
ut
#>
```