Java library to run multiple unrelated commands on a remote server via ssh

坚强是说给别人听的谎言 提交于 2019-11-28 09:54:55

问题


My Java application has to work like this:

  1. User select bash commands in GUI and press "send."
  2. Application return distinct and independent answers for each command (e.g. we could store them in different files).
  3. Commands each run interactively, not in a batch (it can't be something like "ls\n pwd \n" etc)
  4. After each command, the application will check if the results are ok. If so, it will send the next command.
  5. We need to execute su <user> on the remote host.

This will be a plugin for a bigger app, so answers like "try something else" (i.e. RPC, web services) will not help me :(

As far as i understand i have to use SHELL or at least keep channel connected.

I have tested jsch , sshj and ethz.ssh2 but with bad results.

I've dug throu stackoverflow answers for questions like: "sending-commands-to-server-via-jsch-shell-channel" etc. But they all focus on sending whole commands in one line. I need an interactive, persistent SSH session.

I've used ExpectJ (with a little hack of output stream). It has resolved points 1,3,4,5.

But there is a problem with point 2. In my app I need to get separated answer. But we will not know their length. Command prompts can be different. Anyone knows how to "hack" ExpectJ so it will be some how more synchronized? I am looking for acting like this : send , wait for full answer, send, wait... I've tried some basic synchronization tricks but this end in timeouts and connection lost usually.


回答1:


You should use ExpectJ, a Java implementation of the Unix expect utility.




回答2:


not sure if you still have the problems, in any case, it might contribute to other people.

ExpectJ is indeed the Java implementation of Unix expect. and you should definitely buy the "explore expect book" then look into it, it is worth it.

For your question: when you spawn a process, you listen to the return output, match it to a prompt, then send some command. if you want to analyze the output, you buffer that output, and do some actions before the next send()

to do so, you need to use the interact() method of the spawn class you used. http://expectj.sourceforge.net/apidocs/index.html

and for interact and how it works: http://oreilly.com/catalog/expect/chapter/ch03.html look for this part: "The interact Command"



来源:https://stackoverflow.com/questions/12690248/java-library-to-run-multiple-unrelated-commands-on-a-remote-server-via-ssh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!