UIKitSshTerminalView.swift 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. //
  2. // UIKitSshTerminalView.swift
  3. // iOS
  4. //
  5. // Created by Miguel de Icaza on 4/22/20.
  6. // Copyright © 2020 Miguel de Icaza. All rights reserved.
  7. //
  8. import Foundation
  9. import UIKit
  10. import SwiftTerm
  11. import SwiftSH
  12. public class SshTerminalView: TerminalView, TerminalViewDelegate {
  13. var shell: SSHShell?
  14. var authenticationChallenge: AuthenticationChallenge?
  15. public override init (frame: CGRect)
  16. {
  17. super.init (frame: frame)
  18. delegate = self
  19. do {
  20. authenticationChallenge = .byPassword(username: "miguel", password: try String (contentsOfFile: "/Users/miguel/password"))
  21. shell = try? SSHShell(sshLibrary: Libssh2.self,
  22. host: "192.168.86.78",
  23. port: 22,
  24. environment: [Environment(name: "LANG", variable: "en_US.UTF-8")],
  25. terminal: "xterm-256color")
  26. connect()
  27. } catch {
  28. }
  29. }
  30. func connect()
  31. {
  32. if let s = shell {
  33. s.withCallback { [unowned self] (data: Data?, error: Data?) in
  34. if let d = data {
  35. DispatchQueue.main.async {
  36. let slice = Array(d) [0...]
  37. self.feed(byteArray: slice)
  38. }
  39. }
  40. }
  41. .connect()
  42. .authenticate(self.authenticationChallenge)
  43. .open { [unowned self] (error) in
  44. if let error = error {
  45. self.feed(text: "[ERROR] \(error)\n")
  46. } else {
  47. let t = self.getTerminal()
  48. s.setTerminalSize(width: UInt (t.cols), height: UInt (t.rows))
  49. }
  50. }
  51. }
  52. }
  53. required init?(coder: NSCoder) {
  54. fatalError("init(coder:) has not been implemented")
  55. }
  56. // TerminalViewDelegate conformance
  57. public func scrolled(source: TerminalView, position: Double) {
  58. //
  59. }
  60. public func setTerminalTitle(source: TerminalView, title: String) {
  61. //
  62. }
  63. public func sizeChanged(source: TerminalView, newCols: Int, newRows: Int) {
  64. if let s = shell {
  65. s.setTerminalSize(width: UInt (newCols), height: UInt (newRows))
  66. }
  67. }
  68. public func send(source: TerminalView, data: ArraySlice<UInt8>) {
  69. shell?.write(Data (data)) { err in
  70. print ("Error sending")
  71. }
  72. }
  73. }