Hello Cem,

when using jsch, there is no reason to use screen.
You can just create as many parallel channels, as
you like.

Exec.java from jsch examples contains all the helpful hints.

I assembled a JUnit test and a simple UserInfo which provides
either password, or keyfile/passphrase and does not insist on
knownHost checks.
In other words: NOT FOR PRODUCTION USE (especially the
known hosts check can be added easily, if you have an openssh
client around to seed the known hosts file).

Put the files in package test, add nlog4j (combines slf4j and
log4j) and jsch.jar, change user, host and password
(or use the other constructor of SSHUserInfo) and run the JUnit test.

The test method needs a refactoring and the SSHUserInfo should be
named SshUserInfo, but you get the picture.

Hope this helps,

Heiner

[email protected] wrote:
> hello,
> 
> i am a newbie in linux and hope the question makes sense...
> 
> 
> i want to execute a linux command from a java class in order to automate
>  a process that i make in putty...
> 
> what i make on shell is 
> 
> 1. screen -R Test (creating a new screen)
> 2. then changing directory (cd myDir)
> 3. and there executing  a command  (do xxxxx)
> 
> is there anyway to achieve this by JSch ??
> 
> any idea appreciated
> regards cem
> 
> 
> 
> 
> 
> 
> 
>       
> 
> ------------------------------------------------------------------------------
> This SF.net email is sponsored by:
> SourcForge Community
> SourceForge wants to tell your story.
> http://p.sf.net/sfu/sf-spreadtheword
> _______________________________________________
> JSch-users mailing list
> [email protected]
> https://lists.sourceforge.net/lists/listinfo/jsch-users
> 

-- 
Heiner Westphal
Peter-Michely Str. 18
D-66117 Saarbrücken

Mail : [email protected]
Tel. : +49-(0)681-5006118
Mobil: +49-(0)177-5752640
package test;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import junit.framework.TestCase;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;


/**
 * Simple test to verify semicolon separated commands work with Jsch 
ExecChannel.
 *
 * @author [email protected]
 */
public class TestJschExec extends TestCase {

    private static final Logger LOG = LoggerFactory.getLogger(TestJschExec.class
            .getName());

    static final int DEFAULT_BUFFER_SIZE = 4096;
    static final long TIMEOUT = 5000L;
    static final long POLL_TIMEOUT = 1000L;

    /**
     * Verify, if a jsch exec channel can handle two commands at once.
     * @throws Exception let JUnit handle these.
     */
    public void testTwoCommands() throws Exception {
        JSch jsch = new JSch();
        Session session=jsch.getSession("user", "myhost.example.com", 22);
        UserInfo userInfo = new SSHUserInfo("toSecretToBeTrue");
        session.setUserInfo(userInfo);
        session.connect();
        ChannelExec channel = (ChannelExec) session.openChannel("exec");

        String command = "cd /var/tmp; pwd";
        channel.setCommand(command);

        channel.setInputStream(null); // < /dev/null
        channel.setErrStream(System.err); // forward stderr to JVM's
        InputStream is = channel.getInputStream(); // capture stdout
        channel.connect(); // connect and execute command

        // read command output
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int exitStatus = 0;
        final long endTime = System.currentTimeMillis() + TIMEOUT;
        while (System.currentTimeMillis() < endTime) {
            while (is.available() > 0) {
                int count = is.read(buffer, 0, DEFAULT_BUFFER_SIZE);
                if (count >= 0) {
                    bos.write(buffer, 0, count);
                } else {
                    break;
                }
            }
            if (channel.isClosed()) {
                exitStatus = channel.getExitStatus();
                break;
            }
            try {
                Thread.sleep(POLL_TIMEOUT);
            } catch (InterruptedException e) {
                LOG.debug("Ignoring interrupt.");
            }
        }
        assertEquals(0, exitStatus);
        channel.disconnect();
        assertEquals("/var/tmp\n", bos.toString());
    }

}
package test;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcraft.jsch.UserInfo;

/**
 * User info for silent operation.
 * That is no password/passphrase prompt possible.
 *
 * @author [email protected]
 */
public final class SSHUserInfo implements UserInfo {

    /** Our log. */
    private static final Logger LOG = LoggerFactory.getLogger(SSHUserInfo.class
            .getName());

    /** The password. */
    private final String password;
    /** True, if the password or pass phrase has been retrieved at least once. 
*/
    private boolean secretDelivered = false;
    /** The keyFile. */
    private final String keyFile;
    /** True, if the pass phrase has been retrieved at least once. */
    private final String passphrase;

    /**
     * Create UserInfo for password authentication.
     *
     * @param password Password of the remote user.
     */
    public SSHUserInfo(final String password) {

        super();
        LOG.debug("SSHUserInfo(********)");
        this.password = password;
        this.keyFile = null;
        this.passphrase = null;
    }

    /**
     * Create UserInfo for public key/passphrase authentication.
     *
     * @param keyFileName File containing the (one of the) users's private key.
     * @param passphrase Passphrase securing the keyfile.
     */
    public SSHUserInfo(final String keyFileName, final String passphrase) {

        super();
        LOG.debug("SSHUserInfo(" + keyFileName + ", ********)");
        this.password = null;
        this.keyFile = keyFileName;
        this.passphrase = passphrase;
    }

    /**
     * {...@inheritdoc}
     *
     * @see com.jcraft.jsch.UserInfo#getPassphrase()
     */
    public String getPassphrase() {

        LOG.debug("getPassphrase()=********");
        secretDelivered = true;
        return passphrase;
    }

    /**
     * {...@inheritdoc}
     *
     * @see com.jcraft.jsch.UserInfo#getPassword()
     */
    public String getPassword() {

        LOG.debug("getPassword()=********");
        secretDelivered = true;
        return password;
    }

    /**
     * {...@inheritdoc}
     *
     * @see com.jcraft.jsch.UserInfo#promptPassword(java.lang.String)
     */
    public boolean promptPassword(final String message) {

        // Tell Jsch prompting for PW was successful the first time, but
        // failed if asked more than once (the first pw did not work, we
        // got only one.
        LOG.debug("promptPassword(" + message + ")=" + !secretDelivered);
        return !secretDelivered;
    }

    /**
     * {...@inheritdoc}
     *
     * @see com.jcraft.jsch.UserInfo#promptPassphrase(java.lang.String)
     */
    public boolean promptPassphrase(final String message) {

        // Tell JSCH prompting for pass phrase was successful the first time, 
but
        // failed if asked more than once (the first pass phrase did not work, 
we
        // got only one).
        LOG.debug("promptPassphrase(" + message + ")=" + !secretDelivered);
        return !secretDelivered;
    }

    /**
     * {...@inheritdoc}
     *
     * @see com.jcraft.jsch.UserInfo#promptYesNo(java.lang.String)
     */
    public boolean promptYesNo(final String message) {

        LOG.debug("promptYesNo(" + message + ")=true");
        // Used, if known hosts check failed (i.e. host key not known).
        // Answer means: continue anyways
        return true;
    }

    /**
     * {...@inheritdoc}
     *
     * @see com.jcraft.jsch.UserInfo#showMessage(java.lang.String)
     */
    public void showMessage(final String message) {

        LOG.debug("showMessage(" + message + ")");
    }

    /**
     * @return Returns the key file.
     */
    public String getKeyFile() {

        LOG.debug("getKeyFile()=" + keyFile);
        return keyFile;
    }

}
------------------------------------------------------------------------------
This SF.net email is sponsored by:
SourcForge Community
SourceForge wants to tell your story.
http://p.sf.net/sfu/sf-spreadtheword
_______________________________________________
JSch-users mailing list
[email protected]
https://lists.sourceforge.net/lists/listinfo/jsch-users

Reply via email to