首页 > 解决方案 > 如何使用 swift 4 和 Playgrounds 运行诸如“bash -c ssh ...”之类的程序并与之交互?

问题描述

如何使用 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 就足够了,但到目前为止我还没有成功。以下是我发现的一些资源,可提供有关劫持的一些信息:

劫持的大书呆子

中篇

关于是否以及如何实现这一点的任何想法?

标签: swiftbashsshprocessswift-playground

解决方案


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

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


推荐阅读