How to monitor windows using ssh-powershell in python

Source: Internet
Author: User

How to monitor windows using ssh-powershell in python

This example describes how to monitor windows using ssh-powershell in python. Share it with you for your reference. The specific analysis is as follows:

For server monitoring, whether it is writing scripts by yourself or using some open-source tools such as nagios and zenoss in linux. However, some companies still use windows as servers. Compared with linux, windows does not have a convenient shell. commands provided by cmd are far from linux convenience for monitoring. However, if powershell (win7, 2008) is installed on windows, it is much more convenient than before. linux commands can basically be executed in powershell, such as viewing the process or ps.

I encapsulated a python script that calls powershell through ssh (through the pexpect module), which includes ps, netstat, ping detection, and viewing hard disk, cpu information, load, and memory information. By creating an ssh_win32 Class Object and calling its method, the returned python objects are parsed.

Ssh_powershell.py:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

#! /Usr/bin/env python

#-*-Coding: UTF-8 -*-

Import re

From pexpect import *

Class ssh_win32:

Def _ init _ (self, user, host, password = None, systemroot = 'C', papath = '', timeout = 5, verbose = 0 ):

Self. user = user # monitor the username of the machine

Self. host = host # ip address of the monitored Machine

Self. verbose = verbose

Self. password = password # password

Self. timeout = timeout # timeout of Command Execution

Self. systemroot = systemroot # drive letter installed on windows

If not papath: path of #powershell.exe

Self. powershell_path = self. systemroot + ':/WINDOWS/system32/WindowsPowerShell/v1.0/powershell.exe'

Self. key = [

'Authenticity ',

'Assword :',

'@@@@@@@@@@@@',

'COMMAND not found .',

EOF,

]

Self. f = open ('ssh. out', 'w ')

Def ssh (self, command ):

Cmd = 'ssh-l % s % s' % (self. user, self. host, command)

Print "cmd:", cmd

Con = spawn (cmd, timeout = self. timeout)

Seen = con. Exact CT (self. key)

If seen = 0:

Con. sendline ('yes ')

Seen = con. Exact CT (self. key)

If seen = 1:

# If not self. password:

# Self. password = getpass. getpass ('remote password :')

Con. sendline (self. password)

Try:

Res = con. read ()

Except t Exception, e:

Res = con. before

# Print "res:", res

Return res

Def ssh_disk (self ):

Cmd = self. powershell_path + "Get-WmiObject win32_logicaldisk"

Res = self. ssh (cmd)

Disk = {}

If res:

Res = res. split ('no such file or directory') [-1]. replace ('\ R', ''). split (' \ n ')

Res = [c for c in res if c]

# Print 'res: ', res

Predisk = 'C'

For d in res:

# Print d

Key, value = d. split (':', 1)

# Print d

# Print 'key: ', key, 'value:', value

Key = key. strip ()

Value = value. strip ()

If key = 'deviceid' and value not in disk. keys ():

Predisk = value

Disk [predisk] = {}

Disk [predisk] [key] = value

Else:

If key in ['freespace', 'SIZE']:

If value:

Value = int (value)/1024/1024/1024

Disk [predisk] [key] = value

For d in disk. keys ():

If disk [d] ['drivetype ']! = '3 ':

Disk. pop (d)

# Print 'disk: ', disk

Return disk

Def ssh_cpu (self ):

Cmd = self. powershell_path + 'gwmi-computername localhost win32_Processor'

Res = self. ssh (cmd)

Res = res. split ('no such file or directory') [-1]. replace ('\ R', ''). split (' \ n ')

Res = [r for r in res if r]

# Print res

Cpu = {}

For I in res:

# Print '=' * 10

# Print I

I = I. split (':')

# Print I

If len (I) = 2:

Key, value = I

Else:

Continue

Key = key. strip ()

Value = value. strip ()

# Print 'key: ', key

# Print 'value: ', value

Cpu [key] = value

Return cpu

Def ssh_memory (self ):

Totalmem = self. powershell_path + 'get-WmiObject win32_OperatingSystem totalvisiblememorysize'

Freemem = self. powershell_path + 'get-WmiObject win32_OperatingSystem FreePhysicalMemory'

Memory = {}

For cmd in [totalmem, freemem]:

Res = self. ssh (cmd)

If 'win32 _ OperatingSystem 'in res:

Res = res. replace ('\ R', ''). split (' \ n ')

Res = [m for m in res if m] [-1]

Print 'res: ', res

Key, value = res. split (':')

Key = key. strip ()

Value = value. strip ()

Memory [key] = value

Else:

Print "not return data"

Return None

Return memory

Def ssh_ping (self, host ):

Cmd = 'Ping-n 1% s' % host

Patt = R'. +? (\ D *) % loss .*'

Res = self. ssh (cmd). replace ('\ R', ''). replace (' \ n ','')

Print res

M = re. match (patt, res)

If m:

Lost_percent = m. group (1)

Print 'lost _ percent: ', lost_percent

Return int (lost_percent)

Else:

Return None

Def ssh_ps (self ):

Cmd = self. powershell_path + 'ps'

Res = self. ssh (cmd)

Ps = []

If '-- -----------' in res:

Res = res. replace ('\ R', ''). split (' -- ----------- ') [-1]. split (' \ n ')

Res = [d for d in res if d. strip ()]

For p in res:

Process = {}

Row = [para for para in p. split ('') if para. strip ()]

Process ['handle'] = row [0]

Process ['npm '] = row [1]

Process ['ps'] = row [2]

Process ['ws '] = row [3]

Process ['vm '] = row [4]

Process ['cpu '] = row [5]

Process ['id'] = row [6]

Process ['process _ name'] = row [-1]

Ps. append (process)

# Print ps

Return ps

Else:

Return None

Def ssh_netstat (self ):

Cmd = 'netstat-ao'

Res = self. ssh (cmd)

Netstat = []

If 'pid 'in res:

Res = res. replace ('\ R', ''). split ('pid') [-1]. split ('\ n ')

Res = [d for d in res if d. strip ()]

For p in res:

Process = {}

Row = [para for para in p. split ('') if para. strip ()]

Process ['proto'] = row [0]

Process ['local _ address'] = row [1]

Process ['forn N _ address'] = row [2]

Process ['state'] = row [3]

Process ['pid '] = row [-1]

Netstat. append (process)

# Print netstat

Return netstat

Else:

Return None

If _ name _ = "_ main __":

Cmd = "c:/WINDOWS/system32/WindowsPowerShell/v1.0/powershell.exe ps"

User = 'admin'

Host = '192. 168.123.105'

Password = '000000'

Ssh = ssh_win32 (user, host, password, systemroot = 'C', timeout = 5)

# Print ssh. ssh_cpu ()

# Print "\ n"

# Print ssh. ssh_disk ()

# Print "\ n"

# Print ssh. ssh_memory ()

# Print ssh. ssh_ping (host)

# Print ssh. ssh_ps ()

# Print ssh. ssh_netstat ()

I hope this article will help you with Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.