private Exception Connectclient()
        {
            //initialize new Sftp connection
            client         = new Sftp();
            client.Timeout = -1;
            client.ReconnectionMaxRetries = 10;

            //connect to client
            try
            {
                client.Connect(Packet.LoginData.Url);
            }
            catch (Exception ex)
            {
                client.Disconnect();
                return(ex);
            }

            //authenticate user
            try
            {
                client.Authenticate(Packet.LoginData.Username, Packet.LoginData.Password);
            }
            catch (Exception ex)
            {
                client.Disconnect();
                return(ex);
            }

            return(null);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Get all file names in a directory
        /// </summary>
        /// <returns>
        /// Array of file names as strings
        /// </returns>
        public async Task <string[]> DirectoryListAsync(string fileNamePrefix, string folderName)
        {
            return(await Task.Run(
                       () =>
            {
                List <string> fileNames = new List <string>();
                using (Sftp client = new Sftp())
                {
                    client.Connect(SftpUri);
                    client.Login(Username, Password);
                    client.ChangeDirectory(folderName);
                    SftpItemCollection list = client.GetList();
                    foreach (SftpItem item in list)
                    {
                        if (item.Name.ToUpper().StartsWith(fileNamePrefix.ToUpper()))
                        {
                            fileNames.Add(item.Name);
                        }
                    }
                }

                return fileNames.ToArray();
            }
                       ));
        }
Ejemplo n.º 3
0
        public void ShouldSetPassword()
        {
            string p   = "password";
            Sftp   ssh = Sftp.Server("localhost").Password(p);

            Expect.AreEqual(ssh.Config.Password, p, "Password was not set properly");
        }
        private string IsSFtpServerAvailable(LoginData loginData)
        {
            Sftp ftpClient = new Sftp();

            try
            {
                ftpClient.Connect(loginData.Url);
            }
            catch (Exception ex)
            {
                return(string.Format("- Cannot connect to ftp server '{0}'", loginData.Url));
            }

            if (!ftpClient.IsConnected)
            {
                return(string.Format("- Cannot connect to ftp server '{0}'", loginData.Url));
            }

            try
            {
                ftpClient.Authenticate(loginData.Username, loginData.Password);
            }
            catch (Exception ex)
            {
                ftpClient.Disconnect();
                return(string.Format("- Invalid credentials for server '{0}', username '{1}'", loginData.Url, loginData.Username));
            }
            ftpClient.Disconnect();
            return("");
        }
        public static Dictionary <string, string> GetGdmXAuth(MeeGoDevice targetDevice)
        {
            Sftp sftp = null;

            try {
                sftp = new Sftp(targetDevice.Address, targetDevice.Username, targetDevice.Password);
                sftp.Connect();
                var files = sftp.GetFileList("/var/run/gdm/auth-for-" + targetDevice.Username + "*");
                sftp.Close();
                if (files.Count == 1)
                {
                    return(new Dictionary <string, string> ()
                    {
                        { "XAUTHLOCALHOSTNAME", "localhost" },
                        { "DISPLAY", ":0.0" },
                        { "XAUTHORITY", "/var/run/gdm/" + files[0] + "/database" }
                    });
                }
            } catch (Exception ex) {
                LoggingService.LogError("Error getting xauth via sftp", ex);
                if (sftp != null)
                {
                    try {
                        sftp.Close();
                    } catch (Exception ex2) {
                        LoggingService.LogError("Error closing sftp connection", ex2);
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 6
0
 /// <summary>
 /// Create a stream for writing to an SFTP resource.
 /// </summary>
 /// <param name="sftp"></param>
 /// <param name="channel"></param>
 /// <param name="handle"></param>
 internal SftpStream(Sftp sftp, byte[] handle)
     : base()
 {
     this.sftp   = sftp;
     this.handle = handle;
     this.reader = false;
 }
Ejemplo n.º 7
0
        /* the only function in the class that delete file on the sftp server */
        public static void Delete(string host, string username, string password, string fileName)
        {
            JSch js = new JSch();

            // declare sftp connection
            Sftp sftp = new Sftp(host, username, password);

            sftp.Connect();

            // Create a session with SFTP credentials
            Session session = js.getSession(sftp.Username, sftp.Host);

            // Get a UserInfo object
            UserInfo ui = new UInfo(sftp.Password);

            // Pass user info to session
            session.setUserInfo(ui);

            // Open the session
            session.connect();

            // Tell it is an SFTP
            Channel     channel = session.openChannel("sftp");
            ChannelSftp cSftp   = (ChannelSftp)channel;

            cSftp.connect();

            // Delete the file
            cSftp.rm(fileName);

            // disconnection
            channel.disconnect();
            cSftp.exit();
            sftp.Close();
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            Sftp sftp = new Sftp(SFTPConnectSample.Properties.Settings.Default.HostName, SFTPConnectSample.Properties.Settings.Default.UserName, SFTPConnectSample.Properties.Settings.Default.Password);

            sftp.Connect();
            #region Require if you want to delete Files
            JSch    objjsh  = new JSch();
            Session session = objjsh.getSession(SFTPConnectSample.Properties.Settings.Default.UserName, SFTPConnectSample.Properties.Settings.Default.HostName);
            // Get a UserInfo object
            UserInfo ui = new UInfo(SFTPConnectSample.Properties.Settings.Default.Password);;
            // Pass user info to session
            session.setUserInfo(ui);
            // Open the session
            session.connect();
            Channel     channel = session.openChannel("sftp");
            ChannelSftp cSftp   = (ChannelSftp)channel;
            cSftp.connect();
            #endregion
            ArrayList res = sftp.GetFileList(SFTPConnectSample.Properties.Settings.Default.FromPath + "*.xml");
            foreach (var item in res)
            {
                if (item.ToString() != "." && item.ToString() != "..")
                {
                    //File Copy from Remote
                    sftp.Get(SFTPConnectSample.Properties.Settings.Default.FromPath + item, Path.Combine(Application.StartupPath, SFTPConnectSample.Properties.Settings.Default.DirectoryPath + "/" + item));
                    //File Delete from Remote
                    cSftp.rm(SFTPConnectSample.Properties.Settings.Default.FromPath + item);
                    //Upload File
                    sftp.Put(Path.Combine(Path.Combine(Application.StartupPath, "XMLFiles"), item.ToString()), SFTPConnectSample.Properties.Settings.Default.ToPath + item);
                }
            }
            channel.disconnect();
            cSftp.exit();
            sftp.Close();
        }
Ejemplo n.º 9
0
        private async Task <Message> ReadAsync(string path, string fileName)
        {
            var stream   = new MemoryStream();
            var fullPath = Path.Combine(path, fileName).Replace('\\', '/');

            using (var sftpClient = new Sftp())
            {
                sftpClient.TransferType = _transferType;

                await sftpClient.ConnectAsync(_serverAddress, _port);

                await sftpClient.LoginAsync(_userName, _password);

                await sftpClient.GetFileAsync(fullPath, stream);

                await sftpClient.DisconnectAsync();
            }

            // Rewind the stream:
            stream.Position = 0;

            return(new Message {
                ContentStream = stream
            });
        }
Ejemplo n.º 10
0
        public static bool ValidateClinicSftpDetails(List <ProgramProperty> listPropsForClinic, bool doTestConnection = true)
        {
            //No need to check RemotingRole;no call to db.
            string sftpAddress = listPropsForClinic.Find(x => x.PropertyDesc == "SftpServerAddress")?.PropertyValue;
            int    sftpPort;

            if (!int.TryParse(listPropsForClinic.Find(x => x.PropertyDesc == "SftpServerPort")?.PropertyValue, out sftpPort) ||
                sftpPort < ushort.MinValue ||              //0
                sftpPort > ushort.MaxValue) //65,535
            {
                sftpPort = 22;              //default to port 22
            }
            string userName     = listPropsForClinic.Find(x => x.PropertyDesc == "SftpUsername")?.PropertyValue;
            string userPassword = listPropsForClinic.Find(x => x.PropertyDesc == "SftpPassword")?.PropertyValue;

            if (string.IsNullOrWhiteSpace(sftpAddress) || string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(userPassword))
            {
                return(false);
            }
            if (doTestConnection)
            {
                return(Sftp.IsConnectionValid(sftpAddress, userName, userPassword, sftpPort));
            }
            return(true);
        }
Ejemplo n.º 11
0
        private static bool ValidarConexionSftp()
        {
            Sftp client = new Sftp(sftpServidor, sftpUsuario, sftpPassword);

            _log.DebugFormat("Validando conexion Sftp. Servidor:{0}, Usuario:{1}, Password: {2}", sftpServidor, sftpUsuario, sftpPassword);

            try
            {
                client.Connect();

                if (client.Connected)
                {
                    _log.DebugFormat("Conexion exitosa");
                    return(true);
                }
                else
                {
                    _log.DebugFormat("No se pudo establecer la conexion");
                }
            }catch (Exception ex)
            {
                _log.Error(ex.Message);
            }

            return(false);
        }
Ejemplo n.º 12
0
        /* constructor that initialize folders for xml feed */
        public ShopCa()
        {
            #region Folder Check
            // check and generate folders
            if (!Directory.Exists(rootDir))
            {
                Directory.CreateDirectory(rootDir);
            }

            newOrderDir = rootDir + "\\ShopCaNewOrders";
            if (!Directory.Exists(newOrderDir))
            {
                Directory.CreateDirectory(newOrderDir);
            }

            completeOrderDir = rootDir + "\\ShopCaCompleteOrders";
            if (!Directory.Exists(completeOrderDir))
            {
                Directory.CreateDirectory(completeOrderDir);
            }
            #endregion

            // get credentials for shop.ca sftp log on and initialize the field
            using (SqlConnection connection = new SqlConnection(Credentials.AscmCon))
            {
                SqlCommand command = new SqlCommand("SELECT Field1_Value, Username, Password From ASCM_Credentials WHERE Source='Shop.ca - SFTP'", connection);
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                reader.Read();

                // initialize Sftp
                sftp = new Sftp(reader.GetString(0), reader.GetString(1), reader.GetString(2));
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Upload a file to destinationDirectory of Exact targets Sftp location
        /// </summary>
        /// <param name="pathOfFileToBeTransfered"></param>
        /// <param name="address"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <param name="destinationDirectory"></param>
        public void UploadFile(string pathOfFileToBeTransfered, string address, string username, string password, string destinationDirectory)
        {
            Sftp fileTransfer = null;

            if (string.IsNullOrWhiteSpace(pathOfFileToBeTransfered))
            {
                throw new ArgumentNullException("pathOfFileToBeTransfered");
            }

            try
            {
                SshParameters connectionParameters = new SshParameters(address, username, password);
                using (fileTransfer = new Sftp(connectionParameters))
                {
                    fileTransfer.Connect();
                    fileTransfer.SetBinaryMode();
                    fileTransfer.RemoteDir = destinationDirectory;
                    fileTransfer.Upload(pathOfFileToBeTransfered);
                }

                return;
            }
            finally
            {
                if (fileTransfer != null && fileTransfer.IsConnected)
                {
                    fileTransfer.Disconnect();
                }

                fileTransfer = null;
            }
        }
Ejemplo n.º 14
0
        private void DownloadAndStoreFile(ConversionStartResult conversionResult, DirectoryInfo targetFolder)
        {
            Licensing.Key = DocumentConverterSettings.Default.SftpLicenseKey;

            try
            {
                using (var client = new Sftp())
                {
                    client.Connect(conversionResult.UploadUrl, conversionResult.Port);
                    client.Login(conversionResult.User, conversionResult.Password);

                    var remotePath = $"{client.GetCurrentDirectory()}{conversionResult.ConvertedFileName}";
                    var targetPath = Path.Combine(targetFolder.FullName, $"{conversionResult.ConvertedFileName}");

                    if (!client.FileExists(remotePath))
                    {
                        Console.WriteLine($"ERROR: File {conversionResult.ConvertedFileName} not found on SFTP server.");
                    }

                    var length = client.GetFile(remotePath, targetPath);
                    Console.WriteLine($"Converted file {targetPath} and downloaded {length} bytes");
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
Ejemplo n.º 15
0
        private async Task UploadFile(JobInitResult jobInitResult, FileInfo toBeConverted)
        {
            Licensing.Key = sftpLicenseKey;
            using (var client = new Sftp())
            {
                await client.ConnectAsync(jobInitResult.UploadUrl, jobInitResult.Port);

                await client.LoginAsync(jobInitResult.User, jobInitResult.Password);

                var uploadName = $"{client.GetCurrentDirectory()}{toBeConverted.Name}";
                Log.Verbose("Uploading file {FullName} to {UploadName}", toBeConverted.FullName, uploadName);
                if (toBeConverted.Exists)
                {
                    await client.PutFileAsync(toBeConverted.FullName, uploadName);

                    Log.Verbose("Upload successfull");
                }
                else
                {
                    Log.Verbose("File {FullName} does not exist, or cannot be accessed.", toBeConverted.FullName);
                    throw new FileNotFoundException("File could not be uploaded, because source file is not accessible or cannot be found",
                                                    toBeConverted.FullName);
                }
            }
        }
Ejemplo n.º 16
0
 public void CanUploadToRootDir()
 {
     using (var file = new DummyFile(1024 * 1024 * 3))
     {
         Sftp.UploadFile(Cs, file.FileInfo.FullName, true);
     }
 }
Ejemplo n.º 17
0
        private void efwSimpleButton2_Click(object sender, EventArgs e)
        {
            try
            {
                string sftpURL       = "14.63.165.36";
                string sUserName     = "******";
                string sPassword     = "******";
                int    nPort         = 22023;
                string sftpDirectory = "/domalifefiles/files/product/domamall";

                // 저장 경로

                string LocalDirectory = "D:\\temp";  //Local directory from where the files will be uploaded
                string FileName       = "test1.jpg"; //File name, which one will be uploaded

                Sftp sSftp = new Sftp(sftpURL, sUserName, sPassword);

                sSftp.Connect(nPort);
                // sSftp.Mkdir("/domalifefiles/files/product/domamall/temp");
                sSftp.Put(LocalDirectory + "/" + FileName, sftpDirectory + "/" + FileName);
                sSftp.Close();
            }
            catch (Exception ex)
            {
                return;
            }
        }
Ejemplo n.º 18
0
        public async Task <bool> SaveToCache(IBus bus, CacheRetentionCategory retentionCategory, string file)
        {
            if (!File.Exists(file))
            {
                throw new FileNotFoundException("Unable to upload file to cache because file was not found", file);
            }

            var cacheConnectionInfoRequest = new CacheConnectionInfoRequest();
            var requestClient =
                CreateRequestClient <CacheConnectionInfoRequest, CacheConnectionInfoResponse>(bus, BusConstants.CacheConnectionInfoRequestQueue);

            var response = await requestClient.Request(cacheConnectionInfoRequest);


            try
            {
                using (var client = new Sftp())
                {
                    client.Connect(response.Machine, (int)response.Port);
                    Log.Information("connected to {host}:{port}", response.Machine, response.Port);

                    client.Login(retentionCategory.ToString(), response.Password);

                    Log.Information("{username} logged in successfully ", retentionCategory);
                    client.Upload(file, "/", TraversalMode.NonRecursive, TransferMethod.Copy, ActionOnExistingFiles.OverwriteAll);
                    return(true);
                }
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Unexpexted error while uploading to cache");
            }

            return(false);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// 登录到Sftp服务器
        /// </summary>
        /// <param name="config">Sftp参数</param>
        /// <returns></returns>
        public OperationReturn LogOn(SftpHelperConfig config)
        {
            OperationReturn optReturn = new OperationReturn();

            optReturn.Result = true;
            optReturn.Code   = 0;
            try
            {
                if (mSftp != null)
                {
                    try
                    {
                        if (mSftp.Connected)
                        {
                            mSftp.Connected = false;
                        }
                        mSftp = null;
                    }
                    catch { }
                }
                mSftp = new Sftp();
                mSftp.OnSSHServerAuthentication += (s, se) => se.Accept = true;
                mSftp.SSHHost = config.ServerHost;
                mSftp.SSHPort = config.ServerPort;
                mSftp.SSHUser = config.LoginUser;
                switch (config.AuthType)
                {
                case 1:
                    mSftp.SSHAuthMode = SftpSSHAuthModes.amPassword;
                    mSftp.SSHPassword = config.LoginPassword;
                    break;

                case 2:
                    mSftp.SSHAuthMode = SftpSSHAuthModes.amPublicKey;
                    mSftp.SSHCert     = new Certificate(CertStoreTypes.cstPFXFile, config.CertFile, config.CertPassword, config.CertPassword);
                    break;

                case 3:
                    mSftp.SSHAuthMode = SftpSSHAuthModes.amMultiFactor;
                    mSftp.SSHPassword = config.LoginPassword;
                    mSftp.SSHCert     = new Certificate(CertStoreTypes.cstPFXFile, config.CertFile, config.CertPassword, config.CertSubject);
                    break;

                default:
                    optReturn.Result  = false;
                    optReturn.Code    = Defines.RET_CONFIG_INVALID;
                    optReturn.Message = string.Format("Auth type not support.\t{0}", config.AuthType);
                    return(optReturn);
                }
                mSftp.SSHLogon(config.ServerHost, config.ServerPort);
                return(optReturn);
            }
            catch (Exception ex)
            {
                optReturn.Result  = false;
                optReturn.Code    = Defines.RET_FAIL;
                optReturn.Message = ex.Message;
                return(optReturn);
            }
        }
Ejemplo n.º 20
0
        public void ShouldSetSshUserName()
        {
            string un  = "userTest";
            Sftp   ssh = Sftp.Server("localhost").UserName(un);

            Expect.AreEqual(ssh.Config.UserName, un, "UserName was not set properly");
        }
Ejemplo n.º 21
0
 public void CanUploadToSubSubDir()
 {
     using (var file = new DummyFile(1024 * 1024 * 3))
     {
         Sftp.UploadFile(Cs, file.FileInfo.FullName, true, "a/b/c");
     }
 }
Ejemplo n.º 22
0
        private void Form1_Load(object sender, EventArgs e)
        {
            /*
             * // Get a UserInfo object
             * UserInfo ui = new UInfo(SFTPConnectSample.Properties.Settings.Default.Password); ;
             * // Pass user info to session
             * session.setUserInfo(ui);
             * // Open the session
             * session.connect();
             * Channel channel = session.openChannel("sftp");
             * ChannelSftp cSftp = (ChannelSftp)channel;
             * cSftp.connect();
             */
            try
            {
                sftp = new Sftp(SFTPshare.Properties.Settings.Default.HostName, SFTPshare.Properties.Settings.Default.UserName, SFTPshare.Properties.Settings.Default.Password);
            }
            catch (Exception) { MessageBox.Show("Error instantiating sftp"); }
            try {
                sftp.AddIdentityFile(privateKeyPath);
            }
            catch (Exception) { MessageBox.Show("Error connecting with private key"); }
            try {
                sftp.Connect();
            }
            catch (Exception) { }

            //ArrayList res = sftp.GetFileList(".");



            //ArrayList Newres = sftp.GetFileList(".");
            //filesRecap = sftp.GetFileList(".");
        }
Ejemplo n.º 23
0
        public static List <string> SFTPScanDirs(Sftp sftpHandler, string initialPath, int recursionLevel)
        {
            var outListFiles = new List <string>();
            var pathElements = initialPath.Split('/');
            var dirpath      = initialPath.Substring(0, initialPath.LastIndexOf('/'));

            if (string.IsNullOrWhiteSpace(dirpath))
            {
                dirpath += "/";
            }
            var pattern = pathElements[pathElements.Length - 1];

            var bHasPattern = pattern.Contains("*") || pattern.Contains("?");

            if (!bHasPattern)
            {
                dirpath += pattern;
            }

            SFTPScanDirs(sftpHandler, dirpath, recursionLevel, ref outListFiles);

            return((bHasPattern)
                        ? outListFiles.LikeDir(pattern)
                        : outListFiles);
        }
Ejemplo n.º 24
0
        /// <summary>
        /// 推至遠程
        /// </summary>
        private void ToPut()
        {
            try
            {
                //fortify漏洞-----------------------------------------------add by bruce 20131220
                _password = AntiXSS.GetSafeHtmlFragment(_password);
                //fortify漏洞-----------------------------------------------add by bruce 20131220
                //開始進行SFTP程序
                _sftp = new Sftp(_hostName, _userName, _password);


                _sftp.Connect(_port);
                System.Threading.Thread.Sleep(3000);
                _sftp.Put(_fromFilePath, _toFilePath);
                System.Threading.Thread.Sleep(3000);
                _sftp.Close();

                //write log
                string msg = "";
                msg = "遠程" + _hostName + _toFilePath + ", 檔案已產生。";
                Console.WriteLine(msg);
                LogController.WriteLog("SimpleSftp.Put", msg);
            }
            catch (Exception ex)
            {
                LogController.WriteLog("SimpleSftp.Put", ex.ToString());
                throw ex;
            }
        }
Ejemplo n.º 25
0
        public async Task <List <ReceiveFileResult> > ReceiveFilesAsync(string path, string fileMask, bool receiveMultiple = true)
        {
            var handledFiles = new List <ReceiveFileResult>();

            using (var client = new Sftp())
            {
                client.TransferType = _transferType;

                await client.ConnectAsync(_serverAddress, _port, SslMode.None);

                await client.LoginAsync(_userName, _password);

                // Get files from the specified path using the given file name mask:
                var items = await client.GetListAsync(path);

                var files = items.GetFiles(fileMask);

                // Ignore files that are already transfering / failed and sort the remaining by filename
                var sortedFiles = files.Where(f => !(f.StartsWith(".") && f.EndsWith(".tmp"))).OrderBy(f => f).ToList();

                if (!receiveMultiple && (sortedFiles.Count > 1))
                {
                    // only process the first file
                    var singleFile = sortedFiles.First();
                    sortedFiles = new List <string> {
                        singleFile
                    };
                }


                // Try to rename the files with temporary names:
                foreach (var file in sortedFiles)
                {
                    var result = new ReceiveFileResult
                    {
                        FileName     = file,
                        TempFileName = $".{Guid.NewGuid()}.tmp",
                        Path         = path,
                        IsError      = false
                    };

                    try
                    {
                        await client.RenameAsync(Path.Combine(path, result.FileName).Replace('\\', '/'), Path.Combine(path, result.TempFileName).Replace('\\', '/'));
                    }
                    catch (Exception ex)
                    {
                        result.IsError = true;
                        result.Message = $"Renaming the file '{result.FileName}' to '{result.TempFileName}' failed: {ex.Message}.";
                    }

                    handledFiles.Add(result);
                }

                await client.DisconnectAsync();
            }

            return(handledFiles);
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Uploads the file FTP.
        /// </summary>
        /// <param name="passKey">The pass key.</param>
        /// <param name="server">The server.</param>
        /// <param name="username">The username.</param>
        /// <param name="password">The password.</param>
        /// <param name="claim">The claim.</param>
        /// <param name="folder">The folder.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <returns>The <see cref="bool"/>.</returns>
        public bool UploadFileFTP(string passKey, string server, string username, string password, byte[] claim, string folder, string fileName)
        {
            if (!ValidationAndEncryptDecrypt.ValidateKey(passKey))
            {
                return(false);
            }

            string tempDir = "C:\\DrScribe\\GatewayEDI\\" + username + "\\claims\\";

            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }

            try
            {
                var arraySize = claim.GetUpperBound(0);

                try
                {
                    if (File.Exists(tempDir + "\\" + fileName.Replace(".tmp", ".txt")))
                    {
                        File.Delete(tempDir + "\\" + fileName.Replace(".tmp", ".txt"));
                    }
                }
                catch (Exception e)
                {
                    WriteEventLogEntry(e);
                }

                FileStream fs = new FileStream(tempDir + "\\" + fileName.Replace(".tmp", ".txt"), FileMode.OpenOrCreate, FileAccess.Write);
                fs.Write(claim, 0, arraySize);
                fs.Close();

                SshTransferProtocolBase sshCp = new Sftp(server, username);
                sshCp.Password = password;

                sshCp.Connect();

                string serverFile = fileName.Replace(".tmp", ".txt");

                if (folder != string.Empty)
                {
                    serverFile = "/" + folder + "/" + serverFile;
                }

                sshCp.Put(tempDir + "\\" + fileName.Replace(".tmp", ".txt"), serverFile);

                sshCp.Close();
                sshCp.Destroy();

                File.Delete(tempDir + fileName.Replace(".tmp", ".txt"));
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Ejemplo n.º 27
0
 public void CanUpload2FilesToRootDir()
 {
     using (var file1 = new DummyFile(1024 * 1024 * 3))
         using (var file2 = new DummyFile(1024 * 1024 * 3))
         {
             Sftp.UploadFiles(Cs, file1.FileInfo.DirectoryName, SearchPattern, true);
         }
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Creates a stream for reading from an SFTP resource.
 /// </summary>
 /// <param name="sftp"></param>
 /// <param name="channel"></param>
 /// <param name="handle"></param>
 /// <param name="length"></param>
 public SftpStream(Sftp sftp, byte[] handle, ulong length)
     : base()
 {
     this.sftp    = sftp;
     this.handle  = handle;
     this.length2 = (long)(this.length = length);
     this.reader  = true;
 }
Ejemplo n.º 29
0
        static void Main(string[] args)
        {
            Sftp sftp = new Sftp("[SERVER]", "[USERNAME]", string.Empty);

            sftp.AddIdentityFile("[Path to Private kEY]");
            sftp.Connect();
            sftp.Put(@"D:\temp\blog\feed.csv", "[PATH OF FILE ON SERVER]");
            sftp.Delete("[PATH OF FILE ON SERVER]");
        }
Ejemplo n.º 30
0
        static void Main(string[] args)
        {
            Sftp sftp = new Sftp();

            sftp.host            = "12.3.456.7";
            sftp.keyFilelocation = @"C:\SFTP\arquivo Chave";
            sftp.DownloadAll(@"/Arquivos/Files", @"/ArquivosLidos/Files", @"C:\SFTP\download\");
            sftp.uploadFile(@"C:\SFTP\upload\arquivo.txt", @"/Arquivos/UploadFiles/");
        }
Ejemplo n.º 31
0
        public SFTPUtil(String host, String user, String pass)
        {
            this.host = host;
            this.user = user;
            this.pass = pass;

            sftp = new Sftp(host, user, pass);

            sftp.Connect();
        }
Ejemplo n.º 32
0
 public SftpClient()
 {
     _sftpClient = new Sftp();
     _sftpClient.OnSSHServerAuthentication += sftp_OnSSHServerAuthentication;
 }