2016-08-23 8 views
1

私はテスト中のデバイス(ルータ)にコマンドを送信するために使用したいTelnetを実行するためのスクリプトを書いています。ルータとの通信方法

私のTelnetスクリプト:

import sys, time, telnetlib 

sys.path.insert(0, '/tmp') 
import options 

def telnet_connect(): 

     HOST = "%s" %options.DUT_telnet_ip 
     PORT = "%s" %options.DUT_telnet_port 
     username = "%s" %options.DUT_telnet_username 
     password = "%s" %options.DUT_telnet_password 

     tn = telnetlib.Telnet(HOST, PORT, 10) 
     time.sleep(5) 
     tn.write("\n") 
     tn.read_until("login:", 2) 
     tn.write(username) 
     tn.read_until("Password:", 2) 
     tn.write(password) 
     tn.write("\n") 
     response = tn.read_until("$", 5) 
     return response 

def telnet_close(): 
     response = tn.write("exit\n") 
     return response 

私はそれをTelnet接続によるルータのバージョンを確認します別のプログラムでは、このスクリプトを使用します。上記の関数を呼び出してtelnetを実行し、他のコマンドを送信するスクリプトが必要です。 「バージョン」または「LS」

+1

をあなたの質問は、実際にあるものは非常に明確ではありません... –

+0

あなたが求めているものを分離しないと、あなたはあなたの質問を下降させます。 –

+1

'tn'は' telnet_close() 'で定義されていません。おそらく、telnetインスタンスをパラメータとして渡すことをお勧めします。つまり、これは実行されません。 – dhke

答えて

1

以上のクラスのように、これを行うために試してみてください。

import sys, time, telnetlib 

sys.path.insert(0, '/tmp') 


class TelnetConnection(): 

    def init(self, HOST, PORT): 

     self.tn = telnetlib.Telnet(HOST, PORT, 10) 

    def connect(self, username, password): 
     tn = self.tn 
     tn.write("\n") 
     tn.read_until("login:", 2) 
     tn.write(username) 
     tn.read_until("Password:", 2) 
     tn.write(password) 
     tn.write("\n") 
     response = tn.read_until("$", 5) 
     return response 

    def close(self): 
     tn = self.tn 
     response = tn.write("exit\n") 
     return response 

# create here then a method to communicate as you wish 

次のように次に、あなたがそれを使用することができます。

import options 
HOST = "%s" %options.DUT_telnet_ip 
PORT = "%s" %options.DUT_telnet_port 
username = "%s" %options.DUT_telnet_username 
password = "%s" %options.DUT_telnet_password 
connection = TelnetConnection(HOST, PORT) 
connection.connect(username, password) 

connection.do_all_operations_you_want() # write your own method for that 

connection.close() 
+0

ありがとうございます –

関連する問題