0

我希望使用 Java 访问远程服务器,访问文件并更新我的文件,或者更新服务器上的文件。

有没有一种简单的方法可以使用用户名@主机和密码访问远程服务器,这将允许我上传和下载文件?

谢谢

4

3 回答 3

0

您可以使用JSch通过 ssh 远程访问文件。

于 2012-09-05T16:07:44.803 回答
0

使用合适的工具来完成工作:rsync

于 2012-09-05T16:08:39.043 回答
0

如果您想在打开 ssh 连接的同时连接到机器,要运行 OS 命令,您可以使用 trilead。这是将打开连接的方法的示例。

    public static Connection newConnectionNoPassword(String host, String username, File privateKey) {
    Connection newConn = new Connection(host);
    try {
        newConn.connect(); // Ignoring ConnectionInfo returned value.
        //If the authentication was successful the authenticated connection will be returend
        if ( newConn.authenticateWithPublicKey(username, privateKey, null)){
            return newConn;
        }else{
            newConn.close();
            return null;
        }
    } catch (IOException ioe) {
        newConn.close();
        ioe.printStackTrace();
        return null;
    }
}

如果您使用 maven,您可以通过将以下依赖项添加到您的 pom.xml 来获取它:

    <dependency>
        <groupId>com.trilead</groupId>
        <artifactId>trilead-ssh2</artifactId>
        <version>build213-svnkit-1.3-patch</version>
    </dependency>

为了从服务器上传\下载文件,您可以使用 trilead SCPClient。以下是从远程服务器下载文件到本地文件夹的示例:

    public void downloadFiles(String[] remoteFiles, String localDir) throws IllegalArgumentException, IOException {
    checkNotEmpty(localDir);
    checkNotEmpty(remoteFiles);

    File dir = new File(localDir);
    if (!dir.exists() || !dir.mkdirs()) {
        throw new IOException("Failed to create local directory : " + localDir);
    }

    SCPClient scp = new SCPClient(this.conn);
    try {
        scp.get(remoteFiles, localDir);
    } catch (IOException e) {
        throw new IOException("Failed to copy remote files to local folder", e);
    }
}

希望能帮助到你..

于 2012-09-11T07:41:21.133 回答