getSession() public method

public getSession ( String username, String host ) : Session
username String
host String
return Session
Ejemplo n.º 1
0
		public static void RunExample(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.Message);
			}
		}
Ejemplo n.º 2
0
 public void Connect()
 {
     InitVAHInfo();
     try
     {
         JSch jsch = new JSch();
         _ssn = jsch.getSession(_usr, _hip, _hp);
         System.Collections.Hashtable hashConfig = new Hashtable();
         hashConfig.Add("StrictHostKeyChecking", "No");
         _ssn.setConfig(hashConfig);
         jsch.addIdentity(_ppk);
         _ssn.connect();
         if (_ssn.isConnected())
         {
             Console.WriteLine("Log Successfully.");
         }
         else
         {
             Console.WriteLine("Log failed.");
         }
     }
     catch (Tamir.SharpSsh.jsch.JSchException jschex)
     {
         Console.WriteLine(jschex.Message);
     }
     catch (Exception anyex)
     {
         Console.WriteLine(anyex.Message);
     }
 }
Ejemplo n.º 3
0
        public SshHelper(string host, string username, string password)
        {
            this.host = host;
            JSch jsch=new JSch();
            Session session=jsch.getSession(username, host, 22);
            session.setPassword( password );

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

            session.connect();

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

            writer_po = new PipedOutputStream();
            PipedInputStream writer_pi = new PipedInputStream( writer_po );

            PipedInputStream reader_pi = new PipedInputStream();
            PipedOutputStream reader_po = new PipedOutputStream( reader_pi );
            reader = new StreamReader (reader_pi,Encoding.UTF8);

            channel.setInputStream( writer_pi );
            channel.setOutputStream( reader_po );

            channel.connect();
            channel.setPtySize(132, 132, 1024, 768);
        }
Ejemplo n.º 4
0
		public static void Run()
		{
			JSch jsch=new JSch();
			Session session=jsch.getSession("root", "rhmanage", 22);
			session.setPassword( "cisco" );

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

			session.connect();
			
				Channel channel=session.openChannel("exec"); 
				((ChannelExec)channel).setCommand("ifconfig");

				StreamReader sr = new StreamReader( channel.getInputStream() );

				channel.connect();

				string line;

				while( (line=sr.ReadLine()) != null )
				{
					Console.WriteLine( line );
				}		

				channel.disconnect();
				session.disconnect();
		}
Ejemplo n.º 5
0
        public static void Connect()
        {
            try
             {
                 var jsch = new JSch();

                 _session = jsch.getSession(Settings.SSHUsername, Settings.SSHHost, Settings.SSHPort);
                 _session.setHost(Settings.SSHHost);
                 _session.setPassword(Settings.SSHPassword);
                 UserInfo ui = new MyUserInfo(Settings.SSHPassword);
                 _session.setUserInfo(ui);
                 _session.connect();
                 int port;
                 if (!int.TryParse(Settings.Port, out port))
                     port = 3306;
                 _session.setPortForwardingL(Settings.SSHLocalPort, "localhost", port);
                 if (!_session.isConnected())
                    Enabled = false;
             }
             catch (Exception ex)
             {
                Enabled = false;
                Trace.WriteLine(ex.Message + " at ssh connect.");
                Disconnect();
            }
        }
Ejemplo n.º 6
0
        public SshHelper(string Host, string UserName, string Password)
        {
            host = Host;
            var jsch = new JSch();
            session = jsch.getSession(UserName, host, 22);
            session.setPassword(Password);

            var config = new Hashtable { { "StrictHostKeyChecking", "no" } };
            session.setConfig(config);

            session.connect();

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

            writer_po = new PipedOutputStream();
            var writer_pi = new PipedInputStream(writer_po);

            var reader_pi = new PipedInputStream();
            var reader_po = new PipedOutputStream(reader_pi);
            reader = new StreamReader(reader_pi, Encoding.UTF8);

            channel.setInputStream(writer_pi);
            channel.setOutputStream(reader_po);

            channel.connect();
            channel.setPtySize(132, 132, 1024, 768);
        }
Ejemplo n.º 7
0
		public static void RunExample(String[] arg)
		{
			try
			{
				JSch jsch=new JSch();

				//Get the "known hosts" 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);
			}
		}
Ejemplo n.º 8
0
 /// <summary>
 /// 构造方法
 /// </summary>
 /// <param name="host"></param>
 /// <param name="user"></param>
 /// <param name="pwd"></param>
 public SftpHelper(string host, string user, string pwd)
 {
     string[] arr = host.Split(':');
     string ip = arr[0];
     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);
 }
Ejemplo n.º 9
0
		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);
			}
		}
Ejemplo n.º 10
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 = "";
		}
Ejemplo n.º 11
0
		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);

				//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.Message);
			}
		}
Ejemplo n.º 12
0
		/// <summary>
		/// Constructs a new SSH stream.
		/// </summary>
		/// <param name="host">The hostname or IP address of the remote SSH machine</param>
		/// <param name="username">The name of the user connecting to the remote machine</param>
		/// <param name="password">The password of the user connecting to the remote machine</param>
		public SshStream(string host, string username, string password)
		{
			this.m_host = host;
			JSch jsch=new JSch();
			m_session=jsch.getSession(username, host, 22);
			m_session.setPassword( 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);

			Prompt = "\n";
			m_escapeCharPattern = "\\[[0-9;?]*[^0-9;]";
		}
Ejemplo n.º 13
0
		///<summary>Returns true if the communications were successful, and false if they failed. Both sends and retrieves.</summary>
		public static bool Launch(Clearinghouse clearhouse,int batchNum) {
			clearinghouse=clearhouse;
			//Before this function is called, the X12 file for the current batch has already been generated in
			//the clearinghouse export folder. The export folder will also contain batch files which have failed
			//to upload from previous attempts and we must attempt to upload these older batch files again if
			//there are any.
			//Step 1: Retrieve reports regarding the existing pending claim statuses.
			//Step 2: Send new claims in a new batch.
			bool success=true;
			//Connect to the Denti-Cal SFTP server.
			Session session=null;
			Channel channel=null;
			ChannelSftp ch=null;
			JSch jsch=new JSch();
			try {
				session=jsch.getSession(clearinghouse.LoginID,remoteHost);
				session.setPassword(clearinghouse.Password);
				Hashtable config=new Hashtable();
				config.Add("StrictHostKeyChecking","no");
				session.setConfig(config);
				session.connect();
				channel=session.openChannel("sftp");
				channel.connect();
				ch=(ChannelSftp)channel;
			}
			catch(Exception ex) {
				MessageBox.Show(Lan.g("DentiCal","Connection Failed")+": "+ex.Message);
				return false;
			}
			try {
				string homeDir="/Home/"+clearhouse.LoginID+"/";
				//At this point we are connected to the Denti-Cal SFTP server.
				if(batchNum==0) { //Retrieve reports.
					if(!Directory.Exists(clearhouse.ResponsePath)) {
						throw new Exception("Clearinghouse response path is invalid.");
					}
					//Only retrieving reports so do not send new claims.
					string retrievePath=homeDir+"out/";
					Tamir.SharpSsh.java.util.Vector fileList=ch.ls(retrievePath);
					for(int i=0;i<fileList.Count;i++) {
						string listItem=fileList[i].ToString().Trim();
						if(listItem[0]=='d') {
							continue;//Skip directories and focus on files.
						}
						Match fileNameMatch=Regex.Match(listItem,".*\\s+(.*)$");
						string getFileName=fileNameMatch.Result("$1");
						string getFilePath=retrievePath+getFileName;
						string exportFilePath=CodeBase.ODFileUtils.CombinePaths(clearhouse.ResponsePath,getFileName);
						Tamir.SharpSsh.java.io.InputStream fileStream=null;
						FileStream exportFileStream=null;
						try {
							fileStream=ch.get(getFilePath);
							exportFileStream=File.Open(exportFilePath,FileMode.Create,FileAccess.Write);//Creates or overwrites.
							byte[] dataBytes=new byte[4096];
							int numBytes=fileStream.Read(dataBytes,0,dataBytes.Length);
							while(numBytes>0) {
								exportFileStream.Write(dataBytes,0,numBytes);
								numBytes=fileStream.Read(dataBytes,0,dataBytes.Length);
							}
						}
						catch {
							success=false;
						}
						finally {
							if(exportFileStream!=null) {
								exportFileStream.Dispose();
							}
							if(fileStream!=null) {
								fileStream.Dispose();
							}
						}
						if(success) {
							//Removed the processed report from the Denti-Cal SFTP so it does not get processed again in the future.
							try {
								ch.rm(getFilePath);
							}
							catch {
							}
						}
					}
				}
				else { //Send batch of claims.
					if(!Directory.Exists(clearhouse.ExportPath)) {
						throw new Exception("Clearinghouse export path is invalid.");
					}
					string[] files=Directory.GetFiles(clearhouse.ExportPath);
					for(int i=0;i<files.Length;i++) {
						//First upload the batch file to a temporary file name. Denti-Cal does not process file names unless they start with the Login ID.
						//Uploading to a temporary file and then renaming the file allows us to avoid partial file uploads if there is connection loss.
						string tempRemoteFilePath=homeDir+"in/temp_"+Path.GetFileName(files[i]);
						ch.put(files[i],tempRemoteFilePath);
						//Denti-Cal requires the file name to start with the Login ID followed by a period and end with a .txt extension.
						//The middle part of the file name can be anything.
						string remoteFilePath=homeDir+"in/"+clearhouse.LoginID+"."+Path.GetFileName(files[i]);
						ch.rename(tempRemoteFilePath,remoteFilePath);
						File.Delete(files[i]);//Remove the processed file.
					}
				}
			}
			catch {
				success=false;
			}
			finally {
				//Disconnect from the Denti-Cal SFTP server.
				channel.disconnect();
				ch.disconnect();
				session.disconnect();
			}
			return success;
		}
Ejemplo n.º 14
0
		public static void RunExample(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);
				
				String proxy=InputForm.GetUserInput("Enter proxy server",
					"hostname:port");

				string proxy_host=proxy.Substring(0, proxy.IndexOf(':'));
				int proxy_port=int.Parse(proxy.Substring(proxy.IndexOf(':')+1));

				session.setProxy(new ProxyHTTP(proxy_host, proxy_port));

				// 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);
			}
		}
Ejemplo n.º 15
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);
            }
        }
Ejemplo n.º 16
0
        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 = 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 LitleOnlineException("Error occured while attempting to establish an SFTP connection", e);
            }
            catch (JSchException e)
            {
                throw new LitleOnlineException("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 LitleOnlineException("Error occured while attempting to upload and save the file to SFTP", e);
            }

            channelSftp.quit();

            session.disconnect();
        }
Ejemplo n.º 17
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 LitleOnlineException("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);
        }
Ejemplo n.º 18
0
        public static bool Connect(string thost,string tuser,string tpass,string tport)
        {
            try
            {
                JSch jsch = new JSch();
                host = thost;
                user = tuser;
                pass = tpass;
                sshPort = Convert.ToInt32(tport);

                session = jsch.getSession(user, host, sshPort);
                session.setHost(host);
                session.setPassword(pass);
                UserInfo ui = new MyUserInfo();
                session.setUserInfo(ui);
                session.connect();
                session.setPortForwardingL(lPort, "127.0.0.1", rPort);
                return true;
            }
            catch (Exception ex)
            {
                error = ex;
                return false;
            }
        }
Ejemplo n.º 19
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);
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        ///  This class creates a jsch instance using the host that user wants. This makes it possible to
        ///  forward the MySql Database port to a user's local port.
        /// </summary>
        public string jschServer(string host, string user, string password)
        {
            try
            {
                // Create a new JSch instance
                JSch jsch = new JSch();

                // Saves the info to make other sessions
                this.host = host;
                this.user = user;
                this.password = password;

                // Create a new SSH session
                session = jsch.getSession(user, password, port);
                session.setHost(host); ;
                session.setPassword(password);

                // Creates a userinfo instance to pass into the session
                UserInfo ui = new MyUserInfo();
                session.setUserInfo(ui);

                session.connect();

                return null;
            }
            catch (Exception ex)
            {
                session.disconnect();
                return ex.Message;
            }
        }
Ejemplo n.º 21
0
		///<summary>Returns true if the communications were successful, and false if they failed. Both sends and retrieves.</summary>
		public static bool Launch(Clearinghouse clearhouse,int batchNum){
			clearinghouse=clearhouse;
			//Before this function is called, the X12 file for the current batch has already been generated in
			//the clearinghouse export folder. The export folder will also contain batch files which have failed
			//to upload from previous attempts and we must attempt to upload these older batch files again if
			//there are any.
			//Step 1: Retrieve reports regarding the existing pending claim statuses.
			//Step 2: Send new claims in a new batch.
			bool success=true;
			//Connect to the MDE SFTP server.
			Session session=null;
			Channel channel=null;
			ChannelSftp ch=null;
			JSch jsch=new JSch();
			try{
				session=jsch.getSession(clearinghouse.LoginID,remoteHost,22);
				session.setPassword(clearinghouse.Password);
				Hashtable config=new Hashtable();
				config.Add("StrictHostKeyChecking", "no");
				session.setConfig(config);
				session.connect();
				channel=session.openChannel("sftp");
				channel.connect();
				ch=(ChannelSftp)channel;
			}catch(Exception ex){
				MessageBox.Show(Lan.g("MercuryDE","Connection Failed")+": "+ex.Message);
				return false;
			}
			try{
				//At this point we are connected to the MDE SFTP server.
				if(batchNum==0){
					if(!Directory.Exists(clearhouse.ResponsePath)){
						throw new Exception("Clearinghouse response path is invalid.");
					}
					//Only retrieving reports so do not send new claims.
					string retrievePath="/"+rootFolderName+"/Out/997/";
					Tamir.SharpSsh.java.util.Vector fileList=ch.ls(retrievePath);
					for(int i=0;i<fileList.Count;i++){
						string listItem=fileList[i].ToString().Trim();
						if(listItem[0]=='d'){
							continue;//Skip directories and focus on files.
						}
						Match fileNameMatch=Regex.Match(listItem,".*\\s+(.*)$");
						string getFileName=fileNameMatch.Result("$1");
						string getFilePath=retrievePath+getFileName;
						string exportFilePath=CodeBase.ODFileUtils.CombinePaths(clearhouse.ResponsePath,getFileName);						
						Tamir.SharpSsh.java.io.InputStream fileStream=null;
						FileStream exportFileStream=null;
						try{
							fileStream=ch.get(getFilePath);
							exportFileStream=File.Open(exportFilePath,FileMode.Create,FileAccess.Write);//Creates or overwrites.
							byte[] dataBytes=new byte[4096];
							int numBytes=fileStream.Read(dataBytes,0,dataBytes.Length);
							while(numBytes>0){
								exportFileStream.Write(dataBytes,0,numBytes);
								numBytes=fileStream.Read(dataBytes,0,dataBytes.Length);
							}
						}catch{
							success=false;
						}finally{
							if(exportFileStream!=null){
								exportFileStream.Dispose();
							}
							if(fileStream!=null){
								fileStream.Dispose();
							}
						}
						string archiveFilePath=retrievePath+"Archive/"+getFileName;
						try{
							ch.rm(archiveFilePath);
						}catch{
							//Remove any destination files by the same exact name. The file will most likely not be present.
						}
						ch.rename(getFilePath,archiveFilePath);
					}
				}else{
					if(!Directory.Exists(clearhouse.ExportPath)){
						throw new Exception("Clearinghouse export path is invalid.");
					}
					//First upload the batch to the temporary directory.
					string[] files=Directory.GetFiles(clearhouse.ExportPath);
					for(int i=0;i<files.Length;i++){
						string accountNumber=clearinghouse.ISA08;
						string dateTimeStr=DateTime.Now.ToString("yyyyMMddhhmmss");
						string remoteFileName=accountNumber+dateTimeStr+i.ToString().PadLeft(3,'0')+".837D.txt";
						string remoteTempFilePath="/"+rootFolderName+"/In/837D/Temp/"+remoteFileName;
						ch.put(files[i],remoteTempFilePath);
						//Read, Write and Execute permissions for everyone. This appears to cause no effect.
						ch.chmod((((7<<3)|7)<<3)|7,remoteTempFilePath);
						string remoteFilePath="/"+rootFolderName+"/In/837D/"+remoteFileName;
						ch.rename(remoteTempFilePath,remoteFilePath);
						File.Delete(files[i]);//Remove the processed file.
					}
				}
			}catch{
				success=false;
			}finally{
				//Disconnect from the MDE SFTP server.
				channel.disconnect();
				ch.disconnect();
				session.disconnect();
			}
			return success;
		}
Ejemplo n.º 22
0
        protected void OpenSSH()
        {
            try
            {
                //Create a new SSH session
                _jsch = new JSch();
                _sshSession = _jsch.getSession(
                    Settings.SSHUserID,
                    Settings.SSHHost,
                    int.Parse(Settings.SSHPort));

                _sshSession.setHost(Settings.SSHHost);
                _sshSession.setPassword(Settings.SSHPassword);

                UserInfo ui = new JschUserInfo();
                _sshSession.setUserInfo(ui);

                // Connect
                _sshSession.connect();

                //Set port forwarding on the opened session
                _sshSession.setPortForwardingL(
                    int.Parse(Settings.SSHLocalPort),
                    Settings.SSHForwardingHost,
                    int.Parse(Settings.SSHRemotePort));

                if (!_sshSession.isConnected())
                    throw new Exception("SSH Session did not connect.");
            }
            catch (Exception ex)
            {
                MessageBox.Show(string.Format("Could not start due to SSH Error:\n{0}", ex));
                return;
            }
        }
Ejemplo n.º 23
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;
        }
Ejemplo n.º 24
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 LitleOnlineException("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 LitleOnlineException("Error occured while attempting to retrieve and save the file from SFTP", e);
            }

            channelSftp.quit();

            session.disconnect();
        }
Ejemplo n.º 25
0
		public static void RunExample(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.Message);
			}
		}
Ejemplo n.º 26
0
        protected override void OnStart(string[] args)
        {
            bool ontWorkerInstantiated = false;

            if (Repository.Configuration.Processes == null)
                return;

            if (Repository.Configuration.Database.SSH.Enabled)
            {
                try
                {
                    //Create a new SSH session
                    _jsch = new JSch();
                    _sshSession = _jsch.getSession(
                        Repository.Configuration.Database.SSH.UserID,
                        Repository.Configuration.Database.SSH.Host,
                        Repository.Configuration.Database.SSH.Port);

                    _sshSession.setHost(Repository.Configuration.Database.SSH.Host);
                    _sshSession.setPassword(Repository.Configuration.Database.SSH.Password);

                    UserInfo ui = new JschUserInfo();
                    _sshSession.setUserInfo(ui);

                    // Connect
                    _sshSession.connect();

                    //Set port forwarding on the opened session
                    _sshSession.setPortForwardingL(
                        Repository.Configuration.Database.SSH.LocalPort,
                        Repository.Configuration.Database.SSH.ForwardingHost,
                        Repository.Configuration.Database.SSH.RemotePort);

                    if (!_sshSession.isConnected())
                        throw new Exception("SSH Session did not connect.");
                }
                catch (Exception ex)
                {
                    EventLogWriter.WriteError("Could not start due to SSH Error:\n{0}", ex);
                    return;
                }
            }

            foreach (TextMinerServiceSettingsProcess process in Repository.Configuration.Processes)
            {
                if (!process.Enabled)
                    continue;

                switch (process.Type)
                {
                    case ProcessType.OntologySubsetWorker:
                        {
                            // Only one thread of this type allowed
                            if (ontWorkerInstantiated == true)
                                continue;

                            process.Worker = new Worker.OntologySubset(process.PollingInterval, process.Timeout, process.ResponseTimeout);
                            ontWorkerInstantiated = true;
                            break;
                        }
                    case ProcessType.PubMed:
                        {
                            process.Worker = new Worker.PubMed(process.PollingInterval, process.Timeout, process.PostPollingInterval, process.ResponseTimeout, process.OntogratorTab);
                            break;
                        }
                    case ProcessType.Pubget:
                        {
                            process.Worker = new Worker.Pubget(process.PollingInterval, process.Timeout, process.PostPollingInterval, process.ResponseTimeout, process.OntogratorTab);
                            break;
                        }
                    case ProcessType.ClinicalTrialsGov:
                        {
                            process.Worker = new Worker.ClinicalTrialsGov(process.PollingInterval, process.Timeout, process.PostPollingInterval, process.ResponseTimeout, process.OntogratorTab);
                            break;
                        }
                    default:
                        {
                            continue;
                        }
                }

                process.Thread = new Thread(new ThreadStart(process.Worker.Start));
                process.Thread.Start();
            }
        }
Ejemplo n.º 27
0
        ///SFTP Code Starting here
        ///hell yeah
        private void sftp_login()
        {
            JSch jsch = new JSch();

            String host = ftpHost();
            String user = ftpUser();

            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(ftpPort());

            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            sftpc = (ChannelSftp)channel;
            //sftpc = (ChannelSftp)channel;
        }
Ejemplo n.º 28
0
 public bool OpenConnection(RemoteSystem _defaultGateway, int _localPort)
 {
     if (!this.IsConnected ()) {
         var jsch = new JSch ();
         var gw = _defaultGateway;
         this.LPort = _localPort;
         this.SSHSession = jsch.getSession (gw.GetUser (), gw.GetHost (), gw.GetPortNumber ());
         this.SSHSession.setUserInfo (new RemoteUserInfo (gw));
         try {
             this.SSHSession.connect ();
         } catch (Tamir.SharpSsh.jsch.JSchException ex) {
             Console.WriteLine ("Could not establish connection to remote gateway.");
             return false;
         }
         if (this.IsConnected ()) {
             this.SSHSession.setPortForwardingL (this.LPort, this.GetHost (), this.GetPortNumber ());
             this.RemoteSession = new RemoteConnection (this);
             this.RemoteSession.ConnectionClosed += (object sender, ConnectionEventArgs args) => { this.CloseConnection (); };
             this.RemoteSession.Open ();
         }
     }
     return this.IsConnected ();
 }
Ejemplo n.º 29
0
		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);
			}			
		}
Ejemplo n.º 30
0
        internal bool SSHConnect()
        {
            try
            {
                channels_ = new Dictionary<int, ChannelSftp>();

                jsch_ = new JSch();
                Hashtable config = new Hashtable();
                config["StrictHostKeyChecking"] = "no";

                if (identity_ != null)
                    jsch_.addIdentity(identity_, passphrase_);

                session_ = jsch_.getSession(user_, host_, port_);
                session_.setConfig(config);
                session_.setUserInfo(new DokanUserInfo(password_, passphrase_));
                session_.setPassword(password_);

                session_.connect();

                return true;
            }
            catch (Exception e)
            {
                Debug(e.ToString());
                return false;
            }
        }