ssh.dart 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:typed_data';
  4. import 'package:dartssh2/dartssh2.dart';
  5. import 'package:example/src/virtual_keyboard.dart';
  6. import 'package:flutter/cupertino.dart';
  7. import 'package:xterm/xterm.dart';
  8. const host = 'localhost';
  9. const port = 22;
  10. const username = '<your username>';
  11. const password = '<your password>';
  12. void main() {
  13. runApp(MyApp());
  14. }
  15. class MyApp extends StatelessWidget {
  16. @override
  17. Widget build(BuildContext context) {
  18. return CupertinoApp(
  19. title: 'xterm.dart demo',
  20. home: MyHomePage(),
  21. );
  22. }
  23. }
  24. class MyHomePage extends StatefulWidget {
  25. MyHomePage({Key? key}) : super(key: key);
  26. @override
  27. // ignore: library_private_types_in_public_api
  28. _MyHomePageState createState() => _MyHomePageState();
  29. }
  30. class _MyHomePageState extends State<MyHomePage> {
  31. late final terminal = Terminal(inputHandler: keyboard);
  32. final keyboard = VirtualKeyboard(defaultInputHandler);
  33. var title = host;
  34. @override
  35. void initState() {
  36. super.initState();
  37. initTerminal();
  38. }
  39. Future<void> initTerminal() async {
  40. terminal.write('Connecting...\r\n');
  41. final client = SSHClient(
  42. await SSHSocket.connect(host, port),
  43. username: username,
  44. onPasswordRequest: () => password,
  45. );
  46. terminal.write('Connected\r\n');
  47. final session = await client.shell(
  48. pty: SSHPtyConfig(
  49. width: terminal.viewWidth,
  50. height: terminal.viewHeight,
  51. ),
  52. );
  53. terminal.buffer.clear();
  54. terminal.buffer.setCursor(0, 0);
  55. terminal.onTitleChange = (title) {
  56. setState(() => this.title = title);
  57. };
  58. terminal.onResize = (width, height, pixelWidth, pixelHeight) {
  59. session.resizeTerminal(width, height, pixelWidth, pixelHeight);
  60. };
  61. terminal.onOutput = (data) {
  62. session.write(utf8.encode(data) as Uint8List);
  63. };
  64. session.stdout
  65. .cast<List<int>>()
  66. .transform(Utf8Decoder())
  67. .listen(terminal.write);
  68. session.stderr
  69. .cast<List<int>>()
  70. .transform(Utf8Decoder())
  71. .listen(terminal.write);
  72. }
  73. @override
  74. Widget build(BuildContext context) {
  75. return CupertinoPageScaffold(
  76. navigationBar: CupertinoNavigationBar(
  77. middle: Text(title),
  78. backgroundColor:
  79. CupertinoTheme.of(context).barBackgroundColor.withOpacity(0.5),
  80. ),
  81. child: Column(
  82. children: [
  83. Expanded(
  84. child: TerminalView(terminal),
  85. ),
  86. VirtualKeyboardView(keyboard),
  87. ],
  88. ),
  89. );
  90. }
  91. }