简体   繁体   中英

Printing Ascii Text from using Telnet in Python 3.0

So I'm unable to actually print all of the information that I see after issuing a "help" command. Do i need to change the length of the skt.receive()? Or is there a way to simply print all of the data that comes through? It seems like there has to be a way to account for a data that you want to print of an unknown length? Or am I approaching this in the wrong way. Thanks.

#!/usr/bin/python

host = '192.168.1.50'
port = 23
msg = "help\r"
msg2 = "y\r"


import socket
import sys
import time

try:
    skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, e:
    print("Error creating socket: %s" % e)
    sys.exit(1)

try:
    skt.connect((host,port))
except socket.gaierror, e:
    print("Address-related error connecting to server: %s" % e)
    sys.exit(1)
except socket.error, e:
    print("Error connecting to socket: %s" % e)
    time.sleep(15)
    skt.connect((host,port))
    sys.exit(1)

try:
    print(skt.send(msg))
    skt.send('help\r')
    print("SEND: %s" % msg) 
except socket.error, e:
    print("Error sending data: %s" % e)
    sys.exit(1)

while 1:
    try:
        buf = skt.recv(50000000000)
        if(len(buf)):
            print(buf)
            if 'AMX' in buf:
                print("Length buff")
                if 'AMX' in buf:
                    print(skt.send(msg))
                    #print("first wait")
                    #print("RECV: %s" % buf)
                    #time.sleep(9)
                    #print("second wait")
                    sys.exit(1)

    except socket.error, e:
        print("Error receiving data: %s" % e)
        sys.exit(1)
    if not len(buf):
        break
    sys.stdout.write(buf)

Have you considered using telnetlib , rather than re-inventing the wheel? :)

Example:

import telnetlib

HOST = "192.168.1.50"

tn = telnetlib.Telnet(HOST)
tn.write("help\n")
print tn.read_all()

So the telnetlib def makes things easier and streamlines the process. No sense in reinventing the wheel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM