MRM MRM - 3 days ago 7
Python Question

Function used to create one session only for each object in python

I'm trying to create a class to connect to box using pexpect and grab some data from that box, and I have difficulty of creating a function that contains the pexpect session for my box and initializes it for each object that I create in the class code example below.

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

def get_some_data(self,command)
list = session.before.splitlines()
return list

now my problem is if I do create a new object a new session will be created for each object, and that is not required I can use only one session for every object I create from this class

Answer Source

You can use a class method to connect, and a class variable for the pexpects object, the connection. Then objects created in that class can use the connection object.

This example uses pexpect to connect via sshto a host, using a class method once. Then it runs commands on that host using different objects.

import pexpect

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

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

    def check_conn(self):
        # placeholder for true checks
        print self.Name + ' is ' + str(self.Is_connected)

    def cmd(self, command):
        self.ssh.expect('> ')
        print self.ssh.before, self.ssh.after

userathost = 'xxx@xxxxx'

print 'Connect to ' + userathost

conn_1 = Comms()
print 'whoami?'

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

This is rather bare-bones, missing in the first place suitable checks.

It prints, redacted for personal details as indicated by [description]

Connect to xxx@xxxxx

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

xxx@xxxxx is True
With another object: pwd:
[path to my home]
[my prompt] > 

The [...] contain information on my account on that host.

The connection can, and should, be configured more nicely (for one thing, to supress echo).