该脚本应该打开与远程设备的telnet会话,发送命令,然后将输出写入文件。 CC和CA分别代表Ctrl + C和Ctrl +A。我能提出的唯一可能的解释是,远程设备没有在最后发送Ctrl + C,但是shell输出显示它是。 / p>
代码:
#!/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行是所需的输出。为什么代码会继续进行另一个迭代。
答案 0 :(得分:0)
在tn.close
之后需要括号。 Python与Ruby或Lua不同,您必须显式调用该函数。
tn.close # gives the value of the function (<bound method Whatever.close of <Whatever object at 0x0000d15ea5e>>
tn.close() # calls the function