简体   繁体   English

从linux telnet捕获输出到python脚本

[英]catch output from linux telnet to a python script

My problem is that i want to do something like this in linux console 我的问题是我想在linux控制台中做类似的事情

telnet 192.168.255.28 > process.py ie i would like to do some transformation with console telnet output using python script. telnet 192.168.255.28> process.py,即我想使用python脚本对控制台telnet输出进行一些转换。 I'm see Popen in python for this case, but i can't understand how can i get input from telnet if it do not stop all time.. Pleas any ideas. 在这种情况下,我在python中看到了Popen,但是我不明白如何从telnet那里获取输入信息,如果它不能一直停下来。

Have you considered telnetlib ? 您考虑过telnetlib吗? It seems like pretty much exactly what you're looking for? 您似乎在寻找什么呢?

If you can adapt your solution, telnetlib seems like the right way to do it -- +1 to xitrium. 如果您能适应您的解决方案,则telnetlib似乎是正确的方法-+1到xitrium。

That said, though, if you're dead set on piping the output of telnet into your Python script, it'll be coming in on standard in. That means you can do something like this: 就是说,尽管如此,如果您不愿意将telnet的输出传递到Python脚本中,它将以标准输入形式出现。这意味着您可以执行以下操作:

try:
    while True:
        line = raw_input()
        do_stuff(line)
except EOFError:
    pass    # the telnet process finished; there's no more input

which will grab the output from telnet, one line at a time. 它将从telnet一次抓取一行的输出。 If you want finer control, you can get the input using sys.stdin.read() . 如果需要更好的控制,可以使用sys.stdin.read()获得输入。

Important: In your question, you said (for example) telnet 192.168.255.28 > process.py . 重要提示:在您的问题中,您说(例如) telnet 192.168.255.28 > process.py This is wrong; 这是错误的; instead of piping the output from telnet into your script, it will save the output to file, overwriting your script. 无需将telnet的输出传递到脚本中,而是将输出保存到文件中,从而覆盖脚本。 What you want is a pipe: telnet 192.168.255.28 | process.py 您想要的是管道: telnet 192.168.255.28 | process.py telnet 192.168.255.28 | process.py . telnet 192.168.255.28 | process.py

As xitrium mentioned, it would be better if you used telnetlib. 如xitrium所述,如果您使用telnetlib会更好。 You can dispense with the whole mess of shell redirection etc. 您可以省去shell重定向等整个过程。

If you do something like telnet foo | process.py 如果您执行telnet foo | process.py telnet foo | process.py , you can read your programs stdin ( sys.stdin ) to get the output of the telnet program. telnet foo | process.py ,您可以读取程序stdin( sys.stdin )以获取telnet程序的输出。 When you're happy, you can exit and terminate the pipeline. 高兴时,您可以退出并终止管道。 subprocess.Popen would be used if you're trying to open the telnet program as a subprocess of the interpreter. subprocess.Popen会,如果你想打开使用telnet程序作为解释的一个子进程。 I'm not sure you wanted that. 我不确定您是否想要那样。

In any case, telnetlib is the right way to go it seems. 无论如何,telnetlib似乎是正确的选择。 If you simply want an output text processor, consider perl. 如果只需要输出文本处理器,请考虑使用perl。 It's strengths lean in that direction. 它的优势在于那个方向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM