在 paramiko 频道的输出中找不到子字符串

Can't find substring in an output from paramiko's channel

Python 3.7.4。我正在使用 Paramiko 启动 bash 脚本:

        channel = ssh.get_transport().open_session()
        channel.get_pty()
        channel.invoke_shell()
        time.sleep(1)
        if channel.recv_ready():
            output = channel.recv(1024).decode('ascii')
        print(output)

        cd = 'cd test/'
        install = './test.sh'
        channel.send(cd + '\n')
        channel.send(install + '\n')

        while True:
            time.sleep(1)
            if channel.recv_ready():
                output = channel.recv(2048).decode('ascii')
                if (r'User \x1b[1mtest\x1b[m\x0f does not exist, creating test user..' in output):
                    print('Test script started successfully')
                    break
            else:
                time.sleep(1)
                if not(channel.recv_ready()):
                    break

while循环中的部分输出值为:

'cd test/\r\n[root@hostname test]# ./test.sh\r\nUser \x1b[1mtest\x1b[m\x0f does not exist, creating test user..\r\nuseradd: warning: the home directory already exists.\r\n(...)'

我不明白为什么 (r'User \x1b[1mtest\x1b[m\x0f does not exist, creating test user..' in output) 不是真的。我尝试使用带反斜杠转义序列的普通字符串将输出解码为 UTF-8,但这也不起作用。

我在代码的其他部分使用不同的字符串时遇到了同样的问题,因此为了让它正常工作,我缩短了它们以删除所有斜线。但最好知道我做错了什么。

如果您使用原始字符串,\r \n\x1b[1m 等转义序列将不会具有相同的含义。例如 r"\n" 表示字面意思是一个字符 \ 然后是字符 n,但是 "\n" 表示换行:

>>> print(r"\n")
\n
>>> print("\n")


>>> 

所以你应该先解码为 utf-8,然后使用普通字符串,而不是原始字符串。