Executing a script |
An SshScript will begin execution as soon as a connection is established with the SSH server. Therefore it is recommended that your SshScript be created and all tasks added before the Ssh.Connect method is invoked.
As an example the code example below will demonstrate how to automatically login to a SSH server, execute a command and logout. Some assumptions have been made about your shell prompt. Your shell prompt may differ although the fundamental process would be the same.
Example
[C#]
// create login credentials
SshParameters sshParams = new SshParameters(hostname,username,password);
// create new Ssh instance
Ssh ssh = new Ssh(sshParams);
// create new SshScript and associate with Ssh instance
SshScript script = new SshScript(ssh);
// create first task
SshTask task1 = new SshTask("$","ls -al","$");
// create second task
SshTask task2 = new SshTask("$","pwd","$");
// add tasks to script to be executed in order
script.AddTask(task1);
script.AddTask(task2);
// connect and execute tasks
ssh.Connect();
// wait until last task is complete
while(!task2.IsComplete) {
Thread.Sleep(100);
}
// print out results of task1
Console.WriteLine(task1.Response);
// print out results of task2
Console.WriteLine(task2.Response);
// disconnect
ssh.Disconnect();
[VB]
' create login credentials
Dim sshParams As SshParameters = New SshParameters(hostname, username, password)
' create new Ssh instance
Dim ssh As Ssh = New Ssh(sshParams)
' create new SshScript and associate with Ssh instance
Dim script As SshScript = New SshScript(ssh)
' create first task
Dim task1 As SshTask = New SshTask("$", "ls -al", "$")
' create second task
Dim task2 As SshTask = New SshTask("$", "pwd", "$")
' add tasks to script to be executed in order
script.AddTask(task1)
script.AddTask(task2)
' connect and execute tasks
ssh.Connect
' wait until last task is complete
While Not task2.IsComplete
Thread.Sleep(100)
End While
' print out results of task1
Console.WriteLine(task1.Response)
' print out results of task2
Console.WriteLine(task2.Response)
' disconnect
ssh.Disconnect