Printing logs from a telnet connection

82 Views Asked by At

I am trying to do the following actions: I have to do the following things:your text

  1. From a Linux Server (intermediate Server), login to different server
  2. Run command such as chg-trm:trm=:all=yes
  3. Redirect the output to a file on the same linux server (some predefined directory)
  4. Create a new file ( from point 3) every 5 minutes with a name having date and time

The Python version is 2.6.6. I am getting the error as : Connected..... Welcome to different server. Select a terminal from the list below: (21,33,44)

Terminal entry timeout - session reset message.

The error says connection closed by remote host. Terminal entry timeout - session reset message.

Connection to <remote ip> closed by remote host.
An error occurred: telnet connection closed
Traceback (most recent call last):
  File "logs_13102023_10.py", line 116, in <module>
    connection_to_different_Server(user_id, user_password)
  File "logs_13102023_10.py", line 73, in connection_todifferent_server
    generate_output()
  File "logs_13102023_10.py", line 88, in generate_output
    logs += tn.read_very_eager().decode('utf-8')
  File "/usr/lib64/python2.6/telnetlib.py", line 358, in read_very_eager
    return self.read_very_lazy()
  File "/usr/lib64/python2.6/telnetlib.py", line 395, in read_very_lazy
    raise EOFError, 'telnet connection closed'
EOFError: telnet connection closed

The code :

`import subprocess
import telnetlib
import time 
from datetime import datetime
import hashlib

user_id = "id"
# Hashing the password 
user_password = hashlib.sha256("password".encode()).hexdigest()
# Path where the log files generated would be saved
# output_directory = "path"
tn = None 
terminal_choice = ''

def connection_to_different_server(user_id, user_password):
    global tn,terminal_choice 
    # Creating a SSH Tunnel
    login_command = 'ssh -N -f -L 23001:127.0.0.1:23 <remote ip>'
    try:
        # Creates a new process for ssh tunelling
        subprocess.Popen(login_command, shell=True)
        time.sleep(2)
        # Creating a telnet connection
        tn = telnetlib.Telnet('127.0.0.1', 23001)
        # Printing the data received from the telnet connection
        print(tn.read_all().decode('utf-8'))
        # Selecting the terminal
        message = tn.read_until(b'Select a terminal from the list below:')
        print(message.decode('utf-8'))
        message = message.decode('utf-8')
        for term in message.split("\n"):
            if '(' in term:
                term = term.replace("(", "").replace(")","")
                available_terminals = [int(num) for num in term.split(',')]
        # available_terminals = [term for term in message.decode('utf-8').splitlines() if term.isdigit()]
        #available_terminals = [int(term) for term in message.decode('utf-8').split() if term.isdigit()]
        if '17' in available_terminals:
            terminal_choice = '17'
        elif '18' in available_terminals:
            terminal_choice = '18'
        else:
            terminal_choice = available_terminals[0] if available_terminals else ''
            print(terminal_choice)
            # print(f'No specific terminal found. Choosing the first available terminal: {terminal_choice}')
            print('No specific terminal found. Choosing the first available terminal: %s' % terminal_choice)
        #tn.write(f'{terminal_choice}\n'.encode('utf-8'))
        #print('Available Terminals:', available_terminals)
        #print('Terminal choice: %s' % terminal_choice)
        tn.write('%s\n' % terminal_choice.encode('utf-8'))
        response = tn.read_all().decode('utf-8')
        print(response)
        # Enter the user id
        message = tn.read_until(b'login:uid=')
        print(message.decode('utf-8'))
        #tn.write(f'{user_id}\n'.encode('utf-8'))
        tn.write('%s\n' % user_id.encode('utf-8'))

        # Enter the password
        message = tn.read_until(b'Enter Password :')
        print(message.decode('utf-8'))
        #tn.write(f'{user_password}\n'.encode('utf-8'))
        tn.write('%s\n' % user_password.encode('utf-8'))

        # If the connection gets closed then attempts to relogin
        if "Connection closed by foreign host." in tn.read_very_eager().decode('utf-8'):
            print("Connection closed by the remote host. Re-logging...")
            tn.close()
            connection_to_eagle(user_id, user_password)
    except Exception as e:
        # print(f"An error occurred: {str(e)}")
        print("An error occurred: {0}".format(str(e)))
    #generate_output(terminal_choice)
    generate_output()

def generate_output():
    global tn, terminal_choice
    try:
        #change_terminal = f'chg-trm:trm={terminal_choice}:all=yes'
        change_terminal = 'chg-trm:trm=%s:all=yes' % terminal_choice
        #subprocess.check_output(change_terminal, shell=True)
        p = subprocess.Popen(change_terminal, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        p.communicate()
        start_time = time.time()
        end_time = start_time + 300
        logs = ""
        while time.time() < end_time:
            tn.write(b'\n') 
            logs += tn.read_very_eager().decode('utf-8')
        filename = get_output_filename()
        try:
            with open(filename, 'w') as file:
                file.write(logs.decode('utf-8'))
        except IOError as e:
           # return f"Error writing to file: {str(e)}"     
            return "Error writing to file: %s" % str(e)
  
    except subprocess.CalledProcessError as e:
        #print(f"Error while running chg-trm command: {str(e)}")
        print("Error while running chg-trm command: %s" % str(e))


# To create the file with the name of date and time
def get_output_filename():
    current_datetime = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
    # filename = f"{output_directory}output_{current_datetime}.txt"
    #filename = f"output_{current_datetime}.txt"
    filename = "output_%s.txt" % current_datetime
    return filename

if __name__ == "__main__":
    # Running the function after every five minutes to print the logs
    while True:
        # Checks if the telnet connection is open before closing it
        if tn:
            tn.close()
        connection_to_eagle(user_id, user_password)
        print("Waiting for the script to print the next logs...")
        time.sleep(300)

Please help me resolve the issue.

0

There are 0 best solutions below