在python中访问telnet会话 [英] Accessing a telnet session in python
问题描述
所以我需要访问一个telnet会话.更具体地说,JPL的星历服务.我完全知道我需要在命令提示符下执行的操作,但是在使用telnetlib
程序包时遇到了麻烦.
so I need to access a telnet session. More specifically JPL's ephemeris service. I know exactly what I need to do in the command prompt, but I've had trouble using the telnetlib
package.
这是我需要通过命令提示符执行的步骤:
Here are the steps I need to take through command prompt:
telnet
o horizons.jpl.nasa.gov 6775
DES=C/2012 X1;
y
E
o
H06
y
2013-Nov-7 9:00
2013-Nov-17 9:00
1d
y
1,4,9,19,20,24
,然后有大量输出需要保存到文本文件,或者简单地保存为变量.我待会儿使用.
and then after that there is a large output that I need to save to a text file, or simply keep as a variable. I'll be using it later.
按照这些输入逐步操作应该可以使您获得我需要掌握的确切信息
And following these inputs step by step should get you to the exact bit of information I need to grab
有什么建议吗?
推荐答案
我会使用 telnetlib.Telnet.expect()
,如下所示:
I would use telnetlib.Telnet.expect()
, something like this:
import telnetlib
t = telnetlib.Telnet()
t.open('horizons.jpl.nasa.gov', 6775)
expect = ( ( r'Horizons>', 'DES=C/2012 X1\n' ),
( r'Continue.*:', 'y\n' ),
( r'Select.*E.phemeris.*:', 'E\n'),
( r'Observe.*:', 'o\n' ),
( r'Coordinate center.*:', 'H06\n' ),
( r'Confirm selected station.*>', 'y\n'),
( r'Accept default output.*:', 'y\n'),
( r'Starting *UT.* :', '2013-Nov-7 09:00\n' ),
( r'Ending *UT.* :', '2013-Nov-17 09:00\n' ),
( r'Output interval.*:', '1d\n' ),
( r'Select table quant.* :', '1,4,9,19,20,24\n' ),
( r'Scroll . Page: .*%', ' '),
( r'Select\.\.\. .A.gain.* :', 'X\n' )
)
with open('results.txt', 'w') as fp:
while True:
try:
answer = t.expect(list(i[0] for i in expect), 10)
except EOFError:
break
fp.write(answer[2])
fp.flush()
t.write(expect[answer[0]][1])
这篇关于在python中访问telnet会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!