2017-08-12 74 views
1

我試圖創建一個類來使用pexpect連接到框,並從該框中獲取一些數據,並且我很難創建一個包含我盒子的pexpect會話的函數併爲我在下面的類代碼示例中創建的每個對象進行初始化。只爲python中的所有對象創建一個會話

class A: 
    def __init__(self) 
     # in this way a session will be created for each object and i don't 
     # need that i need only one session to open for any object created. 
     session = pexpect.spawn('ssh myhost') 
     session.expect('[email protected]#') 

    def get_some_data(self,command) 
     session.sendline(command) 
     session.expect('[email protected]#') 
     list = session.before.splitlines() 
     return list 

我現在的問題是,如果我確實創造了一個新的會話會爲每個對象創建一個新的對象,而且不需要我只能使用一個會話我從這個類創建的每一個對象

+0

所以我想代碼工作,你只需要鍛鍊一個會話策略? –

+0

是的,它的工作,但我需要能夠打開所有對象的一個​​pexpect連接。 – MRM

回答

2

您可以使用class methodpexpect的實例(子)連接並設置class variable。然後在這個類的實例方法可以使用類變量

import pexpect 

class Comms: 
    Is_connected = False 
    Name = None 
    ssh = None 

    @classmethod 
    def connect(cls, name): 
     cls.Name = name 
     cls.ssh = pexpect.spawn('ssh ' + name) 
     cls.ssh.expect('password:') 
     cls.ssh.sendline('*****') 
     cls.ssh.expect('> ') 
     print cls.ssh.before, cls.ssh.after 
     cls.Is_connected = True 

    @classmethod 
    def close(cls): 
     cls.ssh.close() 
     cls.ssh, cls.Is_connected = None, False 

    def check_conn(self): 
     print self.Name + ' is ' + str(self.Is_connected) 
     return self.Is_connected 

    def cmd(self, command): 
     self.ssh.sendline(command) 
     self.ssh.expect('> ') 
     return self.ssh.before + self.ssh.after 

在實例方法中使用的self.ssh是使用類變量的類裏面,如果沒有分配到的方式。如果將它分配給它,則會創建一個具有相同名稱的實例變量。在這種情況下,由於沒有理由在本課中分配給ssh,所以這種情況不會發生。

類方法接收該類作爲隱式參數,因此可以使用cls.ssh。內部的實例方法一個還可以得到對類的引用,然後使用cls.ssh

def cmd(self, command): 
    cls = self.__class__ 
    cls.ssh.sendline(command) 
    ... 

類變量可以在任何地方用作Comms.ssh。這是一個相當枯燥的課程。

現在使用類方法連接到主機,並通過不同的實例

from comms import Comms 

userathost = '[email protected]' 

print 'Connect to ' + userathost 
Comms.connect(userathost) 

conn_1 = Comms() 
conn_1.check_conn() 
print conn_1.cmd('whoami') 
print 

conn_2 = Comms() 
print 'With another instance object: pwd:' 
print conn_2.cmd('pwd') 

Comms.close() 

[description]

 
Connect to [email protected] 

Last login: Sat Aug 12 01:04:52 2017 from ***** 
[... typical greeting on this host] 
[my prompt] > 
[email protected] is True 
whoami 
[my username] 
[my prompt] > 

With another instance object: pwd: 
pwd 
[path to my home] 
[my prompt] > 

刪節什麼印刷品,對於個人信息的連接應建立和輸出運行命令處理得更好,但這大約是pexpect


對於類/靜態方法和變量見,例如

相關問題