SSH login+SFTP using java and execute command

Dear All
I needed to automate the login to a ssh client and execute some commands after hours of googling and trying couples of API and free tools i conclude that the best tool for me is j2ssh is
http://sourceforge.net/projects/sshtools

Here is snapshot of how you can login and fire some commands

ConfigurationLoader.initialize(false);

SshClient ssh = new SshClient();

ssh.setSocketTimeout(30000);

SshConnectionProperties properties = new SshConnectionProperties();

properties.setHost(this.server);

properties.setPrefPublicKey(”ssh-rsa”);

// Connect to the host

ssh.connect(properties);

// Create a password authentication instance

PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();

// Get the users name

pwd.setUsername(this.user); // Get the password

pwd.setPassword(this.password);

// Try the authentication

int result = ssh.authenticate(pwd);

// Evaluate the result

this.field.setText(”firing command”);

SessionChannelClient session = ssh.openSessionChannel();

session.requestPseudoTerminal(”vt100″, 80, 24, 0, 0, “”);

if (session.startShell()) {

ByteArrayInputStream ins1 = new ByteArrayInputStream(”cd reports;cd CAResults;unzip -o ToUpload.zip\r”.getBytes());

//ByteArrayInputStream ins2=new ByteArrayInputStream(”cd reports\r”.getBytes());

// ByteArrayInputStream ins3=new ByteArrayInputStream(”cd reports\r”.getBytes());

IOStreamConnector input = new IOStreamConnector();

IOStreamConnector output = new IOStreamConnector();

IOStreamConnector error = new IOStreamConnector();

output.setCloseOutput(false);

input.setCloseInput(false);

error.setCloseOutput(false);

input.connect(ins1, session.getOutputStream());

output.connect(session.getInputStream(), System.out);

error.connect(session.getStderrInputStream(), System.out);

// session.getState().waitForState(ChannelState.CHANNEL_CLOSED);

Thread.sleep(30000);

this.field.setText(”Over and out from USA”);

session.close();

Here is how you can do SFTP

ConfigurationLoader.initialize(false);

this.clientS = new SshClient();

clientS.connect(this.server);

PasswordAuthenticationClient pwd = new PasswordAuthenticationClient();

pwd.setUsername(this.user);

pwd.setPassword(this.password);

int result = clientS.authenticate(pwd);

this.client = clientS.openSftpClient();

this.client.cd(this.workingdir);

this.field.setText(this.client.pwd());

this.client.put(local.toString());

Leave a Reply

Security Code: