Skip to content
Snippets Groups Projects
Commit 7e84feda authored by Jan Kožusznik's avatar Jan Kožusznik
Browse files

commit

parents
No related branches found
No related tags found
No related merge requests found
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>
/target/
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>java-scpclient</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>
eclipse.preferences.version=1
org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8
org.eclipse.jdt.core.compiler.compliance=1.8
org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.source=1.8
activeProfiles=
eclipse.preferences.version=1
resolveWorkspaceProjects=true
version=1
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cz.it4i.fiji</groupId>
<artifactId>java-scpclient</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.jcraft/jsch -->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.54</version>
</dependency>
</dependencies>
</project>
package cz.it4i.fiji.scpclient;
import com.jcraft.jsch.Identity;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.KeyPair;
class ByteIdentity implements Identity{
private KeyPair keyPair;
public ByteIdentity(JSch jsch,byte []prvKey) throws JSchException {
this.keyPair = KeyPair.load(jsch, prvKey, null);
}
@Override
public boolean setPassphrase(byte[] passphrase) throws JSchException {
return keyPair.decrypt(passphrase);
}
@Override
public byte[] getPublicKeyBlob() {
return keyPair.getPublicKeyBlob();
}
@Override
public byte[] getSignature(byte[] data) {
return keyPair.getSignature(data);
}
@Override
public boolean decrypt() {
return false;
}
@Override
public String getAlgName() {
return null;
}
@Override
public String getName() {
return keyPair.getPublicKeyComment();
}
@Override
public boolean isEncrypted() {
return keyPair.isEncrypted();
}
@Override
public void clear() {
keyPair.dispose();
keyPair = null;
}
}
package cz.it4i.fiji.scpclient;
import com.jcraft.jsch.Identity;
import com.jcraft.jsch.IdentityRepository;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.KeyPair;
class IdentityFile implements Identity{
private KeyPair kpair;
private String identity;
static IdentityFile newInstance(String prvfile, String pubfile, JSch jsch) throws JSchException{
KeyPair kpair = KeyPair.load(jsch, prvfile, pubfile);
return new IdentityFile(jsch, prvfile, kpair);
}
static IdentityFile newInstance(String name, byte[] prvkey, byte[] pubkey, JSch jsch) throws JSchException{
KeyPair kpair = KeyPair.load(jsch, prvkey, pubkey);
return new IdentityFile(jsch, name, kpair);
}
private IdentityFile(JSch jsch, String name, KeyPair kpair) throws JSchException{
this.identity = name;
this.kpair = kpair;
}
/**
* Decrypts this identity with the specified pass-phrase.
* @param passphrase the pass-phrase for this identity.
* @return <tt>true</tt> if the decryption is succeeded
* or this identity is not cyphered.
*/
public boolean setPassphrase(byte[] passphrase) throws JSchException{
return kpair.decrypt(passphrase);
}
/**
* Returns the public-key blob.
* @return the public-key blob
*/
public byte[] getPublicKeyBlob(){
return kpair.getPublicKeyBlob();
}
/**
* Signs on data with this identity, and returns the result.
* @param data data to be signed
* @return the signature
*/
public byte[] getSignature(byte[] data){
return kpair.getSignature(data);
}
/**
* @deprecated This method should not be invoked.
* @see #setPassphrase(byte[] passphrase)
*/
public boolean decrypt(){
throw new RuntimeException("not implemented");
}
/**
* Returns the name of the key algorithm.
* @return "ssh-rsa" or "ssh-dss"
*/
public String getAlgName(){
return new String("ssh-rsa");
}
/**
* Returns the name of this identity.
* It will be useful to identify this object in the {@link IdentityRepository}.
*/
public String getName(){
return identity;
}
/**
* Returns <tt>true</tt> if this identity is cyphered.
* @return <tt>true</tt> if this identity is cyphered.
*/
public boolean isEncrypted(){
return kpair.isEncrypted();
}
/**
* Disposes internally allocated data, like byte array for the private key.
*/
public void clear(){
kpair.dispose();
kpair = null;
}
/**
* Returns an instance of {@link KeyPair} used in this {@link Identity}.
* @return an instance of {@link KeyPair} used in this {@link Identity}.
*/
public KeyPair getKeyPair(){
return kpair;
}
}
package cz.it4i.fiji.scpclient;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.Identity;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
public class ScpClient {
public static void main(String[] args) throws JSchException, IOException {
boolean u = new ScpClient("salomon.it4i.cz", "koz01", "/home/koz01/.ssh/it4i_rsa", "nejlepsivyzkum")
.upload(Paths.get("/home/koz01/aaa/vecmath.jar"), "/home/koz01/");
boolean d = new ScpClient("salomon.it4i.cz", "koz01", "/home/koz01/.ssh/it4i_rsa", "nejlepsivyzkum")
.download("/home/koz01/proof", Paths.get("/home/koz01/aaa/proof"));
System.out.println(u);
System.out.println(d);
}
private String hostName;
private String username;
private JSch jsch = new JSch();
public ScpClient(String hostName, String username, Identity privateKeyFile) throws JSchException {
super();
init(hostName, username, privateKeyFile);
}
public ScpClient(String hostName, String userName, String keyFile, String pass) throws JSchException {
Identity id = IdentityFile.newInstance(keyFile, null, jsch);
try {
id.setPassphrase(pass.getBytes("UTF-8"));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
init(hostName, userName, id);
}
private void init(String hostName, String username, Identity privateKeyFile) throws JSchException {
this.hostName = hostName;
this.username = username;
jsch.addIdentity(privateKeyFile, null);
}
public boolean download(String lfile, Path rfile) throws JSchException, IOException {
Session session = connectionSession();
try {
// exec 'scp -f rfile' remotely
String command = "scp -f " + lfile;
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
// get I/O streams for remote scp
try (OutputStream out = channel.getOutputStream(); InputStream in = channel.getInputStream()) {
channel.connect();
byte[] buf = new byte[1024];
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
while (true) {
int c = checkAck(in);
if (c != 'C') {
break;
}
// read '0644 '
in.read(buf, 0, 5);
long filesize = 0L;
while (true) {
if (in.read(buf, 0, 1) < 0) {
// error
break;
}
if (buf[0] == ' ')
break;
filesize = filesize * 10L + (long) (buf[0] - '0');
}
@SuppressWarnings("unused")
String file = null;
for (int i = 0;; i++) {
in.read(buf, i, 1);
if (buf[i] == (byte) 0x0a) {
file = new String(buf, 0, i);
break;
}
}
// System.out.println("filesize="+filesize+", file="+file);
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
// read a content of lfile
try (OutputStream fos = Files.newOutputStream(rfile)) {
int foo;
while (true) {
if (buf.length < filesize)
foo = buf.length;
else
foo = (int) filesize;
foo = in.read(buf, 0, foo);
if (foo < 0) {
// error
break;
}
fos.write(buf, 0, foo);
filesize -= foo;
if (filesize == 0L)
break;
}
}
if (checkAck(in) != 0) {
return false;
}
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
}
}
} finally {
session.disconnect();
}
return true;
}
public boolean upload(Path file, String rfile) throws JSchException, IOException {
Session session = connectionSession();
boolean ptimestamp = true;
// exec 'scp -t rfile' remotely
String command = "scp " + (ptimestamp ? "-p" : "") + " -t " + rfile;
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
try {
// get I/O streams for remote scp
try (OutputStream out = channel.getOutputStream(); InputStream in = channel.getInputStream()) {
channel.connect();
if (checkAck(in) != 0) {
return false;
}
if (ptimestamp) {
command = "T " + (file.toFile().lastModified() / 1000) + " 0";
// The access time should be sent here,
// but it is not accessible with JavaAPI ;-<
command += (" " + (file.toFile().lastModified() / 1000) + " 0\n");
out.write(command.getBytes());
out.flush();
if (checkAck(in) != 0) {
return false;
}
}
// send "C0644 filesize filename", where filename should not include '/'
long filesize = file.toFile().length();
command = "C0644 " + filesize + " ";
command += file.getFileName().toString();
command += "\n";
out.write(command.getBytes());
out.flush();
if (checkAck(in) != 0) {
return false;
}
byte[] buf = new byte[1024];
// send a content of lfile
try (InputStream fis = Files.newInputStream(file)) {
while (true) {
int len = fis.read(buf, 0, buf.length);
if (len <= 0)
break;
out.write(buf, 0, len); // out.flush();
}
}
// send '\0'
buf[0] = 0;
out.write(buf, 0, 1);
out.flush();
if (checkAck(in) != 0) {
return false;
}
out.close();
}
} finally {
channel.disconnect();
session.disconnect();
}
return true;
}
private Session connectionSession() throws JSchException {
Session session = jsch.getSession(username, hostName);
UserInfo ui = new P_UserInfo();
session.setUserInfo(ui);
session.connect();
return session;
}
private class P_UserInfo implements UserInfo {
@Override
public String getPassphrase() {
return null;
}
@Override
public String getPassword() {
return null;
}
@Override
public boolean promptPassword(String message) {
return false;
}
@Override
public boolean promptPassphrase(String message) {
return false;
}
@Override
public boolean promptYesNo(String message) {
return true;
}
@Override
public void showMessage(String message) {
}
}
static int checkAck(InputStream in) throws IOException {
int b = in.read();
// b may be 0 for success,
// 1 for error,
// 2 for fatal error,
// -1
if (b == 0)
return b;
if (b == -1)
return b;
if (b == 1 || b == 2) {
StringBuffer sb = new StringBuffer();
int c;
do {
c = in.read();
sb.append((char) c);
} while (c != '\n');
if (b == 1) { // error
System.out.print(sb.toString());
}
if (b == 2) { // fatal error
System.out.print(sb.toString());
}
}
return b;
}
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment