我试图连接到主机,然后使用“ su-john”更改用户,然后以john身份执行命令。仅使用JSch是否有可能?
问题是在创建会话并打开通道并执行上述命令后,它应该要求输入密码,但没有任何反应。
这是我连接到远程计算机的方式:
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();
然后我通过如下runSshCommand()方法执行命令:
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();
}
当我更改用户时,是否必须创建另一个频道,或者如何使其工作?
因为如果我用
runSshCommand("su - john",session);
runSshCommand("tail -1 ~/mylog.log",session);
它只执行“ su”命令,但没有完成用户的更改,之后执行“ tail”将导致错误,因为“ tom”还没有文件:/
基本上,我希望我的应用程序连接到计算机,更改用户,读取一个文件并返回数据。任何人都可以阐明一下吗?