Represents remote connection information class.
This class is NOT thread-safe. Do not use the same ConnectionInfo with multiple client instances.
상속: IConnectionInfoInternal
예제 #1
24
 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);
     }
 }
        public override ProcessOutput ExecuteCcm(string args, int timeout = 90000, bool throwOnProcessError = true)
        {
            var executable = GetExecutable(ref args);
            Trace.TraceInformation(executable + " " + args);

            var output = new ProcessOutput();
            if (_sshClient == null)
            {
                Trace.TraceInformation("Connecting ssh client...");
                var kauth = new KeyboardInteractiveAuthenticationMethod(_user);
                var pauth = new PasswordAuthenticationMethod(_user, _password);

                var connectionInfo = new ConnectionInfo(_ip, _port, _user, kauth, pauth);

                kauth.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                {
                    foreach (var prompt in e.Prompts)
                    {
                        if (prompt.Request.ToLowerInvariant().StartsWith("password"))
                        {
                            prompt.Response = _password;
                        }
                    }
                };

                if (!string.IsNullOrEmpty(_privateKeyFilePath))
                {
                    var privateKeyAuth = new PrivateKeyAuthenticationMethod(_user, new PrivateKeyFile[]
                    {
                        new PrivateKeyFile(_privateKeyFilePath)
                    });
                    connectionInfo = new ConnectionInfo(_ip, _port, _user, privateKeyAuth);
                }

                _sshClient = new SshClient(connectionInfo);
            }
            if (!_sshClient.IsConnected)
                _sshClient.Connect();

            var result = _sshClient.RunCommand(string.Format(@"{0} {1}", executable, args));
            output.ExitCode = result.ExitStatus;
            if (result.Error != null)
            {
                output.OutputText.Append(result.Error);
            }
            else
            {
                output.OutputText.Append(result.Result);
            }

            if (throwOnProcessError)
            {
                ValidateOutput(output);
            }
            return output;
        }
        public static async Task<ConnectionReturn> CheckConnection(string teamNumberS, TimeSpan timeout)
        {
            int teamNumber;
            int.TryParse(teamNumberS, out teamNumber);


            if (teamNumber < 0)
            {
                teamNumber = 0;
            }
            string roboRioMDNS = string.Format(RoboRioMdnsFormatString, teamNumber);
            string roboRIOIP = string.Format(RoboRioIpFormatString, teamNumber / 100, teamNumber % 100);

            if (await GetWorkingConnectionInfo(roboRioMDNS, timeout))
            {
                return new ConnectionReturn(ConnectionType.MDNS, roboRioMDNS, true);
            }
            else if (await GetWorkingConnectionInfo(RoboRioUSBIp, timeout))
            {
                return new ConnectionReturn(ConnectionType.USB, RoboRioUSBIp, true);
            }
            else if (await GetWorkingConnectionInfo(roboRIOIP, timeout))
            {
                return new ConnectionReturn(ConnectionType.IP, roboRIOIP, true);
            }
            s_lvUserConnectionInfo = null;
            s_adminConnectionInfo = null;
            return null;
        }
예제 #4
0
        private void button1_Click(object sender, EventArgs e)
        {
            string host = textBoxServer.Text.Trim();
            string userName = textBoxUserName.Text.Trim();
            string psw = textBoxPassword.Text.Trim();
            string url = textBoxCoomand.Text.Trim();
            string location = @" -P  " + textBoxLocation.Text.Trim();
            string finalCommand = @"wget -bqc '" + url + "' " + location + " ";
            ConnectionInfo conInfo = new ConnectionInfo(host, 22, userName, new AuthenticationMethod[]{
                new PasswordAuthenticationMethod(userName,psw)
            });
            SshClient client = new SshClient(conInfo);
            try
            {
                client.Connect();
                var outptu = client.RunCommand(finalCommand);
            }
            catch (Exception ex)
            {
                textBoxDisplay.Text = ex.Message;
                throw;
            }

            client.Disconnect();
            client.Dispose();
            SetLastValues(host, userName, psw, textBoxLocation.Text.Trim());
        }
예제 #5
0
 public Dantherm(string ip, string username, string password)
 {
     this.ip             = ip;
     this.username       = username;
     this.password       = password;
     this.connectionInfo = new ConnectionInfo(this.ip, username, new PasswordAuthenticationMethod(username, password),
                                              new PrivateKeyAuthenticationMethod("rsa.key"));
 }
예제 #6
0
 ConnectionInfo connInfo;//строка подключения
 public SshExpect(ConnectionData host)
     : base(host)
 {
     connInfo = new ConnectionInfo(host.address, host.port, host.username, new AuthenticationMethod[]{
         new PasswordAuthenticationMethod(host.username, host.password)
         }
     );
 }
예제 #7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseClient"/> class.
        /// </summary>
        /// <param name="connectionInfo">The connection info.</param>
        /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
        public BaseClient(ConnectionInfo connectionInfo)
        {
            if (connectionInfo == null)
                throw new ArgumentNullException("connectionInfo");

            this.ConnectionInfo = connectionInfo;
            this.Session = new Session(connectionInfo);
        }
예제 #8
0
 public Ssh(string host, int port, string user, string pass)
 {
     _con = new ConnectionInfo(host,port,user,
         new AuthenticationMethod[]
         {
             new PasswordAuthenticationMethod(user,pass)
         });
 }
예제 #9
0
 public SftpForm(ConnectionInfo connectionInfo)
 {
     InitializeComponent();
       this.connectionInfo = connectionInfo;
       this.sftpClient = new SftpClient(this.connectionInfo);
       this.sftpClient.Connect();
       refresh();
 }
예제 #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseClient"/> class.
        /// </summary>
        /// <param name="connectionInfo">The connection info.</param>
        /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
        /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
        /// <remarks>
        /// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, then the
        /// connection info will be disposed when this instance is disposed.
        /// </remarks>
        protected BaseClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
        {
            if (connectionInfo == null)
                throw new ArgumentNullException("connectionInfo");

            ConnectionInfo = connectionInfo;
            _ownsConnectionInfo = ownsConnectionInfo;
            _keepAliveInterval = Infinite;
        }
예제 #11
0
        public void UploadFile(string fullSourcePath, string fileName)
        {
            var host = ConfigurationManager.AppSettings["Host"];
            var user = ConfigurationManager.AppSettings["User"];
            var port = ConfigurationManager.AppSettings["Port"];
            var pass = ConfigurationManager.AppSettings["Password"];
            var path = ConfigurationManager.AppSettings["Path"];
            var key = ConfigurationManager.AppSettings["PrivateKey"];

            int p = 22;
            if (!string.IsNullOrEmpty(port))
                p = int.Parse(port);

            Log.Info("Uploading '{0}' to {1}@{2}:{3}", fileName, user, host, p);

            AuthenticationMethod auth;
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(user)) {
                Log.Info("Using public key authentication with key {0}", key);
                auth = new PrivateKeyAuthenticationMethod(user ,new PrivateKeyFile[]{ new PrivateKeyFile(key) });
            } else if (!string.IsNullOrEmpty(user) && !string.IsNullOrEmpty(pass)){
                Log.Info("Using password authentication");
                auth = new PasswordAuthenticationMethod(user,pass);
            } else {
                throw new Exception("Please ensure that username, and either PrivateKey or Password setting are defined in the configuration file.");
            }

            ConnectionInfo ConnNfo = new ConnectionInfo(host, p, user, new AuthenticationMethod[]{ auth } );

            string targetPath = fileName;
            if (!String.IsNullOrEmpty(path)) {
                // If the Path config setting specifies the file name,
                // then ignore the local file name and always upload to the same target
                if (!String.IsNullOrWhiteSpace(Path.GetFileName(path))) {
                    targetPath = path;
                } else {
                    targetPath = Path.Combine(path, targetPath);
                    // To avoid path guessing by .NET, we first combine the path, then force
                    // potential backslashes with linux slashes.
                    // This will obviously kill any space escaping in the path, so we need to bring those back
                    bool hadSpaceEscapes = targetPath.Contains("\\ ");
                    targetPath = targetPath.Replace('\\', '/');
                    if (hadSpaceEscapes)
                        targetPath = targetPath.Replace("/ ", "\\ ");
                }
            }

            using (var scp = new ScpClient(ConnNfo)) {
                scp.Connect();

                Log.Info("Connection opened, uploading file.");
                scp.Upload(new FileInfo(fullSourcePath), targetPath);
                Log.Info("File uploaded, closing connection.");
                scp.Disconnect();
            }
        }
예제 #12
0
 public SftpFilesystem(ConnectionInfo connectionInfo, string rootpath,string label=null, bool useOfflineAttribute = false,
              bool debugMode = false, int attributeCacheTimeout = 5, int directoryCacheTimeout = 60)
     : base(connectionInfo)
 {
     _rootpath = rootpath;
     _directoryCacheTimeout = directoryCacheTimeout;
     _attributeCacheTimeout = attributeCacheTimeout;
     _useOfflineAttribute = useOfflineAttribute;
     _debugMode = debugMode;
     _volumeLabel = label??String.Format("{0} on '{1}'", ConnectionInfo.Username, ConnectionInfo.Host);
 }
예제 #13
0
 private void addSftpTab(ConnectionInfo connectionInfo)
 {
     TabPage t = new TabPage(connectionInfo.Host);
     SftpForm f = new SftpForm(connectionInfo);
     f.Location = new Point(10, 10);
     f.TopLevel = false;
     f.Dock = DockStyle.Fill;
     f.Visible = true;
     t.Controls.Add(f);
     sftpTabControl.TabPages.Add(t);
 }
예제 #14
0
 public Ssh(string host, int port, string user, Stream key, string keypass)
 {
     _con = new ConnectionInfo(host,port,user,
         new AuthenticationMethod[]
         {
             new PrivateKeyAuthenticationMethod(user,new PrivateKeyFile[]
             {
                 (keypass!=null) ? new PrivateKeyFile(key,keypass) : new PrivateKeyFile(key)
             })
         });
 }
예제 #15
0
파일: Program.cs 프로젝트: wdstest/myrtille
        /// <summary>
        /// Connect SSH client to remote host
        /// </summary>
        private static void ConnectSSHClient()
        {
            try
            {
                if (string.IsNullOrEmpty(UserName))
                {
                    throw new SshAuthenticationException("Missing Username");
                }

                if (string.IsNullOrEmpty(Password))
                {
                    throw new SshAuthenticationException("Missing Password");
                }

                Uri serverUri;
                var serverHost = ServerAddress;
                var serverPort = 22;
                if (Uri.TryCreate("tcp://" + ServerAddress, UriKind.Absolute, out serverUri))
                {
                    serverHost = serverUri.Host;
                    if (serverUri.Port > 0)
                    {
                        serverPort = serverUri.Port;
                    }
                }

                var connectionInfo = new Renci.SshNet.ConnectionInfo(serverHost, serverPort, UserName, new PasswordAuthenticationMethod(UserName, Password));
                connectionInfo.Encoding = Encoding.UTF8;

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

                shellStream = client.CreateShellStream("xterm", Columns, Rows, Width, Height, 1024);
                shellStream.DataReceived += ShellStream_DataReceived;
            }
            catch (Exception e)
            {
                if (ConsoleOutput)
                {
                    Console.WriteLine(e.Message);
                }

                Trace.TraceError("Failed to connect ssh client, remote session {0} ({1})", RemoteSessionID, e);
                throw;
            }
            finally
            {
                if (client != null && !client.IsConnected)
                {
                    client.Dispose();
                    pipeMessaging.ClosePipes();
                }
            }
        }
예제 #16
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BaseClient"/> class.
        /// </summary>
        /// <param name="connectionInfo">The connection info.</param>
        /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
        /// <param name="serviceFactory">The factory to use for creating new services.</param>
        /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="serviceFactory"/> is null.</exception>
        /// <remarks>
        /// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, then the
        /// connection info will be disposed when this instance is disposed.
        /// </remarks>
        internal BaseClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory)
        {
            if (connectionInfo == null)
                throw new ArgumentNullException("connectionInfo");
            if (serviceFactory == null)
                throw new ArgumentNullException("serviceFactory");

            ConnectionInfo = connectionInfo;
            _ownsConnectionInfo = ownsConnectionInfo;
            _serviceFactory = serviceFactory;
            _keepAliveInterval = SshNet.Session.InfiniteTimeSpan;
        }
예제 #17
0
        public void Connect()
        {
            PluginConfigurationEntity configuration;
            using (var gateway = GlobalConfigurationGatewayFactory())
            {
                configuration = gateway.GetGlobalConfiguration();
            }

            var keyStream = new MemoryStream(Encoding.UTF8.GetBytes(configuration.PrivateKey));
            var connectionInfo = new ConnectionInfo(configuration.Host, configuration.Port, configuration.User,
                new PrivateKeyAuthenticationMethod(configuration.User, new PrivateKeyFile(keyStream)));
            _sshClient = new Renci.SshNet.SshClient(connectionInfo);
            _sshClient.Connect();
        }
예제 #18
0
        static void Main(string[] args)
        {
            string servers = ConfigurationManager.AppSettings["servers"];
            string username = ConfigurationManager.AppSettings["username"];
            string password = ConfigurationManager.AppSettings["password"];
            foreach (string server in servers.Split(','))
            {
                ConnectionInfo ConnNfo = new ConnectionInfo(server, 22, username,
                    new AuthenticationMethod[]{
                        // Pasword based Authentication
                        new PasswordAuthenticationMethod(username,password)
                    }
                    );

                string[] items = { "active_pwr", "energy_sum", "v_rms", "pf","enabled" };

                using (var sshclient = new SshClient(ConnNfo))
                {
                    Console.WriteLine("Connecting to {0}", server);
                    sshclient.Connect();
                    // quick way to use ist, but not best practice - SshCommand is not Disposed, ExitStatus not checked...
                    foreach (string itemName in items)
                    {
                        for (int port = 1; port < 7; port++)
                        {
                            string outputFileName = string.Format("{0}-{1}-{2}.txt", server, itemName, port);
                            Console.WriteLine(string.Format("{0}{1}", itemName, port));
                            string result = sshclient.CreateCommand(string.Format("cat /proc/power/{0}{1}", itemName, port)).Execute();
                            if (!File.Exists(outputFileName))
                            {
                                using (var writer = File.CreateText(outputFileName))
                                {
                                    writer.WriteLine(string.Format("{0}, {1}", DateTime.Now.Ticks, result));
                                }
                            }
                            else
                            {
                                using (var writer = File.AppendText(outputFileName))
                                {
                                    writer.WriteLine(string.Format("{0}, {1}", DateTime.Now.Ticks, result));
                                }
                            }
                            Console.WriteLine(result);
                        }
                    }
                    sshclient.Disconnect();
                }
            }
        }
예제 #19
0
        public Task <LivenessResult> IsHealthy(LivenessExecutionContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                _logger?.LogInformation($"{nameof(SftpLiveness)} is checking SFTP connections.");

                foreach (var item in _options.ConfiguredHosts.Values)
                {
                    var connectionInfo = new ConnectionInfo(item.Host, item.UserName, item.AuthenticationMethods.ToArray());

                    using (var sftpClient = new SftpClient(connectionInfo))
                    {
                        sftpClient.Connect();

                        var connectionSuccess = sftpClient.IsConnected && sftpClient.ConnectionInfo.IsAuthenticated;

                        if (connectionSuccess)
                        {
                            if (item.FileCreationOptions.createFile)
                            {
                                using (var stream = new MemoryStream(new byte[] { 0x0 }, 0, 1))
                                {
                                    sftpClient.UploadFile(stream, item.FileCreationOptions.remoteFilePath);
                                }
                            }
                        }
                        else
                        {
                            _logger?.LogWarning($"The {nameof(SftpLiveness)} check fail for sftp host {item.Host}.");

                            return(Task.FromResult(
                                       LivenessResult.UnHealthy($"Connection with sftp host {item.Host}:{item.Port} failed")));
                        }
                    }
                }

                _logger?.LogInformation($"The {nameof(SftpLiveness)} check success.");

                return(Task.FromResult(
                           LivenessResult.Healthy()));
            }
            catch (Exception ex)
            {
                _logger?.LogWarning($"The {nameof(SftpLiveness)} check fail with the exception {ex.ToString()}.");

                return(Task.FromResult(
                           LivenessResult.UnHealthy(ex)));
            }
        }
예제 #20
0
 public static void Add(string hostname, string username, string password, string keyFilePath)
 {
     var connInfo = new ConnectionInfo(
                        hostname,
                        username,
                        new AuthenticationMethod[] {
             new PasswordAuthenticationMethod(username, password),
             new PrivateKeyAuthenticationMethod(
                 username,
                 new [] { new PrivateKeyFile(keyFilePath, password) }),
         });
     
     // TODO: refactoring in SD?
     // ConnectionData.Entries.Add(connInfo);
     Entries.Add(connInfo);
 }
예제 #21
0
        private static void ScpUpload(string host, int port, string username, string privateKeyPath, string privateKeyPassphrase, string filePath, string destinationFilePath)
        {
            ConnectionInfo connInfo = new ConnectionInfo(host, username, new AuthenticationMethod[] {
                new PrivateKeyAuthenticationMethod(username, new PrivateKeyFile[] {
                    new PrivateKeyFile(privateKeyPath, privateKeyPassphrase)
                })
            });

            using (var scp = new ScpClient(connInfo))
            {
                scp.Connect();
                scp.Upload(new FileInfo(filePath), destinationFilePath);
                scp.Disconnect();
                ManageClipboard(filePath);
            }
        }
예제 #22
0
        /// <summary>
        /// 初期化
        /// </summary>
        /// <param name="host"></param>
        /// <param name="port"></param>
        /// <param name="userName"></param>
        /// <param name="userPasword"></param>
        protected override void Initialization(string host, int port, string userName, string userPasword)
        {
            // 基底クラス初期化
            base.Initialization(host, port, userName, userPasword);

            // 認証情報生成
            this.m_AuthenticationMethodList.Add(new PasswordAuthenticationMethod(userName, userPasword)
            {
            });

            // 接続情報生成
            this.m_ConnectionInfo = new ConnectionInfo(host, port, userName, this.m_AuthenticationMethodList.ToArray());

            // SSHクライアントオブジェクト生成
            this.m_Client = new Renci.SshNet.SshClient(this.m_ConnectionInfo);
        }
예제 #23
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SftpClient"/> class.
        /// </summary>
        /// <param name="connectionInfo">The connection info.</param>
        /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
        public ScpClient(ConnectionInfo connectionInfo)
            : base(connectionInfo)
        {
            this.OperationTimeout = new TimeSpan(0, 0, 0, 0, -1);
            this.BufferSize = 1024 * 16;

            if (_byteToChar == null)
            {
                _byteToChar = new char[128];
                var ch = '\0';
                for (int i = 0; i < 128; i++)
                {
                    _byteToChar[i] = ch++;
                }
            }
        }
예제 #24
0
 private ConnectionInfo GenerateConnectionInfo(string host, string username, string password)
 {
     var auth1 = new PasswordAuthenticationMethod(username, password);
     var auth2 = new KeyboardInteractiveAuthenticationMethod(username);
     auth2.AuthenticationPrompt += delegate(object sender, Renci.SshNet.Common.AuthenticationPromptEventArgs e)
     {
         foreach (var prompt in e.Prompts)
         {
             if (prompt.Request.Equals("Password: ", StringComparison.InvariantCultureIgnoreCase))
             {
                 prompt.Response = password;
             }
         }
     };
     ConnectionInfo ci = new ConnectionInfo(host, username, auth1, auth2);
     return ci;
 }
        public Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
        {
            try
            {
                foreach (var item in _options.ConfiguredHosts.Values)
                {
                    var connectionInfo = new ConnectionInfo(item.Host, item.Port, item.UserName, item.AuthenticationMethods.ToArray());

                    if (context.Registration.Timeout > TimeSpan.Zero)
                    {
                        connectionInfo.Timeout = context.Registration.Timeout;
                    }

                    using (var sftpClient = new SftpClient(connectionInfo))
                    {
                        sftpClient.Connect();

                        var connectionSuccess = sftpClient.IsConnected && sftpClient.ConnectionInfo.IsAuthenticated;
                        if (connectionSuccess)
                        {
                            if (item.FileCreationOptions.createFile)
                            {
                                using (var stream = new MemoryStream(new byte[] { 0x0 }, 0, 1))
                                {
                                    sftpClient.UploadFile(stream, item.FileCreationOptions.remoteFilePath);
                                }
                            }
                        }
                        else
                        {
                            return(Task.FromResult(
                                       new HealthCheckResult(context.Registration.FailureStatus, description: $"Connection with sftp host {item.Host}:{item.Port} failed.")));
                        }
                    }
                }

                return(Task.FromResult(
                           HealthCheckResult.Healthy()));
            }
            catch (Exception ex)
            {
                return(Task.FromResult(
                           new HealthCheckResult(context.Registration.FailureStatus, exception: ex)));
            }
        }
예제 #26
0
        public Task <(string, bool)> IsHealthy(HttpContext context, LivenessExecutionContext livenessContext,
                                               CancellationToken cancellationToken = default)
        {
            try
            {
                foreach (var item in _options.ConfiguredHosts.Values)
                {
                    var connectionInfo = new ConnectionInfo(item.Host, item.UserName, item.AuthenticationMethods.ToArray());

                    using (var sftpClient = new SftpClient(connectionInfo))
                    {
                        sftpClient.Connect();

                        var connectionSuccess = sftpClient.IsConnected && sftpClient.ConnectionInfo.IsAuthenticated;

                        if (connectionSuccess)
                        {
                            if (item.FileCreationOptions.createFile)
                            {
                                using (var stream = new MemoryStream(new byte[] { 0x0 }, 0, 1))
                                {
                                    sftpClient.UploadFile(stream, item.FileCreationOptions.remoteFilePath);
                                }
                            }
                        }
                        else
                        {
                            return(Task.FromResult(($"Connection with sftp host {item.Host}:{item.Port} failed", false)));
                        }
                    }
                }

                return(Task.FromResult((BeatPulseKeys.BEATPULSE_HEALTHCHECK_DEFAULT_OK_MESSAGE, true)));
            }
            catch (Exception ex)
            {
                var message = !livenessContext.IsDevelopment ? string.Format(BeatPulseKeys.BEATPULSE_HEALTHCHECK_DEFAULT_ERROR_MESSAGE, livenessContext.Name)
                    : $"Exception {ex.GetType().Name} with message ('{ex.Message}')";

                return(Task.FromResult((message, false)));
            }
        }
예제 #27
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SftpUploader"/> class
        /// with the specified <see cref="SftpClient"/>.
        /// </summary>
        /// <param name="info">An object containing the connection info.</param>
        /// <param name="timeout">
        /// The time in milliseconds to wait for a response from the server.
        /// </param>
        public SftpUploader(ConnectionInfo info, int timeout = 30000)
        {
            try
            {
                var keyFile = new PrivateKeyFile(info.PrivateKeyPath);
                client = new SftpClient(info.Host, info.Port, info.UserName,
                    keyFile);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex);
            }

            if (client == null)
            {
                client = new SftpClient(info.Host, info.Port, info.UserName,
                    info.Password);
            }
            client.ConnectionInfo.Timeout = TimeSpan.FromMilliseconds(timeout);
        }
예제 #28
0
        public SshClient(object options)
        {
            BlendedJSEngine.Clients.Value.Add(this);
            var host       = options.GetProperty("host").ToStringOrDefault();
            var port       = options.GetProperty("port").ToIntOrDefault(22);
            var user       = options.GetProperty("user").ToStringOrDefault();
            var password   = options.GetProperty("password").ToStringOrDefault();
            var privateKey = options.GetProperty("privateKey").ToStringOrDefault();

            if (string.IsNullOrEmpty(privateKey) == false)
            {
                byte[]         primateKeyBytes = Encoding.UTF8.GetBytes(privateKey);
                PrivateKeyFile primateKeyFile  = new PrivateKeyFile(new MemoryStream(primateKeyBytes));
                var            connectionInfo  = new Renci.SshNet.ConnectionInfo(host, port, user,
                                                                                 new PrivateKeyAuthenticationMethod(user, primateKeyFile));
                _client = new Renci.SshNet.SshClient(connectionInfo);
            }
            else
            {
                var connectionInfo = new Renci.SshNet.ConnectionInfo(host, port, user,
                                                                     new PasswordAuthenticationMethod(user, password));
                _client = new Renci.SshNet.SshClient(connectionInfo);
            }
        }
예제 #29
0
 /// <summary>
 /// Initializes a new instance of the <see cref="BaseClient"/> class.
 /// </summary>
 /// <param name="connectionInfo">The connection info.</param>
 /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
 /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
 /// <remarks>
 /// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, then the
 /// connection info will be disposed when this instance is disposed.
 /// </remarks>
 protected BaseClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
     : this(connectionInfo, ownsConnectionInfo, new ServiceFactory())
 {
 }
예제 #30
0
        /// <summary>
        /// Connect SSH client to remote host
        /// </summary>
        private static void ConnectSSHClient()
        {
            try
            {
                if (string.IsNullOrEmpty(UserName))
                {
                    throw new SshAuthenticationException("Missing Username");
                }

                if (string.IsNullOrEmpty(Password))
                {
                    throw new SshAuthenticationException("Missing Password");
                }

                Uri serverUri;
                var serverHost = ServerAddress;
                var serverPort = 22;
                if (Uri.TryCreate("tcp://" + ServerAddress, UriKind.Absolute, out serverUri))
                {
                    serverHost = serverUri.Host;
                    if (serverUri.Port > 0)
                    {
                        serverPort = serverUri.Port;
                    }
                }

                Renci.SshNet.ConnectionInfo connectionInfo = null;

                //Quick hack to add support for private key
                if (System.Text.RegularExpressions.Regex.IsMatch(Password, @"^-+ *BEGIN (?<keyName>\w+( \w+)*) PRIVATE KEY *-+\r?\n((Proc-Type: 4,ENCRYPTED\r?\nDEK-Info: (?<cipherName>[A-Z0-9-]+),(?<salt>[A-F0-9]+)\r?\n\r?\n)|(Comment: ""?[^\r\n]*""?\r?\n))?(?<data>([a-zA-Z0-9/+=]{1,80}\r?\n)+)-+ *END \k<keyName> PRIVATE KEY *-+"))
                {
                    PrivateKeyFile pkf = null;
                    if (Password.IndexOf("ENCRYPTED") == -1)
                    {
                        pkf = new PrivateKeyFile(new System.IO.MemoryStream(Encoding.ASCII.GetBytes(Password)));
                    }
                    else
                    {
                        var endpvk     = "-----END RSA PRIVATE KEY-----";
                        var passphrase = Password.Substring(Password.IndexOf(endpvk) + endpvk.Length);
                        pkf = new PrivateKeyFile(new System.IO.MemoryStream(Encoding.ASCII.GetBytes(Password)), passphrase);
                    }

                    connectionInfo = new Renci.SshNet.ConnectionInfo(serverHost, serverPort, UserName, new PrivateKeyAuthenticationMethod(UserName, pkf));
                }
                else
                {
                    connectionInfo = new Renci.SshNet.ConnectionInfo(serverHost, serverPort, UserName, new PasswordAuthenticationMethod(UserName, Password));
                }

                connectionInfo.Encoding = Encoding.UTF8;

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

                shellStream = client.CreateShellStream("xterm", Columns, Rows, Width, Height, 1024);
                shellStream.DataReceived += ShellStream_DataReceived;

                //Add support for StartProgram
                if (!string.IsNullOrEmpty(StartProgram))
                {
                    HandleKeyboardInput(StartProgram);
                }
            }
            catch (Exception e)
            {
                if (ConsoleOutput)
                {
                    Console.WriteLine(e.Message);
                }

                Trace.TraceError("Failed to connect ssh client, remote session {0} ({1})", RemoteSessionID, e);
                throw;
            }
            finally
            {
                if (client != null && !client.IsConnected)
                {
                    client.Dispose();
                    pipeMessaging.ClosePipes();
                }
            }
        }
예제 #31
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NetConfClient"/> class.
 /// </summary>
 /// <param name="connectionInfo">The connection info.</param>
 /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
 /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <c>null</c>.</exception>
 /// <remarks>
 /// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, then the
 /// connection info will be disposed when this instance is disposed.
 /// </remarks>
 private NetConfClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
     : this(connectionInfo, ownsConnectionInfo, new ServiceFactory())
 {
 }
예제 #32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NetConfClient"/> class.
 /// </summary>
 /// <param name="connectionInfo">The connection info.</param>
 /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
 /// <param name="serviceFactory">The factory to use for creating new services.</param>
 /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <c>null</c>.</exception>
 /// <exception cref="ArgumentNullException"><paramref name="serviceFactory"/> is <c>null</c>.</exception>
 /// <remarks>
 /// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, then the
 /// connection info will be disposed when this instance is disposed.
 /// </remarks>
 internal NetConfClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory)
     : base(connectionInfo, ownsConnectionInfo, serviceFactory)
 {
     _operationTimeout          = SshNet.Session.Infinite;
     AutomaticMessageIdHandling = true;
 }
예제 #33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SftpClient"/> class.
 /// </summary>
 /// <param name="connectionInfo">The connection info.</param>
 /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <c>null</c>.</exception>
 public NetConfClient(ConnectionInfo connectionInfo)
     : this(connectionInfo, false)
 {
 }
예제 #34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SshClient" /> class.
 /// </summary>
 /// <param name="connectionInfo">The connection info.</param>
 /// <example>
 ///     <code source="..\..\Renci.SshNet.Tests\Classes\PasswordConnectionInfoTest.cs" region="Example PasswordConnectionInfo" language="C#" title="Connect using PasswordConnectionInfo object" />
 ///     <code source="..\..\Renci.SshNet.Tests\Classes\PasswordConnectionInfoTest.cs" region="Example PasswordConnectionInfo PasswordExpired" language="C#" title="Connect using PasswordConnectionInfo object with passwod change option" />
 ///     <code source="..\..\Renci.SshNet.Tests\Classes\PrivateKeyConnectionInfoTest.cs" region="Example PrivateKeyConnectionInfo PrivateKeyFile" language="C#" title="Connect using PrivateKeyConnectionInfo" />
 ///     <code source="..\..\Renci.SshNet.Tests\Classes\SshClientTest.cs" region="Example SshClient Connect Timeout" language="C#" title="Specify connection timeout when connecting" />
 /// </example>
 /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
 public SshClient(ConnectionInfo connectionInfo)
     : base(connectionInfo)
 {
 }
예제 #35
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SftpClient"/> class.
 /// </summary>
 /// <param name="connectionInfo">The connection info.</param>
 /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
 /// <param name="serviceFactory">The factory to use for creating new services.</param>
 /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
 /// <exception cref="ArgumentNullException"><paramref name="serviceFactory"/> is null.</exception>
 /// <remarks>
 /// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, then the
 /// connection info will be disposed when this instance is disposed.
 /// </remarks>
 internal SftpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory)
     : base(connectionInfo, ownsConnectionInfo, serviceFactory)
 {
     OperationTimeout = new TimeSpan(0, 0, 0, 0, -1);
     BufferSize = 1024 * 32;
 }
예제 #36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SftpClient"/> class.
 /// </summary>
 /// <param name="connectionInfo">The connection info.</param>
 /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
 /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
 /// <remarks>
 /// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, then the
 /// connection info will be disposed when this instance is disposed.
 /// </remarks>
 private SftpClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
     : this(connectionInfo, ownsConnectionInfo, new ServiceFactory())
 {
 }
예제 #37
0
        private void btnUnixDetect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var KeyboardInteractive = new Ssh.KeyboardInteractiveAuthenticationMethod(Host.Username);
                var Password            = new Ssh.PasswordAuthenticationMethod(Host.Username, AES.DecryptString(Host.Password));
                var encryptedPassword   = Host.Password;
                KeyboardInteractive.AuthenticationPrompt += delegate(object sender1, Ssh.Common.AuthenticationPromptEventArgs e1)
                {
                    foreach (var prompt in e1.Prompts)
                    {
                        if (prompt.Request.ToLower().Contains("password"))
                        {
                            prompt.Response = AES.DecryptString(encryptedPassword);
                        }
                    }
                };
                var conn = new Ssh.ConnectionInfo(Host.Value,
                                                  Host.Username,
                                                  Password,
                                                  KeyboardInteractive);
                using (Ssh.SshClient client = new Ssh.SshClient(conn))
                {
                    client.Connect();
                    var termdic = new Dictionary <Ssh.Common.TerminalModes, uint>();
                    termdic.Add(Ssh.Common.TerminalModes.ECHO, 0);

                    using (var shell = client.CreateShellStream("gogrid", 80, 24, 800, 600, 1024, termdic))
                    {
                        using (var output = new StreamReader(shell))
                            using (var input = new StreamWriter(shell))
                            {
                                input.AutoFlush = true;
                                while (shell.Length == 0)
                                {
                                    Thread.Sleep(500);
                                }
                                //shell.WriteLine("stty raw -echo"); // disable echo
                                while (shell.Length != 0)
                                {
                                    shell.Read();
                                }
                                shell.Write("([ -d ~/oraInventory/ContentsXML/ ] && [ -e ~/oraInventory/ContentsXML/inventory.xml ])  && echo epmi1 || echo epmi0\n");
                                while (shell.Length == 0)
                                {
                                    Thread.Sleep(500);
                                }
                                var resp = shell.ReadLine();
                                while (shell.Length != 0)
                                {
                                    shell.Read();
                                }
                                if (System.Text.RegularExpressions.Regex.IsMatch(resp, "epmi1$"))
                                {
                                    shell.Write("cat ~/oraInventory/ContentsXML/inventory.xml\n");
                                    while (shell.Length == 0)
                                    {
                                        Thread.Sleep(500);
                                    }
                                    resp = Read(output, true);
                                    XmlDocument doc = new XmlDocument();
                                    doc.LoadXml(resp);
                                    var nodes = doc.SelectNodes("INVENTORY/HOME_LIST/HOME");
                                    for (int i = 0; i < nodes.Count; i++)
                                    {
                                        if (Regex.IsMatch(nodes[i].Attributes["NAME"].Value, @"EpmSystem_\S+"))
                                        {
                                            tbxUnixPath.Text = nodes[i].Attributes["LOC"].Value;
                                            break;
                                        }
                                    }
                                    MessageBox.Show("Success");
                                }
                            }
                    }
                    client.Disconnect();
                }
            }
            catch (Ssh.Common.SshAuthenticationException)
            {
                MessageBox.Show("Failed to authenticate to server. Check username and password.");
            }
            catch (Exception)
            {
                MessageBox.Show("Unknown error.");
            }
        }
예제 #38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SftpClient"/> class.
 /// </summary>
 /// <param name="connectionInfo">The connection info.</param>
 /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
 public NetConfClient(ConnectionInfo connectionInfo)
     : this(connectionInfo, false)
 {
 }
예제 #39
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SftpClient"/> class.
 /// </summary>
 /// <param name="connectionInfo">The connection info.</param>
 /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <b>null</b>.</exception>
 public SftpClient(ConnectionInfo connectionInfo)
     : this(connectionInfo, false)
 {
 }
예제 #40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NetConfClient"/> class.
 /// </summary>
 /// <param name="connectionInfo">The connection info.</param>
 /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
 /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
 /// <remarks>
 /// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, then the
 /// connection info will be disposed when this instance is disposed.
 /// </remarks>
 private NetConfClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo)
     : base(connectionInfo, ownsConnectionInfo)
 {
     this.OperationTimeout = new TimeSpan(0, 0, 0, 0, -1);
     this.AutomaticMessageIdHandling = true;
 }
예제 #41
0
 /// <summary>
 /// Creates a new <see cref="ISession"/> with the specified <see cref="ConnectionInfo"/>.
 /// </summary>
 /// <param name="connectionInfo">The <see cref="ConnectionInfo"/> to use for creating a new session.</param>
 /// <returns>
 /// An <see cref="ISession"/> for the specified <see cref="ConnectionInfo"/>.
 /// </returns>
 /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is <c>null</c>.</exception>
 public ISession CreateSession(ConnectionInfo connectionInfo)
 {
     return new Session(connectionInfo, this);
 }
예제 #42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NetConfClient"/> class.
 /// </summary>
 /// <param name="connectionInfo">The connection info.</param>
 /// <param name="ownsConnectionInfo">Specified whether this instance owns the connection info.</param>
 /// <param name="serviceFactory">The factory to use for creating new services.</param>
 /// <exception cref="ArgumentNullException"><paramref name="connectionInfo"/> is null.</exception>
 /// <exception cref="ArgumentNullException"><paramref name="serviceFactory"/> is null.</exception>
 /// <remarks>
 /// If <paramref name="ownsConnectionInfo"/> is <c>true</c>, then the
 /// connection info will be disposed when this instance is disposed.
 /// </remarks>
 internal NetConfClient(ConnectionInfo connectionInfo, bool ownsConnectionInfo, IServiceFactory serviceFactory)
     : base(connectionInfo, ownsConnectionInfo, serviceFactory)
 {
     OperationTimeout = new TimeSpan(0, 0, 0, 0, -1);
     AutomaticMessageIdHandling = true;
 }
예제 #43
-1
 private ConnectionInfo GenerateConnectionInfo()
 {
     var auth1 = new PasswordAuthenticationMethod(username, password);
     var auth2 = new KeyboardInteractiveAuthenticationMethod(username);
     auth2.AuthenticationPrompt += auth2_AuthenticationPrompt;
     ConnectionInfo ci = new ConnectionInfo(host, username, auth1, auth2);
     return ci;
 }
예제 #44
-1
        public SSHClient(string host, string port, string username, string password)
        {
            int portNum = 0;
            if(!int.TryParse(port, out portNum))
            {
                throw new Exception($"Port: {port}, must be an integer.");
            }

            try
            {
                var auth = new PasswordAuthenticationMethod(username, password);

                _connectionInfo = new ConnectionInfo(host, username, auth);
                _sshClient = new SshClient(_connectionInfo);
                _sftpClient = new SftpClient(_connectionInfo);
            }
            catch (Exception)
            {
                throw;
            }
        }