0

ssh を介して UNIX サーバーに接続し、「ls」コマンドを実行してその出力を取得しようとしました。コードはこんな感じ

SessionChannelClient session = client.openSessionChannel();
       session.startShell();
       String cmd = "ls -l";
       session.executeCommand(cmd);           
       ChannelInputStream in = session.getInputStream();
       ChannelOutputStream out = session.getOutputStream();
       IOStreamConnector input = new IOStreamConnector(System.in, session.getOutputStream());
       IOStreamConnector output = new IOStreamConnector(session.getInputStream(), System.out);

実行後、ログファイルに出力がありませんでした。私が見つけたのは、示されているようにチャネル要求が失敗していることです

1019 [main] 情報 com.sshtools.j2ssh.connection.ConnectionProtocol - チャネル要求が成功しました 1020 [main] 情報 com.sshtools.j2ssh.session.SessionChannelClient - コマンド実行を要求しています- コマンドは ls -l 1021 [main] INFO com.sshtools.j2ssh.connection.ConnectionProtocol - セッション チャネル 1021 の実行要求を送信中 [main] INFO com.sshtools.j2ssh.transport.TransportProtocolCommon - SSH_MSG_CHANNEL_REQUEST 1021 [main] INFO を送信中com.sshtools.j2ssh.connection.ConnectionProtocol - チャネル要求応答 1032 を待機中 [トランスポート プロトコル 1] 情報 com.sshtools.j2ssh.transport.TransportProtocolCommon - 受信 SSH_MSG_CHANNEL_EXTENDED_DATA 1033 [ssh-接続 1] com.sshtools.j2ssh.transport をデバッグします。サービス - ルーティング SSH_MSG_CHANNEL_EXTENDED_DATA 1033 [ssh-connection 1] DEBUG com.sshtools.j2ssh.transport.Service - 処理終了 SSH_MSG_CHANNEL_EXTENDED_DATA 1075 [トランスポートプロトコル 1] INFO com.sshtools.j2ssh.transport.TransportProtocolCommon - 受信 SSH_MSG_CHANNEL 7 [main] com 10_FAIL5 .sshtools.j2ssh.connection.ConnectionProtocol - チャネル要求が失敗しました

なぜこうなった ?

4

1 に答える 1

2

startShell または を使用できますexecuteCommandが、両方を使用することはできません。

executeCommand選択した特定のシェル (/bin/bash など) を呼び出すことのみを目的としています。ほとんどの場合startShell、デフォルトのシェルを起動するために使用できます。

指定したコマンドを実行するために必要なのはこれだけです。

final String cmd = "ls -l" + '\n';       
session.startShell();
session.getOutputStream().write(cmd.getBytes());

または、代わりに executeCommand を使用します。

final String cmd = "ls -l";    
session.executeCommand(String.format("sh -c \"%s\"", cmd));

InputStream同じ方法でstdout と stderr に接続して、コマンドの結果を確認できます。SessionChannelClientさらに、は 1 つのコマンドしか処理できないことに注意してください。2 番目のコマンドを送信するには、別のインスタンスを作成する必要があります。

J2SSH ドキュメントをダウンロードすることをお勧めします。内部には、API の基本操作を説明するj2ssh-getting-started.htmがあります。

于 2013-01-26T01:44:56.500 に答える