当前位置:   article > 正文

Python asyncssh 万金油服务器端,万金油客户端 Demo

python asyncssh
import asyncio, asyncssh, sys
import threading
import time


def yesinstall(chan):
    time.sleep(10)
    chan.write("ls\n")


class MySSHClientSession(asyncssh.SSHClientSession):
    def data_received(self, data, datatype):
        print(data, end='')

    def connection_lost(self, exc):
        if exc:
            print('SSH session error: ' + str(exc), file=sys.stderr)


class MySSHClient(asyncssh.SSHClient):
    def connection_made(self, conn):
        print('Connection made to %s.' % conn.get_extra_info('peername')[0])

    def auth_completed(self):
        print('Authentication successful.')


async def run_client():
    conn, client = await asyncssh.create_connection(MySSHClient, '127.0.0.1', username='root', password='123123',
                                                    port=8023)

    async with conn:
        chan, session = await conn.create_session(MySSHClientSession, '', term_type='xterm-color', term_size=(80, 24))

        writer = threading.Thread(target=yesinstall(chan))
        writer.start()

        await chan.wait_closed()


try:
    asyncio.get_event_loop().run_until_complete(run_client())
except (OSError, asyncssh.Error) as exc:
    sys.exit('SSH connection failed: ' + str(exc))

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
#!/usr/bin/env python3.6

import asyncssh
import sys
import os
import asyncio
from asyncio.subprocess import PIPE

COMMAND_TERMINATOR = ";"


# AUTHORIZED_KEY_LOC = os.environ["SERVER_AUTHORIZED_KEYS_DIR"]
# HOST_KEY_LOC = os.environ["SERVER_HOST_KEY_LOC"]

async def handle_client(process):
    if process.command:
        print('Line was = %s\n' % process.command)
        local_proc = await asyncio.create_subprocess_shell(
            process.command, stdin=PIPE, stdout=PIPE, stderr=PIPE)
        # stdout, stderr = await local_proc.communicate()
        # print(f'[{process.command!r} exited with {local_proc.returncode}]')
        # if stdout:
        #     print(f'[stdout]\n{stdout.decode()}')
        # if stderr:
        #     print(f'[stderr]\n{stderr.decode()}')
        await process.redirect(stdin=local_proc.stdin, stdout=local_proc.stdout,
                               stderr=local_proc.stderr)
        await process.stdout.drain()
        process.exit(0)
        print("命令执行结束")
    else:
        process.stdout.write('Enter numbers one per line, or EOF when done:\n')
        try:
            async for line in process.stdin:
                line = line.rstrip('\n')
                if line:
                    try:
                        local_proc = await asyncio.create_subprocess_shell(
                            line, stdin=PIPE, stdout=PIPE, stderr=PIPE)
                        await process.redirect(stdin=local_proc.stdin, stdout=local_proc.stdout,
                                               stderr=local_proc.stderr)
                        # process.stdout.write('chenzhenyang@LAPTOP-1KF5BTDO:~$')
                    except ValueError:
                        process.stderr.write('Invalid number: %s\n' % line)
        except asyncssh.BreakReceived as e:
            print(e)
            pass
        # process.stdout.write('Total = %s\n' % total)
        # process.exit(0)


class MySSHServer(asyncssh.SSHServer):
    def connection_made(self, conn):
        self._conn = conn

    # def begin_auth(self, username):
    #     try:
    #         self._conn.set_authorized_keys('{0}/{1}'.format(AUTHORIZED_KEY_LOC, username))
    #     except IOError:
    #         pass
    #
    #     return True

    def password_auth_supported(self):
        return True

    def validate_password(self, username, password):
        return True


async def start_server():
    await asyncssh.create_server(MySSHServer, '', 8023,
                                 server_host_keys=['ssh_host_key'],
                                 process_factory=handle_client)


def main():
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(start_server())
    except (OSError, asyncssh.Error) as exc:
        sys.exit('Error starting server: ' + str(exc))
    loop.run_forever()


if __name__ == "__main__":
    main()

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/79980
推荐阅读
相关标签
  

闽ICP备14008679号