我想使用Swift语言连接到SSH。
我有主机,端口,用户名和密码的详细信息。
您可以指导我一个用于在Swift和代码片段中使用的API吗?
您可以使用Objective-C Framework NMSSHnmssh github
或在Swift中使用我的简短版本,该版本使用该库进行连接,身份验证,发送或执行命令
github链接
您可以使用podifle
添加该框架pod 'PVPMikrotikSSH', :git => 'https://github.com/BlindDev/PVPMikrotikSSH.git'
随时在GitHub中创建任何问题。
我没有在git上添加任何描述,因为我只为我的项目做到了,然后意识到它对某人有帮助。
我会将描述放在githb
上这是一些简短的示例
基本 - 在POD安装后导入框架:
import Foundation
import PVPMikrotikSSH
class SSHManager {
private var pvpManager: PVPSSHManager
static let defaultHost = "192.168.88.1"
init(host: String, userName: String, password: String?) {
pvpManager = PVPSSHManager(host: host, userName: userName, password: password)
}
convenience init() {
self.init(host: SSHManager.defaultHost, userName: "admin", password: "")
}
}
要启动连接,您可以向该管理器添加更多功能
func initiateConnection(completion: ((_ success: Bool) -> Void)?) {
pvpManager.connectSessionAndAuthorize {(error) in
if let sessionError = error {
switch sessionError {
case .noPassword:
print("Session not connected: No password")
completion?(false)
case .notConnected:
print("Session not connected")
completion?(false)
case .notAuthorized:
print("Session not authorized")
completion?(false)
default:
//there are few more types of errors just use them if you need
print("Session is not connected")
completion?(false)
}
}else{
print("Session connected")
completion?(true)
}
}
}
要执行命令,您可以向该管理器添加更多功能:
func execute(_ command: String, result: ((_ result: String?)-> Void)?) {
pvpManager.executeCommand(command: command, completionHandler: { (error, result) in
//you can add error recognizer here
completion?(result)
})
}