using IMCS.CCS.body;
using Renci.SshNet;
using System;
using System.IO;
namespace IMCS.CCS.DeviceProtocol
{
public class DeviceSFTP
{
#region 声明一个ScpClient类型的变量
private ScpClient ssh;
private SftpClient sftp;
private SshClient sshClient;
///
/// SCP连接状态
///
public bool Connected { get { return ssh.IsConnected; } }
#endregion
#region
///
/// 构造方法
///
/// IP
/// 端口
/// 用户名
/// 密码
public DeviceSFTP(string ip, string port, string user, string pwd)
{
ssh = new ScpClient(ip, Int32.Parse(port), user, pwd);
}
public DeviceSFTP(SFTPDeviceBody body)
{
ssh = new ScpClient(body.Ip, Int32.Parse(body.Port), body.UserName, body.Password);
}
#endregion
#region
///
/// 连接SCP
///
/// true成功
public bool Connect()
{
try
{
if (!Connected)
{
ssh.Connect();
}
return true;
}
catch (Exception ex)
{
throw new Exception(string.Format("连接SFTP失败,原因:{0}", ex.Message));
}
}
#endregion
#region 断开SCP
///
/// 断开SCP
///
public bool Disconnect()
{
try
{
if (ssh != null && Connected)
{
ssh.Disconnect();
}
return true;
}
catch (Exception ex)
{
throw new Exception(string.Format("断开SFTP失败,原因:{0}", ex.Message));
}
}
#endregion
#region SFTP上传文件
///
/// SCP上传文件
///
/// 本地路径
/// 远程路径
public int Put(string localPath, string remotePath)
{
try
{
FileInfo file = new FileInfo(localPath);
FileStream fs = new FileStream(localPath, FileMode.Open);
Connect();
ssh.Upload(fs, remotePath);
// ssh.Upload(file, remotePath);
Disconnect();
return 1;
}
catch (Exception ex)
{
throw new Exception(string.Format("SFTP文件上传失败,原因:{0}", ex.Message));
}
}
#endregion
#region SFTP获取文件
///
/// SCP获取文件
///
/// 远程路径
/// 本地路径
public void Get(string remotePath, DirectoryInfo localPath)
{
try
{
Connect();
ssh.Download(remotePath, localPath);
Disconnect();
}
catch (Exception ex)
{
throw new Exception(string.Format("SFTP文件获取失败,原因:{0}", ex.Message));
}
}
#endregion
public void DeleteFile(SFTPDeviceBody body, string filename)
{
using (SshClient sshClient = new SshClient(body.Ip, Int32.Parse(body.Port), body.UserName, body.Password))
{
//连接
sshClient.Connect();
//执行命令
//rm -rf /var/log/httpd/access
var cmd = sshClient.RunCommand($"rm -f /card/user/sinumerik/data/prog/webApiMESFILE/{filename}");
//ExitStatus == 0 执行成功
//
if (cmd.ExitStatus == 0)
{
Console.WriteLine(cmd.Result);//执行结果
}
else
{
Console.WriteLine(cmd.Error);//错误信息
}
//断开连接
sshClient.Disconnect();
}
}
#region SFTP删除文件
///
/// SCP获取文件
///
public void test()
{
using (SshClient sshClient = new SshClient("192.168.170.205", Int32.Parse("22"), "manufact", "SUNRISE"))
{
//连接
sshClient.Connect();
//执行命令
var cmd = sshClient.RunCommand("cd /card/user/sinumerik/data/prog/webApiMESFILE && ls");
//ExitStatus == 0 执行成功
//
if (cmd.ExitStatus == 0)
{
Console.WriteLine(cmd.Result);//执行结果
}
else
{
Console.WriteLine(cmd.Error);//错误信息
}
//断开连接
sshClient.Disconnect();
}
}
#endregion
}
}