Provides SCP client functionality.
Exemplo n.º 1
2
        public void Connect(string remoteIp, string username, string password)
        {
            sshClient = new SshClient(remoteIp, username, password);
            scpClient = new ScpClient(remoteIp, username, password);

            Connect();
        }
Exemplo n.º 2
2
 public void Upload(string fileToUpload,string remotePath, string host)
 {
     try
     {
         using (ScpClient c = new ScpClient(host, m_userName, m_userPassword))
         {
             Log.DebugFormat("Uploading file: {0} to {1}", fileToUpload, host);
             c.Connect();
             c.Upload(new FileInfo(fileToUpload), remotePath);
             ExitStatus = 0;
             c.Disconnect();
         }
     }
     catch (Exception ex)
     {
         Log.ErrorFormat("Failed to upload : {0} to {1} because: {2}", fileToUpload, host, ex);
         ExitStatus = -1;
     }
 }
Exemplo n.º 3
1
        /// <summary>
        /// Copy from source to target
        /// </summary>
        /// <returns></returns>
        public override bool Execute(SshClient client)
        {
            Debug.WriteLine("CopyCommand");

            var scp = new ScpClient(client.ConnectionInfo) {BufferSize = 8*1024};

            Debug.WriteLine("Connect");

            // Need this or we get Dropbear exceptions...
            scp.Connect();

            Debug.WriteLine("Upload");

            bool status = false;
            try
            {
                scp.Upload(new FileInfo(Source), Target);
                status = true;
            } catch(Exception e)
            {
                Logger.Warn("Exception in SCP transfer: " + e.Message);
            }

            Debug.WriteLine("Done");

            return status;
        }
Exemplo n.º 4
1
        /// <summary>
        /// ListenPort
        /// </summary>
        /// <returns></returns>
        public string ListenPort()
        {
            Constants.log.Info("Entering ScpListener ListenPort Method!");
            string response = string.Empty;

            if (_scpClient == null && _connInfo == null)
            {
                Constants.log.Info("Calling ScpListener InitializeListener Method!");
                InitializeListener();
            }

            try
            {
                _scpClient = new ScpClient(_connInfo);
                _scpClient.Connect();
                _scpClient.Upload(new DirectoryInfo(this.Path), "/home/" + this.Path);
                response = "Uploaded successfully!";
            }
            catch (Exception ex)
            {
                Constants.log.Error(ex.Message);
                response = ex.Message;
            }

            Constants.log.Info("Exiting ScpListener ListenPort Method!");
            return response;
        }
Exemplo n.º 5
0
        private bool download()
        {
            folderBrowserDialog.Description = "Choose Where To Download";
              if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
            if (listView1.SelectedItems.Count > 0) {
              try {
            listView1.Enabled = false;
            ScpClient scpClient =
                new ScpClient(this.sftpClient.ConnectionInfo);
            scpClient.Connect();
            foreach (ListViewItem lvi in listView1.SelectedItems) {
              SftpFile sf = (SftpFile)(lvi.Tag);

              if (sf.IsDirectory) {
                scpClient.Download(sf.FullName,
                    new System.IO.DirectoryInfo(folderBrowserDialog.SelectedPath).CreateSubdirectory(sf.Name));
              } else {
                scpClient.Download(sf.FullName,
                    new System.IO.FileInfo(folderBrowserDialog.SelectedPath + "\\" + sf.Name));
              }
            }
            scpClient.Disconnect();
              } catch (Exception ex) {
              } finally {
            listView1.Enabled = true;
              }
            }
              }
              return true;
        }
Exemplo n.º 6
0
        public SshManager(string remoteIp, string username, string password, bool autoConnect = false)
        {
            sshClient = new SshClient(remoteIp, username, password);
            scpClient = new ScpClient(remoteIp, username, password);

            if (autoConnect)
                Connect();
        }
Exemplo n.º 7
0
 public Uploader(TargetProfile p)
 {
     Ip = p.IpAddress.ToString();
     UserName = p.Login;
     var password = p.Pass.ToString(); //TODO: remove vulnerability breach 
     _scpClient = new ScpClient(Ip, UserName, password);
     _sshClient = new SshClient(Ip, UserName, password);
 }
Exemplo n.º 8
0
 public override void Dispose()
 {
     if (_scp != null)
     {
         _scp.Dispose();
         _scp = null;
     }
 }
Exemplo n.º 9
0
 /// <summary>
 /// Copy a file from the remote to the local machine
 /// </summary>
 /// <param name="p1"></param>
 /// <param name="p2"></param>
 public FileInfo CopyToLocal(string remoteFileName, string localFileName)
 {
     var scp = new ScpClient(_host, _username, Passwords.FetchPassword(_host, _username));
     scp.Connect();
     var lf = new FileInfo(localFileName);
     scp.Download(remoteFileName, lf);
     return lf;
 }
Exemplo n.º 10
0
        /// <summary>
        /// Open a Connection to the cloudera
        /// </summary> 
        private void OpenConnecion()
        {
            sshClient = new SshClient(hostname, userName, password);
            sshClient.Connect();

            scpClient = new ScpClient(hostname, userName, password);
            scpClient.Connect();
        }
Exemplo n.º 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();
            }
        }
Exemplo n.º 12
0
        public SCP(Target target)
        {
            _scp = new ScpClient(target.TargetServer.Host,
                target.TargetServer.UserInfo,
                target.Password);

            log.InfoFormat("SCP - Connecting to {0}", target.TargetServer);
            _scp.Connect();

            _targetPath = target.TargetServer.LocalPath;
            if (!_targetPath.EndsWith("/")) _targetPath += "/";
        }
Exemplo n.º 13
0
		public ScpUpload(string IPAddress, string localPath, string remotePath)
		{
			_localPath = localPath;
			_remotePath = remotePath;
			_scpClient = new ScpClient(IPAddress, "root", "");
			_sshHelper = new SshCommandHelper(IPAddress);
			_fileHash = UserSettings.Instance.LastUploadHash;

			Success = false;
			SuccessWithWarnings = false;
			ErrorMessage = "";
		}
Exemplo n.º 14
0
        public static void flash_px4(string firmware_file)
        {
            if (is_solo_alive)
            {
                using (SshClient client = new SshClient("10.1.1.10", 22, "root", "TjSDBkAu"))
                {
                    client.KeepAliveInterval = TimeSpan.FromSeconds(5);
                    client.Connect();

                    if (!client.IsConnected)
                        throw new Exception("Failed to connect ssh");

                    var retcode = client.RunCommand("rm -rf /firmware/loaded");
                    
                    using (ScpClient scpClient = new ScpClient(client.ConnectionInfo))
                    {
                        scpClient.Connect();

                        if (!scpClient.IsConnected)
                            throw new Exception("Failed to connect scp");

                        scpClient.Upload(new FileInfo(firmware_file), "/firmware/" + Path.GetFileName(firmware_file));
                    }

                    var st = client.CreateShellStream("bash", 80, 24, 800, 600, 1024*8);

                    // wait for bash prompt
                    while (!st.DataAvailable)
                        System.Threading.Thread.Sleep(200);

                    st.WriteLine("loadPixhawk.py; exit;");
                    st.Flush();

                    StringBuilder output = new StringBuilder();

                    while (client.IsConnected)
                    {
                        var line = st.Read();
                        Console.Write(line);
                        output.Append(line);
                        System.Threading.Thread.Sleep(100);

                        if (output.ToString().Contains("logout"))
                            break;
                    }
                }
            }
            else
            {
                throw new Exception("Solo is not responding to pings");
            }
        }
Exemplo n.º 15
0
        public void Connect()
        {
            if(Protocol == SSHTransferProtocol.SCP)
            {
                ScpClt = new ScpClient(Host, Port, User, Password);
                ScpClt.Connect();
            }

            if (Protocol == SSHTransferProtocol.SFTP)
            {
                SftpClt = new SftpClient(Host, Port, User, Password);
                SftpClt.Connect();
            }
        }
Exemplo n.º 16
0
        public SSHHelper(string serverAddr, string port, string userName, string password)
        {
            _serverAddr = serverAddr;
            _password = password;
            _port = port;
            _username = userName;
            
            int portNum;
            bool success = int.TryParse(port, out portNum);

            if(success){
                _sshConnection = new SshClient(serverAddr, portNum, userName, password);
                _scpConnection = new ScpClient(serverAddr, portNum, userName, password);
            }
        }
Exemplo n.º 17
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);
            }
        }
Exemplo n.º 18
0
        public static void getData(String WAPath, String username, String password, String host)
        {
            String localPath  = "Cache.db-wal";
            String remotePath = WAPath + "/Library/Caches/net.whatsapp.WhatsApp/Cache.db-wal";
            String pwFile     = WAPath + "/Library/pw.dat";

            var scp = new Renci.SshNet.ScpClient(host, username, password);

            try
            {
                scp.Connect();
            }
            catch (Exception error)
            {
                Console.WriteLine("Coundn't connect to iPhone");
            }

            if (scp.IsConnected)
            {
                Console.WriteLine("SCP started (" + host + "). Downloading files...");
            }

            try
            {
                Stream cacheFile = File.OpenWrite(localPath);
                scp.Download(remotePath, cacheFile);
                cacheFile.Close();
            }

            catch (Exception error)
            {
                Console.WriteLine("\nCache.db-wal not found");
            }
            try
            {
                Stream filePW = File.OpenWrite("pw.dat");
                scp.Download(pwFile, filePW);
                filePW.Close();
            }
            catch (Exception error)
            {
                Console.WriteLine("\npw.dat not found\n");
            }

            scp.Disconnect();
        }
Exemplo n.º 19
0
        private void InternalConnect(string host, int port, string username, string password, string workingDirectory)
        {
            if (_isConnected)
            {
                // Change the working directory only if we use ScpClient.
                if (_scpClient != null)
                {
                    ChangeWorkingDirectory(workingDirectory);
                }
                return;
            }

            // Restart timer
            _stopWatch.Restart();
            _lastElapsedMilliseconds = 0;

            // Start connection ...
            PrintTime($"Connecting to {username}@{host}:{port} ...");

            _sshClient = new SshClient(host, port, username, password);
            _sshClient.Connect();

            try
            {
                // Use SFTP for file transfers
                var sftpClient = new SftpClient(host, port, username, password);
                sftpClient.Connect();
                _sftpClient = sftpClient;
            }
            catch (Exception ex)
            {
                // Use SCP if SFTP fails
                PrintTime($"Error: {ex.Message} Is SFTP supported for {username}@{host}:{port}? We are using SCP instead!");
                _scpClient = new ScpClient(host, port, username, password);
                _scpClient.Connect();
            }

            var _connectionInfo = _sshClient.ConnectionInfo;

            PrintTime($"Connected to {_connectionInfo.Username}@{_connectionInfo.Host}:{_connectionInfo.Port} via SSH and {(_sftpClient != null ? "SFTP" : "SCP")}");

            _isConnected = true;

            ChangeWorkingDirectory(workingDirectory);
        }
Exemplo n.º 20
0
        public SSHConnection(string host, string username)
        {
            // Fetch the username and password.
            var sclist = new CredentialSet(host);
            var passwordInfo = sclist.Load().Where(c => c.Username == username).FirstOrDefault();
            if (passwordInfo == null)
            {
                throw new ArgumentException(string.Format("Please create a generic windows credential with '{0}' as the target address, '{1}' as the username, and the password for remote SSH access to that machine.", host, username));
            }

            // Create the connection, but do it lazy so we don't do anything if we aren't used.
            _client = new Lazy<SshClient>(() => {
                var c = new SshClient(host, username, passwordInfo.Password);
                c.Connect();
                return c;
            });

            // Create the scp client for copying things
            _scp = new Lazy<ScpClient>(() =>
            {
                var c = new ScpClient(host, username, passwordInfo.Password);
                c.Connect();
                c.ErrorOccurred += (sender, error) => _scpError = error.Exception;
                return c;
            });

            // And create a shell stream. Initialize to find the prompt so we can figure out, later, when
            // a task has finished.
            _shell = new Lazy<ShellStream>(() => {
                var s = _client.Value.CreateShellStream("Commands", TerminalWidth, 200, 132, 80, 240 * 200);
                s.WaitTillPromptText();
                s.WriteLine("# this initialization");
                DumpTillFind(s, "# this initialization");
                s.ReadLine(); // Get past the "new-line" that is at the end of the printed comment above
                _prompt = s.ReadRemainingText(100);
                Trace.WriteLine("Initialization: prompt=" + _prompt, "SSHConnection");
                return s;
            });
        }
Exemplo n.º 21
0
        public void Download(string file, string host)
        {
            try
            {
                string fileName = "./" +  Path.GetFileName(file);

                using (ScpClient c = new ScpClient(host,m_userName,m_userPassword))
                {
                    Log.DebugFormat("Downloading {0} ,from: {1}", file, host);
                    c.Connect();
                    c.Download(file, new FileInfo(fileName));
                    ExitStatus = 0;
                    c.Disconnect();
                }
                Log.Debug("Reading file...");
                Result = File.ReadAllText(fileName);
            }
            catch (Exception ex)
            {
                Log.ErrorFormat("Failed to download:{0} from: {1} because: {2}", file, host, ex);
                ExitStatus = -1;
            }
        }
        public static async Task<bool> DeployFiles(IEnumerable files, string deployLocation, ConnectionUser user)
        {
            ConnectionInfo connectionInfo;
            switch (user)
            {
                case ConnectionUser.Admin:
                    connectionInfo = s_adminConnectionInfo;
                    break;
                case ConnectionUser.LvUser:
                    connectionInfo = s_lvUserConnectionInfo;
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(user), user, null);
            }

            if (connectionInfo == null) return false;
            using (ScpClient scp = new ScpClient(connectionInfo))
            {
                try
                {
                    await Task.Run(() => scp.Connect());
                }
                catch (SshOperationTimeoutException)
                {
                    return false;
                }
                var settings = (SettingsPageGrid)Frc_ExtensionPackage.Instance.PublicGetDialogPage(typeof(SettingsPageGrid));
                bool verbose = settings.Verbose || settings.DebugMode;
                foreach (FileInfo fileInfo in from string s in files where File.Exists(s) select new FileInfo(s))
                {
                    if (verbose)
                    {
                        OutputWriter.Instance.WriteLine($"Deploying File: {fileInfo.Name}");
                    }
                    await Task.Run(() => scp.Upload(fileInfo, deployLocation));
                }
            }
            return true;
        }
Exemplo n.º 23
0
 public void GetTable(string host, string userName, string rootPassword)
 {
     string file = "Table.txt";
         string fileName = "./" + Path.GetFileName(file);
         using (ScpClient c = new ScpClient(host, userName, rootPassword))
         {
             c.Connect();
             c.Download(file, new FileInfo(fileName));
             c.Disconnect();
         }
 }
Exemplo n.º 24
0
        private bool tryInitConnection()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name);
            var ip = ConfigurationManager.AppSettings["HostIP"];
            var userName = ConfigurationManager.AppSettings["HostPass"];
            var pass = ConfigurationManager.AppSettings["UserName"];

            try {
                sshConn = new SshClient(ip, userName, pass);

                sshConn.Connect();
                sshConn.Disconnect();
            }
            catch
            {
                return false;
            }
            try
            {
                scpClient = new ScpClient(ip, userName, pass);

                scpClient.Connect();
                scpClient.Disconnect();
            }
            catch
            {
                return false;
            }

            try
            {
                sftpConn = new SftpClient(ip, userName, pass);

                sftpConn.Connect();
                sftpConn.Disconnect();

                return true;
            }
            catch
            {
                return false;
            }
        }
Exemplo n.º 25
0
 public LinuxExecutor(SshClient ssh, SftpClient sftp, ScpClient scp)
 {
     sshConn = ssh;
     sftpConn = sftp;
     scpClient = scp;
 }
		private static void CopyTheLatestSourceFiles()
		{
			string currentDirectory = Directory.GetCurrentDirectory();
			IEnumerable<string> directoryInfo =
				Directory.GetFiles(currentDirectory, "BuildIndicatron*.*", SearchOption.AllDirectories)
				         .Union(Directory.GetFiles(currentDirectory, "*.html", SearchOption.AllDirectories));
			ConnectionInfo connectionInfo = new PasswordConnectionInfo(Host, UserName, Password);
            
			var scpClient = new ScpClient(connectionInfo);
			scpClient.Connect();
			_log.Info(string.Format("Copy {0} files", directoryInfo.Count()));
			foreach (string source in directoryInfo.Where(x => !x.Contains(".Test.dll")))
			{
				string sourceName = source.Replace(currentDirectory + "\\", "");
				string remoteFileName = Path.Combine(_homePiBuildindicatronServer, sourceName.Replace("\\", "/"));
				_log.Info(string.Format("Upload:{0} to {1}", sourceName, remoteFileName));
				scpClient.Upload(new FileInfo(source), remoteFileName);
			}
			scpClient.Disconnect();
		}
Exemplo n.º 27
0
 /// <summary>
 /// Upload a file to the connected server.
 /// </summary>
 /// <param name="fileinfo">Local file</param>
 /// <param name="newfile">Server upload full-qualified filename</param>
 public bool UploadFile(FileInfo fileinfo, string newfile)
 {
     bool retVal = false;
     if (!disposed && base.IsConnected)
     {
         using (ScpClient transfer = new ScpClient(base.ConnectionInfo))
         {
             try
             {
                 transfer.Connect();
                 transfer.OperationTimeout = new TimeSpan(0, 1, 0);
                 transfer.Upload(fileinfo, newfile);
                 retVal = true;
             }
             catch
             {
                 retVal = false;
             }
             finally
             {
                 transfer.Disconnect();
             }
         }
     }
     return retVal;
 }
Exemplo n.º 28
0
        protected override void ProcessRecord()
        {
            if (_keyfile.Equals(""))
            {
                foreach (var computer in _computername)
                {
                    #region AuthUserPass
                    //###########################################
                    //### Connect using Username and Password ###
                    //###########################################

                    ConnectionInfo connectInfo;
                    KeyboardInteractiveAuthenticationMethod kIconnectInfo;
                    if (_proxyserver != "")
                    {
                        #region Proxy
                        // Set the proper proxy type
                        var ptype = ProxyTypes.Http;
                        WriteVerbose("A Proxy Server has been specified");
                        switch (_proxytype)
                        {
                            case "HTTP":
                                ptype = ProxyTypes.Http;
                                break;
                            case "Socks4":
                                ptype = ProxyTypes.Socks4;
                                break;
                            case "Socks5":
                                ptype = ProxyTypes.Socks5;
                                break;
                        }

                        kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.GetNetworkCredential().UserName);
                        var passconnectInfo = new PasswordAuthenticationMethod(_credential.GetNetworkCredential().UserName, _credential.GetNetworkCredential().Password);

                        WriteVerbose("Connecting to " + computer + " with user " + _credential.GetNetworkCredential().UserName);
                        connectInfo = new ConnectionInfo(computer,
                            _port,
                            _credential.GetNetworkCredential().UserName,
                            ptype,
                            _proxyserver,
                            _proxyport,
                            _proxycredential.GetNetworkCredential().UserName,
                            _proxycredential.GetNetworkCredential().Password,
                            kIconnectInfo,
                            passconnectInfo);

                        #endregion
                    } // Proxy Server
                    else
                    {
                        #region No Proxy
                        WriteVerbose("Using Username and Password authentication for connection.");
                        // Connection info for Keyboard Interactive
                        kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.GetNetworkCredential().UserName);
                        var passconnectInfo = new PasswordAuthenticationMethod(_credential.GetNetworkCredential().UserName, _credential.GetNetworkCredential().Password);

                        WriteVerbose("Connecting to " + computer + " with user " + _credential.GetNetworkCredential().UserName);
                        connectInfo = new ConnectionInfo(computer,
                            _port,
                            _credential.GetNetworkCredential().UserName,
                            passconnectInfo,
                            kIconnectInfo);

                        #endregion
                    }// No Proxy

                    // Event Handler for interactive Authentication
                    kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                                prompt.Response = _credential.GetNetworkCredential().Password;
                        }
                    };
                    //Ceate instance of SCP Client with connection info
                    var client = new ScpClient(connectInfo);

                    // Handle host key
                    string computer1 = computer;
                    client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                    {
                        var sb = new StringBuilder();
                        foreach (var b in e.FingerPrint)
                        {
                            sb.AppendFormat("{0:x}:", b);
                        }
                        string fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);

                        if (_sshHostKeys.ContainsKey(computer1))
                        {
                            if (_sshHostKeys[computer1] == fingerPrint)
                            {
                                //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer);
                                e.CanTrust = true;
                            }
                            else
                            {
                                throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer1);
                            }
                        }
                        else
                        {
                            var choices = new Collection<ChoiceDescription>
                            {
                                new ChoiceDescription("Y"),
                                new ChoiceDescription("N")
                            };

                            int choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);

                            if (choice == 0)
                            {
                                var keymng = new TrustedKeyMng();
                                //this.Host.UI.WriteVerboseLine("Saving fingerprint " + FingerPrint + " for host " + computer);
                                keymng.SetKey(computer1, fingerPrint);
                                e.CanTrust = true;
                            }
                            else
                            {
                                e.CanTrust = false;
                            }
                        }
                    };

                    // Set the connection timeout
                    client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                    // Set the Operation Timeout
                    client.OperationTimeout = TimeSpan.FromSeconds(_operationtimeout);

                    // Connect to  host using Connection info
                    client.Connect();
                    client.BufferSize = 1024;

                    // Print progess of download.
                    client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                    {
                        var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size));

                        if (e.Size != 0)
                        {
                            progressRecord.PercentComplete = Convert.ToInt32((e.Downloaded * 100) / e.Size);

                            Host.UI.WriteProgress(1, progressRecord);
                        }
                    };
                    WriteVerbose("Connection succesfull");
                    var localfullPath = Path.GetFullPath(_localfile);

                    WriteVerbose("Downloading " + _remotefile);
                    var fil = new FileInfo(@localfullPath);

                    // Download the file
                    client.Download(_remotefile, fil);

                    client.Disconnect();
                } //end foreach computer
                    #endregion
            } //Use/Password Auth
            else
            {
                //##########################
                //### Connect using Keys ###
                //##########################

                WriteVerbose("Using SSH Key authentication for connection.");
                var fullPath = Path.GetFullPath(_keyfile);

                if (File.Exists(fullPath))
                {
                    foreach (var computer in _computername)
                    {
                        PrivateKeyConnectionInfo connectionInfo;
                        if (_proxyserver != "")
                        {
                            // Set the proper proxy type
                            var ptype = ProxyTypes.Http;
                            WriteVerbose("A Proxy Server has been specified");
                            switch (_proxytype)
                            {
                                case "HTTP":
                                    ptype = ProxyTypes.Http;
                                    break;
                                case "Socks4":
                                    ptype = ProxyTypes.Socks4;
                                    break;
                                case "Socks5":
                                    ptype = ProxyTypes.Socks5;
                                    break;
                            }

                            if (_credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, 
                                    _port,
                                    _credential.GetNetworkCredential().UserName, 
                                    sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), _credential.GetNetworkCredential().Password);

                                if (_proxycredential.UserName == "")
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        _port,
                                        _credential.GetNetworkCredential().UserName,
                                        ptype,
                                        _proxyserver,
                                        _proxyport,
                                        sshkey);
                                }
                                else
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        _port,
                                        _credential.GetNetworkCredential().UserName,
                                        ptype,
                                        _proxyserver,
                                        _proxyport,
                                        _proxycredential.GetNetworkCredential().UserName,
                                        _proxycredential.GetNetworkCredential().Password,
                                        sshkey);
                                }
                            }
                        }
                        else
                        {

                            if (_credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, 
                                    _port,
                                    _credential.GetNetworkCredential().UserName, 
                                    sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), _credential.GetNetworkCredential().Password);
                                connectionInfo = new PrivateKeyConnectionInfo(computer, 
                                    _port,
                                    _credential.GetNetworkCredential().UserName, 
                                    sshkey);
                            }
                        }

                        //Ceate instance of SCP Client with connection info
                        var client = new ScpClient(connectionInfo);

                        // Handle host key
                        string computer1 = computer;
                        client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                        {
                            var sb = new StringBuilder();
                            foreach (var b in e.FingerPrint)
                            {
                                sb.AppendFormat("{0:x}:", b);
                            }
                            string fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);

                            if (_sshHostKeys.ContainsKey(computer1))
                            {
                                if (_sshHostKeys[computer1] == fingerPrint)
                                {
                                    //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer1);
                                }
                            }
                            else
                            {
                                var choices = new Collection<ChoiceDescription>
                                {
                                    new ChoiceDescription("Y"),
                                    new ChoiceDescription("N")
                                };

                                int choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);

                                if (choice == 0)
                                {
                                    var keymng = new TrustedKeyMng();

                                    keymng.SetKey(computer1, fingerPrint);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    e.CanTrust = false;
                                }
                            }
                        };

                        // Set the connection timeout
                        client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                        // Set the Operation Timeout
                        client.OperationTimeout = TimeSpan.FromSeconds(_operationtimeout);

                        // Connect to  host using Connection info
                        client.Connect();

                        client.BufferSize = 1024;

                        // Print progess of download.
                        client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                        {
                            var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size));

                            if (e.Size != 0)
                            {
                                progressRecord.PercentComplete = Convert.ToInt32((e.Downloaded * 100) / e.Size);

                                Host.UI.WriteProgress(1, progressRecord);
                            }
                        };

                        WriteVerbose("Connection succesfull");
                        var localfullPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(_localfile);

                        WriteVerbose("Downloading " + _remotefile);
                        var fil = new FileInfo(@localfullPath);

                        // Download the file
                        client.Download(_remotefile, fil);

                        client.Disconnect();
                    }

                }// file exist
                else
                {
                    throw new FileNotFoundException("Key file " + fullPath + " was not found.");
                }
            }

        } // End process record
Exemplo n.º 29
0
 private void UploadTable(string hostName, string userName, string rootPassword)
 {
     using (ScpClient c = new ScpClient(hostName, userName, rootPassword))
     {
         c.Connect();
         const string remotePath = "/";
         c.Upload(new FileInfo("Table.sh"), remotePath);
         c.Disconnect();
     }
 }
Exemplo n.º 30
0
        protected override void ProcessRecord()
        {
            if (keyfile.Equals(""))
            {
                foreach (var computer in computername)
                {
                    #region AuthUserPass
                    //###########################################
                    //### Connect using Username and Password ###
                    //###########################################

                    ConnectionInfo connectInfo;
                    KeyboardInteractiveAuthenticationMethod KIconnectInfo;
                    if (proxyserver != "")
                    {
                        #region Proxy
                        // Set the proper proxy type
                        var ptype = Renci.SshNet.ProxyTypes.Http;
                        WriteVerbose("A Proxy Server has been specified");
                        switch (proxytype)
                        {
                            case "HTTP":
                                ptype = Renci.SshNet.ProxyTypes.Http;
                                break;
                            case "Socks4":
                                ptype = Renci.SshNet.ProxyTypes.Socks4;
                                break;
                            case "Socks5":
                                ptype = Renci.SshNet.ProxyTypes.Socks5;
                                break;
                        }

                        KIconnectInfo = new KeyboardInteractiveAuthenticationMethod(credential.GetNetworkCredential().UserName);
                        var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password);

                        WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName);
                        connectInfo = new ConnectionInfo(computer,
                            port,
                            credential.GetNetworkCredential().UserName,
                            ptype,
                            proxyserver,
                            proxyport,
                            proxycredential.GetNetworkCredential().UserName,
                            proxycredential.GetNetworkCredential().Password,
                            KIconnectInfo,
                            PassconnectInfo);

                        #endregion
                    } // Proxy Server
                    else
                    {
                        #region No Proxy
                        WriteVerbose("Using Username and Password authentication for connection.");
                        // Connection info for Keyboard Interactive
                        KIconnectInfo = new KeyboardInteractiveAuthenticationMethod(credential.GetNetworkCredential().UserName);
                        var PassconnectInfo = new PasswordAuthenticationMethod(credential.GetNetworkCredential().UserName, credential.GetNetworkCredential().Password);

                        WriteVerbose("Connecting to " + computer + " with user " + credential.GetNetworkCredential().UserName);
                        connectInfo = new Renci.SshNet.ConnectionInfo(computer, credential.GetNetworkCredential().UserName,
                                    PassconnectInfo,
                                    KIconnectInfo);

                        #endregion
                    }// No Proxy

                    // Event Handler for interactive Authentication
                    KIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                                prompt.Response = credential.GetNetworkCredential().Password;
                        }
                    };
                    try
                    {
                        //Ceate instance of SCP Client with connection info
                        var Client = new ScpClient(connectInfo);

                        // Handle host key
                        Client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                        {
                            var sb = new StringBuilder();
                            foreach (var b in e.FingerPrint)
                            {
                                sb.AppendFormat("{0:x}:", b);
                            }
                            string FingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);
                            //this.Host.UI.WriteVerboseLine("Key algorithm of " + Client.ConnectionInfo.CurrentHostKeyAlgorithm);
                            //this.Host.UI.WriteVerboseLine("Key exchange alhorithm " + Client.ConnectionInfo.CurrentKeyExchangeAlgorithm);
                            //this.Host.UI.WriteVerboseLine("Host key fingerprint: " + FingerPrint);
                            if (SSHHostKeys.ContainsKey(computer))
                            {
                                if (SSHHostKeys[computer] == FingerPrint)
                                {
                                    //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer);
                                }
                            }
                            else
                            {
                                Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>();
                                choices.Add(new ChoiceDescription("Y"));
                                choices.Add(new ChoiceDescription("N"));

                                int choice = this.Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + FingerPrint, choices, 1);

                                if (choice == 0)
                                {
                                    var keymng = new TrustedKeyMng();
                                    //this.Host.UI.WriteVerboseLine("Saving fingerprint " + FingerPrint + " for host " + computer);
                                    keymng.SetKey(computer, FingerPrint);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    e.CanTrust = false;
                                }
                            }
                        };

                        // Set the connection timeout
                        Client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(connectiontimeout);

                        // Set the Operation Timeout
                        Client.OperationTimeout = TimeSpan.FromSeconds(operationtimeout);

                        // Connect to  host using Connection info
                        Client.Connect();
                        Client.BufferSize = 1024;

                        // Print progess of download.
                        Client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                        {
                            var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size));

                            if (e.Size != 0)
                            {
                                progressRecord.PercentComplete = Convert.ToInt32((e.Downloaded * 100) / e.Size);

                                this.Host.UI.WriteProgress(1, progressRecord);
                            }
                        };

                        var localfullPath = Path.GetFullPath(localfolder);
                        WriteVerbose("Downloading " + remotefolder);
                        DirectoryInfo dirinfo = new DirectoryInfo(@localfullPath);
                        Client.Download(remotefolder, dirinfo);
                        Client.Disconnect();
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                } //end foreach computer
                    #endregion
            } //Use/Password Auth
            else
            {
                //##########################
                //### Connect using Keys ###
                //##########################

                WriteVerbose("Using SSH Key authentication for connection.");
                var fullPath = Path.GetFullPath(keyfile);

                if (File.Exists(fullPath))
                {
                    foreach (var computer in computername)
                    {
                        PrivateKeyConnectionInfo connectionInfo;
                        if (proxyserver != "")
                        {
                            // Set the proper proxy type
                            var ptype = Renci.SshNet.ProxyTypes.Http;
                            WriteVerbose("A Proxy Server has been specified");
                            switch (proxytype)
                            {
                                case "HTTP":
                                    ptype = Renci.SshNet.ProxyTypes.Http;
                                    break;
                                case "Socks4":
                                    ptype = Renci.SshNet.ProxyTypes.Socks4;
                                    break;
                                case "Socks5":
                                    ptype = Renci.SshNet.ProxyTypes.Socks5;
                                    break;
                            }

                            if (credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), credential.GetNetworkCredential().Password);

                                if (proxycredential.UserName == "")
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        credential.GetNetworkCredential().UserName,
                                        ptype,
                                        proxyserver,
                                        proxyport,
                                        sshkey);
                                }
                                else
                                {
                                    connectionInfo = new PrivateKeyConnectionInfo(computer,
                                        credential.GetNetworkCredential().UserName,
                                        ptype,
                                        proxyserver,
                                        proxyport,
                                        proxycredential.GetNetworkCredential().UserName,
                                        proxycredential.GetNetworkCredential().Password,
                                        sshkey);
                                }
                            }
                        }
                        else
                        {

                            if (credential.GetNetworkCredential().Password == "")
                            {
                                WriteVerbose("Using key with no passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath));
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }
                            else
                            {
                                WriteVerbose("Using key with passphrase.");
                                var sshkey = new PrivateKeyFile(File.OpenRead(@fullPath), credential.GetNetworkCredential().Password);
                                connectionInfo = new PrivateKeyConnectionInfo(computer, credential.GetNetworkCredential().UserName, sshkey);
                            }
                        }

                        try
                        {
                            //Ceate instance of SCP Client with connection info
                            var Client = new ScpClient(connectionInfo);

                            // Handle host key
                            Client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                            {
                                var sb = new StringBuilder();
                                foreach (var b in e.FingerPrint)
                                {
                                    sb.AppendFormat("{0:x}:", b);
                                }
                                string FingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);
                                //this.Host.UI.WriteVerboseLine("Key algorithm of " + Client.ConnectionInfo.CurrentHostKeyAlgorithm);
                                //this.Host.UI.WriteVerboseLine("Key exchange alhorithm " + Client.ConnectionInfo.CurrentKeyExchangeAlgorithm);
                                //this.Host.UI.WriteVerboseLine("Host key fingerprint: " + FingerPrint);
                                if (SSHHostKeys.ContainsKey(computer))
                                {
                                    if (SSHHostKeys[computer] == FingerPrint)
                                    {
                                        //this.Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerpring for host " + computer);
                                        e.CanTrust = true;
                                    }
                                    else
                                    {
                                        throw new System.Security.SecurityException("SSH fingerprint mistmatch for host " + computer);
                                    }
                                }
                                else
                                {
                                    Collection<ChoiceDescription> choices = new Collection<ChoiceDescription>();
                                    choices.Add(new ChoiceDescription("Y"));
                                    choices.Add(new ChoiceDescription("N"));

                                    int choice = this.Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + FingerPrint, choices, 1);

                                    if (choice == 0)
                                    {
                                        var keymng = new TrustedKeyMng();
                                        //this.Host.UI.WriteVerboseLine("Saving fingerprint " + FingerPrint + " for host " + computer);
                                        keymng.SetKey(computer, FingerPrint);
                                        e.CanTrust = true;
                                    }
                                    else
                                    {
                                        e.CanTrust = false;
                                    }
                                }
                            };

                            // Set the connection timeout
                            Client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(connectiontimeout);

                            // Set the Operation Timeout
                            Client.OperationTimeout = TimeSpan.FromSeconds(operationtimeout);

                            // Connect to  host using Connection info
                            Client.Connect();

                            Client.BufferSize = 1024;

                            // Print progess of download.
                            Client.Downloading += delegate(object sender, ScpDownloadEventArgs e)
                            {
                                var progressRecord = new ProgressRecord(1, "Downloading " + e.Filename, String.Format("{0} Bytes Downloaded of {1}", e.Downloaded, e.Size));

                                if (e.Size != 0)
                                {
                                    progressRecord.PercentComplete = Convert.ToInt32((e.Downloaded * 100) / e.Size);

                                    this.Host.UI.WriteProgress(1, progressRecord);
                                }
                            };

                            var localfullPath = Path.GetFullPath(localfolder);
                            WriteVerbose("Downloading " + remotefolder);
                            DirectoryInfo dirinfo = new DirectoryInfo(@localfullPath);
                            Client.Download(remotefolder, dirinfo);
                            Client.Disconnect();
                        }
                        catch (Exception ex)
                        {
                            throw ex;
                        }
                    }

                }// file exist
                else
                {
                    throw new System.IO.FileNotFoundException("Key file " + fullPath + " was not found.");
                }
            }
        }
        protected override void ProcessRecord()
        {
            foreach (var computer in _computername)
            {
                ConnectionInfo connectInfo;
                if (_keyfile.Equals(""))
                {
                    WriteVerbose("Using SSH Username and Password authentication for connection.");
                    var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.UserName);
                    connectInfo = ConnectionInfoGenerator.GetCredConnectionInfo(computer,
                        _port,
                        _credential,
                        _proxyserver,
                        _proxytype,
                        _proxyport,
                        _proxycredential,
                        kIconnectInfo);

                    // Event Handler for interactive Authentication
                    kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                                prompt.Response = _credential.GetNetworkCredential().Password;
                        }
                    };

                }
                else
                {
                    WriteVerbose("Using SSH Key authentication for connection.");
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                        _port,
                        _keyfile,
                        _credential,
                        _proxyserver,
                        _proxytype,
                        _proxyport,
                        _proxycredential);
                }

                //Ceate instance of SSH Client with connection info
                var client = new ScpClient(connectInfo);


                // Handle host key
                var computer1 = computer;
                client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                {
                    var sb = new StringBuilder();
                    foreach (var b in e.FingerPrint)
                    {
                        sb.AppendFormat("{0:x}:", b);
                    }
                    var fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);

                    if (_sshHostKeys.ContainsKey(computer1))
                    {
                        if (_sshHostKeys[computer1] == fingerPrint)
                        {
                            if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                            {
                                Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer1);
                            }
                            e.CanTrust = true;
                        }
                        else
                        {
                            var ex = new System.Security.SecurityException("SSH fingerprint mismatch for host " + computer1);
                            ThrowTerminatingError(new ErrorRecord(
                                ex,
                                "SSH fingerprint mismatch for host " + computer1,
                                ErrorCategory.SecurityError,
                                computer1));
                        }
                    }
                    else
                    {
                        int choice;
                        if (_acceptkey)
                        {
                            choice = 0;
                        }
                        else
                        {
                            var choices = new Collection<ChoiceDescription>
                                {
                                    new ChoiceDescription("Y"),
                                    new ChoiceDescription("N")
                                };

                            choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);
                        }
                        if (choice == 0)
                        {
                            var keymng = new TrustedKeyMng();
                            keymng.SetKey(computer1, fingerPrint);
                            e.CanTrust = true;
                        }
                        else
                        {
                            e.CanTrust = false;
                        }
                    }
                };
                // Set the connection timeout
                client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                // Connect to host using Connection info
                client.Connect();
                //client.BufferSize = 1024;

                var counter = 0;
                // Print progess of download.
                client.Uploading += delegate(object sender, ScpUploadEventArgs e)
                {
                    if (e.Size != 0)
                    {
                        counter ++;
                        
                        if (counter > 900)
                        {
                            var percent = Convert.ToInt32((e.Uploaded * 100) / e.Size);

                            if (percent == 100)
                            {
                                return;
                            }

                            var progressRecord = new ProgressRecord(1, 
                                "Uploading " + e.Filename, 
                                String.Format("{0} Bytes Uploaded of {1}", 
                                e.Uploaded, e.Size)) {PercentComplete = percent};

                            Host.UI.WriteProgress(1, progressRecord);
                            counter = 0;
                        }
                    }
                };

                WriteVerbose("Connection successful");
                
                // Resolve the path even if a relative one is given.
                ProviderInfo provider;
                var pathinfo = GetResolvedProviderPathFromPSPath(_localfile, out provider);
                var localfullPath = pathinfo[0];

                if (File.Exists(@localfullPath))
                {
                    WriteVerbose("Uploading " + localfullPath);
                    var fil = new FileInfo(@localfullPath);
                    var remoteFullpath = RemotePath.TrimEnd(new[] { '/' }) + "/" + fil.Name;
                    client.Upload(fil, remoteFullpath);

                    client.Disconnect();
                }
                else
                {
                    var ex = new FileNotFoundException("File to upload " + localfullPath + " was not found.");

                    ThrowTerminatingError(new ErrorRecord(
                                                    ex,
                                                    "File to upload " + localfullPath + " was not found.",
                                                    ErrorCategory.InvalidArgument,
                                                    localfullPath));
                }
            }

        } // End process record
Exemplo n.º 32
-1
        protected override void ProcessRecord()
        {
            foreach (var computer in _computername)
            {
                ConnectionInfo connectInfo;
                if (_keyfile.Equals(""))
                {
                    WriteVerbose("Using SSH Username and Password authentication for connection.");
                    var kIconnectInfo = new KeyboardInteractiveAuthenticationMethod(_credential.UserName);
                    connectInfo = ConnectionInfoGenerator.GetCredConnectionInfo(computer,
                        _port,
                        _credential,
                        _proxyserver,
                        _proxytype,
                        _proxyport,
                        _proxycredential,
                        kIconnectInfo);

                    // Event Handler for interactive Authentication
                    kIconnectInfo.AuthenticationPrompt += delegate(object sender, AuthenticationPromptEventArgs e)
                    {
                        foreach (var prompt in e.Prompts)
                        {
                            if (prompt.Request.Contains("Password"))
                                prompt.Response = _credential.GetNetworkCredential().Password;
                        }
                    };

                }
                else
                {
                    WriteVerbose("Using SSH Key authentication for connection.");
                    connectInfo = ConnectionInfoGenerator.GetKeyConnectionInfo(computer,
                        _port,
                        _keyfile,
                        _credential,
                        _proxyserver,
                        _proxytype,
                        _proxyport,
                        _proxycredential);
                }

                //Ceate instance of SSH Client with connection info
                var client = new ScpClient(connectInfo);

                // Handle host key
                if (_force)
                {
                    WriteWarning("Host key is not being verified since Force switch is used.");
                }
                else
                {
                    var computer1 = computer;
                    client.HostKeyReceived += delegate(object sender, HostKeyEventArgs e)
                    {

                        var sb = new StringBuilder();
                        foreach (var b in e.FingerPrint)
                        {
                            sb.AppendFormat("{0:x}:", b);
                        }
                        var fingerPrint = sb.ToString().Remove(sb.ToString().Length - 1);

                        if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                        {
                            Host.UI.WriteVerboseLine("Fingerprint for " + computer1 + ": " + fingerPrint);
                        }

                        if (_sshHostKeys.ContainsKey(computer1))
                        {
                            if (_sshHostKeys[computer1] == fingerPrint)
                            {
                                if (MyInvocation.BoundParameters.ContainsKey("Verbose"))
                                {
                                    Host.UI.WriteVerboseLine("Fingerprint matched trusted fingerprint for host " + computer1);
                                }
                                e.CanTrust = true;

                            }
                            else
                            {
                                e.CanTrust = false;

                            }
                        }
                        else
                        {
                            if (_errorOnUntrusted)
                            {
                                e.CanTrust = false;
                            }
                            else
                            {
                                int choice;
                                if (_acceptkey)
                                {
                                    choice = 0;
                                }
                                else
                                {
                                    var choices = new Collection<ChoiceDescription>
                                    {
                                        new ChoiceDescription("Y"),
                                        new ChoiceDescription("N")
                                    };

                                    choice = Host.UI.PromptForChoice("Server SSH Fingerprint", "Do you want to trust the fingerprint " + fingerPrint, choices, 1);
                                }
                                if (choice == 0)
                                {
                                    var keymng = new TrustedKeyMng();
                                    keymng.SetKey(computer1, fingerPrint);
                                    e.CanTrust = true;
                                }
                                else
                                {
                                    e.CanTrust = false;
                                }
                            }
                        }
                    };
                }
                try
                {
                    // Set the connection timeout
                    client.ConnectionInfo.Timeout = TimeSpan.FromSeconds(_connectiontimeout);

                    // Connect to host using Connection info
                    client.Connect();
                }
                catch (Renci.SshNet.Common.SshConnectionException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (Renci.SshNet.Common.SshOperationTimeoutException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationTimeout, client);
                    WriteError(erec);
                }
                catch (Renci.SshNet.Common.SshAuthenticationException e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.SecurityError, client);
                    WriteError(erec);
                }
                catch (Exception e)
                {
                    ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client);
                    WriteError(erec);
                }
                if (client.IsConnected)
                {
                    client.BufferSize = 1024;

                    // Print progess of upload.

                    if (!_noProgress)
                    {
                        client.Uploading += delegate(object sender, ScpUploadEventArgs e)
                        {
                            var progressRecord = new ProgressRecord(1, "Uploading " + e.Filename, String.Format("{0} Bytes Uploaded of {1}", e.Uploaded, e.Size))
                            {
                                PercentComplete = Convert.ToInt32((e.Uploaded * 100) / e.Size)
                            };

                            Host.UI.WriteProgress(1, progressRecord);
                        };
                    }

                    // Resolve the path even if a relative one is given.
                    ProviderInfo provider;
                    var pathinfo = GetResolvedProviderPathFromPSPath(_localfolder, out provider);
                    var localfullPath = pathinfo[0];

                    //var localfullPath = Path.GetFullPath(_localfolder);
                    if (Directory.Exists(localfullPath))
                    {
                        try
                        {
                            WriteVerbose("Uploading " + _remotefolder);
                            var dirinfo = new DirectoryInfo(@localfullPath);
                            client.Upload(dirinfo, _remotefolder);
                        }
                        catch (Exception e)
                        {
                            ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client);
                            WriteError(erec);
                        }

                    }
                    else
                    {
                        var ex = new DirectoryNotFoundException("Directory " + localfullPath + " was not found.");
                        WriteError(new ErrorRecord(ex,
                                                   "Directory " + localfullPath + " was not found.",
                                                   ErrorCategory.InvalidArgument,
                                                   localfullPath));
                    }
                    client.Disconnect();
                }
            }
        }