目录
整体目标
实现本地电脑向Liunx服务器发送命令行指令,实现python程序的运行,并将运行后的结果发送回本地电脑。
安装SSH.NET库
直接依赖项里NuGet查照安装即可
上传下载方法
代码摘自https://zhuanlan.zhihu.com/p/449829353,略有改动
public string RunDown(string serverPath, string localPath)
{
try
{
using (var sftp = new SftpClient(this.Host, 22, this.User, this.Psw))
{
sftp.Connect();
using (var fileStream = File.OpenWrite(localPath))
{
sftp.DownloadFile(serverPath, fileStream);
}
sftp.Disconnect();
sftp.Dispose();
return "success";//返回空字符串
}
}
catch (Exception ex)
{
return $"下载失败,原因:{ex.Message}";
}
}
public string RunUp(string upFileName, string serverPath)
{
try
{
using (var sftp = new SftpClient(this.Host, 22, this.User, this.Psw))
{
sftp.Connect();
using (var fileStream = File.OpenRead(upFileName))
{
sftp.UploadFile(fileStream, serverPath, true, null);//true表示可以覆写
}
sftp.Disconnect();
sftp.Dispose();
return "success";
}
}//try
catch (Exception ex)
{
return $"上传失败,原因是:{ex.Message}";
}//catch
}
连接方法
private void RunCommand()
{
using (var client = new SshClient(host,22,user,psw))
{
client.Connect();
var cmd = client.CreateCommand("command1; command2");
//这里命令注意目录,每一次执行都是从根部从头开始。
//例如执行/home/xxxx/目录下的python文件.
//client.CreateCommand("cd /home/xxxx");
//client.CreateCommand("python3 -u hsad.py");会报错
//client.CreateCommand("cd /home/xxxx;python3 -u hsad.py");这样用;连起来才是正确的
var rasyncht = cmd.BeginExecute();
using (var reader = new StreamReader(cmd.OutputStream, Encoding.UTF8, true, 1024, true))
{
while (!rasynch.IsCompleted || !reader.EndOfStream)
{
string line = reader.ReadLine();
if (line != null)
{
Console.WriteLine(line)
}
}
}
cmd.EndExecute(rasynch);
client.Disconnect();
}
}
常见问题
- 尽量使用CreateCommand或者RunCommand两个函数去执行。
- 当运行的程序运行时间较长时需要等待程序的运行,下面的代码用于判断程序是否运行结束。
while (!result.IsCompleted || !reader.EndOfStream)
- 因为CreateCommand方法不使用终端仿真,而python程序在没有中断的情况下执行缓冲输出,因此在需要获得程序输出的情况下应当使用-u后缀。
python3 -u test.py
- 程序运行错误时注意检查程序里面的相对地址,当你使用绝对地址的命令运行程序时,程序内的地址需要相应的改为绝对地址。或者将命令分为先cd到程序目录再执行两步。
参考
How to continuously write output from Python Program running on a remote host (Raspberry Pi) executed with C# SSH.NET on local console? - Stack Overflowhttps://stackoverflow.com/questions/57609499/how-to-continuously-write-output-from-python-program-running-on-a-remote-host-rc# - Execute long time command in SSH.NET and display the results continuously in TextBox - Stack Overflow
https://stackoverflow.com/questions/47386713/execute-long-time-command-in-ssh-net-and-display-the-results-continuously-in-tex
[C#.net资料]SSH远程操作Linux实时通信,上传下载 - 知乎 (zhihu.com)https://zhuanlan.zhihu.com/p/449829353