首先pom.xml以下:windows
<dependency> <groupId>com.jcraft</groupId> <artifactId>jsch</artifactId> <version>0.1.54</version> </dependency>
Java代碼以下:服務器
public static void main(String[] args) throws JSchException, SftpException, IOException { ChannelSftp sftp = null; // 登陸 JSch jsch = new JSch(); Session session = jsch.getSession("duanjt", "127.0.0.1", 25); session.setPassword("admin"); Properties properties = new Properties(); // StrictHostKeyChecking // "若是設爲"yes",ssh將不會自動把計算機的密匙加入"$HOME/.ssh/known_hosts"文件, // 且一旦計算機的密匙發生了變化,就拒絕鏈接。 properties.put("StrictHostKeyChecking", "no"); session.setConfig(properties); session.connect(); Channel channel = session.openChannel("sftp"); channel.connect(); sftp = (ChannelSftp) channel; String file = "d:\\WifiTerminalInfoLog.gz"; sftp.mkdir("myduanjt");// 建立目錄,若是文件夾已存在會拋出異常,可經過異常處理的方式來判斷文件夾是否存在 sftp.cd("myduanjt");// 跳轉目錄 FileInputStream fis = new FileInputStream(file); sftp.put(fis, new File(file).getName());// 上傳文件。默認會覆蓋已有的文件 fis.close(); sftp.disconnect(); session.disconnect(); }
說明:session
1.這裏只是一個demo,沒有對異常這些作有效的處理ssh
2.SFTP不區分主動模式和被動模式spa
3.完畢以後記得關閉鏈接.net
4.服務端的sftp用的是freeSSHd軟件code
5.windows可經過FreeSSHd部署sftp服務,也可經過Serv-U部署ftp服務,FileZilla Server也可搭建ftp服務xml
Linux可經過vsftpd部署sftp服務,也可經過此軟件部署ftp服務(注意:列出的確定能夠,有的ftp服務器也能夠設置後支持sftp)blog
FreeSSHd配置SFTP服務參考:https://blog.csdn.net/flyingshuai/article/details/77935753?locationNum=5&fps=1部署