dimanche 27 avril 2014

how to use jsch codeto run commands on remote unix server without giving password?


Vote count:

0




I have used jcraft to connect to a remote server and execute commands and it is working too.But I am giving the user credentials and connecting to server.Is it possible to connect to the server without giving the password?


I have tried using this code:



import com.jcraft.jsch.*;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch.*;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
import java.io.*;

public class testrad
{public static void main(String args[])
{
String user="uname";
String host="hostname";
String cmd="sh rdh_count.sh r10040";
JSch jsch = new JSch();
try
{
Session session=jsch.getSession(user,host,22);
session.setPassword("psw");
UserInfo usrInfo=new MyUserInfo();
session.setUserInfo(usrInfo);
session.connect();
Channel channel=session.openChannel("exec");
((ChannelExec) channel).setCommand(cmd);
channel.setXForwarding(true);
InputStream in = channel.getInputStream();
channel.connect();
channel.setInputStream(System.in);
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())
{
in.close();
break;
}
try
{
Thread.sleep(1000);}
catch (Exception ee)
{
}
}
channel.disconnect();
session.disconnect();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("Exception"+e);
}


} public static class MyUserInfo implements UserInfo { public String getPassword() { return "password"; } public String getPassphrase() {

return ""; } public boolean promptPassword(String arg0) { return true; } public boolean promptPassphrase(String arg0) { return true; } public boolean promptYesNo(String arg0) { return true; } public void showMessage(String arg0) { } } }



asked 55 secs ago






Aucun commentaire:

Enregistrer un commentaire