ssh.dart 2.4 KB

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