使用SFTP上传文件

时间:2015-11-25 05:17:45

标签: java tomcat sftp

我正在尝试通过以下代码将文件上传到我本地系统中的tomcat的webapps文件夹,我们还需要在使用此代码之前完成任何安装

public class DeployManager {

public static void main(String[] args) {

    String SFTPHOST = "1.2.3.4";
    int SFTPPORT = 22;
    String SFTPUSER = "username";
    String SFTPPASS = "password";
    String SFTPWORKINGDIR = "C:\\Program Files\\Apache Software Foundation\\Tomcat 8.0\\webapps\\";
    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        session.setPassword(SFTPPASS);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        channel = session.openChannel("sftp");
        channel.connect();
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd("..");
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File("C:\\Users\\Jainesh_Trivedi\\Desktop\\WAR\\AutohostDemo1_1145.war");
        channelSftp.put(new FileInputStream(f), f.getName());
    } catch (Exception ex) {
        ex.printStackTrace();

    }
}}

但我收到以下错误:

    com.jcraft.jsch.JSchException: java.net.ConnectException: Connection refused: connect
    at com.jcraft.jsch.Util.createSocket(Util.java:258)
    at com.jcraft.jsch.Session.connect(Session.java:186)
    at com.jcraft.jsch.Session.connect(Session.java:145)
    at com.autohost.java.DeployManager.main(DeployManager.java:30)
Caused by: java.net.ConnectException: Connection refused: connect
    at java.net.DualStackPlainSocketImpl.connect0(Native Method)
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at java.net.Socket.<init>(Unknown Source)
    at com.jcraft.jsch.Util.createSocket(Util.java:252)
    ... 3 more

1 个答案:

答案 0 :(得分:0)

您需要确保在机器上使用IP“10.74.64.102”运行sftp。我猜它是你的本地Windows机器。