コード例 #1
0
ファイル: SFTPUtils.cs プロジェクト: chanhappy/.Net
        private FtpStatusCode UploadFile(SFTPUploadArgument uploadArgument)
        {
            m_Logger.Debug($"uploadArgument:{uploadArgument}");

            Requires.NotNull(uploadArgument, "uploadArgument");
            Requires.NotNullOrEmpty(uploadArgument.RemoteHost, "remoteHost");
            Requires.NotNullOrEmpty(uploadArgument.LocalPathWithFileName, "localPathWithFileName");
            Requires.NotNullOrEmpty(uploadArgument.BaseDirectory, "baseDirectory");
            Requires.NotNullOrEmpty(uploadArgument.TargetPath, "targetPath");
            Requires.NotNullOrEmpty(uploadArgument.UserName, "userName");
            Requires.NotNullOrEmpty(uploadArgument.Password, "password");
            _sftpClient = GetInstance(uploadArgument.RemoteHost, uploadArgument.UserName, uploadArgument.Password);
            var sftpResult = _sftpClient.UploadFile(uploadArgument.IsNeedCheckDirectory, uploadArgument.LocalPathWithFileName, uploadArgument.BaseDirectory, uploadArgument.TargetPath, uploadArgument.UpFileName);

            if (!string.IsNullOrEmpty(uploadArgument.NeedChage) && uploadArgument.NeedChage != "0")
            {
                short    newPermission = Convert.ToInt16(uploadArgument.Permission);
                string   _baseDir      = uploadArgument.BaseDirectory + "/";
                string[] paths         = uploadArgument.TargetPath.Split('/');
                foreach (string path in paths)
                {
                    _baseDir = _baseDir + path + "/";
                    _sftpClient.changePermission(_baseDir, newPermission);
                }
                //  如果未传入上传后的文件名,使用源文件的名称
                string fileName = string.IsNullOrWhiteSpace(uploadArgument.UpFileName) ? Path.GetFileName(uploadArgument.LocalPathWithFileName) : uploadArgument.UpFileName;
                _sftpClient.changePermission(_baseDir + "/" + fileName, newPermission);
            }
            return(sftpResult);
        }
コード例 #2
0
 private void SFTPForm_FormClosed(object sender, FormClosedEventArgs e)
 {
     if (_ownerForm != null)
     {
         _ownerForm.FormClosed -= new FormClosedEventHandler(_ownerForm_FormClosed);
         _ownerForm             = null;
         _sftp = null;
     }
 }
コード例 #3
0
ファイル: SFTPUtils.cs プロジェクト: chanhappy/.Net
 private SFTPClient GetInstance(string host, string username, string password)
 {
     if (_sftpClient == null || _host != host || _username != username || _password != password)
     {
         _host       = host;
         _username   = username;
         _password   = password;
         _sftpClient = new SFTPClient(host, username, password);
     }
     return(_sftpClient);
 }
コード例 #4
0
ファイル: SFTPUtils.cs プロジェクト: chanhappy/.Net
        private FtpStatusCode RenameFile(SFTPRenameArgument renameArgument)
        {
            m_Logger.Debug($"renameArgument:{renameArgument}");

            Requires.NotNull(renameArgument, "renameArgument");
            Requires.NotNullOrEmpty(renameArgument.RemoteHost, "remoteHost");
            Requires.NotNullOrEmpty(renameArgument.RemotePathWithOldFile, "remotePathWithOldFile");
            Requires.NotNullOrEmpty(renameArgument.RemotePathWithNewFile, "remotePathWithNewFile");
            Requires.NotNullOrEmpty(renameArgument.UserName, "userName");
            Requires.NotNullOrEmpty(renameArgument.Password, "password");
            _sftpClient = GetInstance(renameArgument.RemoteHost, renameArgument.UserName, renameArgument.Password);
            var sftpResult = _sftpClient.RenameFileName(renameArgument.RemotePathWithOldFile, renameArgument.RemotePathWithNewFile);

            return(sftpResult);
        }
コード例 #5
0
ファイル: SFTPToolbar.cs プロジェクト: stone89son/poderosa
        public CommandResult InternalExecute(ICommandTarget target, params IAdaptable[] args)
        {
            ISSHConnection sshConnection = GetSSHConnection(target) as ISSHConnection;

            if (sshConnection == null || sshConnection.SSHProtocol != SSHProtocol.SSH2)
            {
                return(CommandResult.Ignored);
            }

            string connectionName = GetTerminalName(target);

            if (connectionName == null)
            {
                connectionName = SFTPPlugin.Instance.StringResource.GetString("Common.UnknownPeer");
            }

            Form ownerForm = GetForm(target);

            if (!ConfirmToUse(ownerForm, "SFTP"))
            {
                return(CommandResult.Cancelled);
            }

            SFTPClient sftp = null;

            try {
                sftp = SFTPClient.OpenSFTPChannel(sshConnection);

                SFTPForm form = new SFTPForm(ownerForm, sftp, connectionName);
                form.Show();    // Note: don't specify owner to avoid fixed z-order.

                return(CommandResult.Succeeded);
            }
            catch (Exception e) {
                if (sftp != null)
                {
                    try {
                        sftp.Close();
                    }
                    catch (Exception) {
                    }
                    sftp = null;
                }

                RuntimeUtil.ReportException(e);
                return(CommandResult.Failed);
            }
        }
コード例 #6
0
ファイル: SFTPUtils.cs プロジェクト: chanhappy/.Net
 public void UploadFiles(SFTPUploadArgument[] uploadArguments, string host, string username, string password, CallbackContext callbackContext)
 {
     try
     {
         Requires.NotNullOrEmpty(host, "remoteHost");
         Requires.NotNullOrEmpty(username, "userName");
         Requires.NotNullOrEmpty(password, "password");
         foreach (SFTPUploadArgument uploadArgument in uploadArguments)
         {
             m_Logger.Debug($"uploadArgument:{uploadArgument}");
             Requires.NotNull(uploadArgument, "uploadArgument");
             Requires.NotNullOrEmpty(uploadArgument.LocalPathWithFileName, "localPathWithFileName");
             Requires.NotNullOrEmpty(uploadArgument.BaseDirectory, "baseDirectory");
             Requires.NotNullOrEmpty(uploadArgument.TargetPath, "targetPath");
         }
         List <FtpStatusCode> result = new List <FtpStatusCode>();
         _sftpClient = GetInstance(host, username, password);
         foreach (SFTPUploadArgument uploadArgument in uploadArguments)
         {
             var sftpResult = _sftpClient.UploadFile(uploadArgument.IsNeedCheckDirectory, uploadArgument.LocalPathWithFileName, uploadArgument.BaseDirectory, uploadArgument.TargetPath, uploadArgument.UpFileName);
             if (!string.IsNullOrEmpty(uploadArgument.NeedChage) && uploadArgument.NeedChage != "0")
             {
                 short    newPermission = Convert.ToInt16(uploadArgument.Permission);
                 string   _baseDir      = uploadArgument.BaseDirectory + "/";
                 string[] paths         = uploadArgument.TargetPath.Split('/');
                 foreach (string path in paths)
                 {
                     _baseDir = _baseDir + path + "/";
                     _sftpClient.changePermission(_baseDir, newPermission);
                 }
                 _sftpClient.changePermission(_baseDir + uploadArgument.UpFileName, newPermission);
             }
             result.Add(sftpResult);
         }
         callbackContext.SendPluginResult(new PluginResult(PluginResult.Status.OK, result));
     }
     catch (Exception ex)
     {
         m_Logger.Error(ex);
         callbackContext.Error(new
         {
             type    = "Exception",
             code    = "",
             message = ex.Message,
             details = ex.StackTrace
         });
     }
 }
コード例 #7
0
 public int UploadFile(string Host, int Port, string userName, string password, string filePath, Guid RequestId)
 {
     try
     {
         Log.Info("Executing UploadFile");
         using (var client = new SFTPClient(Host, Port, userName, password))
         {
             Provider.UploadDocument(RequestId, System.IO.Path.GetFileName(filePath), client.FileStream(filePath));
             client.Disconnect();
         }
     }
     catch (Exception ex)
     {
         Log.Error(ex);
     }
     return(0);
 }
コード例 #8
0
ファイル: SFTPUtils.cs プロジェクト: chanhappy/.Net
 public void DownloadFiles(SFTPDownloadArgument[] downloadArguments, string host, string userName, string password, CallbackContext callbackContext)
 {
     try
     {
         Requires.NotNullOrEmpty(host, "remoteHost");
         Requires.NotNullOrEmpty(userName, "userName");
         Requires.NotNullOrEmpty(password, "password");
         foreach (SFTPDownloadArgument downloadArgument in downloadArguments)
         {
             string[] paths    = downloadArgument.RemotePathWithFileName.Split('/');
             string   fileName = paths[paths.Length - 1];
             m_Logger.Debug($"downloadArgument:{downloadArgument}");
             Requires.NotNull(downloadArgument, "downloadArgument");
             Requires.NotNullOrEmpty(downloadArgument.RemotePathWithFileName, "remotePathWithFileName");
             Requires.NotNullOrEmpty(downloadArgument.LocalPathWithoutFileName, "localPathWithoutFileName");
             if (File.Exists(downloadArgument.LocalPathWithoutFileName + "\\" + fileName))
             {
                 File.Delete(downloadArgument.LocalPathWithoutFileName + "\\" + fileName);
             }
         }
         List <FtpStatusCode> result = new List <FtpStatusCode>();
         _sftpClient = GetInstance(host, userName, password);
         foreach (SFTPDownloadArgument downloadArgument in downloadArguments)
         {
             var sftpResult = _sftpClient.DownloadFile(downloadArgument.RemotePathWithFileName, downloadArgument.LocalPathWithoutFileName);
             result.Add(sftpResult);
         }
         callbackContext.Success(new PluginResult(PluginResult.Status.OK, result));
     }
     catch (Exception ex)
     {
         m_Logger.Error(ex);
         callbackContext.Error(new
         {
             type    = "Exception",
             code    = "",
             message = ex.Message,
             details = ex.StackTrace
         });
     }
 }
コード例 #9
0
ファイル: SFTPUtils.cs プロジェクト: chanhappy/.Net
 public void UploadFileLegacy(SFTPUploadArgument uploadArgument, CallbackContext callbackContext)
 {
     try
     {
         var sftpResult = UploadFile(uploadArgument);
         _sftpClient.Close();
         _sftpClient = null;
         callbackContext.SendPluginResult(new PluginResult(PluginResult.Status.OK, sftpResult));
     }
     catch (Exception e)
     {
         m_Logger.Error(e);
         callbackContext.Error(new
         {
             type    = "Exception",
             code    = "",
             message = e.Message,
             details = e.StackTrace
         });
     }
 }
コード例 #10
0
ファイル: SFTPUtils.cs プロジェクト: chanhappy/.Net
 public void RenameFileLegacy(SFTPRenameArgument renameArgument, CallbackContext callbackContext)
 {
     try
     {
         var sftpResult = RenameFile(renameArgument);
         _sftpClient.Close();
         _sftpClient = null;
         callbackContext.SendPluginResult(new PluginResult(PluginResult.Status.OK, sftpResult));
     }
     catch (Exception ex)
     {
         m_Logger.Error(ex);
         callbackContext.Error(new
         {
             type    = "Exception",
             code    = "",
             message = ex.Message,
             details = ex.StackTrace
         });
     }
 }
コード例 #11
0
        //获取一个可用的SFTPClient
        private SFTPClient GetAvailableSFTP()
        {
            //关闭之前的
            Close();

            SSHConnector con = SSHConnector.Create();

            ssh = con.Connect(new TcpClientTransport(ipAddress, 22), loginUser, true);

            PasswordAuthentication pwd = new PasswordAuthentication();

            pwd.Password = loginPass;

            // Authenticate the user
            if (ssh.Authenticate(pwd) == AuthenticationResult.COMPLETE)
            {
                // Open up a session and do something..
                sftp = new SFTPClient(ssh);
            }
            return(sftp);
        }
コード例 #12
0
        /// <summary>
        /// Constructor
        /// </summary>
        public SFTPForm(Form ownerForm, SFTPClient sftp, string connectionName)
        {
            InitializeComponent();

            if (!this.DesignMode)
            {
                this._sftp               = sftp;
                this._ownerForm          = ownerForm;
                this._remoteName         = connectionName;
                this.Text                = "SFTP - " + connectionName;
                this.progressBar.Maximum = PROGRESSBAR_MAX;

                PrepareTreeIcons();
                SetIcon();
                SetText();

                ClearProgressBar();

                // Note: Setting TreeViewNodeSorter property enables sorting.
                treeViewRemote.TreeViewNodeSorter = new NodeSorter();
            }
        }
コード例 #13
0
ファイル: SFTPUtils.cs プロジェクト: chanhappy/.Net
        private FtpStatusCode DownloadFile(SFTPDownloadArgument downloadArgument)
        {
            m_Logger.Debug($"downloadArgument:{downloadArgument}");
            string[] paths    = downloadArgument.RemotePathWithFileName.Split('/');
            string   fileName = paths[paths.Length - 1];

            Requires.NotNull(downloadArgument, "downloadArgument");
            Requires.NotNullOrEmpty(downloadArgument.RemoteHost, "remoteHost");
            Requires.NotNullOrEmpty(downloadArgument.RemotePathWithFileName, "remotePathWithFileName");
            Requires.NotNullOrEmpty(downloadArgument.LocalPathWithoutFileName, "localPathWithoutFileName");
            Requires.NotNullOrEmpty(downloadArgument.UserName, "userName");
            Requires.NotNullOrEmpty(downloadArgument.Password, "password");
            m_Logger.Debug("本地文件路径:" + downloadArgument.LocalPathWithoutFileName + "\\" + fileName);
            if (File.Exists(downloadArgument.LocalPathWithoutFileName + "\\" + fileName))
            {
                File.Delete(downloadArgument.LocalPathWithoutFileName + "\\" + fileName);
            }
            _sftpClient = GetInstance(downloadArgument.RemoteHost, downloadArgument.UserName, downloadArgument.Password);
            var sftpResult = _sftpClient.DownloadFile(downloadArgument.RemotePathWithFileName, downloadArgument.LocalPathWithoutFileName);

            return(sftpResult);
        }
コード例 #14
0
        /// <summary>
        /// Перенос вагонов
        /// </summary>
        public int Transfer()
        {
            MT mettrans;

            if (error_settings)
            {
                LogRW.LogWarning("Выполнение метода ArrivalMT.Transfer() - отменено, ошибка нет данных Settings.", this.eventID);
                return(0);
            }
            LogRW.LogInformation(String.Format("Сервис переноса вагонов из МТ в БД Railway :{0} - запущен", this.className), this.eventID);
            try
            {
                SFTPClient csftp = new SFTPClient(connect_SFTP);
                csftp.fromPathsHost  = fromPathHost;
                csftp.FileFiltrHost  = FileFiltrHost;
                csftp.toDirPath      = toDirPath;
                csftp.toTMPDirPath   = toTMPDirPath;
                csftp.DeleteFileHost = DeleteFile;
                csftp.RewriteFile    = RewriteFile;
                csftp.CopyToDir();
            }
            catch (Exception e)
            {
                LogRW.LogError(String.Format("[ArrivalMT.Transfer]: Общая ошибка выполнения копирования из SFTP (источник: {0}, № {1}, описание:  {2})", e.Source, e.HResult, e.Message), this.eventID);
            }
            try
            {
                mettrans                     = new MT();
                mettrans.FromPath            = toTMPDirPath;
                mettrans.DeleteFile          = DeleteFile;
                mettrans.DayMonitoringTrains = dayMonitoringTrains;
                return(mettrans.Transfer());
            }
            catch (Exception e)
            {
                LogRW.LogError(String.Format("[ArrivalMT.Transfer]: Общая ошибка переноса xml-файлов в БД Railway (источник: {0}, № {1}, описание:  {2})", e.Source, e.HResult, e.Message), this.eventID);
            }
            return(0);
        }
コード例 #15
0
 public IList <FileDescriptor> ListFiles(string Host, string Port, string Account, string Password, string Folder)
 {
     try
     {
         Log.Info("Executing ListFiles");
         List <FileDescriptor> resultListing = new List <FileDescriptor>();
         using (SFTPClient client = new SFTPClient(Host, int.Parse(Port), Account, Password))
         {
             client.ListDirectory(Folder).ForEach(f => resultListing.Add(new FileDescriptor()
             {
                 FileName = f.Name, FileType = System.IO.Path.GetExtension(f.FullName), IsDirectory = f.IsDirectory, IsRegularFile = f.IsRegularFile, FullName = f.FullName, Size = f.Length.ToString(), DisplayName = f.FullName + " " + f.Length.ToString() + "kb"
             }));
             client.Disconnect();
         }
         return(resultListing);
     }
     catch (Exception ex)
     {
         Log.Error(ex);
     }
     return(null);
 }
コード例 #16
0
        /// <summary>
        /// 遍历路径 规则 一层一层的获取 先文件后子目录
        ///
        /// 由于递归不便处理异常,特修改为循环遍历树形结构,以实现递归效果 xiecongwen 20140716
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public IEnumerable Ls(SFTPFile file)
        {
            var sshlog = new Common.Util.SSHLogManager();
            NTree <SFTPFile> parent = new NTree <SFTPFile>(file);
            //后序遍历树
            NTree <SFTPFile> child = null;

            #region 自下而上 后序遍历

            while (true)
            {
                string path = parent.Data.AbsolutePath;
                #region 判断是否有子节点 ps:将子目录添加到子节点,返回子文件

                SFTPFile[] dirs  = null;
                SFTPFile[] files = null;
                #region 获取
                try
                {
                    #region 获取子目录,并添加到子节点
                    dirs = sftp.TopDirLs(path);
                    if (dirs != null && dirs.Count() > 0)
                    {
                        foreach (var dir in dirs)
                        {
                            parent.AddChild(dir);
                        }
                    }
                    #endregion

                    #region 获取子文件
                    files = sftp.TopFileLs(path);
                    #endregion
                }
                catch (Exception ex)
                {
                    parent.RemoveAllChildren();
                    //记录报错路径,并忽略其子目录
                    sshlog.WriteLog(new Common.Util.SSHLog()
                    {
                        DateTime = DateTime.Now, LogType = Common.Util.SSHLogType.Failure, Message = path
                    });
                    logger.Error(ex.Message);

                    //更新sftp连接对象
                    sftp = GetAvailableSFTP();
                }
                #endregion

                //返回子文件
                if (files != null && files.Count() > 0)
                {
                    foreach (var f in files)
                    {
                        yield return(f);
                    }
                }
                #endregion

                //判断是否有子节点
                child = parent.PushChild();
                if (child == null)
                {
                    //如果没有子节点,则回溯至上层,否则跳出(表示遍历结束)
                    again : if (parent.Depth > 0)
                    {
                        parent = parent.Parent;
                    }
                    else
                    {
                        yield break;
                    }

                    child = parent.PushChild();
                    if (child == null)
                    {
                        goto again;
                    }
                }

                //作为父节点 进行循环
                parent = child;
            }

            #endregion
        }