Java 测试是否向“提供了密码”;苏";命令在JSch库中成功
我试图在Java 测试是否向“提供了密码”;苏";命令在JSch库中成功,java,session,connect,jsch,channel,Java,Session,Connect,Jsch,Channel,我试图在su下的服务器上远程执行命令。具体而言,我正在远程执行: su -c '[command]' 当我登录到远程服务器时,此功能就可以工作。连接会话并远程运行命令的代码如下所示: 希望我的问题很简单:如何检查是否退出。write是否响应su命令中提供的密码提示?频道似乎已连接,只要不涉及su,程序就可以运行 理想情况下,行动顺序为: 远程命令已初始化->提示输入密码->远程输入密码[故障点]->执行命令 它必须是su。它不能是sudo /** * Method to connect to
su
下的服务器上远程执行命令。具体而言,我正在远程执行:
su -c '[command]'
当我登录到远程服务器时,此功能就可以工作。连接会话并远程运行命令的代码如下所示:
希望我的问题很简单:如何检查是否退出。write
是否响应su
命令中提供的密码提示?频道似乎已连接,只要不涉及su
,程序就可以运行
理想情况下,行动顺序为:
远程命令已初始化->提示输入密码->远程输入密码[故障点]->执行命令
它必须是su
。它不能是sudo
/**
* Method to connect to session.
*/
protected void connectSession(Session session){
try {
//connect to session and open exec channel
session.connect();
channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command); //set the command
((ChannelExec)channel).setPty(true); //set PTY tru for Password input
((ChannelExec)channel).setErrStream(System.err);
in = channel.getInputStream(); //set input stream
out=channel.getOutputStream(); //set output stream and connect
channel.connect();
System.out.println("Channel was connected");
out.write((sudo_pass+"\n").getBytes()); //write password upon prompt
out.flush();
//I believe the out.write and the out.flush section is not working. It probably breaks right before here.
System.out.println("Wrote sudo Pass");
} catch (JSchException | IOException e) {
System.out.println("Could not connect to session");
e.printStackTrace();
}
}
@覆盖
受保护的整数RunCommand()引发异常{
int j=0;
System.out.println(“运行命令:”+命令);
第二届会议(第二届会议);
字节[]tmp=新字节[1024];
while(in.available()>0){
inti=in.read(tmp,0,1024);
如果(i0)继续;
System.out.println(“退出状态:+channel.getExitStatus());
打破
}
试试{Thread.sleep(1000);}
捕获(异常ee){}
通道断开();
}
我从以下机构借了很多钱:
- 及
希望这能帮助任何有类似问题的人 如果输入错误的密码,
su
命令将中止并返回非零退出代码
因此,您只需检查“exec”通道是否在输入密码后关闭。如果它确实关闭,则表示您“输入”了错误的密码
如果输入正确的密码,su
将启动一个shell并一直等待命令(或执行-c
指定的命令)
请注意,
su
命令是专门为不自动化而设计的。试图自动化是错误的
正确的方法包括:
- 使用无密码的sudo命令仅限于执行特定任务的单个脚本
- 将私钥用于
用户仅限于用于特定任务的单个脚本根用户
sudo-p
开关仅更改提示消息,不影响输入的读取方式。启动时,sudo
和su
都会读取密码。在这方面他们是一样的,不是吗?你想检查什么?在您写入密码之前是否有任何提示(=如果另一方实际需要密码)?或者在您写入密码后是否正确处理了密码?
@Override
protected Integer RunCommand() throws Exception {
int j = 0;
System.out.println("Running command: " + command);
connectSession(session);
byte[] tmp=new byte[1024];
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()){
if(in.available()>0) continue;
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}
catch(Exception ee){}
channel.disconnect();
}