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
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