我正在寻找一种方法来帮助我在树莓派中打开二进制客户端并在该客户端中发送一些命令。我尝试两种方法:
SshClient sshclient = new SshClient(HostAddress, "pi", "raspberry");
sshclient.Connect();
using (SshCommand sc = sshclient.CreateCommand(
"rm /tmp/liblog.txt;
cd /home/pi;
sudo ./myClient -s ffdd::aabb:3;
setdefault;
exit"))
{
var asyncExecute = sc.BeginExecute();
sc.OutputStream.CopyTo(Console.OpenStandardOutput());
Delay(60000);
sc.EndExecute(asyncExecute);
}
sshclient.Disconnect();
sshclient.Dispose();
如您所见,我这里有 5 个命令,在我运行 myClient 之前,ssh 进程工作正常。但是当客户端运行时,下一个命令不再执行。myClient 正在运行,但它不执行进一步的操作。我也在尝试这种方式并得到相同的结果:
public void runMyClient(string HostAddress)
{
string command = " /nointeractiveinput /command "open " + HostProtocol + "://" + HostLogin + "@" + HostAddress +
"/" "call cd /home/pi/"" +
" "call ./myClient -s ffdd::aabb:3"" +
" "call setdefault"";
Console.WriteLine(command);
System.Diagnostics.Process cmd = new System.Diagnostics.Process();
cmd.StartInfo.FileName = ""C:\Program Files (x86)\WinSCP\WinSCP.com"";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.Arguments = command;
cmd.Start();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());
cmd.WaitForExit();
cmd.StandardInput.Close();
cmd.Close();
}
感谢您的帮助。
我刚刚找到了解决我的问题的方法:( 对于这种情况,只需使用 CreateShellStream 和 StreamReader/StreamWriter 即可实现此目的。
SshClient sshclient = new SshClient(HostAddress, "pi", "raspberry");
sshclient.Connect();
string default_set_status_done = "DEFAULT_SET_DONE";
string default_set_status_failed = "DEFAULT_SET_FAIL";
var s = sshclient.CreateShellStream("Commands", 240, 200, 132, 80, 1024);
var reader = new StreamReader(s);
var writer = new StreamWriter(s);
writer.AutoFlush = true;
// Do the read command
writer.WriteLine("rm /tmp/liblog.txt");
Thread.Sleep(200);
writer.WriteLine("cd /home/pi/");
Thread.Sleep(200);
writer.WriteLine("sudo ./myClient -s ffdd::aabb:3");
Thread.Sleep(200);
writer.WriteLine("setdefault");
Thread.Sleep(30000);
writer.WriteLine("exit");
Thread.Sleep(10000);
string l = "";
while ((l = reader.ReadLine()) != null)
{
Console.WriteLine(l);
if (l.Contains(default_set_status_done))
{
ReportService.LogOk("set default completed.");
}
else if (l.Contains(default_set_status_failed))
{
Inconclusive("set default failed!");
}
}
这对我有用。 您可以在此处找到更多参考资料:https://csharp.hotexamples.com/examples/Renci.SshNet/SshClient/CreateShellStream/php-sshclient-createshellstream-method-examples.html