web-dev-qa-db-ja.com

JSchを使用して、lsを実行せずにリモートファイルが存在するかどうかを確認する方法はありますか?

JSchを使用して、lsを実行せずにリモートファイルが存在するかどうかを確認し、ファイルをループして名前の一致を見つける方法はありますか?

ありがとう

13
cagcowboy

(これは、ライブラリのSFTP部分を使用している場合、私がそれについて考えずに行った仮定です。)

そのls(String path)はファイル名を受け入れると思いました。現時点では確認できません。

そうでない場合は、手動で繰り返す必要はありません。セレクターバリアントを使用できます。

ls(String path, ChannelSftp.LsEntrySelector selector)
3
Dave Newton

これは私が JSch でディレクトリの存在をチェックする方法です。

注:この質問とは関係ありませんが、役に立つと思う人もいます。

Dirが存在しない場合はディレクトリを作成します

ChannelSftp channelSftp = (ChannelSftp)channel;
String currentDirectory=channelSftp.pwd();
String dir="abc";
SftpATTRS attrs=null;
try {
    attrs = channelSftp.stat(currentDirectory+"/"+dir);
} catch (Exception e) {
    System.out.println(currentDirectory+"/"+dir+" not found");
}

if (attrs != null) {
    System.out.println("Directory exists IsDir="+attrs.isDir());
} else {
    System.out.println("Creating dir "+dir);
    channelSftp.mkdir(dir);
}
14
AabinGunz

次のようなこともできます。

try {
    channelSftp.lstat(name);
} catch (SftpException e){
    if(e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE){
    // file doesn't exist
    } else {
    // something else went wrong
        throw e;
    }
}

存在しないものに対してlstatを実行すると、IDが2のSftpExecptionが取得されます。それ以外の場合は、ファイルに関する情報が取得されます。

11
zelinka

実際、私のプロジェクトではlsはループなしで動作しています。ファイル名を指定してls呼び出しパスに渡すだけです。

private static boolean exists(ChannelSftp channelSftp, String path) {
    Vector res = null;
    try {
        res = channelSftp.ls(path);
    } catch (SftpException e) {
        if (e.id == SSH_FX_NO_SUCH_FILE) {
            return false;
        }
        log.error("Unexpected exception during ls files on sftp: [{}:{}]", e.id, e.getMessage());
    }
    return res != null && !res.isEmpty();
}

たとえば、URLがfile.txtのファイルsftp://[email protected]/path/to/some/random/folder/file.txtがあります。関数existspath/path/to/some/random/folder/file.txtとして渡します

6
import Java.util.ArrayList;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class FileExists {

ChannelExec channelExec = null;
static Channel channel = null;

static String Host = "hostname";
static String user = "username";
static String password = "password$";

public static void main(String[] args) {
    String filename = "abc.txt";
    String filepath = "/home/toolinst/ggourav";
    try {
        Channel channel = getChannelSftp(Host, user, password);
        channel.connect();
        ChannelSftp channelSftp = (ChannelSftp) channel;
        channelSftp.cd(filepath);
        String path = channelSftp.ls(filename).toString();
        if (!path.contains(filename)) {
            System.out.println("File doesn't exist.");
        } else
            System.out.println("File already exist.");

    } catch (Exception e) {
        e.printStackTrace();
    }

}

private static Channel getChannelSftp(String Host, String user, String password) {
    try {
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, Host, 22);
        Java.util.Properties config = new Java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        config.put("PreferredAuthentications", "publickey,keyboard-interactive,password");
        session.setConfig(config);
        session.setPassword(password);
        session.connect();
        channel = session.openChannel("sftp");

    } catch (Exception e) {
        System.out.println("Failed to get sftp channel. " + e);
    }
    return channel;
}

}

1
Gourav Goutam

あなたはによってチェックすることができます

 if [ -e FILE_NAME ] ; then
    //do something
 fi

または

  if [ -d DIRNAME ]

ディレクトリ用

または

    if [ -l SYMLINK ]

ソフトリンク用

これがお役に立てば幸いです


リモートマシンでコマンドを実行する例を次に示します http://www.jcraft.com/jsch/examples/Exec.Java.html

lsを実行するか、スクリプト全体を渡すことができます。スクリプトをリモートマシンにコピーして実行するのと同じです。

1
Nishant

以前の回答で-1を見ました。あなたが理解するのが明確でなかったことを願っています。以下は、同じ機能のコード全体です。また、これに関するその他の情報が必要な場合はお知らせください。

import Java.util.ArrayList;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class FileExists {

ChannelExec channelExec = null;
static Channel channel = null;

static String Host = "hostname";
static String user = "username";
static String password = "password$";

public static void main(String[] args) {
    String filename = "abc.txt";
    String filepath = "/home/toolinst/ggourav";
    try {
        Channel channel = getChannelSftp(Host, user, password);
        channel.connect();
        ChannelSftp channelSftp = (ChannelSftp) channel;
        channelSftp.cd(filepath);
        String path = channelSftp.ls(filename).toString();
        if (!path.contains(filename)) {
            System.out.println("File doesn't exist.");
        } else
            System.out.println("File already exist.");

    } catch (Exception e) {
        e.printStackTrace();
    }

}

private static Channel getChannelSftp(String Host, String user, String password) {
    try {
        JSch jsch = new JSch();
        Session session = jsch.getSession(user, Host, 22);
        Java.util.Properties config = new Java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        config.put("PreferredAuthentications", "publickey,keyboard-interactive,password");
        session.setConfig(config);
        session.setPassword(password);
        session.connect();
        channel = session.openChannel("sftp");

    } catch (Exception e) {
        System.out.println("Failed to get sftp channel. " + e);
    }
    return channel;
}

}

0
Gourav Goutam