ssh.dart 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:typed_data';
  4. import 'package:dartssh2/dartssh2.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({Key? key}) : super(key: key);
  25. @override
  26. // ignore: library_private_types_in_public_api
  27. _MyHomePageState createState() => _MyHomePageState();
  28. }
  29. class _MyHomePageState extends State<MyHomePage> {
  30. final terminal = Terminal();
  31. var title = host;
  32. @override
  33. void initState() {
  34. super.initState();
  35. initTerminal();
  36. }
  37. Future<void> initTerminal() async {
  38. terminal.write('Connecting...\r\n');
  39. final client = SSHClient(
  40. await SSHSocket.connect(host, port),
  41. username: username,
  42. onPasswordRequest: () => password,
  43. );
  44. terminal.write('Connected\r\n');
  45. final session = await client.shell(
  46. pty: SSHPtyConfig(
  47. width: terminal.viewWidth,
  48. height: terminal.viewHeight,
  49. ),
  50. );
  51. terminal.buffer.clear();
  52. terminal.buffer.setCursor(0, 0);
  53. terminal.onTitleChange = (title) {
  54. setState(() => this.title = title);
  55. };
  56. terminal.onResize = (width, height, pixelWidth, pixelHeight) {
  57. session.resizeTerminal(width, height, pixelWidth, pixelHeight);
  58. };
  59. terminal.onOutput = (data) {
  60. session.write(utf8.encode(data) as Uint8List);
  61. };
  62. session.stdout
  63. .cast<List<int>>()
  64. .transform(Utf8Decoder())
  65. .listen(terminal.write);
  66. session.stderr
  67. .cast<List<int>>()
  68. .transform(Utf8Decoder())
  69. .listen(terminal.write);
  70. }
  71. @override
  72. Widget build(BuildContext context) {
  73. return CupertinoPageScaffold(
  74. navigationBar: CupertinoNavigationBar(
  75. middle: Text(title),
  76. backgroundColor:
  77. CupertinoTheme.of(context).barBackgroundColor.withOpacity(0.5),
  78. ),
  79. child: TerminalView(
  80. terminal,
  81. ),
  82. );
  83. }
  84. }