I try make auto-reconnecting ssh client on asyncssh. (SshConnectManager must stay in background and make ssh sessions when need)
class SshConnectManager(object):
def __init__(self, host, username, password, port=22):self._host = hostself._username = usernameself._password = passwordself._port = portself.conn = Noneasyncio.async(self.start_connection)@asyncio.coroutine
def start_connection(self):try:Client = self._create_ssh_client()self.conn, _ = yield from asyncssh.create_connection(Client,self._host, port=self._port,username=self._username,password=self._password)except Exception as e:print("Connection error! {}".format(e))asyncio.async(self.start_connection())def _create_ssh_client(self):class MySSHClient(asyncssh.SSHClient):parent = selfdef connection_lost(self, exc):self.parent._handle_connection_lost(exc)return MySSHClientdef _handle_connection_lost(self, exc):print('Connection lost on {}'.format(self.host))print(exc)asyncio.async(self.start_connection)ssh1 = SshConnectManager(settings.host, settings.username, settings.password, settings.port)asyncio.get_event_loop().run_until_complete(...)
Please do not look at _create_ssh_client or other "haks"
Problem is:
$ python3 main.py
Traceback (most recent call last):File "main.py", line 75, in <module>ssh1 = SshConnectManager(settings.host, settings.username, settings.password, settings.port)File "main.py", line 22, in __init__asyncio.async(self.start_connection)File "/usr/lib/python3.4/asyncio/tasks.py", line 565, in asyncraise TypeError('A Future or coroutine is required')
TypeError: A Future or coroutine is required
But self.start_connection is corutine! Or not? Or what is another way start async task from sync code?