我的问题:我希望通过使用java程序将运行时参数传递给脚本来连接到UNIX服务器并运行脚本。 我需要连接到UNIX服务器并通过将运行时参数传递给脚本来运行脚本。我使用下面的代码连接到Unix服务器,并且我成功连接到服务器。脚本具有通用grep命令,带有小逻辑,它具有所有权限。当我运行java代码时,我能够看到输出文本文件但文件中有nodata,但是当我从shell提示符手动运行脚本时,我得到了正确的输出。 请帮我解决这个问题,如果有更好的选择可以满足这个要求,请告诉我。
Java代码:
import com.jscape.inet.ssh.*;
import com.jscape.inet.ssh.util.SshParameters;
import java.io.*;
public class Sshexamplelalit implements SshListener {
// state of SSH connection
private boolean connected = false;
public Sshexamplelalit() {
Ssh ssh = null;
try {
// create new Ssh instance
SshParameters params = new SshParameters("sacsun","mwctrl","m33tz0n3");
System.out.print("sacsun Unix server is connected \n");
ssh = new Ssh(params);
// register to capture events
ssh.addSshListener(this);
System.out.println("sacsun Connecting please wait...\n");
SshScript script = new SshScript(ssh);
SshTask task = new SshTask(">","./SACSUN.sh '07Gretchen01965'",">");
//07Gretchen01965
// connect
script.addTask(task);
ssh.connect();
while(!script.isComplete()) {
System.out.println("Waiting");
Thread.sleep(30000);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(connected) {
ssh.disconnect();
}
} catch(Exception e) {
}
}
}
/**
* Captures SshConnectedEvent
*/
public void connected(SshConnectedEvent ev) {
System.out.println("Connected: " + ev.getHost()+"\n");
connected = true;
System.out.println("Connected to server "+ ev.getHost()+"\n");
}
/**
* Captures SshDataReceivedEvent
*/
public void dataReceived(SshDataReceivedEvent ev) {
ev.getData();
}
/**
* Captures SshDisconnectedEvent
*/
public void disconnected(SshDisconnectedEvent ev) {
System.out.println("Wait server is Disconnecting: " + ev.getHost()+"\n");
connected = false;
}
/*
* Main method for SshExample
*/
public static void main(String[] args) {
Sshexamplelalit test = new Sshexamplelalit();
}
}
脚本:
#!/bin/sh
HOME_DIR=/usr/ftadapters/logs/adapters/rivaadp
HOME_DIR_ARCH=$HOME_DIR/archive
cd $HOME_DIR
rm RivaAdp.txt
rm BrokerLog.txt
rm Result.txt
rm ArchRivaAdp.txt
echo $1 > out.txt
grep -i $1 *.log > RivaAdp.txt
cd $HOME_DIR_ARCH
grep -i $1 *.log > ArchRivaAdp.txt
echo $1 > out.txt
mv ArchRivaAdp.txt ../
cd ..
grep -i 'publishMessage' RivaAdp.txt > BrokerLog.txt
grep -i 'publishMessage' ArchRivaAdp.txt >> BrokerLog.txt
cnt=`cat BrokerLog.txt | wc -l`
echo $cnt
if [ $cnt -gt 0 ]
then
echo "Notifications Received in the Broker Logs" > Result.txt
else
echo "No Data Found in Broker Logs" > Result.txt
fi
答案 0 :(得分:1)
我想你想做一个SshSession:
http://files.jscape.com/sshfactory/docs/javadoc/com/jscape/inet/ssh/SshSession.html
正在发生的是您正在使用的SshScript正在调用脚本,但是isComplete方法没有按照您的预期执行 - 脚本不会将任何状态回传给您的任务。换句话说,您正在远程登录,将脚本作为批处理作业调用,并且isComplete立即返回true,因此具有超时的while循环根本不执行任何操作。
SshTask文档解释了这一点: http://files.jscape.com/sshfactory/docs/javadoc/com/jscape/inet/ssh/SshTask.html
“SshTask类表示在SSH服务器上以批处理(非交互)模式执行的命令”
我发现通常情况下,如果您正在调用某个命令并且需要等待某种类型的睡眠,那么这是一个警告信号表明该设计不正确。
ETA:更多地阅读SshTask上的文档,我认为您还可以为任务设置结束提示,以便Java应用程序可以判断脚本何时完成。