How to reset a comserver via telnet using a python script with telnetlib

590 views Asked by At

I want to write a python script that automatically resets a com server. For this aim, the script has to transmit the commands "2","5","y" I already wrote this little program:

import sched
import time
import sys
from LoggerTelnet import LoggerTelnet

HOST = "xxx.xxx.xx.xxx"
PORT = "yyyy"
UPDATE_TIME = 600

s = sched.scheduler(time.time, time.sleep)

def reset(sc):
    lt = time.localtime()
    print(time.strftime("Datum: %d.%m.%Y, Uhrzeit: %H:%M:%S", lt))
    sys.stdout.flush()
    print("Verbindung zum COM-Server wird aufgebaut")
    sys.stdout.flush()
    tn = LoggerTelnet(HOST, PORT)
    sys.stdout.flush()
    print("Logger wird jetzt resetet")
    sys.stdout.flush()
    tn.kommando("2")
    tn.kommando("5")
    tn.kommando("z")
    tn.close()
    print("Verbindung zum COM-Server wurde geschlossen")
    print("Logger erfolgreich resetet \n\n\n")
    sys.stdout.flush()
    s.enter(UPDATE_TIME, 1, reset, (sc,))

s.enter(UPDATE_TIME, 1, reset, (s,))
s.run()

This program uses my Telnet class:

import telnetlib

class LoggerTelnet(object):

    def __init__(self, host, port):
        try:
            self.tel = telnetlib.Telnet(host, port) 
        except:
            raise Error("Could not connect to Host")
        self.lese_daten()

    def close(self): 
        self.tel.close()

    def lese_daten(self):
        msg = self.tel.read_until("\r\n", 20.0)
        print(msg)
        return msg

    def kommando(self, kom):
        try:
            self.tel.write("%s\r\n" % kom)
        except:
            raise Error("Could not send Command")

        return self.lese_daten()

But this whole program is not working. I think the connection to the server gets established, but the commands are not send or executed. I also get no feedback from the telnet session. Only at the beginning, that the connection is established.

I hope you have an Idea and can help me :-)

Best.

0

There are 0 answers