Terminal Session with Java

I am trying to create a terminal emulator in Java. The java program will accept commands from the user and show its output. I can emulate simple commands like "ls", but I donโ€™t know how to handle commands like "cd". This is because I use the exec () method to execute terminal commands. So, all the commands are executed in the current directory. Commands such as "cd .." are executed, but then they do not have a permanent effect, because each command is executed separately by exec ().
Any ideas How can I emulate a whole session?

+4
source share
3 answers

If you execute commands with exec() , you are not writing a terminal emulator; you are writing a shell. In this case, you will need to keep track of things that the shell is tracking, such as environment variables and the working directory.

If you really want to write a terminal emulator, you will talk to the shell process through a pseudo-terminal. Then your program will simply track what the terminal is monitoring, for example, the status of the line and what appears on the screen.

Working with a pseudo-terminal from Java will be a bit complicated, because most of the documentation assumes that you are using a C api. man pty should start. Your Java process will need to open the main side of the pseudo-terminal using FileStream objects. I am not sure that in Java there is a way to get a child process to open the slave side of the pseudo-terminal; you may need to invoke a shell command using exec() , which will run another shell command with standard input / output / error redirected to the slave side of the pseudo-terminal.

+5
source

JSch is a pure Java SSH2 implementation. JSch allows you to connect to the sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate your functions into your own Java programs.

http://www.jcraft.com/jsch/

+2
source

You really should try Ganymede.

Ganymed SSH-2 for Java is a library that implements the SSH-2 protocol in pure Java (tested on J2SE 1.4.2 and 5.0). This allows you to connect to SSH servers from Java programs. It supports SSH sessions (remote command execution and shell access), local and remote port forwarding, local flow forwarding, X11, SCP and SFTP forwarding.

http://www.ganymed.ethz.ch/ssh2/

Ganymed, along with the apache FTP client, you can also upload and download files.

There is also a built-in sample code for emulating a terminal in Ganymed.

Below is a link to a project that was implemented using Ganymed with the apache FTP client.

Github

Happy coding !!

0
source

All Articles