在 Python 中退出控制台连接

Exit out of a console connection in Python

我正在编写一些 python 代码以登录到包含虚拟应用程序 (VTA) 的白盒设备。将安装两个不同的 VTA,代码将登录到物理设备,然后使用 virsh 控制台(VTA 的名称)登录到 VTA。

我 运行 遇到的问题是退出一个 VTA,然后将 virsh 控制台切换到另一个。 exit 命令只是让我再次进入登录提示,但不会退出控制台连接。

为此,我必须发送“control + ]”才能跳出控制台。我一直在网上搜索以尝试找到解决方案,但我找到的唯一选择是发送并“退出”,然后是“\x1b”。但是,这实际上并没有脱离控制台 window。相反,它结束了我想要的会话。

有没有办法在 python 中发送“Control + ]”?

下面是一些显示步骤的代码:

from paramiko import SSHClient, AutoAddPolicy
import time
import re
import os
import sys
import progressbar
import stat

def create_connection(host):
    username = ''
    password = ''
    port = 22
    connection_info = {
        'port': port,
        'username': username,
        'password': password
    }

    client = SSHClient()
    client.set_missing_host_key_policy(AutoAddPolicy())
    client.connect(host, timeout=10, auth_timeout=10, **connection_info)
    ssh_session = client.invoke_shell()
    ssh_session.settimeout(10.0)

    return ssh_session


def send_commands(ssh_session, commands, sleep_time=1):
    for command in commands:
        ssh_session.send(command)
        time.sleep(sleep_time)

    output = ssh_session.recv(1048576)
    decoded_output = output.decode()
    return decoded_output


console_commands = [
        'virsh console vw-vta\n',
        '\n',
        '\n',  # Place the username of the VTA here
        '\n'  # Place the password of the VTA here
    ]
show_mgmt_commands = [
        'ifconfig ens2 | grep Bcast\n'
    ]

exit_console = [
        'exit\n'
        '\x1b'
    ]
validate_commands = [
        'virsh list\n'
    ]


def validation():
    host = input('What is the IP address? ')
    print('\n')
    print(f'3[1;33m--< Checking {host} for a valid VTA >------------3[0m')

    try:
        ssh_session = create_connection(host)
    except Exception as l:
        print(f"3[1;31mCannot connect to {host}!3[0m")
        return

    validate = send_commands(ssh_session, validate_commands)

    if 'y1564' in validate:
        print(f"3[1;32mThere is a Y1564 VTA running! Obtaining information...3[0m")
        ssh_session = create_connection(host)
        console = send_commands(ssh_session, console_commands)

        try:
            show_mgmt = send_commands(ssh_session, show_mgmt_commands, sleep_time=2)

        except Exception as e:
            print(f"3[1;31mCouldn't reach the console on " f"3[1;33m{host}3[0m"f"3[1;31m. This VTA will need to be rebuilt.3[0m")



        if 'Login incorrect' in show_mgmt:
            print(f"3[1;31m--< Begin ERROR MESSAGE >------------3[0m")
            print(show_mgmt)
            print(f"3[1;31m--< End ERROR MESSAGE >------------3[0m")
            print(f"3[1;31mThis VTA has the incorrect password!3[0m")
            print(f'{host},VTA Password Error', file=f)
            exit = send_commands(ssh_session, exit_console)
            return
        else:
            try:
                mgmt = show_mgmt.split('addr:')[1].split(" ")[0]
            except Exception as g:
                print(f"3[1;31mThis VTA is corrupt and will need to be rebuilt!3[0m")
                exit = send_commands(ssh_session, exit_console)
                return
            print("Y1564 VTA IP: ", mgmt)
            exit = send_commands(ssh_session, exit_console)

    else:
        print("3[1;33mThere is NOT a Y1564 VTA running on 3[0m"f"3[1;34m {host}3[0m")
    
    ssh_session.close()

if __name__ == '__main__':
    full_check()

此函数完成后,代码的第二部分将调用类似的函数。但是它失败了,因为之前的函数没有断开控制台连接。代码尝试发送下一个函数的命令,同时它仍在前一个 VTA 中。

这是一个显示它在做什么的输出:

What is the IP address? 1.1.1.1


--< Checking 1.1.1.1 for a valid VTA >------------
There is a Y1564 VTA running! Obtaining information...
Y1564 VTA IP:  10.10.10.10
exit
logout


--< Checking 1.1.1.1 for a valid VTA >------------
Ubuntu 16.04.6 LTS y1564 ttyS0

y1564 login:

virsh list
Password:
There is NOT a VTA running on 1.1.1.1

上面的输出显示,当退出命令为 运行 且后跟 \x1b 时,它没有正确退出,而是尝试从下一部分发送“virsh list”命令。

您用来发送 ctrl+] 的十六进制字符是错误的。将您的退出控制台命令更新为: exit_console = [ 'exit\n', '\x01D' ]

ASCII 参考:http://www.physics.udel.edu/~watson/scen103/ascii.html

您似乎也在使用 invoke_shell() 方法,您可以使用 close() 方法退出特定的 shell 并根据需要建立新方法。

Paramiko 参考:http://docs.paramiko.org/en/stable/api/channel.html