コード例 #1
0
ファイル: AES.cs プロジェクト: stux2000/dokan
		public static void Main(String[] arg)
		{
			try
			{
				//Create a new JSch instance
				JSch jsch=new JSch();
			
				//Prompt for username and server host
				Console.WriteLine("Please enter the user and host info at the popup window...");
				String host = InputForm.GetUserInput
					("Enter username@hostname",
					Environment.UserName+"@localhost");
				String user=host.Substring(0, host.IndexOf('@'));
				host=host.Substring(host.IndexOf('@')+1);

				//Create a new SSH session
				Session session=jsch.getSession(user, host, 22);

				// username and password will be given via UserInfo interface.
				UserInfo ui=new MyUserInfo();
				session.setUserInfo(ui);

				//Add AES128 as default cipher in the session config store
				System.Collections.Hashtable config=new System.Collections.Hashtable();
				config.Add("cipher.s2c", "aes128-cbc,3des-cbc");
				config.Add("cipher.c2s", "aes128-cbc,3des-cbc");
				session.setConfig(config);

				//Connect to remote SSH server
				session.connect();			

				//Open a new Shell channel on the SSH session
				Channel channel=session.openChannel("shell");

				//Redirect standard I/O to the SSH channel
				channel.setInputStream(Console.OpenStandardInput());
				channel.setOutputStream(Console.OpenStandardOutput());

				//Connect the channel
				channel.connect();

				Console.WriteLine("-- Shell channel is connected using the {0} cipher", 
					session.getCipher());

				//Wait till channel is closed
				while(!channel.isClosed())
				{
					System.Threading.Thread.Sleep(500);
				}

				//Disconnect from remote server
				channel.disconnect();
				session.disconnect();			

			}
			catch(Exception e)
			{
				Console.WriteLine(e);
			}
		}
コード例 #2
0
        public static void Main(String[] arg)
        {
            try
            {
                JSch jsch=new JSch();

                //Get the private key filename from the user
                Console.WriteLine("Please choose your private key file...");
                String file = InputForm.GetFileFromUser("Choose your privatekey(ex. ~/.ssh/id_dsa)");
                Console.WriteLine("You chose "+file+".");

                //Add the identity file to JSch
                jsch.addIdentity(file);

                //Prompt for username and server host
                Console.WriteLine("Please enter the user and host info at the popup window...");
                String host = InputForm.GetUserInput
                    ("Enter username@hostname",
                    Environment.UserName+"@localhost");
                String user=host.Substring(0, host.IndexOf('@'));
                host=host.Substring(host.IndexOf('@')+1);

                //Create a new SSH session
                Session session=jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui=new MyUserInfo();
                session.setUserInfo(ui);

                //Connect to remote SSH server
                session.connect();

                //Open a new Shell channel on the SSH session
                Channel channel=session.openChannel("shell");

                //Redirect standard I/O to the SSH channel
                channel.setInputStream(Console.OpenStandardInput());
                channel.setOutputStream(Console.OpenStandardOutput());

                //Connect the channel
                channel.connect();

                //Wait till channel is closed
                while(!channel.isClosed())
                {
                    System.Threading.Thread.Sleep(500);
                }

                //Disconnect from remote server
                channel.disconnect();
                session.disconnect();

            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #3
0
        private void SetSFTPPara(string user, string ip, int port)
        {
            JSch jsch = new JSch();

            jsch.addIdentity(Application.StartupPath + @"/id_rsa");
            m_session = jsch.getSession(user, ip, port);
            MyUserInfo ui = new MyUserInfo();

            m_session.setUserInfo(ui);
        }
コード例 #4
0
        private void SetSFTPPara(string user, string ip, string pwd, int port)
        {
            JSch jsch = new JSch();

            m_session = jsch.getSession(user, ip, port);
            MyUserInfo ui = new MyUserInfo();

            ui.setPassword(pwd);
            m_session.setUserInfo(ui);
        }
コード例 #5
0
        public static void RunExample(String[] arg)
        {
            try
            {
                JSch jsch=new JSch();

                OpenFileDialog chooser = new OpenFileDialog();
                chooser.Title ="Choose your privatekey(ex. ~/.ssh/id_dsa)";
                //chooser.setFileHidingEnabled(false);
                DialogResult returnVal = chooser.ShowDialog();
                if(returnVal == DialogResult.OK)
                {
                    Console.WriteLine("You chose "+
                        chooser.FileName+".");
                    jsch.addIdentity(chooser.FileName
                        //			 , "passphrase"
                        );
                }
                else
                {
                    Console.WriteLine("Error getting key file...");
                    return;
                }
                InputForm inForm = new InputForm();
                inForm.Text = "Enter username@hostname";
                inForm.textBox1.Text = Environment.UserName+"@localhost";

                if (inForm.PromptForInput())
                {
                    String host = inForm.textBox1.Text;
                    String user=host.Substring(0, host.IndexOf('@'));
                    host=host.Substring(host.IndexOf('@')+1);

                    Session session=jsch.getSession(user, host, 22);

                    // username and passphrase will be given via UserInfo interface.
                    UserInfo ui=new MyUserInfo();
                    session.setUserInfo(ui);
                    session.connect();

                    Channel channel=session.openChannel("shell");

                    channel.setInputStream(Console.OpenStandardInput());
                    channel.setOutputStream(Console.OpenStandardOutput());

                    channel.connect();
                }
                inForm.Close();

            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #6
0
        public virtual void FtpPickUp(string destinationFilePath, Dictionary <string, string> config, string fileName)
        {
            ChannelSftp channelSftp;

            var printxml = config["printxml"] == "true";

            var url            = config["sftpUrl"];
            var username       = config["sftpUsername"];
            var password       = config["sftpPassword"];
            var knownHostsFile = config["knownHostsFile"];

            var jsch = new JSch();

            jsch.setKnownHosts(knownHostsFile);

            var session = jsch.getSession(username, url);

            session.setPassword(password);

            try
            {
                session.connect();

                var channel = session.openChannel("sftp");
                channel.connect();
                channelSftp = (ChannelSftp)channel;
            }
            catch (SftpException e)
            {
                throw new CnpOnlineException("Error occured while attempting to establish an SFTP connection", e);
            }

            try
            {
                if (printxml)
                {
                    Console.WriteLine("Picking up remote file outbound/" + fileName + ".asc");
                    Console.WriteLine("Putting it at " + destinationFilePath);
                }
                channelSftp.get("outbound/" + fileName + ".asc", destinationFilePath);
                if (printxml)
                {
                    Console.WriteLine("Removing remote file output/" + fileName + ".asc");
                }
                channelSftp.rm("outbound/" + fileName + ".asc");
            }
            catch (SftpException e)
            {
                throw new CnpOnlineException("Error occured while attempting to retrieve and save the file from SFTP", e);
            } finally {
                channelSftp.quit();

                session.disconnect();
            }
        }
コード例 #7
0
ファイル: Sftp.cs プロジェクト: kdupigny/GlobalAuditTrail
        /// <summary>
        /// Initializes connection to a remote Server with given credentials
        /// </summary>
        private void _Init()
        {
            if (_jsch != null)
            {
                try
                {
                    GatLogger.Instance.AddMessage("Attempting to disconnect SFTP connection ", LogMode.LogAndScreen);
                    _sftpSession.disconnect();
                    _sftpSession = null;
                    _jsch        = null;
                }
                catch (Exception e)
                {
                    _sftpSession = null;
                    _jsch        = null;
                    GatLogger.Instance.AddMessage("There was a failure while restarting connection " + e.Message);
                }

                //wait half a second before reconnecting so we dont flood FTP server with continued failed attempts
                Thread.Sleep(500);
            }

            try
            {
                _jsch        = new JSch();
                _sftpSession = _jsch.getSession(_user, _host, _port);

                _ui = new SftpUserInfo(); // this is needed for the passkey
                _sftpSession.setUserInfo(_ui);

                _sftpSession.setPassword(_pass);
                _sftpSession.connect();

                _channel = _sftpSession.openChannel("sftp");
                _channel.connect();

                _sftpChannel = (ChannelSftp)_channel;
                //_ins = Console.OpenStandardInput();
                //_outs = Console.Out;

                _ChangeRemoteWorkingDirectory(_rootDir);
            }
            catch (Exception e)
            {
                if (!_reportOnce)
                {
                    string failMsg = string.Format("SFTP Connection is failing ({2}@{0}:{1}) \n\t{3}", _host, _port,
                                                   _user, e.Message);
                    GatLogger.Instance.AddMessage(failMsg, LogMode.LogAndScreen);
                    GatLogger.Instance.AddMessage(string.Format("Inner Exception: {0}", e.InnerException));
                    GatLogger.Instance.AddMessage(string.Format("Exception Stack: {0}", e.StackTrace));
                    _reportOnce = true;
                }
            }
        }
コード例 #8
0
    public SFTPHelper(string ip, string user, string password, int port = 22)
    {
        JSch jsch = new JSch();

        session = jsch.getSession(user, ip, port);
        session.setPassword(password);
        Hashtable foo = new Hashtable();

        //不加会默认key登陆
        foo.Add("StrictHostKeyChecking", "no");
        session.setConfig(foo);
    }
コード例 #9
0
        /// <summary>
        /// 实例化 SFTP 对象
        /// </summary>
        /// <param name="ip">服务器IP</param>
        /// <param name="user">用户名</param>
        /// <param name="pwd">密码</param>
        /// <param name="port">端口</param>
        /// <param name="privateKey">私钥</param>
        /// <param name="passphrase">私钥口令</param>
        public SFTPHelper(string ip, string user, string pwd, int port = 22, string privateKey = "", string passphrase = "")
        {
            JSch jsch = new JSch();

            jsch.addIdentity(privateKey, passphrase);
            m_session = jsch.getSession(user, ip, port);
            MyUserInfo ui = new MyUserInfo();

            ui.setPassword(pwd);
            m_session.setUserInfo(ui);
            this.Connect();
        }
コード例 #10
0
ファイル: Shell.cs プロジェクト: ithanshui/DoNet.Common
        public static void Main(String[] arg)
        {
            try
            {
                //Create a new JSch instance
                JSch jsch = new JSch();

                //Prompt for username and server host
                Console.WriteLine("Please enter the user and host info at the popup window...");
                String host = InputForm.GetUserInput
                                  ("Enter username@hostname",
                                  Environment.UserName + "@localhost");
                String user = host.Substring(0, host.IndexOf('@'));
                host = host.Substring(host.IndexOf('@') + 1);

                //Create a new SSH session
                Session session = jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui = new MyUserInfo();
                session.setUserInfo(ui);

                //Connect to remote SSH server
                session.connect();

                //Open a new Shell channel on the SSH session
                Channel channel = session.openChannel("shell");

                //Redirect standard I/O to the SSH channel
                channel.setInputStream(Console.OpenStandardInput());
                channel.setOutputStream(Console.OpenStandardOutput());

                //Connect the channel
                channel.connect();

                Console.WriteLine("-- Shell channel is connected using the {0} cipher",
                                  session.getCipher());

                //Wait till channel is closed
                while (!channel.isClosed())
                {
                    System.Threading.Thread.Sleep(500);
                }

                //Disconnect from remote server
                channel.disconnect();
                session.disconnect();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #11
0
ファイル: SftpHelper.cs プロジェクト: Pelletling/AIPXiaoTong
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="ip">sftp地址</param>
        /// <param name="user">sftp用户名</param>
        /// <param name="pwd">sftp密码</param>
        /// <param name="port">端口,默认20</param>
        public SftpHelper(string ip, string user, string pwd, string port = "20")
        {
            int serverport = Int32.Parse(port);

            JSch jsch = new JSch();

            m_session = jsch.getSession(user, ip, serverport);

            MyUserInfo ui = new MyUserInfo();

            ui.setPassword(pwd);
            m_session.setUserInfo(ui);
        }
コード例 #12
0
ファイル: SshBase.cs プロジェクト: uvbs/FullSource
        protected virtual void ConnectSession(int tcpPort)
        {
            m_session = m_jsch.getSession(m_user, m_host, tcpPort);
            if (Password != null)
            {
                m_session.setPassword(Password);
            }
            Hashtable config = new Hashtable();

            config.Add("StrictHostKeyChecking", "no");
            m_session.setConfig(config);
            m_session.connect();
        }
コード例 #13
0
ファイル: StreamForwarding.cs プロジェクト: nuevollc/Nuevo
        public static void RunExample(String[] arg)
        {
            int port;

            try
            {
                //Create a new JSch instance
                JSch jsch = new JSch();

                //Prompt for username and server host
                Console.WriteLine("Please enter the user and host info at the popup window...");
                String host = InputForm.GetUserInput
                                  ("Enter username@hostname",
                                  Environment.UserName + "@localhost");
                String user = host.Substring(0, host.IndexOf('@'));
                host = host.Substring(host.IndexOf('@') + 1);

                //Create a new SSH session
                Session session = jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui = new MyUserInfo();
                session.setUserInfo(ui);
                session.connect();

                //Get from user the remote host and remote host port
                String foo = InputForm.GetUserInput("Enter host and port", "host:port");
                host = foo.Substring(0, foo.IndexOf(':'));
                port = int.Parse(foo.Substring(foo.IndexOf(':') + 1));

                Console.WriteLine("System.{in,out} will be forwarded to " +
                                  host + ":" + port + ".");
                Channel channel = session.openChannel("direct-tcpip");
                ((ChannelDirectTCPIP)channel).setInputStream(Console.OpenStandardInput());
                ((ChannelDirectTCPIP)channel).setOutputStream(Console.OpenStandardOutput());
                ((ChannelDirectTCPIP)channel).setHost(host);
                ((ChannelDirectTCPIP)channel).setPort(port);
                channel.connect();

                while (!channel.isClosed())
                {
                    System.Threading.Thread.Sleep(500);
                }
                channel.disconnect();
                session.disconnect();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #14
0
ファイル: StreamForwarding.cs プロジェクト: darbio/MTSharpSSH
        public static void Main(String[] arg)
        {
            int port;

            try
            {
                //Create a new JSch instance
                JSch jsch=new JSch();

                //Prompt for username and server host
                Console.WriteLine("Please enter the user and host info at the popup window...");
                String host = InputForm.GetUserInput
                    ("Enter username@hostname",
                    Environment.UserName+"@localhost");
                String user=host.Substring(0, host.IndexOf('@'));
                host=host.Substring(host.IndexOf('@')+1);

                //Create a new SSH session
                Session session=jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui=new MyUserInfo();
                session.setUserInfo(ui);
                session.connect();

                //Get from user the remote host and remote host port
                String foo = InputForm.GetUserInput("Enter host and port", "host:port");
                host=foo.Substring(0, foo.IndexOf(':'));
                port=int.Parse(foo.Substring(foo.IndexOf(':')+1));

                Console.WriteLine("System.{in,out} will be forwarded to "+
                    host+":"+port+".");
                Channel channel=session.openChannel("direct-tcpip");
                ((ChannelDirectTCPIP)channel).setInputStream(Console.OpenStandardInput());
                ((ChannelDirectTCPIP)channel).setOutputStream(Console.OpenStandardOutput());
                ((ChannelDirectTCPIP)channel).setHost(host);
                ((ChannelDirectTCPIP)channel).setPort(port);
                channel.connect();

                while(!channel.isClosed())
                {
                    System.Threading.Thread.Sleep(500);
                }
                channel.disconnect();
                session.disconnect();
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #15
0
 /// <summary>
 /// 通过私钥建立SFTP连接
 /// </summary>
 private void ConnectSFTPByPrivateKey()
 {
     try
     {
         JSch JSchModel = new JSch();
         _session = JSchModel.getSession(_userName, _hostName, _port);
         _session.setUserInfo(new SFTPUserInfoModel());
         CreateConnectSFTP();
     }
     catch (Exception e)
     {
         _log.Error("通过私钥建立SFTP连接失败!", e);
     }
 }
コード例 #16
0
ファイル: SFTPClient.cs プロジェクト: franknew/SOAFramework
        public SFTPClient(string ip = null, int port = 22, string filePath = null, string username = null, string password = null)
        {
            UrlEntity = new SFTPUrl {
                IP = ip, Port = port, Path = filePath
            };
            this.username = username;
            this.password = password;
            JSch jsch = new JSch();

            session = jsch.getSession(username, ip, port);
            STFPUserInfo userInfo = new STFPUserInfo(password);

            session.setUserInfo(userInfo);
        }
コード例 #17
0
ファイル: SFTPClient.cs プロジェクト: franknew/SOAFramework
        public SFTPClient(string url, string username = null, string password = null)
        {
            UrlEntity = new SFTPUrl {
                Url = url
            };
            this.username = username;
            this.password = password;
            JSch jsch = new JSch();

            session = jsch.getSession(username, UrlEntity.IP, UrlEntity.Port);
            STFPUserInfo userInfo = new STFPUserInfo(password);

            session.setUserInfo(userInfo);
        }
コード例 #18
0
        //host:sftp地址   user:用户名   pwd:密码
        public SFTPHelper(string ip, string port, string user, string pwd)
        {
            UnityEngine.Debug.Log("SFTP ip:" + ip + " port:" + port);

            int serverport = Int32.Parse(port);

            JSch jsch = new JSch();

            m_session = jsch.getSession(user, ip, serverport);

            MyUserInfo ui = new MyUserInfo();

            ui.setPassword(pwd);
            m_session.setUserInfo(ui);
        }
コード例 #19
0
        protected void _Connect()
        {
            _jsch = new JSch();
            //session.setConfig();
            _session = _jsch.getSession(this.Username, this.Host, this.Port);
            UserInfo ui = new DirectPasswordUserInfo(this.Password);

            _session.setUserInfo(ui);
            _session.connect();

            _csftp = (ChannelSftp)_session.openChannel("sftp");
            _csftp.connect();

            //RootPath = csftp.getHome();
            RootPath = "";
        }
コード例 #20
0
    //host:sftp地址   user:用户名   pwd:密码
    public SFTPHelper(string host, string user, string pwd)
    {
        //string[] arr = host.Split(':');
        //string ip = arr[0];
        string ip   = host;
        int    port = 22;
        //if (arr.Length > 1) port = Int32.Parse(arr[1]);

        JSch jsch = new JSch();

        m_session = jsch.getSession(user, ip, port);
        MyUserInfo ui = new MyUserInfo();

        ui.setPassword(pwd);
        m_session.setUserInfo(ui);
    }
コード例 #21
0
        /// <summary>
        /// 通过私钥建立SFTP连接
        /// </summary>
        private void ConnectSFTPByPrivateKey()
        {
            try
            {
                JSch JSchModel = new JSch();
                JSchModel.addIdentity(_privateKeyFile, _passphrase);
                _session = JSchModel.getSession(_userName, _hostName, _port);
                _session.setUserInfo(new SFTPUserInfoModel());

                CreateConnectSFTP();
            }
            catch (Exception e)
            {
                _log.Warn("通过私钥建立SFTP连接失败!", e);
            }
        }
コード例 #22
0
        protected virtual void ConnectSession(int tcpPort)
        {
            m_session = m_jsch.getSession(m_user, m_host, tcpPort);

            if (Password != null)
            {
                if (m_userInfo == null)
                {
                    m_userInfo = new DisconnectedKeyboardInteractiveUserInfo(Password);
                }
                else
                {
                    throw new InvalidDataException("Cannot combine a predefined 'UserInfo' object with a predefined 'Password' value.");
                }
            }

            m_session.setUserInfo(m_userInfo);

            //determine how strict to be on host key issues.
            Hashtable config = new Hashtable();

            switch (m_checkType)
            {
            case HostKeyCheckType.AskUser:
                config.Add("StrictHostKeyChecking", "ask");
                break;

            case HostKeyCheckType.ForceMatch:
                config.Add("StrictHostKeyChecking", "yes");
                break;

            case HostKeyCheckType.NoCheck:
                config.Add("StrictHostKeyChecking", "no");
                break;

            default:
                throw new InvalidDataException("Unknown value provided for 'm_checkType' property");
            }
            m_session.setConfig(config);

            if (m_hostKeyFileName != null)
            {
                m_jsch.getHostKeyRepository().setKnownHosts(m_hostKeyFileName);
            }

            m_session.connect();
        }
コード例 #23
0
        internal SftpLogFileInfoSharpSSH(Uri uri)
        {
            this.uri            = uri;
            this.remoteFileName = uri.PathAndQuery;

            string userName = null;
            string password = null;

            if (uri.UserInfo != null && uri.UserInfo.Length > 0)
            {
                string[] split = uri.UserInfo.Split(new char[] { ':' });
                if (split.Length > 0)
                {
                    userName = split[0];
                }
                if (split.Length > 1)
                {
                    password = split[1];
                }
            }
            if (userName == null || password == null)
            {
                IList <string> userNames = new List <string>();
                LoginDialog    dlg       = new LoginDialog(uri.Host, userNames);
                dlg.UserName = userName;
                if (DialogResult.OK == dlg.ShowDialog())
                {
                    password = dlg.Password;
                    userName = dlg.UserName;
                }
            }

            UserInfo userInfo = new SharpSshUserInfo(userName, password);
            JSch     jsch     = new JSch();
            int      port     = uri.Port != -1 ? uri.Port : 22;
            Session  session  = jsch.getSession(userName, this.uri.Host, port);

            session.setUserInfo(userInfo);
            session.connect();
            Channel channel = session.openChannel("sftp");

            channel.connect();
            this.sftpChannel = (ChannelSftp)channel;
            SftpATTRS sftpAttrs = this.sftpChannel.lstat(this.remoteFileName);

            this.originalFileLength = sftpAttrs.getSize();
        }
コード例 #24
0
        private void OpenStream(string username, string password, bool retry)
        {
            try
            {
                JSch jsch = new JSch();
                m_session = jsch.getSession(username, this.m_host, 22);
                //m_session.setPassword( password );
                m_session.setUserInfo(new KeyboardInteractiveUserInfo(password));

                Hashtable config = new Hashtable();
                config.Add("StrictHostKeyChecking", "no");
                m_session.setConfig(config);

                m_session.connect();
                m_channel = (ChannelShell)m_session.openChannel("shell");

                m_in  = m_channel.getInputStream();
                m_out = m_channel.getOutputStream();

                m_channel.connect();
                m_channel.setPtySize(80, 132, 1024, 768);

                if (m_in is PipedInputStream)
                {
                    ((PipedInputStream)m_in).UpdateThreadsFromChannel(m_channel);
                }

                Prompt = "\n";
                m_escapeCharPattern = "\\[[0-9;?]*[^0-9;]";
            }
            catch (Exception e)
            {
                                #if DEBUG
                Console.WriteLine("Error opening SshStream to target: " + m_host + (retry ? ", re-attempting connection" : ""));
                                #endif

                this.Close();
                if (retry)
                {
                    OpenStream(username, password, false);
                }
                else
                {
                    throw e;
                }
            }
        }
コード例 #25
0
        private void connectWithUserAndPassword()
        {
            jsch = new JSch();
            jsch.setKnownHosts("hostsfile");
            try
            {
                session = jsch.getSession(userName, remoteHost);
            }
            catch (JSchException e)
            {
                throw new ApplicationException("Cannot get session to host " +
                                               remoteHost + ":" + port + " : " +
                                               e.toString());
            }

            MyUserInfo ui = new MyUserInfo();

            ui.setPassword(this.password);

            session.setUserInfo(ui);
            session.connect();

            //session.setPassword(password);

            //System.Collections.Hashtable config = new Hashtable();
            //config.Add("StrictHostKeyChecking", "no");
            //System.Windows.Forms.Program.Show(session.getConfig("StrictHostKeyChecking"));
            //session.setConfig(config);

            //session.setUserInfo(new MyUserInfo(password));

            /*
             * try
             * {
             *  session.connect();
             * }
             * catch (JSchException e)
             * {
             *
             *  throw new ApplicationException("Cannot connect to host " +
             *          remoteHost + ":" + port + " : " +
             *          e.toString());
             *
             * }
             */
        }
コード例 #26
0
        /// <summary>
        /// 通过密码建立SFTP连接
        /// </summary>
        private void ConnectSFTPByPassword()
        {
            try
            {
                JSch JSchModel         = new JSch();
                SFTPUserInfoModel User = new SFTPUserInfoModel();
                _session = JSchModel.getSession(_userName, _hostName, _port);
                _session.setPassword(_password);
                User.setPassword(_password);
                _session.setUserInfo(User);

                CreateConnectSFTP();
            }
            catch (Exception e)
            {
                _log.Warn("通过密码建立SFTP连接失败!", e);
            }
        }
コード例 #27
0
        public static void Main(String[] arg)
        {
            int port;

            try
            {
                //Create a new JSch instance
                JSch jsch=new JSch();

                //Prompt for username and server host
                Console.WriteLine("Please enter the user and host info at the popup window...");
                String host = InputForm.GetUserInput
                    ("Enter username@hostname",
                    Environment.UserName+"@localhost");
                String user=host.Substring(0, host.IndexOf('@'));
                host=host.Substring(host.IndexOf('@')+1);

                //Create a new SSH session
                Session session=jsch.getSession(user, host, 22);

                //Get from user the local port, remote host and remote host port
                String foo = InputForm.GetUserInput("Enter -L port:host:hostport","port:host:hostport");
                int lport=int.Parse(foo.Substring(0, foo.IndexOf(':')));
                foo=foo.Substring(foo.IndexOf(':')+1);
                String rhost=foo.Substring(0, foo.IndexOf(':'));
                int rport=int.Parse(foo.Substring(foo.IndexOf(':')+1));

                // username and password will be given via UserInfo interface.
                UserInfo ui=new MyUserInfo();
                session.setUserInfo(ui);
                session.connect();

                Console.WriteLine("localhost:"+lport+" -> "+rhost+":"+rport);

                //Set port forwarding on the opened session
                session.setPortForwardingL(lport, rhost, rport);
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #28
0
        public static void Main(String[] arg)
        {
            int port;

            try
            {
                //Create a new JSch instance
                JSch jsch = new JSch();

                //Prompt for username and server host
                Console.WriteLine("Please enter the user and host info at the popup window...");
                String host = InputForm.GetUserInput
                                  ("Enter username@hostname",
                                  Environment.UserName + "@localhost");
                String user = host.Substring(0, host.IndexOf('@'));
                host = host.Substring(host.IndexOf('@') + 1);

                //Create a new SSH session
                Session session = jsch.getSession(user, host, 22);

                //Get from user the remote port, local host and local host port
                String foo   = InputForm.GetUserInput("Enter -R port:host:hostport", "port:host:hostport");
                int    rport = int.Parse(foo.Substring(0, foo.IndexOf(':')));
                foo = foo.Substring(foo.IndexOf(':') + 1);
                String lhost = foo.Substring(0, foo.IndexOf(':'));
                int    lport = int.Parse(foo.Substring(foo.IndexOf(':') + 1));

                // username and password will be given via UserInfo interface.
                UserInfo ui = new MyUserInfo();
                session.setUserInfo(ui);
                session.connect();

                Console.WriteLine(host + ":" + rport + " -> " + lhost + ":" + lport);

                //Set port forwarding on the opened session
                session.setPortForwardingR(rport, lhost, lport);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #29
0
        public SFTP(string host, string user)
        {
            string[] arr  = host.Split(':');
            string   ip   = arr[0];
            int      port = 22;

            if (arr.Length > 1)
            {
                port = Int32.Parse(arr[1]);
            }

            JSch jsch = new JSch();

            jsch.addIdentity(Application.StartupPath + @"/id_rsa");
            m_session = jsch.getSession(user, ip, port);

            MyUserInfo ui = new MyUserInfo();

            m_session.setUserInfo(ui);
        }
コード例 #30
0
        private void sftp_login()
        {
            JSch jsch = new JSch();

            String host = tHost.Text;
            String user = tUsername.Text;

            Session session = jsch.getSession(user, host, 22);

            // username and password will be given via UserInfo interface.
            UserInfo ui = new MyUserInfo();

            session.setUserInfo(ui);

            session.setPort(Convert.ToInt32(nPort.Value));

            session.connect();

            Channel channel = session.openChannel("sftp");

            channel.connect();
            sftpc = (ChannelSftp)channel;
        }
コード例 #31
0
ファイル: fNewDir.cs プロジェクト: aserfes/FTPbox
        private void sftp_login()
        {
            JSch jsch = new JSch();

            host = ((frmMain)this.Tag).ftpHost();
            UN   = ((frmMain)this.Tag).ftpUser();
            port = ((frmMain)this.Tag).ftpPort();

            Session session = jsch.getSession(UN, host, 22);

            // username and password will be given via UserInfo interface.
            UserInfo ui = new MyUserInfo();

            session.setUserInfo(ui);

            session.setPort(port);

            session.connect();

            Channel channel = session.openChannel("sftp");

            channel.connect();
            sftpc = (ChannelSftp)channel;
        }
コード例 #32
0
        public static void Main(String[] arg)
        {
            if(arg.Length!=2)
            {
                Console.WriteLine("usage: java ScpTo file1 user@remotehost:file2");
                Environment.Exit(-1);
            }

            try
            {

                String lfile=arg[0];
                String user=arg[1].Substring(0, arg[1].IndexOf('@'));
                arg[1]=arg[1].Substring(arg[1].IndexOf('@')+1);
                String host=arg[1].Substring(0, arg[1].IndexOf(':'));
                String rfile=arg[1].Substring(arg[1].IndexOf(':')+1);

                JSch jsch=new JSch();
                Session session=jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui=new MyUserInfo();
                session.setUserInfo(ui);
                session.connect();

                // exec 'scp -t rfile' remotely
                String command="scp -p -t "+rfile;
                Channel channel=session.openChannel("exec");
                ((ChannelExec)channel).setCommand(command);

                // get I/O streams for remote scp
                Stream outs=channel.getOutputStream();
                Stream ins=channel.getInputStream();

                channel.connect();

                byte[] tmp=new byte[1];

                if(checkAck(ins)!=0)
                {
                    Environment.Exit(0);
                }

                // send "C0644 filesize filename", where filename should not include '/'

                int filesize=(int)(new FileInfo(lfile)).Length;
                command="C0644 "+filesize+" ";
                if(lfile.LastIndexOf('/')>0)
                {
                    command+=lfile.Substring(lfile.LastIndexOf('/')+1);
                }
                else
                {
                    command+=lfile;
                }
                command+="\n";
                byte[] buff = Util.getBytes(command);
                outs.Write(buff, 0, buff.Length); outs.Flush();

                if(checkAck(ins)!=0)
                {
                    Environment.Exit(0);
                }

                // send a content of lfile
                FileStream fis=File.OpenRead(lfile);
                byte[] buf=new byte[1024];
                while(true)
                {
                    int len=fis.Read(buf, 0, buf.Length);
                    if(len<=0) break;
                    outs.Write(buf, 0, len); outs.Flush();
                    Console.Write("#");
                }

                // send '\0'
                buf[0]=0; outs.Write(buf, 0, 1); outs.Flush();
                Console.Write(".");

                if(checkAck(ins)!=0)
                {
                    Environment.Exit(0);
                }
                Console.WriteLine("OK");
                Environment.Exit(0);
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #33
0
        public virtual void FtpPoll(string fileName, int timeout, Dictionary <string, string> config)
        {
            fileName = fileName + ".asc";
            var printxml = config["printxml"] == "true";

            if (printxml)
            {
                Console.WriteLine("Polling for outbound result file.  Timeout set to " + timeout + "ms. File to wait for is " + fileName);
            }
            ChannelSftp channelSftp;

            var url            = config["sftpUrl"];
            var username       = config["sftpUsername"];
            var password       = config["sftpPassword"];
            var knownHostsFile = config["knownHostsFile"];

            var jsch = new JSch();

            jsch.setKnownHosts(knownHostsFile);

            var session = jsch.getSession(username, url);

            session.setPassword(password);

            try
            {
                session.connect();

                var channel = session.openChannel("sftp");
                channel.connect();
                channelSftp = (ChannelSftp)channel;
            }
            catch (SftpException e)
            {
                throw new CnpOnlineException("Error occured while attempting to establish an SFTP connection", e);
            }

            //check if file exists
            SftpATTRS sftpAttrs = null;
            var       stopWatch = new Stopwatch();

            stopWatch.Start();
            do
            {
                if (printxml)
                {
                    Console.WriteLine("Elapsed time is " + stopWatch.Elapsed.TotalMilliseconds);
                }
                try
                {
                    sftpAttrs = channelSftp.lstat("outbound/" + fileName);
                    if (printxml)
                    {
                        Console.WriteLine("Attrs of file are: " + sftpAttrs);
                    }
                }
                catch (SftpException e)
                {
                    if (printxml)
                    {
                        Console.WriteLine(e.message);
                    }
                    System.Threading.Thread.Sleep(30000);
                }
            } while (sftpAttrs == null && stopWatch.Elapsed.TotalMilliseconds <= timeout);

            // Close the connections.
            channelSftp.quit();
            session.disconnect();
        }
コード例 #34
0
        //public virtual string SocketStream(string xmlRequestFilePath, string xmlResponseDestinationDirectory, Dictionary<string, string> config)
        //{
        //    var url = config["onlineBatchUrl"];
        //    var port = int.Parse(config["onlineBatchPort"]);
        //    TcpClient tcpClient;
        //    SslStream sslStream;

        //    try
        //    {
        //        tcpClient = new TcpClient(url, port);
        //        sslStream = new SslStream(tcpClient.GetStream(), false, ValidateServerCertificate, null);
        //    }
        //    catch (SocketException e)
        //    {
        //        throw new CnpOnlineException("Error establishing a network connection", e);
        //    }

        //    try
        //    {
        //        sslStream.AuthenticateAsClient(url);
        //    }
        //    catch (AuthenticationException e)
        //    {
        //        tcpClient.Close();
        //        throw new CnpOnlineException("Error establishing a network connection - SSL Authencation failed", e);
        //    }

        //    if ("true".Equals(config["printxml"]))
        //    {
        //        Console.WriteLine("Using XML File: " + xmlRequestFilePath);
        //    }

        //    using (var readFileStream = new FileStream(xmlRequestFilePath, FileMode.Open))
        //    {
        //        var bytesRead = -1;

        //        do
        //        {
        //            var byteBuffer = new byte[1024 * sizeof(char)];
        //            bytesRead = readFileStream.Read(byteBuffer, 0, byteBuffer.Length);

        //            sslStream.Write(byteBuffer, 0, bytesRead);
        //            sslStream.Flush();
        //        } while (bytesRead != 0);
        //    }

        //    var batchName = Path.GetFileName(xmlRequestFilePath);
        //    var destinationDirectory = Path.GetDirectoryName(xmlResponseDestinationDirectory);
        //    if (!Directory.Exists(destinationDirectory))
        //    {
        //        if (destinationDirectory != null) Directory.CreateDirectory(destinationDirectory);
        //    }

        //    if ("true".Equals(config["printxml"]))
        //    {
        //        Console.WriteLine("Writing to XML File: " + xmlResponseDestinationDirectory + batchName);
        //    }

        //    using (var writeFileStream = new FileStream(xmlResponseDestinationDirectory + batchName, FileMode.Create))
        //    {
        //        int bytesRead;

        //        do
        //        {
        //            var byteBuffer = new byte[1024 * sizeof(char)];
        //            bytesRead = sslStream.Read(byteBuffer, 0, byteBuffer.Length);

        //            writeFileStream.Write(byteBuffer, 0, bytesRead);
        //        } while (bytesRead > 0);
        //    }

        //    tcpClient.Close();
        //    sslStream.Close();

        //    return xmlResponseDestinationDirectory + batchName;
        //}

        public virtual void FtpDropOff(string fileDirectory, string fileName, Dictionary <string, string> config)
        {
            ChannelSftp channelSftp;

            var url            = config["sftpUrl"];
            var username       = config["sftpUsername"];
            var password       = config["sftpPassword"];
            var knownHostsFile = config["knownHostsFile"];
            var filePath       = Path.Combine(fileDirectory, fileName);

            var printxml = config["printxml"] == "true";

            if (printxml)
            {
                Console.WriteLine("Sftp Url: " + url);
                Console.WriteLine("Username: "******"Password: "******"Known hosts file path: " + knownHostsFile);
            }

            var jsch = new JSch();

            if (printxml)
            {
                // grab the contents fo the knownhosts file and print
                var hostFile = File.ReadAllText(knownHostsFile);
                Console.WriteLine("known host contents: " + hostFile);
            }

            jsch.setKnownHosts(knownHostsFile);

            // setup for diagnostic
            // Get the KnownHosts repository from JSchs
            var     hkr = jsch.getHostKeyRepository();
            var     hks = hkr.getHostKey();
            HostKey hk;

            if (printxml)
            {
                // Print all knownhosts and keys
                if (hks != null)
                {
                    Console.WriteLine();
                    Console.WriteLine("Host keys in " + hkr.getKnownHostsRepositoryID() + ":");
                    foreach (var t in hks)
                    {
                        hk = t;
                        Console.WriteLine("local HostKey host: <" + hk.getHost() + "> type: <" + hk.getType() + "> fingerprint: <" + hk.getFingerPrint(jsch) + ">");
                    }
                    Console.WriteLine("");
                }
            }

            var session = jsch.getSession(username, url);

            session.setPassword(password);

            try
            {
                session.connect();

                // more diagnostic code for troubleshooting sFTP connection errors
                if (printxml)
                {
                    // Print the host key info of the connected server:
                    hk = session.getHostKey();
                    Console.WriteLine("remote HostKey host: <" + hk.getHost() + "> type: <" + hk.getType() + "> fingerprint: <" + hk.getFingerPrint(jsch) + ">");
                }

                var channel = session.openChannel("sftp");
                channel.connect();
                channelSftp = (ChannelSftp)channel;
            }
            catch (SftpException e)
            {
                throw new CnpOnlineException("Error occured while establishing an SFTP connection", e);
            }
            catch (JSchException e)
            {
                throw new CnpOnlineException("Error occured while attempting to establish an SFTP connection", e);
            }

            try
            {
                if (printxml)
                {
                    Console.WriteLine("Dropping off local file " + filePath + " to inbound/" + fileName + ".prg");
                }
                channelSftp.put(filePath, "inbound/" + fileName + ".prg", ChannelSftp.OVERWRITE);
                if (printxml)
                {
                    Console.WriteLine("File copied - renaming from inbound/" + fileName + ".prg to inbound/" + fileName + ".asc");
                }
                channelSftp.rename("inbound/" + fileName + ".prg", "inbound/" + fileName + ".asc");
            }
            catch (SftpException e)
            {
                throw new CnpOnlineException("Error occured while attempting to upload and save the file to SFTP", e);
            }

            channelSftp.quit();

            session.disconnect();
        }
コード例 #35
0
ファイル: Sftp.cs プロジェクト: darbio/MTSharpSSH
        public static void Main(String[] arg)
        {
            try
            {
                JSch jsch=new JSch();

                InputForm inForm = new InputForm();
                inForm.Text = "Enter username@hostname";
                inForm.textBox1.Text = Environment.UserName+"@localhost";

                if (!inForm.PromptForInput())
                {
                    Console.WriteLine("Cancelled");
                    return;
                }
                String host = inForm.textBox1.Text;
                String user=host.Substring(0, host.IndexOf('@'));
                host=host.Substring(host.IndexOf('@')+1);

                Session session=jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui=new MyUserInfo();
                session.setUserInfo(ui);

                session.connect();

                Channel channel=session.openChannel("sftp");
                channel.connect();
                ChannelSftp c=(ChannelSftp)channel;

                Stream ins=Console.OpenStandardInput();
                TextWriter outs=Console.Out;

                ArrayList cmds=new ArrayList();
                byte[] buf=new byte[1024];
                int i;
                String str;
                int level=0;

                while(true)
                {
                    outs.Write("sftp> ");
                    cmds.Clear();
                    i=ins.Read(buf, 0, 1024);
                    if(i<=0)break;

                    i--;
                    if(i>0 && buf[i-1]==0x0d)i--;
                    //str=Util.getString(buf, 0, i);
                    //Console.WriteLine("|"+str+"|");
                    int s=0;
                    for(int ii=0; ii<i; ii++)
                    {
                        if(buf[ii]==' ')
                        {
                            if(ii-s>0){ cmds.Add(Util.getString(buf, s, ii-s)); }
                            while(ii<i){if(buf[ii]!=' ')break; ii++;}
                            s=ii;
                        }
                    }
                    if(s<i){ cmds.Add(Util.getString(buf, s, i-s)); }
                    if(cmds.Count==0)continue;

                    String cmd=(String)cmds[0];
                    if(cmd.Equals("quit"))
                    {
                        c.quit();
                        break;
                    }
                    if(cmd.Equals("exit"))
                    {
                        c.exit();
                        break;
                    }
                    if(cmd.Equals("rekey"))
                    {
                        session.rekey();
                        continue;
                    }
                    if(cmd.Equals("compression"))
                    {
                        if(cmds.Count<2)
                        {
                            outs.WriteLine("compression level: "+level);
                            continue;
                        }
                        try
                        {
                            level=int.Parse((String)cmds[1]);
                            Hashtable config=new Hashtable();
                            if(level==0)
                            {
                                config.Add("compression.s2c", "none");
                                config.Add("compression.c2s", "none");
                            }
                            else
                            {
                                config.Add("compression.s2c", "zlib,none");
                                config.Add("compression.c2s", "zlib,none");
                            }
                            session.setConfig(config);
                        }
                        catch{}//(Exception e){}
                        continue;
                    }
                    if(cmd.Equals("cd") || cmd.Equals("lcd"))
                    {
                        if(cmds.Count<2) continue;
                        String path=(String)cmds[1];
                        try
                        {
                            if(cmd.Equals("cd")) c.cd(path);
                            else c.lcd(path);
                        }
                        catch(SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if(cmd.Equals("rm") || cmd.Equals("rmdir") || cmd.Equals("mkdir"))
                    {
                        if(cmds.Count<2) continue;
                        String path=(String)cmds[1];
                        try
                        {
                            if(cmd.Equals("rm")) c.rm(path);
                            else if(cmd.Equals("rmdir")) c.rmdir(path);
                            else c.mkdir(path);
                        }
                        catch(SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if(cmd.Equals("chgrp") || cmd.Equals("chown") || cmd.Equals("chmod"))
                    {
                        if(cmds.Count!=3) continue;
                        String path=(String)cmds[2];
                        int foo=0;
                        if(cmd.Equals("chmod"))
                        {
                            byte[] bar=Util.getBytes((String)cmds[1]);
                            int k;
                            for(int j=0; j<bar.Length; j++)
                            {
                                k=bar[j];
                                if(k<'0'||k>'7'){foo=-1; break;}
                                foo<<=3;
                                foo|=(k-'0');
                            }
                            if(foo==-1)continue;
                        }
                        else
                        {
                            try{foo=int.Parse((String)cmds[1]);}
                            catch{}//(Exception e){continue;}
                        }
                        try
                        {
                            if(cmd.Equals("chgrp")){ c.chgrp(foo, path); }
                            else if(cmd.Equals("chown")){ c.chown(foo, path); }
                            else if(cmd.Equals("chmod")){ c.chmod(foo, path); }
                        }
                        catch(SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if(cmd.Equals("pwd") || cmd.Equals("lpwd"))
                    {
                        str=(cmd.Equals("pwd")?"Remote":"Local");
                        str+=" working directory: ";
                        if(cmd.Equals("pwd")) str+=c.pwd();
                        else str+=c.lpwd();
                        outs.WriteLine(str);
                        continue;
                    }
                    if(cmd.Equals("ls") || cmd.Equals("dir"))
                    {
                        String path=".";
                        if(cmds.Count==2) path=(String)cmds[1];
                        try
                        {
                            ArrayList vv=c.ls(path);
                            if(vv!=null)
                            {
                                for(int ii=0; ii<vv.Count; ii++)
                                {
                                    object obj = vv[ii];
                                    if(obj is ChannelSftp.LsEntry)
                                        outs.WriteLine(vv[ii]);
                                }
                            }
                        }
                        catch(SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if(cmd.Equals("lls") || cmd.Equals("ldir"))
                    {
                        String path=".";
                        if(cmds.Count==2) path=(String)cmds[1];
                        try
                        {
                            //java.io.File file=new java.io.File(path);
                            if(!File.Exists(path))
                            {
                                outs.WriteLine(path+": No such file or directory");
                                continue;
                            }
                            if(Directory.Exists(path))
                            {
                                String[] list=Directory.GetDirectories(path);
                                for(int ii=0; ii<list.Length; ii++)
                                {
                                    outs.WriteLine(list[ii]);
                                }
                                continue;
                            }
                            outs.WriteLine(path);
                        }
                        catch(Exception e)
                        {
                            Console.WriteLine(e);
                        }
                        continue;
                    }
                    if(cmd.Equals("get") ||
                        cmd.Equals("get-resume") || cmd.Equals("get-append") ||
                        cmd.Equals("put") ||
                        cmd.Equals("put-resume") || cmd.Equals("put-append")
                        )
                    {
                        if(cmds.Count!=2 && cmds.Count!=3) continue;
                        String p1=(String)cmds[1];
                        //	  String p2=p1;
                        String p2=".";
                        if(cmds.Count==3)p2=(String)cmds[2];
                        try
                        {
                            SftpProgressMonitor monitor=new MyProgressMonitor();
                            if(cmd.StartsWith("get"))
                            {
                                int mode=ChannelSftp.OVERWRITE;
                                if(cmd.Equals("get-resume")){ mode=ChannelSftp.RESUME; }
                                else if(cmd.Equals("get-append")){ mode=ChannelSftp.APPEND; }
                                c.get(p1, p2, monitor, mode);
                            }
                            else
                            {
                                int mode=ChannelSftp.OVERWRITE;
                                if(cmd.Equals("put-resume")){ mode=ChannelSftp.RESUME; }
                                else if(cmd.Equals("put-append")){ mode=ChannelSftp.APPEND; }
                                c.put(p1, p2, monitor, mode);
                            }
                        }
                        catch(SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if(cmd.Equals("ln") || cmd.Equals("symlink") || cmd.Equals("rename"))
                    {
                        if(cmds.Count!=3) continue;
                        String p1=(String)cmds[1];
                        String p2=(String)cmds[2];
                        try
                        {
                            if(cmd.Equals("rename")) c.rename(p1, p2);
                            else c.symlink(p1, p2);
                        }
                        catch(SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if(cmd.Equals("stat") || cmd.Equals("lstat"))
                    {
                        if(cmds.Count!=2) continue;
                        String p1=(String)cmds[1];
                        SftpATTRS attrs=null;
                        try
                        {
                            if(cmd.Equals("stat")) attrs=c.stat(p1);
                            else attrs=c.lstat(p1);
                        }
                        catch(SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        if(attrs!=null)
                        {
                            outs.WriteLine(attrs);
                        }
                        else
                        {
                        }
                        continue;
                    }
                    if(cmd.Equals("version"))
                    {
                        outs.WriteLine("SFTP protocol version "+c.version());
                        continue;
                    }
                    if(cmd.Equals("help") || cmd.Equals("?"))
                    {
                        outs.WriteLine(help);
                        continue;
                    }
                    outs.WriteLine("unimplemented command: "+cmd);
                }
                session.disconnect();
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #36
0
        public static void RunExample(String[] arg)
        {
            try
            {
                JSch jsch=new JSch();

                OpenFileDialog chooser = new OpenFileDialog();
                chooser.Title = "Choose your known_hosts(ex. ~/.ssh/known_hosts)";
                //chooser.setFileHidingEnabled(false);
                DialogResult returnVal = chooser.ShowDialog();
                if(returnVal == DialogResult.OK)
                {
                    Console.WriteLine("You chose "+
                        chooser.FileName+".");
                    jsch.setKnownHosts(chooser.FileName);
                }
                else
                {
                    Console.WriteLine("Error getting host file...");
                    return;
                }

                HostKeyRepository hkr=jsch.getHostKeyRepository();
                HostKey[] hks=hkr.getHostKey();
                if(hks!=null)
                {
                    Console.WriteLine("Host keys in "+hkr.getKnownHostsRepositoryID());
                    for(int i=0; i<hks.Length; i++)
                    {
                        HostKey hk=hks[i];
                        Console.WriteLine(hk.getHost()+" "+
                            hk.getType()+" "+
                            hk.getFingerPrint(jsch));
                    }
                    Console.WriteLine("");
                }

                InputForm inForm = new InputForm();
                inForm.Text = "Enter username@hostname";
                inForm.textBox1.Text = Environment.UserName+"@localhost";

                if (inForm.PromptForInput())
                {
                    String host = inForm.textBox1.Text;
                    String user=host.Substring(0, host.IndexOf('@'));
                    host=host.Substring(host.IndexOf('@')+1);

                    Session session=jsch.getSession(user, host, 22);

                    // username and password will be given via UserInfo interface.
                    UserInfo ui=new MyUserInfo();
                    session.setUserInfo(ui);

                    session.connect();

                    HostKey hk=session.getHostKey();
                    Console.WriteLine("HostKey: "+
                        hk.getHost()+" "+
                        hk.getType()+" "+
                        hk.getFingerPrint(jsch));

                    Channel channel=session.openChannel("shell");

                    channel.setInputStream(Console.OpenStandardInput());
                    channel.setOutputStream(Console.OpenStandardOutput());

                    channel.connect();
                }
                inForm.Close();

            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #37
0
ファイル: Sftp.cs プロジェクト: trautmannalex/sharpssh
        public static void RunExample(String[] arg)
        {
            try
            {
                JSch jsch = new JSch();

                InputForm inForm = new InputForm();
                inForm.Text          = "Enter username@hostname";
                inForm.textBox1.Text = Environment.UserName + "@localhost";

                if (!inForm.PromptForInput())
                {
                    Console.WriteLine("Cancelled");
                    return;
                }
                String host = inForm.textBox1.Text;
                String user = host.Substring(0, host.IndexOf('@'));
                host = host.Substring(host.IndexOf('@') + 1);

                Session session = jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui = new MyUserInfo();
                session.setUserInfo(ui);

                session.connect();

                Channel channel = session.openChannel("sftp");
                channel.connect();
                ChannelSftp c = (ChannelSftp)channel;

                Stream     ins  = Console.OpenStandardInput();
                TextWriter outs = Console.Out;

                ArrayList cmds = new ArrayList();
                byte[]    buf  = new byte[1024];
                int       i;
                String    str;
                int       level = 0;

                while (true)
                {
                    outs.Write("sftp> ");
                    cmds.Clear();
                    i = ins.Read(buf, 0, 1024);
                    if (i <= 0)
                    {
                        break;
                    }

                    i--;
                    if (i > 0 && buf[i - 1] == 0x0d)
                    {
                        i--;
                    }
                    //str=Util.getString(buf, 0, i);
                    //Console.WriteLine("|"+str+"|");
                    int s = 0;
                    for (int ii = 0; ii < i; ii++)
                    {
                        if (buf[ii] == ' ')
                        {
                            if (ii - s > 0)
                            {
                                cmds.Add(Util.getString(buf, s, ii - s));
                            }
                            while (ii < i)
                            {
                                if (buf[ii] != ' ')
                                {
                                    break;
                                }
                                ii++;
                            }
                            s = ii;
                        }
                    }
                    if (s < i)
                    {
                        cmds.Add(Util.getString(buf, s, i - s));
                    }
                    if (cmds.Count == 0)
                    {
                        continue;
                    }

                    String cmd = (String)cmds[0];
                    if (cmd.Equals("quit"))
                    {
                        c.quit();
                        break;
                    }
                    if (cmd.Equals("exit"))
                    {
                        c.exit();
                        break;
                    }
                    if (cmd.Equals("rekey"))
                    {
                        session.rekey();
                        continue;
                    }
                    if (cmd.Equals("compression"))
                    {
                        if (cmds.Count < 2)
                        {
                            outs.WriteLine("compression level: " + level);
                            continue;
                        }
                        try
                        {
                            level = int.Parse((String)cmds[1]);
                            Hashtable config = new Hashtable();
                            if (level == 0)
                            {
                                config.Add("compression.s2c", "none");
                                config.Add("compression.c2s", "none");
                            }
                            else
                            {
                                config.Add("compression.s2c", "zlib,none");
                                config.Add("compression.c2s", "zlib,none");
                            }
                            session.setConfig(config);
                        }
                        catch {}                       //(Exception e){}
                        continue;
                    }
                    if (cmd.Equals("cd") || cmd.Equals("lcd"))
                    {
                        if (cmds.Count < 2)
                        {
                            continue;
                        }
                        String path = (String)cmds[1];
                        try
                        {
                            if (cmd.Equals("cd"))
                            {
                                c.cd(path);
                            }
                            else
                            {
                                c.lcd(path);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("rm") || cmd.Equals("rmdir") || cmd.Equals("mkdir"))
                    {
                        if (cmds.Count < 2)
                        {
                            continue;
                        }
                        String path = (String)cmds[1];
                        try
                        {
                            if (cmd.Equals("rm"))
                            {
                                c.rm(path);
                            }
                            else if (cmd.Equals("rmdir"))
                            {
                                c.rmdir(path);
                            }
                            else
                            {
                                c.mkdir(path);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("chgrp") || cmd.Equals("chown") || cmd.Equals("chmod"))
                    {
                        if (cmds.Count != 3)
                        {
                            continue;
                        }
                        String path = (String)cmds[2];
                        int    foo  = 0;
                        if (cmd.Equals("chmod"))
                        {
                            byte[] bar = Util.getBytes((String)cmds[1]);
                            int    k;
                            for (int j = 0; j < bar.Length; j++)
                            {
                                k = bar[j];
                                if (k < '0' || k > '7')
                                {
                                    foo = -1; break;
                                }
                                foo <<= 3;
                                foo  |= (k - '0');
                            }
                            if (foo == -1)
                            {
                                continue;
                            }
                        }
                        else
                        {
                            try{ foo = int.Parse((String)cmds[1]); }
                            catch {}                           //(Exception e){continue;}
                        }
                        try
                        {
                            if (cmd.Equals("chgrp"))
                            {
                                c.chgrp(foo, path);
                            }
                            else if (cmd.Equals("chown"))
                            {
                                c.chown(foo, path);
                            }
                            else if (cmd.Equals("chmod"))
                            {
                                c.chmod(foo, path);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("pwd") || cmd.Equals("lpwd"))
                    {
                        str  = (cmd.Equals("pwd")?"Remote":"Local");
                        str += " working directory: ";
                        if (cmd.Equals("pwd"))
                        {
                            str += c.pwd();
                        }
                        else
                        {
                            str += c.lpwd();
                        }
                        outs.WriteLine(str);
                        continue;
                    }
                    if (cmd.Equals("ls") || cmd.Equals("dir"))
                    {
                        String path = ".";
                        if (cmds.Count == 2)
                        {
                            path = (String)cmds[1];
                        }
                        try
                        {
                            ArrayList vv = c.ls(path);
                            if (vv != null)
                            {
                                for (int ii = 0; ii < vv.Count; ii++)
                                {
                                    object obj = vv[ii];
                                    if (obj is ChannelSftp.LsEntry)
                                    {
                                        outs.WriteLine(vv[ii]);
                                    }
                                }
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("lls") || cmd.Equals("ldir"))
                    {
                        String path = ".";
                        if (cmds.Count == 2)
                        {
                            path = (String)cmds[1];
                        }
                        try
                        {
                            //java.io.File file=new java.io.File(path);
                            if (!File.Exists(path))
                            {
                                outs.WriteLine(path + ": No such file or directory");
                                continue;
                            }
                            if (Directory.Exists(path))
                            {
                                String[] list = Directory.GetDirectories(path);
                                for (int ii = 0; ii < list.Length; ii++)
                                {
                                    outs.WriteLine(list[ii]);
                                }
                                continue;
                            }
                            outs.WriteLine(path);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                        continue;
                    }
                    if (cmd.Equals("get") ||
                        cmd.Equals("get-resume") || cmd.Equals("get-append") ||
                        cmd.Equals("put") ||
                        cmd.Equals("put-resume") || cmd.Equals("put-append")
                        )
                    {
                        if (cmds.Count != 2 && cmds.Count != 3)
                        {
                            continue;
                        }
                        String p1 = (String)cmds[1];
                        //	  String p2=p1;
                        String p2 = ".";
                        if (cmds.Count == 3)
                        {
                            p2 = (String)cmds[2];
                        }
                        try
                        {
                            SftpProgressMonitor monitor = new MyProgressMonitor();
                            if (cmd.StartsWith("get"))
                            {
                                int mode = ChannelSftp.OVERWRITE;
                                if (cmd.Equals("get-resume"))
                                {
                                    mode = ChannelSftp.RESUME;
                                }
                                else if (cmd.Equals("get-append"))
                                {
                                    mode = ChannelSftp.APPEND;
                                }
                                c.get(p1, p2, monitor, mode);
                            }
                            else
                            {
                                int mode = ChannelSftp.OVERWRITE;
                                if (cmd.Equals("put-resume"))
                                {
                                    mode = ChannelSftp.RESUME;
                                }
                                else if (cmd.Equals("put-append"))
                                {
                                    mode = ChannelSftp.APPEND;
                                }
                                c.put(p1, p2, monitor, mode);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("ln") || cmd.Equals("symlink") || cmd.Equals("rename"))
                    {
                        if (cmds.Count != 3)
                        {
                            continue;
                        }
                        String p1 = (String)cmds[1];
                        String p2 = (String)cmds[2];
                        try
                        {
                            if (cmd.Equals("rename"))
                            {
                                c.rename(p1, p2);
                            }
                            else
                            {
                                c.symlink(p1, p2);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        continue;
                    }
                    if (cmd.Equals("stat") || cmd.Equals("lstat"))
                    {
                        if (cmds.Count != 2)
                        {
                            continue;
                        }
                        String    p1    = (String)cmds[1];
                        SftpATTRS attrs = null;
                        try
                        {
                            if (cmd.Equals("stat"))
                            {
                                attrs = c.stat(p1);
                            }
                            else
                            {
                                attrs = c.lstat(p1);
                            }
                        }
                        catch (SftpException e)
                        {
                            Console.WriteLine(e.message);
                        }
                        if (attrs != null)
                        {
                            outs.WriteLine(attrs);
                        }
                        else
                        {
                        }
                        continue;
                    }
                    if (cmd.Equals("version"))
                    {
                        outs.WriteLine("SFTP protocol version " + c.version());
                        continue;
                    }
                    if (cmd.Equals("help") || cmd.Equals("?"))
                    {
                        outs.WriteLine(help);
                        continue;
                    }
                    outs.WriteLine("unimplemented command: " + cmd);
                }
                session.disconnect();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #38
0
ファイル: Scp.cs プロジェクト: radtek/Ketarin4Linux
        /// <summary>
        /// Initiates a new SCP response on sourceforge.net for downloading a file.
        /// </summary>
        /// <param name="uri">URI to download (includes username and password)</param>
        /// <param name="timeout">Timeout for this session</param>
        public ScpWebResponse(Uri uri, int timeout)
        {
            JSch jsch = new JSch();

            string[] userPass = uri.UserInfo.Split(':');
            if (userPass.Length != 2)
            {
                throw new WebException("Username and password information for sourceforge.net incomplete");
            }

            session = jsch.getSession(userPass[0], "frs.sourceforge.net", 22);

            // username and password will be given via UserInfo interface.
            //UserInfo ui = new UserInfo();
            //session.setUserInfo(ui);
            session.setPassword(userPass[1]);
            Hashtable hastable = new Hashtable();

            hastable.put("StrictHostKeyChecking", "no");
            session.setConfig(hastable);

            if (DbManager.Proxy != null)
            {
                session.setProxy(new ProxyHTTP(DbManager.Proxy.Address.Host, DbManager.Proxy.Address.Port));
            }

            try
            {
                session.connect(timeout);
            }
            catch (JSchException e)
            {
                if (e.Message == "Auth fail")
                {
                    throw new WebException("Invalid username or password for sourceforge");
                }
                throw;
            }

            // exec 'scp -f rfile' remotely
            string sfPath = GetSourceforgePath(uri.LocalPath);

            // Determine file modified date
            ChannelSftp channelSftp = (ChannelSftp)session.openChannel("sftp");

            channelSftp.connect();
            try
            {
                SftpATTRS attrs = channelSftp.lstat(sfPath);
                this.lastModified = RpcApplication.UnixToDotNet(attrs.getMTime());
            }
            catch (SftpException)
            {
                throw new WebException("The file \"" + sfPath + "\" could not be found.");
            }
            finally
            {
                channelSftp.disconnect();
            }

            String  command = "scp -f " + sfPath.Replace(" ", "\\ ");
            Channel channel = session.openChannel("exec");

            ((ChannelExec)channel).setCommand(command);

            // get I/O streams for remote scp
            Stream outs = channel.getOutputStream();
            Stream ins  = channel.getInputStream();

            channel.connect();

            byte[] buf = new byte[1024];

            // send '\0'
            buf[0] = 0; outs.Write(buf, 0, 1); outs.Flush();


            int c = checkAck(ins);

            if (c != 'C')
            {
                return;
            }

            // read '0644 '
            ins.Read(buf, 0, 5);

            while (true)
            {
                ins.Read(buf, 0, 1);
                if (buf[0] == ' ')
                {
                    break;
                }
                this.contentLength = this.contentLength * 10 + (buf[0] - '0');
            }

            for (int i = 0; ; i++)
            {
                ins.Read(buf, i, 1);
                if (buf[i] == (byte)0x0a)
                {
                    Util.getString(buf, 0, i);
                    break;
                }
            }

            this.responseUri = new Uri("scp://" + session.getHost() + sfPath);
            // send '\0'
            buf[0] = 0; outs.Write(buf, 0, 1); outs.Flush();

            this.responseStream = ins;
        }
コード例 #39
0
        public static void Main(String[] arg)
        {
            try
            {
                //Get the "known hosts" filename from the user
                Console.WriteLine("Please select your 'known_hosts' from the poup window...");
                String file = InputForm.GetFileFromUser("Choose your known_hosts(ex. ~/.ssh/known_hosts)");
                Console.WriteLine("You chose "+file+".");
                //Create a new JSch instance
                JSch jsch=new JSch();
                //Set the known hosts file
                jsch.setKnownHosts(file);

                //Get the KnownHosts repository from JSchs
                HostKeyRepository hkr=jsch.getHostKeyRepository();

                //Print all known hosts and keys
                HostKey[] hks=hkr.getHostKey();
                HostKey hk;
                if(hks!=null)
                {
                    Console.WriteLine();
                    Console.WriteLine("Host keys in "+hkr.getKnownHostsRepositoryID()+":");
                    for(int i=0; i<hks.Length; i++)
                    {
                        hk=hks[i];
                        Console.WriteLine(hk.getHost()+" "+
                            hk.getType()+" "+
                            hk.getFingerPrint(jsch));
                    }
                    Console.WriteLine("");
                }

                //Now connect to the remote server...

                //Prompt for username and server host
                Console.WriteLine("Please enter the user and host info at the popup window...");
                String host = InputForm.GetUserInput
                    ("Enter username@hostname",
                    Environment.UserName+"@localhost");
                String user=host.Substring(0, host.IndexOf('@'));
                host=host.Substring(host.IndexOf('@')+1);

                //Create a new SSH session
                Session session=jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui=new MyUserInfo();
                session.setUserInfo(ui);

                //Connect to remote SSH server
                session.connect();

                //Print the host key info
                //of the connected server:
                hk=session.getHostKey();
                Console.WriteLine("HostKey: "+
                    hk.getHost()+" "+
                    hk.getType()+" "+
                    hk.getFingerPrint(jsch));

                //Open a new Shell channel on the SSH session
                Channel channel=session.openChannel("shell");

                //Redirect standard I/O to the SSH channel
                channel.setInputStream(Console.OpenStandardInput());
                channel.setOutputStream(Console.OpenStandardOutput());

                //Connect the channel
                channel.connect();

                Console.WriteLine("-- Shell channel is connected using the {0} cipher",
                    session.getCipher());

                //Wait till channel is closed
                while(!channel.isClosed())
                {
                    System.Threading.Thread.Sleep(500);
                }

                //Disconnect from remote server
                channel.disconnect();
                session.disconnect();
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
コード例 #40
0
        public static void Main(String[] arg)
        {
            if(arg.Length!=2)
            {
                Console.WriteLine("usage: java ScpFrom user@remotehost:file1 file2");
                return;
            }

            try
            {
                String user=arg[0].Substring(0, arg[0].IndexOf('@'));
                arg[0]=arg[0].Substring(arg[0].IndexOf('@')+1);
                String host=arg[0].Substring(0, arg[0].IndexOf(':'));
                String rfile=arg[0].Substring(arg[0].IndexOf(':')+1);
                String lfile=arg[1];

                String prefix=null;
                if(Directory.Exists(lfile))
                {
                    prefix=lfile+Path.DirectorySeparatorChar;
                }

                JSch jsch=new JSch();
                Session session=jsch.getSession(user, host, 22);

                // username and password will be given via UserInfo interface.
                UserInfo ui=new MyUserInfo();
                session.setUserInfo(ui);
                session.connect();

                // exec 'scp -f rfile' remotely
                String command="scp -f "+rfile;
                Channel channel=session.openChannel("exec");
                ((ChannelExec)channel).setCommand(command);

                // get I/O streams for remote scp
                Stream outs=channel.getOutputStream();
                Stream ins=channel.getInputStream();

                channel.connect();

                byte[] buf=new byte[1024];

                // send '\0'
                buf[0]=0; outs.Write(buf, 0, 1); outs.Flush();

                while(true)
                {
                    int c=checkAck(ins);
                    if(c!='C')
                    {
                        break;
                    }

                    // read '0644 '
                    ins.Read(buf, 0, 5);

                    int filesize=0;
                    while(true)
                    {
                        ins.Read(buf, 0, 1);
                        if(buf[0]==' ')break;
                        filesize=filesize*10+(buf[0]-'0');
                    }

                    String file=null;
                    for(int i=0;;i++)
                    {
                        ins.Read(buf, i, 1);
                        if(buf[i]==(byte)0x0a)
                        {
                            file=Util.getString(buf, 0, i);
                            break;
                        }
                    }

                    //Console.WriteLine("filesize="+filesize+", file="+file);

                    // send '\0'
                    buf[0]=0; outs.Write(buf, 0, 1); outs.Flush();

                    // read a content of lfile
                    FileStream fos=File.OpenWrite(prefix==null ?
                    lfile :
                        prefix+file);
                    int foo;
                    while(true)
                    {
                        if(buf.Length<filesize) foo=buf.Length;
                        else foo=filesize;
                        ins.Read(buf, 0, foo);
                        fos.Write(buf, 0, foo);
                        filesize-=foo;
                        if(filesize==0) break;
                    }
                    fos.Close();

                    byte[] tmp=new byte[1];

                    if(checkAck(ins)!=0)
                    {
                        Environment.Exit(0);
                    }

                    // send '\0'
                    buf[0]=0; outs.Write(buf, 0, 1); outs.Flush();
                }
                Environment.Exit(0);
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }