I'm trying to connect to a host, then change the user using "su - john" and then execute a command as john. Is it possible with using only JSch?
The problem is that after I create a session and open the channel and execute the aforementioned command it should request password, but nothing happens.
This is how I connect to the remote machine:
String address = "myremote.computer.com";
JSch jsch = new JSch();
String user = "tom";
String host = address;
String password = "l33tpaSSw0rd";
Session session = jsch.getSession( user, host, 22 );
java.util.Properties config = new java.util.Properties();
config.put( "StrictHostKeyChecking", "no" );
session.setConfig( config );
session.setPassword( password );
session.connect();
Then I execute commands via runSshCommand()
method which looks like this:
try
{
Channel channel = session.openChannel( "exec" );
channel.setInputStream( null );
channel.setOutputStream( System.out );
( (ChannelExec) channel ).setCommand( command );
channel.connect();
InputStream in = channel.getInputStream();
byte[] tmp = new byte[1024];
while ( true )
{
while ( in.available() > 0 )
{
int i = in.read( tmp, 0, 1024 );
if ( i < 0 )
{
break;
}
System.out.print( new String( tmp, 0, i ) );
}
if ( channel.isClosed() )
{
break;
}
try
{
Thread.sleep( 1000 );
}
catch ( Exception ee )
{
}
}
channel.disconnect();
}
catch ( Exception e )
{
e.printStackTrace();
}
Do I have to create another channel, when I change users, or how to make this work?
Because if I use
runSshCommand("su - john",session);
runSshCommand("tail -1 ~/mylog.log",session);
it just executes the "su" command but it doesn't finish the change of users and afterwards executing "tail" will result in an error because "tom" hasn't got the file :/
Basically I would like my application to connect to the machine, change user, read one file and return the data. Can anyone shed some light, please?