2012-04-12 1 views
4

저는 파이썬의 telnetlib을 사용하여 일부 컴퓨터에 텔넷하고 몇 가지 명령을 실행하고 있는데,이 명령의 출력을 얻고 싶습니다.실시간으로 telnetlib로 출력 읽기

따라서, 현재의 시나리오는 무엇인가 - 이제

tn = telnetlib.Telnet(HOST) 
tn.read_until("login: ") 
tn.write(user + "\n") 
if password: 
    tn.read_until("Password: ") 
    tn.write(password + "\n") 

tn.write("command1") 
tn.write("command2") 
tn.write("command3") 
tn.write("command4") 
tn.write("exit\n") 

sess_op = tn.read_all() 
print sess_op 
#here I get the whole output 

, 내가 sess_op에있는 모든 통합 된 출력을 얻을 수 있습니다.

tn = telnetlib.Telnet(HOST) 
tn.read_until("login: ") 
tn.write(user + "\n") 
if password: 
    tn.read_until("Password: ") 
    tn.write(password + "\n") 

tn.write("command1") 
#here I want to get the output for command1 
tn.write("command2") 
#here I want to get the output for command2 
tn.write("command3") 
tn.write("command4") 
tn.write("exit\n") 

sess_op = tn.read_all() 
print sess_op 

답변

2
- 다음과 같이 내가 원하는

하지만, 바로 내가 다른 컴퓨터의 쉘에서 일하고 있어요 것처럼 그 실행 후 Command2를 실행하기 전에 다음 Command1의 출력을 얻을 수 있습니다

telnetlib 모듈 here의 설명서를 참조해야합니다.
이 시도 - telnetlib와 함께 작업하는 동안 나는 비슷한으로 실행

tn = telnetlib.Telnet(HOST) 
tn.read_until("login: ") 
tn.write(user + "\n") 
if password: 
    tn.read_until("Password: ") 
    tn.write(password + "\n") 

tn.write("command1") 
print tn.read_eager() 
tn.write("command2") 
print tn.read_eager() 
tn.write("command3") 
print tn.read_eager() 
tn.write("command4") 
print tn.read_eager() 
tn.write("exit\n") 

sess_op = tn.read_all() 
print sess_op 
+4

내 경우에는 작동하지 않습니다. – theharshest

7

.

그런 다음 각 명령 끝에 캐리지 리턴이 누락되고 새 행이 생기고 모든 명령에 대해 read_eager가 수행되었습니다. 이런 식으로 뭔가 :

tn = telnetlib.Telnet(HOST, PORT) 
tn.read_until("login: ") 
tn.write(user + "\r\n") 
tn.read_until("password: ") 
tn.write(password + "\r\n") 

tn.write("command1\r\n") 
ret1 = tn.read_eager() 
print ret1 #or use however you want 
tn.write("command2\r\n") 
print tn.read_eager() 
... and so on 

대신의 같은 명령을 작성 :

tn.write("command1") 
print tn.read_eager() 

이 대신 충분한 수 있습니다 만 "\ n"을 추가, 당신을 위해 단지 "\ n을"함께 작업하는 경우 "\ r \ n"하지만 제 경우에는 "\ r \ n"을 사용해야했고 아직 새로운 행을 사용하지 않았습니다.