swift - 如何使用 swift 4 和 playgrounds 运行诸如 "bash -c ssh ..."之类的程序并与之交互?

标签 swift bash ssh process swift-playground

如何使用 swift 4 和 playgrounds 在 bash 终端中运行 ssh 等程序并与之交互?终端命令可以在 Mac swift playground 中执行,代码如下:

@discardableResult func shell(_ command: String) -> String {
let task = Process()

task.launchPath = "/bin/bash"
task.arguments = ["-c", command]

let pipe = Pipe()

task.standardOutput = pipe
task.launch()

let data = pipe.fileHandleForReading.readDataToEndOfFile()

let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue)! as String

return output
}

// Example usage:
let t = shell("ls")
print("\(t)") //prints dir listing

但是,我希望能够与 ssh 之类的程序进行交互,而不是像 ls 这样的非交互程序。例如命令:

let t = shell("ssh xxx.xxx.xxx.xxx -T -l root -p 22") 

将启动 ssh,ssh 将通过终端提示输入密码。我希望能够以编程方式提供密码并继续。在我看来,由于 SSH 在终端上下文中运行,劫持终端 stdin 和 stdout 应该足够了,但到目前为止我还没有成功。以下是我发现的一些资源,它们提供了一些有关劫持的信息:

Big nerd on highjacking

Medium article

关于是否可以实现以及如何实现的任何想法?

最佳答案

ssh 直接从 /dev/tty 而不是 stdin 读取密码。要以编程方式控制 tty,您需要 pty 模块/API,其中的工具如 Expect正在使用。

我对 Swift 一无所知,所以不确定它是否有类似的 pty 模块。如果没有,那么您可以使用 Expect运行 ssh

关于swift - 如何使用 swift 4 和 playgrounds 运行诸如 "bash -c ssh ..."之类的程序并与之交互?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54301972/

相关文章:

GitLab 和 SSH/HTTP 连接

Python 结构 : Skip refused SSH connections?

ios - 用于扩展非泛型类型的尾随 where 子句

ios - 当打开另一个特定应用程序 (Facebook) 时,可以从我的应用程序发送推送通知吗?

regex - CRON 的 Bash 正则表达式

bash - Docker exec 引用变量

linux - 如何获取目录的最新文件

shell - 在后台运行的 ssh 进程被暂停

ios - 在 Swift 中指定 UITextField 的边框半径

ios - tabBar 按钮重叠。我怎样才能更好地将它们分开?