java - 为什么通过 shell 通道运行多个命令不能一致且按顺序运行?(JSch)
问题描述
我正在使用 Jsch 在远程服务器上运行 shell 脚本,我设法取得了进展(感谢您在这里回答了一个问题),但我的代码仍然有几个问题。
- 它不会按顺序运行命令,并且使用 printscreen.println() 方法始终如一地给出。
- 我的程序在带有一些断点的调试模式下很好地执行 shell 命令,但在运行模式或没有调试点的情况下不执行命令。
ps.println() 方法中的 runScript 方法中的命令不会始终按顺序运行。printResilt() 方法也无法在运行模式下打印(执行)命令。
public void runScript(Channel channel) throws Exception {
// Gets an InputStream for this channel. All data arriving in as messages from the remote side can be read from this stream.
try {
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops, true);
channel.setOutputStream(System.out, true);
// Execute the command
channel.connect();
InputStream in = channel.getInputStream();
ps.println("sudo su - sudouser");
ps.println("ksh -x \"/path/to/script/shellscript.sh\" arg1 arg2 arg3 arg4 arg5 arg6 arg7");
ps.println("exit");
ps.close();
printResult(in, channel);
}
catch(IOException ioExp) {
ioExp.printStackTrace();
}
//retrieve the exit status of the remote command corresponding to this channel
//int exitStatus = channelExec.getExitStatus();
//Safely disconnect channel and disconnect session. If not done then it may cause resource leak
channel.disconnect();
session.disconnect();
}
/**
* @param input
* @param channel
*/
private static void printResult(InputStream in,
Channel channel) throws Exception
{
int SIZE = 1024;
byte[] tmp = new byte[SIZE];
while (true) {
try {
Thread.sleep(1000);
} catch (Exception ee) {}
while (in.available() > 0) {
int i = in.read(tmp, 0, 1024);
if (i < 0)
break;
System.out.print(new String(tmp, 0, i));
}
if (channel.isClosed()) {
if(in.available() > 0) {
int i = in.read(tmp, 0, 1024);
System.out.print(new String(tmp, 0, i));
}
System.out.println("exit-status: " + channel.getExitStatus());
break;
}
}
}
主要方法:
public class App
{
public static void main( String[] args ) throws Exception
{
try
{
SFTPUploader sftpUploader = new SFTPUploader();
ChannelSftp sftpChannel = sftpUploader.connectServer();
//close sftp channel after upload
sftpUploader.closeChannel(sftpChannel);
//open executable channel
Channel channel = sftpUploader.openChannel("shell");
//execute shell script
sftpUploader.runScript(channel);
}
catch(SftpException e) {
e.printStackTrace();
}
catch(JSchException jschExp) {
jschExp.printStackTrace();
}
}
}
解决方案
推荐阅读
- gmail-api - 使用 gmail 插件将电子邮件地址列入白名单
- javascript - 防止用户使用 JS/jQuery 在输入中键入多个字符
- ios - Branch.IO showShareSheet 不生成 ShortUrl
- python - 为大量数据集训练神经网络
- mysql - Mysql 计数和连接
- git - Cherry-pick 合并提交因空提交而失败
- c# - 字典中的正则表达式或通配符。TryGetValue
- struts2 - Struts2 迭代器标签
- sql-server - 如何在 MS Azure SQL 中每天在特定时间自动执行存储过程?
- solr - 分片之间的 IDF 相似性无法按预期工作,仅使用本地分片信息