-
-
Notifications
You must be signed in to change notification settings - Fork 4
Examples
Andrew Lambert edited this page Oct 23, 2021
·
9 revisions
This example demonstrates how to use a single SSH.Session
instance to conduct several different kinds of operations. It uploads a file (file.zip
) to a Unix-like server, extracts it, runs an install.sh
script as root, and then deletes all the temporary files and folders it created during the install.
For the sake of clarity, most operations which can fail are assumed to have succeeded.
Dim session As SSH.Session = SSH.Connect("ssh.example.com", 22, "username", "password")
Dim sftp As New SSH.SFTPSession(session)
sftp.MakeDirectory("somefolder") ' resolves to ~/somefolder/
sftp.WorkingDirectory = "somefolder"
' upload the file to ~/somefolder/
Dim f As FolderItem = GetFolderItem("C:\example\file.zip")
Dim upload As SSH.SFTPStream = sftp.Put(f.Name)
Dim local As BinaryStream = BinaryStream.Open(f)
Do Until local.EOF()
upload.Write(local.Read(1024 * 1024 * 32))
Loop
upload.Close()
local.Close()
' unzip it into ~/somefolder/tmpdir/
Dim sh As SSH.Channel = SSH.OpenChannel(session)
Call sh.Execute("cd ~/somefolder && unzip file.zip -d tmpdir")
Do
Call sh.Poll()
Call sh.Read(sh.BytesReadable, 0) ' ignore the output
Loop Until sh.EOF()
sh.Close()
' run ~/somefolder/tmpdir/install.sh as root
sh = SSH.OpenChannel(session)
Call sh.Execute("cd ~/somefolder/tmpdir && echo mypassword | sudo -S ./install.sh")
Do
Call sh.Poll()
Call sh.Read(sh.BytesReadable, 0) ' ignore the output
Loop Until sh.EOF()
sh.Close()
' rm -rf ~/somefolder/tmpdir/*
sftp.RemoveDirectory("tmpdir", True)
' rm ~/somefolder/file.zip
sftp.RemoveFile(f.Name)
' change to parent directory; resolves to ~/ in this case
sftp.WorkingDirectory = ".."
' rmdir ~/somefolder/
sftp.RemoveDirectory("somefolder")
sftp.Close()
session.Close()
Wiki home | Project page | Bugs | Become a sponsor
Text and code examples are Copyright ©2018-24 Andrew Lambert, offered under the CC BY-SA 3.0 License.