从 telnet 连接打印日志

问题描述 投票:0回答:1

我正在尝试执行以下操作: 我必须做以下事情:

your text

  1. 从Linux服务器(中间服务器)登录到不同的服务器
  2. 运行命令,例如 chg-trm:trm=:all=yes
  3. 将输出重定向到同一 Linux 服务器上的文件(某些预定义的目录)
  4. 每 5 分钟创建一个新文件(从第 3 点开始),名称包含日期和时间 Python版本是2.6.6。 我收到的错误为:已连接...... 欢迎来到不同的服务器。 从下面的列表中选择一个终端: (21,33,44)

终端输入超时 - 会话重置消息。

错误表示连接已被远程主机关闭。

logging ssh connection telnet python-2.6
1个回答
0
投票
`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_eagle(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)
© www.soinside.com 2019 - 2024. All rights reserved.