c# 使用ssh连接远程主机(ssh.net演示)
本教程使用的是ssh.net这个库。项目地址:https://github.com/sshnet/SSH.NET
使用ssh客户端连接远程主机执行命令,并拿到输出结果:
using (var sshClient = new SshClient("host", port,"username", "password")) { sshClient.Connect(); using (var cmd = sshClient.CreateCommand("ls -l")) { var res = cmd.Execute(); Console.Write(res); } }
使用sftp客户端上传文件:
using (var sftpClient = new SftpClient("host", port,"username", "password")) { sftpClient.Connect(); sftpClient.UploadFile(File.Open(@"D:\index.html", FileMode.Open),"/root/index.html"); }
下载文件:
using (var sftpClient = new SftpClient("host", port,"username", "password")) { sftpClient.Connect(); using (var stream = File.Open(@"F:\index.html", FileMode.OpenOrCreate)) { sftpClient.DownloadFile("/root/index.html", stream); } }