文章目录
第十三章 使用SSH - 创建SSH会话
- 示例:通过SFTP列出文件
- 其他示例
%Net.SSH软件包支持SSH(安全外壳)通信。本主题简要介绍此包中的类。
创建SSH会话%Net.SSH.Session表示SSH会话。要使用此类,请执行以下操作:
- 创建类的实例。
- 使用Connect()实例方法连接到服务器。
- 使用AuthenticateWithKeyPair()或AuthenticateWithUsername()向服务器验证身份。
- 使用%Net.SSH.Session的其他方法执行进出远程系统的单个文件的SCP(安全复制)操作、执行远程命令、传输TCP通信或执行SFTP操作。
例如,使用SFTP将会话用于SFTP操作。此方法通过引用返回可用于SFTP操作的%Net.SSH.SFTP实例。
重要提示:有关可以使用这些类的受支持平台的信息,请参阅%Net.SSH.Session和%Net.SSH.SFTP的类参考。
示例:通过SFTP列出文件以下方法显示了如何通过SFTP在服务器上写入文件列表:
Method SFTPDir(ftpserver, username, password) As %Status { set ssh = ##class(%Net.SSH.Session).%New() do ssh.Connect(ftpserver) do ssh.AuthenticateWithUsername(username,password) //open an SFTP session and get that returned by reference do ssh.OpenSFTP(.sftp) //get a list of files do sftp.Dir(".",.files) set i=$ORDER(files("")) while i'="" { write $listget(files(i),1),! set i=$ORDER(files(i)) } quit $$$OK }其他示例
/// Demonstrates the execution of a remote command (by default, uname -a). ClassMethod TestExecute(host As %String, username As %String, password As %String, command As %String = "uname -a", pTimeout As %Integer = -1) As %Status { Set s = ##class(%Net.SSH.Session).%New() Set sc = s.Connect(host) Quit:$$$ISERR(sc) sc If pTimeout'=-1 { Set sc = s.SetTimeout(pTimeout) Quit:$$$ISERR(sc) sc } Set sc = s.AuthenticateWithUsername(username,password) Quit:$$$ISERR(sc) sc Set sc = s.Execute(command,.tDevice) Quit:$$$ISERR(sc) sc Set $ZT="Trap" For { Use tDevice Read X Use $P If X'[$C(13) { For i=1:1:$L(X,$C(10)) Write $P(X,$C(10),i),! } Else { Write X } } Exit Use $P Close tDevice Quit sc Trap Set sc = $S($ZE["<READ>":$$$OK,1:$$$ERROR($$$CacheError,$ZE)) Goto Exit }
/// Demonstrates the use of port forwarding to whatismyipaddress.com via the remote SSH server. ClassMethod TestForwardPort(host As %String, username As %String, password As %String, remotehost As %String = "whatismyipaddress.com", remoteport As %Integer = 80) As %Status { Set s = ##class(%Net.SSH.Session).%New() Set sc = s.Connect(host) Quit:$$$ISERR(sc) sc Set sc = s.AuthenticateWithUsername(username,password) Quit:$$$ISERR(sc) sc Set sc = s.ForwardPort(remotehost,remoteport,.tDevice) Quit:$$$ISERR(sc) sc Set $ZT="Trap" Use tDevice Write "GET / HTTP/1.0"_$C(13,10,13,10) Write *-3 // Flush // Now the response For { Use tDevice Read X Use $P If X'[$C(13) { For i=1:1:$L(X,$C(10)) Write $P(X,$C(10),i),! } Else { Write X } } Exit Use $P Close tDevice Quit sc Trap Set sc = $S($ZE["<READ>":$$$OK,1:$$$ERROR($$$CacheError,$ZE)) Goto Exit }