CreateDirectory() public method

Creates remote directory specified by path.
is null or contains only whitespace characters. Client is not connected. Permission to create the directory was denied by the remote host. -or- A SSH command was denied by the server. A SSH error where is the message from the remote host. The method was called after the client was disposed.
public CreateDirectory ( string path ) : void
path string Directory path to create.
return void
 public bool UploadFile(string filePath)
 {
     ConnectionInfo connectionInfo = new PasswordConnectionInfo(_address, ConstFields.SFTP_PORT, _username, _password);
     try
     {
         using (var sftp = new SftpClient(connectionInfo))
         {
             sftp.Connect();
             using (var file = File.OpenRead(filePath))
             {
                 if (!sftp.Exists(ConstFields.TEMP_PRINT_DIRECTORY))
                 {
                     sftp.CreateDirectory(ConstFields.TEMP_PRINT_DIRECTORY);
                 }
                 sftp.ChangeDirectory(ConstFields.TEMP_PRINT_DIRECTORY);
                 string filename = Path.GetFileName(filePath);
                 sftp.UploadFile(file, filename);
             }
             sftp.Disconnect();
         }
     }
     catch (Renci.SshNet.Common.SshConnectionException)
     {
         Console.WriteLine("Cannot connect to the server.");
         return false;
     }
     catch (System.Net.Sockets.SocketException)
     {
         Console.WriteLine("Unable to establish the socket.");
         return false;
     }
     catch (Renci.SshNet.Common.SshAuthenticationException)
     {
         Console.WriteLine("Authentication of SSH session failed.");
         return false;
     }
     return true;
 }
Ejemplo n.º 2
2
        private static void CreateDirectoriesRecursively(string directory, SftpClient sftp)
        {
            if (sftp.Exists(directory) == false)
            {
                // try creating one above, in case we need it:
                var directoryAbove = FlatRedBall.IO.FileManager.GetDirectory(directory, FlatRedBall.IO.RelativeType.Relative);

                CreateDirectoriesRecursively(directoryAbove, sftp);

                sftp.CreateDirectory(directory);
            }
        }
Ejemplo n.º 3
2
        private void Execute()
        {
            var keyPath = textBoxFile.Text;
            var host = textBoxHost.Text;
            var user = textBoxUser.Text;
            var pass = textBoxPass.Text;

            Action _execute = () =>
            {
                try
                {
                    //Read Key
                    Status("opening key");
                    FileStream file = File.OpenRead(keyPath);

                    //Connect to SFTP
                    Status("sftp connecting");
                    SftpClient sftp = new SftpClient(host, user, pass);
                    sftp.Connect();

                    //users home directory
                    string homepath = "/home/" + user + "/";
                    if (user == "root")
                    {
                        homepath = "/root/";
                    }

                    //Find authorized keys
                    string authKeys = homepath + ".ssh/authorized_keys";
                    if (!sftp.Exists(authKeys))
                    {
                        Status("creating");
                        if (!sftp.Exists(homepath + ".ssh"))
                            sftp.CreateDirectory(homepath + ".ssh");
                        sftp.Create(authKeys);
                    }

                    //Download
                    Status("downloading");
                    Stream stream = new MemoryStream();
                    sftp.DownloadFile(authKeys, stream);
                    Status("downloaded");

                    //Read
                    byte[] buffer = new byte[10240]; //No key should be this large
                    int length = file.Read(buffer, 0, buffer.Length);

                    //Validate
                    String strKey;
                    if (length < 20)
                    {
                        Status("Invalid Key (Length)");
                        return;
                    }
                    if (buffer[0] == (byte) 's' && buffer[1] == (byte) 's' && buffer[2] == (byte) 'h' &&
                        buffer[3] == (byte) '-' && buffer[4] == (byte) 'r' && buffer[5] == (byte) 's' &&
                        buffer[6] == (byte) 'a')
                    {
                        strKey = Encoding.ASCII.GetString(buffer, 0, length).Trim();
                    }
                    else
                    {
                        Status("Invalid Key (Format)");
                        return;
                    }

                    stream.Seek(0, SeekOrigin.Begin);
                    StreamReader reader = new StreamReader(stream);

                    //Check for key that might already exist
                    while (!reader.EndOfStream)
                    {
                        var line = reader.ReadLine().Trim();
                        if (line == strKey)
                        {
                            Status("key already exists");
                            return;
                        }
                    }

                    //Check new line
                    if (stream.Length != 0)
                    {
                        stream.Seek(0, SeekOrigin.End);
                        stream.WriteByte((byte) '\n');
                    }
                    else
                    {
                        stream.Seek(0, SeekOrigin.End);
                    }

                    //Append
                    Status("appending");
                    stream.Write(buffer, 0, length);

                    //Upload
                    Status("uploading");
                    stream.Seek(0, SeekOrigin.Begin);
                    sftp.UploadFile(stream, authKeys);
                    Status("done");

                    //Save key path
                    Settings.Default.KeyPath = textBoxFile.Text;
                    Settings.Default.Save();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            };

            Thread thread = new Thread(new ThreadStart(_execute));
            thread.Start();
        }
Ejemplo n.º 4
0
        private void CreateDirectoryRecursively(string path)
        {
            var current = "";

            if (path[0] == '/')
            {
                path = path.Substring(1);
            }

            var isFirst = true;

            while (!string.IsNullOrEmpty(path))
            {
                var p = path.IndexOf('/');
                if (isFirst)
                {
                    isFirst = false;
                }
                else
                {
                    current += '/';
                }

                if (p >= 0)
                {
                    current += path.Substring(0, p);
                    path     = path.Substring(p + 1);
                }
                else
                {
                    current += path;
                    path     = "";
                }

                try
                {
                    var attributes = _sftpClient.GetAttributes(current);
                    if (!attributes.IsDirectory)
                    {
                        throw new Exception("not directory");
                    }
                }
                catch (SftpPathNotFoundException)
                {
                    _sftpClient.CreateDirectory(current);
                }
            }
        }
Ejemplo n.º 5
0
        protected override async Task CreateDirectory(string cpath)
        {
            var caughtException = default(Exception);
            await Task.Run(() =>
            {
                try
                {
                    _sftpc.CreateDirectory(cpath);
                }
                catch (Exception ex)
                {
                    ex.LogException();
                    caughtException = ex;
                }
            });

            if (caughtException != default(Exception))
            {
                throw caughtException;
            }
        }
Ejemplo n.º 6
0
        private void CreateServerDirectoryIfItDoesntExist(string serverDestinationPath)
        {
            bool serverDirectoryExists = _sftpClient.Exists(serverDestinationPath);

            if (serverDirectoryExists)
            {
                _logger.LogInformation($"The server directory '{serverDestinationPath}' already exists, will upload into it.");
            }
            else
            {
                _logger.LogInformation($"The server directory '{serverDestinationPath}' will be created.");
                string[] directories = serverDestinationPath.Split('/');
                for (int i = 0; i < directories.Length; i++)
                {
                    string dirName = string.Join("/", directories, 0, i + 1);
                    if (!string.IsNullOrWhiteSpace(dirName) && !_sftpClient.Exists(dirName))
                    {
                        System.Diagnostics.Debug.WriteLine($"Creating dir {dirName} on the server.");
                        _sftpClient.CreateDirectory(dirName);
                    }
                }
            }
        }
Ejemplo n.º 7
0
 private void CreateDirectory(SftpClient client, string sourceFolderName, string destination)
 {
     var arr = sourceFolderName.Split(DeployUtil.TransferFolder.ToCharArray());
     var relativeFolder = arr.Last();
     var destinationPath = Path.Combine(destination, relativeFolder);
     if (!client.Exists(destinationPath))
     {
         client.CreateDirectory(destination);
         client.ChangeDirectory(destination);
     }
 }
Ejemplo n.º 8
0
        private static void Main(string[] args)
        {
            string shufSharp = "ShufflySharp";

            var projs = new[] {
                                      shufSharp + @"\Libraries\CommonLibraries\",
                                      shufSharp + @"\Libraries\CommonShuffleLibrary\",
                                      shufSharp + @"\Libraries\ShuffleGameLibrary\",
                                      shufSharp + @"\Libraries\NodeLibraries\",
                                      shufSharp + @"\Servers\ServerManager\", 
                                      shufSharp + @"\Models\",
                                      shufSharp + @"\Client\",
                                      shufSharp + @"\ClientLibs\",
                                      shufSharp + @"\ServerSlammer\",
                              };
            var pre = Directory.GetCurrentDirectory() + @"\..\..\..\..\..\";

            foreach (var proj in projs) {
#if DEBUG
                var from = pre + proj + @"\bin\debug\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
#else
                var from = pre + proj + @"\bin\release\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
#endif
                var to = pre + shufSharp + @"\output\" + proj.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";

                if (File.Exists(to)) tryDelete(to);
                tryCopy(from, to);
            }

            //client happens in buildsite.cs
            var depends = new Dictionary<string, Application>(); 
            depends.Add(shufSharp + @"\Servers\ServerManager\",
                        new Application(true,
                                        new List<string> {
                                                                 @"./NodeLibraries.js",
                                                                 @"./CommonLibraries.js",
                                                                 @"./CommonShuffleLibrary.js",
                                                                 @"./ShuffleGameLibrary.js",
                                                                 @"./Models.js",
                                                                 @"./RawDeflate.js",
                                                         })); 


            depends.Add(shufSharp + @"\Libraries\CommonShuffleLibrary\",
                        new Application(false,
                                        new List<string> {
                                                                 @"./NodeLibraries.js",
                                                         }));
            depends.Add(shufSharp + @"\Libraries\NodeLibraries\", new Application(true, new List<string> {}));
            depends.Add(shufSharp + @"\Libraries\CommonLibraries\", new Application(false, new List<string> {}));
            depends.Add(shufSharp + @"\ClientLibs\", new Application(false, new List<string> {}));
            depends.Add(shufSharp + @"\ServerSlammer\",
                        new Application(true,
                                        new List<string> {
                                                                 @"./NodeLibraries.js",
                                                                 @"./Models.js",
                                                                 @"./ClientLibs.js",
                                                         }));
            depends.Add(shufSharp + @"\Models\", new Application(false, new List<string> {}));
            depends.Add(shufSharp + @"\Libraries\ShuffleGameLibrary\", new Application(false, new List<string> {}));
            depends.Add(shufSharp + @"\Client\",
                        new Application(false,
                                        new List<string> {}));

#if FTP
            string loc = ConfigurationSettings.AppSettings["web-ftpdir"];
            Console.WriteLine("connecting ftp");
            /*   Ftp webftp = new Ftp();
            webftp.Connect(ConfigurationSettings.AppSettings["web-ftpurl"]);
            webftp.Login(ConfigurationSettings.AppSettings["web-ftpusername"], ConfigurationSettings.AppSettings["web-ftppassword"]);

            Console.WriteLine("connected");

            webftp.Progress += (e, c) =>
            {
                var left = Console.CursorLeft;
                var top = Console.CursorTop;

                Console.SetCursorPosition(65, 5);
                Console.Write("|");

                for (int i = 0; i < c.Percentage / 10; i++)
                {
                    Console.Write("=");
                }
                for (int i = (int)(c.Percentage / 10); i < 10; i++)
                {
                    Console.Write("-");
                }
                Console.Write("|");

                Console.Write(c.Percentage + "  %  ");
                Console.WriteLine();
                Console.SetCursorPosition(left, top);
            };
*/
            string serverloc = ConfigurationSettings.AppSettings["server-ftpdir"];
            string serverloc2 = ConfigurationSettings.AppSettings["server-web-ftpdir"];
            Console.WriteLine("connecting server ftp");
            SftpClient client = new SftpClient(ConfigurationSettings.AppSettings["server-ftpurl"], ConfigurationSettings.AppSettings["server-ftpusername"], ConfigurationSettings.AppSettings["server-ftppassword"]);
            client.Connect();

            Console.WriteLine("server connected");

#endif

            foreach (var depend in depends) {
                var to = pre + shufSharp + @"\output\" + depend.Key.Split(new[] {"\\"}, StringSplitOptions.RemoveEmptyEntries).Last() + ".js";
                var output = "";

                Application application = depend.Value;

                if (application.Node) {
                    output += "require('./mscorlib.js');";
                    output += "EventEmitter= require('events.js').EventEmitter;";
                } else {
                    //output += "require('./mscorlib.debug.js');";
                }

                foreach (var depe in application.IncludesAfter) {
                    output += string.Format("require('{0}');", depe);
                }

                var lines = new List<string>();
                lines.Add(output);
                lines.AddRange(File.ReadAllLines(to));

                //      lines.Add(application.After);

                File.WriteAllLines(to, lines);
                var name = to.Split(new char[] {'\\'}, StringSplitOptions.RemoveEmptyEntries).Last();

#if FTP

                long length = new FileInfo(to).Length;
                /*       if (!webftp.FileExists(loc + name) || webftp.GetFileSize(loc + name) != length)
                {
                    Console.WriteLine("ftp start " + length.ToString("N0"));
                    webftp.Upload(loc + name, to);
                    Console.WriteLine("ftp complete " + to);
                }
*/
                if (true || !client.Exists(serverloc + name) || client.GetAttributes(serverloc + name).Size != length) {
                    Console.WriteLine("server ftp start " + length.ToString("N0"));
                    var fileStream = new FileInfo(to).OpenRead();
                    client.UploadFile(fileStream, serverloc + name, true);
                    fileStream.Close();
                    Console.WriteLine("server ftp complete " + to);
                }
                if (true || !client.Exists(serverloc2 + name) || client.GetAttributes(serverloc2 + name).Size != length) {
                    Console.WriteLine("server ftp start " + length.ToString("N0"));
                    var fileStream = new FileInfo(to).OpenRead();
                    client.UploadFile(fileStream, serverloc2 + name, true);
                    fileStream.Close();
                    Console.WriteLine("server ftp complete " + to);
                }
#endif
                if (File.Exists(@"C:\code\node\" + name) && /*new FileInfo(@"C:\code\node\" + name).Length != new FileInfo(to).Length*/ true) {
                    tryDelete(@"C:\code\node\" + name);
                    tryCopy(to, @"C:\code\node\" + name);
                }
            }

            foreach (var d in Directory.GetDirectories(pre + shufSharp + @"\ShuffleGames\")) {
                string game = d.Split('\\').Last();
                var to = pre + shufSharp + @"\output\Games\" + game;
                if (!Directory.Exists(to))

                    Directory.CreateDirectory(to);
                if (d.EndsWith("bin") || d.EndsWith("obj"))
                    continue;
                File.WriteAllText(to + @"\app.js", File.ReadAllText(d + @"\app.js"));

#if FTP

                Console.WriteLine("server ftp start ");

                var fileStream = new FileInfo(to + @"\app.js").OpenRead();
                if (!client.Exists(serverloc + string.Format("Games/{0}", game)))
                    client.CreateDirectory(serverloc + string.Format("Games/{0}", game));
                client.UploadFile(fileStream, serverloc + string.Format("Games/{0}/app.js", game), true);
                fileStream.Close();

                Console.WriteLine("server ftp complete " + to);
#endif
            }
        }
Ejemplo n.º 9
0
 /// <summary>
 /// Sync output of current compilation to <paramref name="dir"/>
 /// </summary>
 /// <param name="dir"></param>
 /// <returns></returns>
 private bool SyncTo(string dir)
 {
     // Copy files over
     using (var sftp = new SftpClient(Machine, Port, Username, Password))
     {
         sftp.Connect();
         if (!sftp.IsConnected)
         {
             return false;
         }
         // Perform recursive copy of all the folders under `dir`. This is required
         // as the sftp client only synchronize directories at their level only, no
         // subdirectory.
         var dirs = new Queue<DirectoryInfo>();
         dirs.Enqueue(new DirectoryInfo(dir));
         var parentPath = new UDirectory(dir);
         while (dirs.Count != 0)
         {
             var currentDir = dirs.Dequeue();
             var currentPath = new UDirectory(currentDir.FullName);
             foreach (var subdir in currentDir.EnumerateDirectories())
             {
                 dirs.Enqueue(subdir);
             }
             // Get the destination path by adding to `Location` the relative path of `dir` to `currentDir`.
             var destination = UPath.Combine(new UDirectory(Location.ItemSpec), currentPath.MakeRelative(parentPath));
             Log.LogMessage("Synchronizing " + currentPath + " with " + destination.FullPath);
             // Try to create a remote directory. If it throws an exception, we will assume
             // for now that the directory already exists. See https://github.com/sshnet/SSH.NET/issues/25
             try
             {
                 sftp.CreateDirectory(destination.FullPath);
                 Log.LogMessage("Creating remote directory " + destination.FullPath);
             }
             catch (SshException)
             {
                 // Do nothing, as this is when the directory already exists
             }
             // Synchronize files.
             foreach (var file in sftp.SynchronizeDirectories(currentPath.FullPath, destination.FullPath, "*"))
             {
                 Log.LogMessage("Updating " + file.Name);
             }
         }
         return true;
     }
 }
        private static string CreateRemoteDirectory(SftpClient sftp, string fileName, string remoteDirectoryPath)
        {
            if (!string.IsNullOrWhiteSpace(remoteDirectoryPath))
            {
                // auto-connect
                if (sftp.IsConnected == false)
                    sftp.Connect();

                var exists = sftp.DoesRemoteFileExist(remoteDirectoryPath);

                if (!exists)
                    sftp.CreateDirectory(remoteDirectoryPath);

                return Path.Combine(remoteDirectoryPath, fileName);
            }
            return fileName;
        }
Ejemplo n.º 11
0
 private static void CreatSSHDir(SftpClient ssh, string file)
 {
     var newDir = Tools.Misc.GetUnixDirecoryOfFile(file);
     if (ssh.Exists(newDir)) return;
     string[] dirs = new string[newDir.ToCharArray().Count(x => x == '/')];
     dirs[0] = newDir;
     for (int i = 1; i < dirs.Count(); i++)
     {
         dirs[i] = Tools.Misc.GetUnixDirecoryOfFile(dirs[i - 1]);
     }
     for (int i = dirs.Count()-1; i >= 0; i--)
     {
         if (ssh.Exists(dirs[i])) continue;
         ssh.CreateDirectory(dirs[i]);
     }
 }
Ejemplo n.º 12
-1
        private bool Sftp(string server, int port, bool passive, string username, string password, string filename, int counter, byte[] contents, out string error, bool rename)
        {
            bool failed = false;
            error = "";
            try
            {
                int i = 0;
                filename = filename.Replace("{C}", counter.ToString(CultureInfo.InvariantCulture));
                if (rename)
                    filename += ".tmp";

                while (filename.IndexOf("{", StringComparison.Ordinal) != -1 && i < 20)
                {
                    filename = String.Format(CultureInfo.InvariantCulture, filename, Helper.Now);
                    i++;
                }

                var methods = new List<AuthenticationMethod> { new PasswordAuthenticationMethod(username, password) };

                var con = new ConnectionInfo(server, port, username, methods.ToArray());
                using (var client = new SftpClient(con))
                {
                    client.Connect();

                    var filepath = filename.Trim('/').Split('/');
                    var path = "";
                    for (var iDir = 0; iDir < filepath.Length - 1; iDir++)
                    {
                        path += filepath[iDir] + "/";
                        try
                        {
                            client.CreateDirectory(path);
                        }
                        catch
                        {
                            //directory exists
                        }
                    }
                    if (path != "")
                    {
                        client.ChangeDirectory(path);
                    }

                    filename = filepath[filepath.Length - 1];

                    using (Stream stream = new MemoryStream(contents))
                    {
                        client.UploadFile(stream, filename);
                        if (rename)
                        {
                            try
                            {
                                //delete target file?
                                client.DeleteFile(filename.Substring(0, filename.Length - 4));
                            }
                            catch (Exception)
                            {
                            }
                            client.RenameFile(filename, filename.Substring(0, filename.Length - 4));
                        }
                    }

                    client.Disconnect();
                }

                MainForm.LogMessageToFile("SFTP'd " + filename + " to " + server + " port " + port, "SFTP");
            }
            catch (Exception ex)
            {
                error = ex.Message;
                failed = true;
            }
            return !failed;
        }
Ejemplo n.º 13
-1
        public void go(string filename)
        {
            if (string.IsNullOrWhiteSpace(filename) || connInfo == null || config.sftpEnabled == false)
            {
                Log.Debug("Not doing SFTP because it wasn't configured properly or at all");
                return;
            }

            FileInfo fi = new FileInfo(filename);
            if(!fi.Exists)
            {
                Log.Error("Can't open file for SFTPing: " + filename);
                return;
            }

            if(!fi.DirectoryName.StartsWith(config.localBaseFolder))
            {
                Log.Error("Can't figure out where the file " + filename + " is relative to the base dir");
                return;
            }

            string rel = fi.DirectoryName.Replace(config.localBaseFolder, "");
            if (rel.StartsWith(Path.DirectorySeparatorChar.ToString()))
                rel = rel.Substring(1);

            SftpClient client = new SftpClient(connInfo);
            string accum = "";
            try
            {
                client.Connect();
                string thedir = null;
                foreach (string str in rel.Split(Path.DirectorySeparatorChar))
                {
                    accum = accum + "/" + str;
                    thedir = config.sftpRemoteFolder + "/" + accum;
                    thedir = thedir.Replace("//", "/");
                    Log.Debug("Trying to create directory " + thedir);
                    try
                    {
                        client.CreateDirectory(thedir);
                    }
                    catch (SshException) { }
                }
                FileStream fis = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    client.BeginUploadFile(fis, thedir + "/" + fi.Name, true, (fini) =>
                    {
                        FileStream ffini = fini.AsyncState as FileStream;
                        if (ffini != null)
                            ffini.Close();
                        if (client != null && client.IsConnected)
                        {
                            client.Disconnect();
                        }
                        Log.Debug("Upload finished!");
                        if(Program.frm != null)
                            Program.frm.SetStatus("Upload finished! / Ready");
                    }, fis, (pct) =>
                    {
                        if(Program.frm != null)
                        {
                            Program.frm.SetStatus("Uploaded " + pct.ToString() + " bytes");
                        }
                    });
            }
            catch(Exception aiee)
            {
                Log.Error("Error: " + aiee.Message);
                Log.Debug(aiee.StackTrace);
            }
        }