python-3.x - Paramiko 中的意外输出

标签 python-3.x paramiko

我正在使用 Paramiko 向路由器发送一些命令,但输出文本几乎不可读。

如何删除输出中的 'b'\r\n

断行的正确方法是什么?

这段代码应该是它应该正确换行的地方:

def print_lines(self, data):
        last_line = data
        if '\n' in data:
            lines = data.splitlines()
            for i in range(0, len(lines)-1):
                print((lines[i]))
            last_line = lines[len(lines) - 1]
            if data.endswith('\n'):
                print(last_line)
                last_line = ''
        return last_line

这是完整的代码:

class ssh:
    shell = None
    client = None
    transport = None

    def __init__(self, address, username, password):
#        print(("Connecting to server on ip", str(address) + "."))
        self.client = paramiko.client.SSHClient()
        self.client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
        self.client.connect(address, username=username, password=password, look_for_keys=False)
        self.transport = paramiko.Transport((address, 22))
        self.transport.connect(username=username, password=password)

        thread = threading.Thread(target=self.process)
        thread.daemon = True
        thread.start()

    def close_connection(self):
        if(self.client != None):
            self.client.close()
            self.transport.close()

    def open_shell(self):
        self.shell = self.client.invoke_shell()

    def send_shell(self, command):
        if(self.shell):
            self.shell.send(command + "\n")
        else:
            print("<h1>Shell não aberta.</h1>")

    def process(self):
        global strdata, fulldata
        while True:
            # Print data when available
            if self.shell is not None and self.shell.recv_ready():
                alldata = self.shell.recv(1024)
                while self.shell.recv_ready():
                    alldata += self.shell.recv(1024)
                strdata = strdata + str(alldata)
                fulldata = fulldata + str(alldata)
                strdata = self.print_lines(strdata) # print all received data except last line

    def print_lines(self, data):
        last_line = data
        if '\n' in data:
            lines = data.splitlines()
            for i in range(0, len(lines)-1):
                print((lines[i]))
            last_line = lines[len(lines) - 1]
            if data.endswith('\n'):
                print(last_line)
                last_line = ''
        return last_line


sshUsername = "admin"
sshPassword = "password"
sshServer = "192.168.40.165"

connection = ssh(sshServer, sshUsername, sshPassword)
connection.open_shell()
connection.send_shell('en')
connection.send_shell('conf t')
connection.send_shell('hostname R5')
time.sleep(1)
print('<h1>'+fulldata+'</h1>')   # This contains the complete data received.
connection.close_connection()

我期望这样:

R5#en
R%#conf t
Enter configuration commands, one per line. End with CNTL/Z.
R5(config)#hostname R5
R5(config)#

但这是结果:

b'\r\nR5#'b'e'b'n'b'\r\n'b'R5#'b'c'b'o'b'n'b'f'b' t'b'\r\n'b'Enter configuration commands, one per line. End with CNTL/Z.\r\nR5(config)#'b'h'b'o'b's'b't'b'n'b'a'b'm'b'e'b' 'b'R'b'5'b'\r\n'b'R5(config)#'

如何正确获取换行符? 请原谅我的大帖。

最佳答案

alldata 从 paramiko 接收字节,而您使用的是 str(bytes),因此您在 b'string' 两边加上引号。你需要使用解码来解码字节

alldata_str = alldata.decode()
strdata = strdata + alldata_str
fulldata = fulldata + alldata_str

有些库可以帮助像路由器一样使用 paramiko netmiko基于paramiko。我还有一个库可以对一般设备进行终端交互式 ssh https://github.com/filintod/pyremotelogin (也基于 paramiko)。还有用于网络的凝固汽油弹 ( https://napalm-automation.net/blog/ )。

关于python-3.x - Paramiko 中的意外输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55840967/

相关文章:

python - 仅当相邻列中同一行的单元格为空白时,如何基于字符拆分字符串

python - 如何在python中将json转换为csv

python - Paramiko/scp - 检查远程主机上是否存在文件

python - 乌类图14.04 : ImportError: No module named client

python - 如何在函数循环之外定义参数?

python - 如果未使用特定迭代器,类似 zip 的函数将失败

python - Azure 和 Databricks 寄予厚望

python - 如何在 python 中使用 paramiko 将输入发送到命令?

python - Django 单元测试模拟

python - "' 连接 ' object has no attribute ' _sftp_live '"当 pysftp 连接失败