天天看點

python soscket監控系統

自己寫的監控服務,想監控windows ,是以用python寫了一個服務,用于執行系統指令

用python 3寫的,2的話需要修改。

server端,也就是被監控端

import socket

import sys,os

host = '0.0.0.0'

port = int(sys.argv[1])

#這裡寫入可以連接配接的用戶端位址

trust = '127.0.0.1,192.168.1.31'

s = None

def conn():

  for res in socket.getaddrinfo(host,port,socket.AF_UNSPEC,socket.SOCK_STREAM,0,socket.AI_PASSIVE):

    af,socktype,proto,canonname,sa = res

    try:

      s = socket.socket(af,socktype,proto)

    except OSError as msg:

      s = None

      continue

      s.bind(sa)

      s.listen(1)

      s.close()

    break

  if s is None:

    print('could not open socket')

    sys.exit(1)

  conn,addr = s.accept()

  error = 'ok'

  if str(addr[0]) not in str(trust):

    error = 'error'

  print('Connected by',addr)

  while True:

    conn.settimeout(5)

    if error != 'error':

      data = conn.recv(102400)

      if not data:break

      data = data.decode(encoding='utf-8',errors='strict')

      comm = str(data)+' '+'2>&1'

      content = os.popen(comm).read()

      content = content.encode(encoding='utf-8',errors='strict')

      conn.send(content)

    else:

      conn.send(b'not trust address')

      break

  conn.close()

while True:

  conn()

用戶端,也就是監控伺服器使用的

import sys

host=sys.argv[1]

port = sys.argv[2]

o = len(sys.argv)

comm = []

for i in range(3,o):

        comm.append(sys.argv[i])

for res in socket.getaddrinfo(host,port,socket.AF_UNSPEC,socket.SOCK_STREAM):

        af,socktype,proto,canonname,sa = res

        try:

                s = socket.socket(af,socktype,proto)

        except OSError as msg:

                s = None

                continue

                s.connect(sa)

                s.close()

        break

if s is None:

        print("could not opensocket")

        sys.exit(1)

comm = ''.join(comm)

comm = comm.replace('[]',' ')

comm = comm.encode(encoding='utf-8',errors='strict')

s.sendall(comm)

data = s.recv(102400)

print(repr(data))

s.close()

sys.exit(0)

使用方法:

服務端啟動服務

python server.pyw 8765

#啟動服務,監聽8765端口

用戶端,也就是監控伺服器使用的腳本

python client.pyw  127.0.0.1 8765 ipcofing

連接配接127.0.0.1的8765端口,執行ipconfig指令,

python client.pyw  127.0.0.1 8765 ipcofing[]/all

如果帶參數的話,空格使用[]代替

繼續閱讀