Paramiko split lines in HTML page

情到浓时终转凉″ 提交于 2019-12-11 14:16:25

问题


In my Paramiko/Python script, i need to output the connection results to a webpage in HTML. When i do this, the result is displayed in one single line, even though there are several. If i just run the code in Python without HTML, i can break the lines. How can show Paramiko output in lines in HTML?

If i use this code below, i get the line breaks correctly in HTML, but that brings me some other issues.:

print("Content-type: text/html")
print("")
print("<html><head>")
print("")
print("</head><body>")

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname='192.168.40.169', username='admin', password='password', port='22')
cmd = '''show run'''
stdin, stdout, stderr = client.exec_command(cmd)
time.sleep(1)
for line in stdout:
    while True:
        line = stdout.readline()
        if not line:
            break
        print(line + '<br />')
print("</body></html>")

Notice the HTML headers and the 'br /' tag when printing. This way it breaks the lines. Except that, this way i can't send multiple commands or pass variables from PHP to Python. The script doesn't accept them (don't know why...)

The problematic script, that accepts PHP variable passing, multiple SSH commands in one session, but that is not breaking lines is like such:

import threading, paramiko
import time
import sys
#==========================
command = sys.argv[1]
command2 = sys.argv[2]
command3 = sys.argv[3]
command4 = sys.argv[4]
command5 = sys.argv[5]
command6 = sys.argv[6]
command7 = sys.argv[7]
command8 = sys.argv[8]
command9 = sys.argv[9]
command10 = sys.argv[10]
#==========================
print("<html><head>")
print("</head><body>")

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 + alldata.decode("UTF-8")
                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(lines.split(last_line))
                last_line = ''
        return last_line

sshUsername = "admin"
sshPassword = "password"
sshServer = "192.168.40.169"

connection = ssh(sshServer, sshUsername, sshPassword)
connection.open_shell()
connection.send_shell(command)
connection.send_shell(command2)
connection.send_shell(command3)
connection.send_shell(command4)
connection.send_shell(command5)
connection.send_shell(command6)
connection.send_shell(command7)
connection.send_shell(command8)
connection.send_shell(command9)
connection.send_shell(command10)
time.sleep(1)
print(fulldata)   # This contains the complete data received.
connection.close_connection()

print("</body></html>")

I think i should probably place a 'br /' tag somewhere, but i've tried everything and it's just not working. :( I really really need help with this one.

The output should be something like this:

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

But this is what i got:

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

Forgive the big post...

来源:https://stackoverflow.com/questions/55901968/paramiko-split-lines-in-html-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!