赞
踩
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))
#!/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()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。