我使用了以下链接中的JSch Sudo示例:
http://www.jcraft.com/jsch/examples/Sudo.java.html
并进行了一些修改,去除了所有对话框,因为我需要在使用PuTTY连接EC2实例时使用它。
现在我的代码看起来像这样:
import com.jcraft.jsch.*;
import java.awt.*;
import javax.swing.*;
import java.io.*;
public class sudo{
public static void main(String[] arg){
try{
JSch jsch=new JSch();
String host=null;
if(arg.length>0){
host=arg[0];
}
String privateKey = "my private key.pem";
jsch.addIdentity(privateKey, "");
Session session=jsch.getSession("ec2-user", "xx.xx.xx.xx", 22);
session.setPassword("");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
String command="sudo mkdir /data";
String sudo_pass="";
Channel channel=session.openChannel("exec");
// man sudo
// -S The -S (stdin) option causes sudo to read the password from the
// standard input instead of the terminal device.
// -p The -p (prompt) option allows you to override the default
// password prompt and use a custom one.
((ChannelExec)channel).setCommand("sudo -S -p '' "+command);
InputStream in=channel.getInputStream();
OutputStream out=channel.getOutputStream();
((ChannelExec)channel).setErrStream(System.err);
channel.connect();
out.write((sudo_pass+"\n").getBytes());
out.flush();
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()){
System.out.println("exit-status: "+channel.getExitStatus());
break;
}
try{Thread.sleep(1000);}catch(Exception ee){}
}
channel.disconnect();
session.disconnect();
}
catch(Exception e){
System.out.println(e);
}
}
}
但是我收到了以下的错误信息:
抱歉,您必须拥有tty权限才能运行sudo
我还尝试使用((ChannelExec) channel).setPty(true)
,但是我可以运行一次程序,但是下一次,对于相同的EC2实例,我会得到以下错误信息,但是对于新实例,第一次再次正常工作。
com.jcraft.jsch.JSchException: Session.connect: java.io.IOException: End of IO Stream Read
sudo mkdir /data
Exception in thread "main" com.jcraft.jsch.JSchException: session is down
at com.jcraft.jsch.Session.openChannel(Session.java:791)
此外,我也无法使用命令行从远程主机进行ssh连接。
请问有人可以指导我如何在远程主机上运行sudo
命令吗?