该脚本应该使用远程设备打开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
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。