私はJavaから一連のunixコマンドを実行しようとしています。基本的には、私がパテより何をしても、私はJavaプログラムでやりたいと思っています。javaを使用して複数のunixコマンドを実行する| Jcraft - Jsch
私は2つのクラスを書いています。
- サーバに接続し、Unixコマンドを実行します。
- unixコマンドをClass1にリストで送信します。
Class2のリストに1つの値しかない場合は、サーバーに接続して実行できます。ただし、リストに複数の値がある場合、コードは最新のコマンド(リストの値)のみを実行し、他のすべての値をスキップします。
Class2のリストにある各値(unixコマンド)を実行します。助けてください。 JCraftのJSchクラスを使用しています。クラス2で
Class1の
package package1;
import java.io.InputStream;
import java.util.List;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class ConnExec
{
static InputStream in;
static byte[] tmp;
static int flag = 0;
public void connExec(List<String> commandLst)
{
String host="serverName.host.dev";
String user="UserName";
String password="PWD";
try
{
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected to the server.....\n");
Channel channel=session.openChannel("exec");
channel.setInputStream(null);
for (int x = 0; x < commandLst.size();x++)
{
((ChannelExec)channel).setCommand(commandLst.get(x));
in=channel.getInputStream();
channel.connect();
tmp=new byte[1024];
while(true)
{
while(in.available()>0)
{
int i=in.read(tmp, 0, 1024);
if(i<0)break;
System.out.print(new String(tmp, 0, i));
System.out.println("\nExecuted.....");
}
if(channel.isClosed())
{
break;
}
}
}
channel.disconnect();
session.disconnect();
System.out.println("Terminated.....\n");
flag = 1;
}
catch(Exception e)
{
e.printStackTrace();
flag = 1;
}
}
}
クラス2
package package1;
import java.util.ArrayList;
import java.util.List;
public class ReadCommands
{
public static void main(String a[])
{
List<String> lst = new ArrayList<String>();
String command1="ls /local/dev/source/folder";
String command2="ls /local/dev/source/folder/inbound";
lst.add(command1);
lst.add(command2);
ConnExec ce = new ConnExec();
ce.connExec(lst);
}
}
[JSCHシェルを介して複数のコマンド]の可能な重複(http://stackoverflow.com/questions/5831594/multiple-commands-through-jsch-shell) –
( http://stackoverflow.com/a/5843935/850848)では、各コマンドを独自の「exec」チャネルで実行する必要があります。ですから、 'Channel channel = session.openChannel(" exec "); channel.setInputStream(null); 'と' channel.disconnect(); 'を' for'ループに追加します。 –
@MartinPrikryl Tried - 動作しませんでした。 –