Exemple #1
0
        public SSHTool(SSHOptions _options, bool _verbose)
        {
            this.options = _options;
            this.verbose = _verbose;

            AuthenticationMethod authentication;

            if (options.PrivateKeyFile != null)
            {
                authentication = new PrivateKeyAuthenticationMethod(options.Username,
                                                                    new PrivateKeyFile[]
                {
                    new PrivateKeyFile(options.PrivateKeyFile, options.Password)
                }
                                                                    );
            }
            else
            {
                authentication = new PasswordAuthenticationMethod(options.Username, options.Password);
            }

            connectionInfo = new ConnectionInfo(options.Hostname, options.Port, options.Username, authentication);

            sshclient  = new SshClient(connectionInfo);
            sftpclient = new SftpClient(connectionInfo);
        }
        //------------------------------------------------------------------
        // コンストラクタ
        public CSftp()
        {
            HostName = "aus-d4w-cloud.ozbackups.com.au"; // 接続先ホスト名
            Port     = 22;                               // ポート
            UserName = "******";                    // ユーザー名
            Password = "******";            // パスワード

            string KeyFile    = @"E:\2.ppk";             // 秘密鍵
            string PassPhrase = "";                      // パスフレーズ

            // パスワード認証
            var _PassAuth = new PasswordAuthenticationMethod(UserName, Password);

            // 秘密鍵認証
            var _PrivateKey = new PrivateKeyAuthenticationMethod(UserName, new PrivateKeyFile[] {
                new PrivateKeyFile(KeyFile, PassPhrase)
            });

            //PrivateKeyFile privateKey;
            //using (var keystrm = new MemoryStream(Encoding.ASCII.GetBytes(keyStr)))
            //{
            //    privateKey = new PrivateKeyFile(keystrm);


            //}
            // 接続情報の生成
            //var _PrivateKey = new PrivateKeyAuthenticationMethod(UserName, privateKey);

            ConnNfo = new ConnectionInfo(HostName, Port, UserName,
                                         new AuthenticationMethod[] {
                _PassAuth,                  // パスワード認証
                _PrivateKey,                // 秘密鍵認証
            }
                                         );
        }
        private ConnectionInfo CreateConnectionInfo(Host host)
        {
            AuthenticationMethod auth = null;

            if (host.SecretType == LoginSecretType.Password)
            {
                auth = new PasswordAuthenticationMethod(host.UserName, host.Password);
            }
            else if (host.SecretType == LoginSecretType.PrivateKey)
            {
                auth = new PrivateKeyAuthenticationMethod(host.UserName, new PrivateKeyFile(host.PrivateKeyPath));
            }

            if (host.Proxy.Type == LocalProxyType.None)
            {
                return(new ConnectionInfo(host.Address, host.Port, host.UserName, auth));
            }
            else
            {
                return(new ConnectionInfo(
                           host: host.Address,
                           port: host.Port,
                           username: host.UserName,
                           proxyType: (ProxyTypes)(int)host.Proxy.Type,
                           proxyHost: host.Proxy.Address,
                           proxyPort: host.Proxy.Port,
                           proxyUsername: host.Proxy.UserName,
                           proxyPassword: host.Proxy.Password,
                           authenticationMethods: auth));
            }
        }
        static void Main(string[] args)
        {
            // 必要な情報を設定する
            var host            = "<HostName>";
            var userName        = "******";
            var passPhrase      = "<PassPhrase>";
            var keyFilePath     = @"<Private Key File Path>";
            var sendFilePath    = @"<Send File Path>";
            var reseiveFilePath = @"<Save File Path>";

            // 認証メソッドを作成
            var authMethod = new PrivateKeyAuthenticationMethod(userName, new PrivateKeyFile(keyFilePath, passPhrase));

            // 接続情報を作成
            var connectionInfo = new ConnectionInfo(host, userName, authMethod);

            // SFTP クライアントを作成
            var client = new SftpClient(connectionInfo);

            // 接続。失敗した場合は例外が発生
            client.Connect();

            // ファイルのアップロード(上書き)
            using var sendStream = File.OpenRead(sendFilePath);
            client.UploadFile(sendStream, Path.GetFileName(sendFilePath), true);

            // ファイルのダウンロード(上書き)
            using var reseiveStream = File.OpenWrite(reseiveFilePath);
            client.DownloadFile(Path.GetFileName(sendFilePath), reseiveStream);

            // 切断
            client.Disconnect();
        }
Exemple #5
0
 public SftpUploader(AppConfig conf)
 {
     this.config = conf;
     if (config.sftpEnabled)
     {
         AuthenticationMethod[] auths = new AuthenticationMethod[1];
         if (String.IsNullOrWhiteSpace(config.sftpPrivateKeyPath))
         {
             auths[0] = new PasswordAuthenticationMethod(config.sftpUsername, Utils.GetBytes(config.sftpPassword));
         }
         else
         {
             try
             {
                 PrivateKeyFile pkf = null;
                 if (string.IsNullOrEmpty(config.sftpPassword))
                 {
                     pkf = new PrivateKeyFile(config.sftpPrivateKeyPath);
                 }
                 else
                 {
                     pkf = new PrivateKeyFile(config.sftpPrivateKeyPath, config.sftpPassword);
                 }
                 auths[0] = new PrivateKeyAuthenticationMethod(config.sftpUsername, pkf);
             }
             catch (IOException)
             {
                 Log.Error("Unable to read private key file: " + config.sftpPrivateKeyPath);
                 return;
             }
         }
         connInfo = new ConnectionInfo(config.sftpRemoteServer, config.sftpUsername, auths);
     }
 }
Exemple #6
0
        public void CreateSFTPConnectionInfo()
        {
            if (settings.ftpProtocol == 0)
            {
                return;
            }

            try
            {
                AuthenticationMethod auth;
                if (settings.ftpMethod == 0)
                {
                    auth = new PasswordAuthenticationMethod(settings.ftpUsername, settings.ftpPassword);
                }
                else
                {
                    var key = settings.ftpPassphrase != string.Empty ? new PrivateKeyFile(settings.ftpKeyfile, settings.ftpPassphrase) : new PrivateKeyFile(settings.ftpKeyfile);
                    auth = new PrivateKeyAuthenticationMethod(settings.ftpUsername, key);
                }

                ftpConnectionInfo = new ConnectionInfo(
                    settings.ftpHost,
                    settings.ftpPort,
                    settings.ftpUsername,
                    auth);
            }
            catch (Exception)
            {
                ftpConnectionInfo = null;
            }
        }
Exemple #7
0
        private static AuthenticationMethod[] privateKeyObject(string username, string publicKeyPath)
        {
            PrivateKeyFile privateKeyFile = new PrivateKeyFile(publicKeyPath);
            PrivateKeyAuthenticationMethod privateKeyAuthenticationMethod = new PrivateKeyAuthenticationMethod(username, privateKeyFile);

            return(new AuthenticationMethod[] { privateKeyAuthenticationMethod });
        }
Exemple #8
0
        public static void CreateSSHTunnel(Server server)
        {
            if (server.Ssh.KeyFilePath != null)
            {
                using (var stream = new FileStream(server.Ssh.KeyFilePath, FileMode.Open, FileAccess.Read))
                {
                    var privateKeyFile       = new PrivateKeyFile(stream, server.Ssh.Password);
                    var authenticationMethod = new PrivateKeyAuthenticationMethod(server.Ssh.User, privateKeyFile);
                    var connectionInfo       = new ConnectionInfo(server.Ssh.Server, server.Ssh.Port, server.Ssh.User, authenticationMethod);

                    server.Ssh.Client = new SshClient(connectionInfo);
                }
            }
            else
            {
                server.Ssh.Client = new SshClient(server.Ssh.Server, server.Ssh.Port, server.Ssh.User, server.Ssh.Password);
            }

            server.Ssh.Client.Connect();
            server.Ssh.ForwardedPort = FreePort();

            var forwardedPort = new ForwardedPortLocal("localhost", (uint)server.Ssh.ForwardedPort, server.Address, server.Port);

            server.Ssh.Client.AddForwardedPort(forwardedPort);
            forwardedPort.Start();
        }
Exemple #9
0
        //------------------------------------------------------------------
        // コンストラクタ
        public CSftp()
        {
            HostName = "localhost";                         // 接続先ホスト名
            Port     = 10221;                               // ポート
            UserName = "******";                 // ユーザー名
            Password = "******";                              // パスワード

            string KeyFile    = @"..\..\docker\ssh\id_rsa"; // 秘密鍵
            string PassPhrase = "";                         // パスフレーズ


            // パスワード認証
            var _PassAuth = new PasswordAuthenticationMethod(UserName, Password);

            // 秘密鍵認証
            var _PrivateKey = new PrivateKeyAuthenticationMethod(UserName, new PrivateKeyFile[] {
                new PrivateKeyFile(KeyFile, PassPhrase)
            });

            // 接続情報の生成
            ConnNfo = new ConnectionInfo(HostName, Port, UserName,
                                         new AuthenticationMethod[] {
                _PassAuth,              // パスワード認証
                _PrivateKey,            // 秘密鍵認証
            }
                                         );
        }
Exemple #10
0
        public SSHclient(string ip, int port, string user, string pw)
        {
            try
            {
                PrivateKeyFile pkf = new PrivateKeyFile(@"C:\Users\lotte_test\Desktop\개인 프로젝트\GoogleSoft\Compute Service\Login Keys\스타2\aa", pw);
                PrivateKeyAuthenticationMethod pam = new PrivateKeyAuthenticationMethod(user, pkf);
                ConnectionInfo connInfo            = new ConnectionInfo(ip, port, user, pam);

                client = new SshClient(connInfo);
                client.Connect();

                if (client.IsConnected)
                {
                    MessageBox.Show("연결 성공");
                }
                else
                {
                    MessageBox.Show("연결 실패");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
 [Ignore] // placeholder for actual test
 public void DisposeTest()
 {
     string username = string.Empty; // TODO: Initialize to an appropriate value
     PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
     PrivateKeyAuthenticationMethod target = new PrivateKeyAuthenticationMethod(username, keyFiles); // TODO: Initialize to an appropriate value
     target.Dispose();
     Assert.Inconclusive("A method that does not return a value cannot be verified.");
 }
 [Ignore] // placeholder for actual test
 public void NameTest()
 {
     string username = string.Empty; // TODO: Initialize to an appropriate value
     PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
     PrivateKeyAuthenticationMethod target = new PrivateKeyAuthenticationMethod(username, keyFiles); // TODO: Initialize to an appropriate value
     string actual;
     actual = target.Name;
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
        public void PrivateKeyAuthenticationMethodConstructorTest()
        {
            string username = string.Empty;               // TODO: Initialize to an appropriate value

            PrivateKeyFile[] keyFiles             = null; // TODO: Initialize to an appropriate value
            PrivateKeyAuthenticationMethod target = new PrivateKeyAuthenticationMethod(username, keyFiles);

            Assert.Inconclusive("TODO: Implement code to verify target");
        }
Exemple #14
0
        private static ConnectionInfo FromPrivateKeyFile(Deployment options)
        {
            var split          = options.Auth.Split(":");
            var username       = split[0];
            var filePath       = split[1];
            var key            = new PrivateKeyAuthenticationMethod(username, new PrivateKeyFile(filePath));
            var connectionInfo = new ConnectionInfo(options.Settings.Host, username, key);

            return(connectionInfo);
        }
        public void DisposeTest()
        {
            string username = string.Empty;                                                                 // TODO: Initialize to an appropriate value

            PrivateKeyFile[] keyFiles             = null;                                                   // TODO: Initialize to an appropriate value
            PrivateKeyAuthenticationMethod target = new PrivateKeyAuthenticationMethod(username, keyFiles); // TODO: Initialize to an appropriate value

            target.Dispose();
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
        public async Task <IActionResult> Get([FromQuery] string code)
        {
            var parameters = new Dictionary <string, string>()
            {
                { "code", code },
                { "grant_type", "authorization_code" },
                { "redirect_uri", "https://*****:*****@"https://oauth2.googleapis.com/token");
            var content = new FormUrlEncodedContent(parameters);
            // Exchange Authorization Code for Access Tokens
            // https://developers.google.com/identity/protocols/oauth2/web-server#exchange-authorization-code
            var tokenResponse = await httpClient.PostAsync(uri.AbsoluteUri, content);

            string tokenResponseString = await tokenResponse.Content.ReadAsStringAsync();

            var options = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true,
            };

            var googleToken = JsonSerializer.Deserialize <GoogleToken>(tokenResponseString, options);

            var envRequest = new HttpRequestMessage(HttpMethod.Get, @"https://cloudshell.googleapis.com/v1alpha1/users/me/environments/default");

            envRequest.Headers.Add("ContentType", "application/json");
            envRequest.Headers.Add("Authorization", "Bearer " + googleToken.AccessToken);
            // Get CloudShell Endpoint Infomation for SSH.
            var envResponse = await httpClient.SendAsync(envRequest);

            string envResponseString = await envResponse.Content.ReadAsStringAsync();

            var csEnv      = JsonSerializer.Deserialize <CloudShellEnviromentResponse>(envResponseString, options);
            var privateKey = new PrivateKeyAuthenticationMethod(csEnv.SshUsername, new PrivateKeyFile[] {
                new PrivateKeyFile("id_rsa")
            });
            var sftpConnInfo = new ConnectionInfo(csEnv.SshHost, csEnv.SshPort, csEnv.SshUsername,
                                                  new AuthenticationMethod[] { privateKey }
                                                  );

            using var sftpClient = new SftpClient(sftpConnInfo);
            // Connect SSH Session.
            sftpClient.Connect();
            // Create Directory and Upload File.
            sftpClient.CreateDirectory($"{sftpClient.WorkingDirectory}/.kube/");
            using var fileStream = System.IO.File.OpenRead("config");
            sftpClient.UploadFile(fileStream, $"{sftpClient.WorkingDirectory}/.kube/config", true);
            sftpClient.Disconnect();
            var openUri = new Uri($@"https://localhost:5001/open.html");

            // Close Session and Redirect to "Open in Cloud Shell" Button Page.
            return(Redirect(openUri.AbsoluteUri));
        }
        public void NameTest()
        {
            string username = string.Empty;                                                                 // TODO: Initialize to an appropriate value

            PrivateKeyFile[] keyFiles             = null;                                                   // TODO: Initialize to an appropriate value
            PrivateKeyAuthenticationMethod target = new PrivateKeyAuthenticationMethod(username, keyFiles); // TODO: Initialize to an appropriate value
            string actual;

            actual = target.Name;
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
 [Ignore] // placeholder for actual test
 public void AuthenticateTest()
 {
     string username = string.Empty; // TODO: Initialize to an appropriate value
     PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
     PrivateKeyAuthenticationMethod target = new PrivateKeyAuthenticationMethod(username, keyFiles); // TODO: Initialize to an appropriate value
     Session session = null; // TODO: Initialize to an appropriate value
     AuthenticationResult expected = new AuthenticationResult(); // TODO: Initialize to an appropriate value
     AuthenticationResult actual;
     actual = target.Authenticate(session);
     Assert.AreEqual(expected, actual);
     Assert.Inconclusive("Verify the correctness of this test method.");
 }
Exemple #19
0
        public SSHConnection(string host, int port, string username, string passKey, Stream fileStream)
        {
            var privateKeyFile = new PrivateKeyFile(fileStream, passKey);
            var privateKeyAuth = new PrivateKeyAuthenticationMethod(username, privateKeyFile);
            var connectionInfo = new ConnectionInfo(host, port, username, authenticationMethods: privateKeyAuth)
            {
                Timeout = TimeSpan.FromSeconds(4)
            };

            Connection = new SshClient(connectionInfo);
            Connection.Connect();
        }
Exemple #20
0
        protected ProtocolBase()
        {
            string sshKeyPath;

            if (this._config.PrivateKeyPath.Trim().Length == 0)
            {
                sshKeyPath = Path.Combine(System.Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".ssh", this._config.PrivateKeyName);
            }
            else
            {
                sshKeyPath = Path.Combine(this._config.PrivateKeyPath, this._config.PrivateKeyName);
            }
            this._privateKeyAuthMethod = new PrivateKeyAuthenticationMethod(this._config.UserName, new PrivateKeyFile(sshKeyPath, this._config.FingerPrint));
        }
Exemple #21
0
        public static ConnectionInfo AsConnectionInfo(this ChannelSettings channelSettings)
        {
            FileInfo privateKey = new FileInfo(channelSettings.PrivateKey);

            if (!File.Exists(privateKey.FullName))
            {
                throw new FileNotFoundException($"File with private key doesn't exist. {privateKey.FullName}");
            }
            PrivateKeyFile privateKeyFile = new PrivateKeyFile(privateKey.FullName);
            PrivateKeyAuthenticationMethod privateKeyAuthenticationMethod = new PrivateKeyAuthenticationMethod(channelSettings.UserName, privateKeyFile);
            int port = channelSettings.Port <= 0 ? Constants.DefaultSftpPort : channelSettings.Port;

            return(new ConnectionInfo(channelSettings.Host, port, channelSettings.UserName, privateKeyAuthenticationMethod));
        }
        public void AuthenticateTest()
        {
            string username = string.Empty;                                                                 // TODO: Initialize to an appropriate value

            PrivateKeyFile[] keyFiles             = null;                                                   // TODO: Initialize to an appropriate value
            PrivateKeyAuthenticationMethod target = new PrivateKeyAuthenticationMethod(username, keyFiles); // TODO: Initialize to an appropriate value
            Session session = null;                                                                         // TODO: Initialize to an appropriate value
            AuthenticationResult expected = new AuthenticationResult();                                     // TODO: Initialize to an appropriate value
            AuthenticationResult actual;

            actual = target.Authenticate(session);
            Assert.AreEqual(expected, actual);
            Assert.Inconclusive("Verify the correctness of this test method.");
        }
Exemple #23
0
        public static SshClient CreateSshClient(ManagedSystem system)
        {
            ConnectionInfo connectionInfo;

            if (!string.IsNullOrEmpty(system.OneTimePassword) && !string.IsNullOrEmpty(system.OneTimeLogin))
            {
                KeyboardInteractiveAuthenticationMethod keyboardAuth = new KeyboardInteractiveAuthenticationMethod(system.OneTimeLogin);
                PasswordAuthenticationMethod            passwordAuth = new PasswordAuthenticationMethod(system.OneTimeLogin, system.OneTimePassword);

                keyboardAuth.AuthenticationPrompt += (sender, args) =>
                {
                    foreach (Renci.SshNet.Common.AuthenticationPrompt prompt in args.Prompts)
                    {
                        if (prompt.Request.IndexOf("Password:"******"Could not create authentication for system {system.Name}.");
            }


            var client = new SshClient(connectionInfo);

            client.HostKeyReceived += (sender, hostKeyArgs) =>
            {
                var receivedFingerprint = new Fingerprint(hostKeyArgs.FingerPrint);
                hostKeyArgs.CanTrust = system.Fingerprint.Matches(receivedFingerprint);

                if (string.IsNullOrEmpty(system.SystemFingerprint))
                {
                    system.SystemFingerprint = receivedFingerprint.Text;
                    throw new AuthenticationException("System fingerprint was filled automatically.");
                }
            };
            client.Connect();

            return(client);
        }
Exemple #24
0
 private async Task <ConnectionInfo> SetUpSftpAsync(FtpConfig config, Func <string, Task <string> > securePassword)
 {
     try
     {
         var passAuthenMethod       = new PasswordAuthenticationMethod(config.Ftp.Credentials.Username, await securePassword.Invoke(config.Ftp.Credentials.AzureKeyVault.SecretName));
         var privateKeyAuthenMethod = new PrivateKeyAuthenticationMethod(config.Ftp.Credentials.Username);
         var connectionInfo         = new ConnectionInfo(config.Ftp.Host, config.Ftp.Port, config.Ftp.Credentials.Username, passAuthenMethod, privateKeyAuthenMethod);
         return(connectionInfo);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemple #25
0
 public ConnectionInfo ToConnectionInfo()
 {
     if (!string.IsNullOrEmpty(PublicKeyPath))
     {
         PrivateKeyFile privateKeyFile = new PrivateKeyFile(PublicKeyPath);
         PrivateKeyAuthenticationMethod privateKeyAuthenticationMethod = new PrivateKeyAuthenticationMethod(UserName, privateKeyFile);
         return(new ConnectionInfo(ServerHost, Port, UserName, privateKeyAuthenticationMethod));
     }
     if (!string.IsNullOrEmpty(Password))
     {
         PasswordAuthenticationMethod passwordAuthenticationMethod = new PasswordAuthenticationMethod(UserName, Password);
         return(new ConnectionInfo(ServerHost, Port, UserName, passwordAuthenticationMethod));
     }
     throw new InvalidOperationException("PublicKeyPath or Password must be specified");
 }
        protected void StartNewConnection(string address, string username, PrivateKeyAuthenticationMethod auth)
        {
            Client?.Dispose();

            var connectionInfo = new ConnectionInfo(address, username, auth)
            {
                Timeout = TimeSpan.FromSeconds(10)
            };

            Client = new SshClient(connectionInfo);

            // TODO: is there a way to verify the other side fingerprint?

            Client.Connect();
        }
Exemple #27
0
        public RemoteShell(Options options)
        {
            this.options = options;

            var privateKeyFile       = new PrivateKeyFile(PathUtility.GetFullPath(options.PrivateKey));
            var AuthenticationMethod = new PrivateKeyAuthenticationMethod(options.Username, privateKeyFile);
            var connectionInfo       = new ConnectionInfo(options.Hostname, options.Port, options.Username, AuthenticationMethod);

            ssh  = new SshClient(connectionInfo);
            sftp = new SftpClient(connectionInfo);

            Console.WriteLine("Connecting to {0}@{1}:{2}", options.Username, options.Hostname, options.Port);

            ssh.Connect();
            sftp.Connect();
        }
        public void ConnectToSSHServerUsingKeys()
        {
            var            keyFile = new PrivateKeyFile(SSH_KEY_FILE_PATH, SSH_KEY_FILE_PASSPHRASE);
            var            authenticationMethod = new PrivateKeyAuthenticationMethod(SSH_USER_NAME, keyFile);
            ConnectionInfo con = new ConnectionInfo(SSH_HOST_NAME, SSH_PORT, SSH_USER_NAME, authenticationMethod);

            using (SftpClient sftp = new SftpClient(con))
            {
                sftp.Connect();
                var files = sftp.ListDirectory(string.Empty);
                foreach (var file in files)
                {
                }
                sftp.Disconnect();
            }
        }
        /// <summary>
        /// バックアップ実行
        /// </summary>
        public void execute()
        {
            var authMethod     = new PrivateKeyAuthenticationMethod(this.RemoteUser, new PrivateKeyFile(this.SshPrivateKeyPath, this.SshPassword));
            var connectionInfo = new ConnectionInfo(this.RemoteHost, this.RemotePort, this.RemoteUser, authMethod);

            using (var client = new SftpClient(connectionInfo))
            {
                // リリースファイル一覧を探索
                string[] files = Directory.GetFiles(this.ReleasePath, "*", SearchOption.AllDirectories);
                foreach (var file in files)
                {
                    // 絶対パスを相対パスへ変換
                    Uri basePath     = new Uri(this.ReleasePath);
                    Uri relativePath = basePath.MakeRelativeUri(new Uri(file));

                    string remoteFile = relativePath.ToString();

                    // バックアップ先ファイル名を決定
                    string backupFilePath = this.BackupPath + relativePath;

                    // ディレクトリが存在しない場合は作成
                    string directoryPath = Path.GetDirectoryName(backupFilePath);
                    if (!Directory.Exists(directoryPath))
                    {
                        Directory.CreateDirectory(directoryPath);
                    }

                    // ダウンロード
                    client.Connect();
                    client.ChangeDirectory(this.RemoteBasePath);
                    if (client.Exists(remoteFile))
                    {
                        using (var fs = File.OpenWrite(backupFilePath))
                        {
                            client.DownloadFile(remoteFile, fs);
                        }
                        this.MessageList.Add("Success : " + relativePath);
                    }
                    else
                    {
                        this.MessageList.Add("FileNotFound : " + relativePath);
                    }
                    client.Disconnect();
                }
            }
        }
Exemple #30
0
        public int Upload(string server, string serverFingerPrint, string localPathFileName, string remotePathFileName)
        {
            string host;
            int    port;
            string username;
            string keyFileName;

            LoadSshClientConfig(server, out host, out port, out username, out keyFileName);

            string filePath = localPathFileName;

            var keyFile  = new PrivateKeyFile(keyFileName);
            var keyFiles = new [] { keyFile };

            PrivateKeyAuthenticationMethod [] methods = new PrivateKeyAuthenticationMethod [] { new PrivateKeyAuthenticationMethod(username, keyFiles) };
            var con = new ConnectionInfo(host, port, username, methods);

            using (SftpClient sftpClient = new SftpClient(con)) {
                sftpClient.HostKeyReceived += delegate(object sender, HostKeyEventArgs e) {
                    if (e.FingerPrint.SequenceEqual(ConvertFingerprintToByteArray(serverFingerPrint)))
                    {
                        e.CanTrust = true;
                    }
                    else
                    {
                        e.CanTrust = false;
                    }
                };
                //client.BufferSize = 1024;
                PrintMessage("Connect to server...");
                sftpClient.Connect();
                PrintMessage("Connection successful :)");

                PrintMessage("Creating FileStream object to stream a file");
                FileStream fs = new FileStream(filePath, FileMode.Open);

                PrintMessage("Uploading to server");
                sftpClient.UploadFile(fs, remotePathFileName);

                PrintMessage("Finished");
            }

            Console.Read();
            return(0);
        }
        //if someone need it...
        public static ConnectionInfo CreateConnectionInfo(string privateKeyPath, string serverIp)
        {
            var            privateKeyFilePath = @HostingEnvironment.MapPath(privateKeyPath);
            ConnectionInfo connectionInfo;

            using (var stream = new FileStream(privateKeyFilePath, FileMode.Open, FileAccess.Read))
            {
                var privateKeyFile = new PrivateKeyFile(stream);
                AuthenticationMethod authenticationMethod = new PrivateKeyAuthenticationMethod(_username, privateKeyFile);

                connectionInfo = new ConnectionInfo(
                    serverIp,
                    _username,
                    authenticationMethod);
            }

            return(connectionInfo);
        }
Exemple #32
0
        public bool IsValidKey(string name)
        {
            var keyPath = KeyNameToPath(name);

            if (!File.Exists(keyPath))
            {
                return(false);
            }

            try
            {
                var _ = new PrivateKeyAuthenticationMethod(username, new PrivateKeyFile(keyPath));
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        private static ConnectionInfo GetConnectionInfo(Parameters input, Options options)
        {
            if (string.IsNullOrEmpty(options.PrivateKeyFileName))
            {
                if (!options.UseKeyboardInteractiveAuthenticationMethod)
                {
                    return(new PasswordConnectionInfo(input.Server, input.Port, input.UserName, input.Password));
                }

                var keyboardInteractiveAuth = Sftp.GetKeyboardInteractiveAuthentication(input.UserName, input.Password);

                PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod(input.UserName, input.Password);

                return(new ConnectionInfo(input.Server, input.Port, input.UserName, pauth, keyboardInteractiveAuth));
            }

            if (string.IsNullOrEmpty(options.Passphrase))
            {
                if (options.UseKeyboardInteractiveAuthenticationMethod)
                {
                    var keyboardInteractiveAuth = Sftp.GetKeyboardInteractiveAuthentication(input.UserName, input.Password);

                    var privateKeyAuth = new PrivateKeyAuthenticationMethod(input.UserName,
                                                                            new PrivateKeyFile(options.PrivateKeyFileName));

                    return(new ConnectionInfo(input.Server, input.Port, input.UserName, privateKeyAuth, keyboardInteractiveAuth));
                }

                return(new PrivateKeyConnectionInfo(input.Server, input.Port, input.UserName, new PrivateKeyFile(options.PrivateKeyFileName)));
            }

            if (options.UseKeyboardInteractiveAuthenticationMethod)
            {
                var keyboardInteractiveAuth = Sftp.GetKeyboardInteractiveAuthentication(input.UserName, input.Password);

                var privateKeyAuth = new PrivateKeyAuthenticationMethod(input.UserName,
                                                                        new PrivateKeyFile(options.PrivateKeyFileName, options.Passphrase));

                return(new ConnectionInfo(input.Server, input.Port, input.UserName, privateKeyAuth, keyboardInteractiveAuth));
            }

            return(new PrivateKeyConnectionInfo(input.Server, input.Port, input.UserName, new PrivateKeyFile(options.PrivateKeyFileName, options.Passphrase)));
        }
 [Ignore] // placeholder for actual test
 public void PrivateKeyAuthenticationMethodConstructorTest()
 {
     string username = string.Empty; // TODO: Initialize to an appropriate value
     PrivateKeyFile[] keyFiles = null; // TODO: Initialize to an appropriate value
     PrivateKeyAuthenticationMethod target = new PrivateKeyAuthenticationMethod(username, keyFiles);
     Assert.Inconclusive("TODO: Implement code to verify target");
 }