0

因此,我无法实际打印发出“帮助”命令后看到的所有信息。我需要更改 skt.receive() 的长度吗?或者有没有办法简单地打印所有通过的数据?似乎必须有一种方法来解释您要打印的未知长度的数据?还是我以错误的方式处理这个问题。谢谢。

#!/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)
4

2 回答 2

4

您是否考虑过使用telnetlib,而不是重新发明轮子?:)

例子:

import telnetlib

HOST = "192.168.1.50"

tn = telnetlib.Telnet(HOST)
tn.write("help\n")
print tn.read_all()
于 2012-08-08T13:08:22.683 回答
0

因此 telnetlib def 使事情变得更容易并简化了流程。重新发明轮子没有意义。

于 2012-08-08T13:19:05.210 回答