开发者社区> 问答> 正文

为什么telnetlib在tn.close语句之后还在继续写文件?而且,它两次发送我的命令

该脚本应该使用远程设备打开telnet会话,发送命令,并将输出写入文件。CC和CA代表Ctrl+C和Ctrl+ a。我能想到的唯一解释是,远程设备没有在最后发送Ctrl+C,但shell输出显示它是。 代码:

#!/usr/bin/python
#Import external modules
import sys
import socket
import telnetlib
import datetime
import csv
import logging
import os

#Import internal variables and functions
from ctrlchar import CA,CC

#import csv file siteProfiles.csv
with open("/home/dev/iotank/site-profiles-staging.csv") as f:
        reader = csv.reader(f, delimiter=',')
        data = []
        for row in  reader:
                data.append(row)

#Variables
TIMEOUT=30 #Telnet timeout in seconds
#251 is CSLD Report, 301 Liquid Sensor Status Report, 201 is Inventory Report
COMMAND="I201"
DEVICE="00"
DATE=datetime.date.today()
TIME=datetime.datetime.now()
TIMESTAMP=TIME.strftime("%m%d%Y%H%M")
sites = len(data)
logging.basicConfig(filename='log.txt',level=logging.DEBUG)
logger= logging.getLogger("basiclog")
REPORTNAME="TESTFI" + TIMESTAMP + ".txt" 
file = open("/home/dev/iotank/report/inventory/" + REPORTNAME, 'w+')
for row in xrange(sites):
        SITE = data[row][0]
        HOST = data[row][1]
        PORT = data[row][2]
        BEGINREPORT=COMMAND + DEVICE
        try:
                tn = telnetlib.Telnet(HOST,PORT,TIMEOUT)
                tn.set_debuglevel(1)
                tn.write(CA)
                tn.write(COMMAND)
                tn.write(DEVICE)
                tn.read_until("TEMP")
                file.write("z" + SITE + "\r\n" + TIMESTAMP)
                file.write(tn.read_until(CC))
                tn.close
                file.seek(-2, os.SEEK_END)
                file.truncate()
        except Exception:
                logger.error(SITE + HOST + "Couldn't connect", exc_info=True)
file.close()

输出:

z080
121720190130
  1  ULTRA LOW DIESEL     12175         0     2929    90.17     1.70    63.77
  2  DYED LSDF             3345         0      970    65.44     0.00    63.61
  3  UNLEAD                1002         0     5014    21.44     0.00    70.17
  4  SUPER                 1078         0     2901    30.33     1.69    70.19
^A
I20100
DEC 17, 2019  2:27 AM

US 280 FUEL CENTER




IN-TANK INVENTORY

TANK PRODUCT             VOLUME TC VOLUME   ULLAGE   HEIGHT    WATER     TEMP
  1  ULTRA LOW DIESEL     12175         0     2929    90.17     1.70    63.79
  2  DYED LSDF             3345         0      970    65.44     0.00    63.61
  3  UNLEAD                1002         0     5014    21.44     0.00    70.15
  4  SUPER                 1078         0     2901    30.33     1.69    70.20

Ctrl+A字符前的前6行是所需的输出。为什么代码在另一个迭代中继续。 问题来源StackOverflow 地址:/questions/59378770/why-is-telnetlib-continuing-to-write-to-file-after-tn-close-statement-also-it

展开
收起
kun坤 2019-12-30 10:51:10 855 0
1 条回答
写回答
取消 提交回答
  • 精于基础,广于工具,熟于业务。

    tn.read_until("TEMP")有可能是这一段代码导致的

    2019-12-31 09:47:48
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载