Executing a command using JSch

落爺英雄遲暮 提交于 2019-12-10 11:27:38

问题


I'm using JSch to automate remotely launching a python script from a background Java process.

Modifying the Shell.java example included in the JSch package, I've successfully installed JSch, connected to my Pi, and even commented out the user/domain/password/host key checking prompt boxes in favor of storing these values directly in my Java code.

After my java code logs into the remote Pi, I'd like it to send something like

sudo nohup python2 myFoo.py & disown

to the terminal.

In the Shell.java example I'm modifying, I see lines of code redirecting the input and output streams of the channel object to System.in and System.out but I'd like to simply manually inject that above line into the remote terminal and disconnect.

Why/my goal:
I have a small mesh network of Pi's running a script for most of the day. I'd like to eliminate downtime, but the code sometimes stops working after looping for 3-4 days straight, (sometimes as long as a week straight before the code bugs out and stops).
The script running on each node updates a mySQL database with a "last check in" field.
I'm hoping to write a small background program in Java that will run indefinitely on my server, checking the "last check in" for each station every now and then, and if it notices a node go down, remotely ssh into it and sudo reboot now, wait about 60-100 seconds, then sudo nohup python2 myFoo.py & disown


回答1:


You have picked a wrong example. The "shell" channel is for implementing an interactive shell session, not for automating a command execution.

Use the "exec" channel, see the Exec.java example.

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


来源:https://stackoverflow.com/questions/42195535/executing-a-command-using-jsch

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