Accessing a telnet session in python

2019-01-24 17:34发布

问题:

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

Any advice?

回答1:

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])


回答2:

Between April and May 2013, some people actually wrote an entire Python package around JPL's Horizons Telnet interface. It can be found here:

https://pypi.python.org/pypi/HorizonJPL