JSch shell channel - Won't close after disconnecting - java

I'm connecting to a remote machine using JSch. In order to restart a service, I need to have su privileges, so I'm using a shell channel instead of exec. I'm able to run the commands just fine, but once I disconnect the channel and session, application gets stuck and the execution doesn't move forward. I need to Ctrl-C to kill the application.
Am I doing anything wrong in my method?
public static void sendCommandWithSudo(String user, String pass, String ip, String command) {
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user, ip, 22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
config.put("PreferredAuthentications", "password");
session.setConfig(config);
session.setPassword(pass);
System.out.println("IP Address: " + ip);
System.out.println("Username: " + user);
System.out.println("Password: " + pass);
System.out.println("Command issued: " + command);
UserInfo ui = new MyUserInfo();
session.setUserInfo(ui);
session.connect();
Channel channel = session.openChannel("shell");
channel.setInputStream(System.in);
channel.setOutputStream(System.out);
PrintStream shellStream = new PrintStream(channel.getOutputStream());
channel.connect(3*1000);
List<String> commands = new ArrayList<String>();
commands.add("sudo su - sudouser");
commands.add(command);
for(String cmd: commands) {
shellStream.println(cmd);
shellStream.flush();
}
Thread.sleep(5000);
channel.disconnect();
session.disconnect();
shellStream.close();
} catch (Exception e) {
System.out.println("Exception caught: " + e.getMessage());
}
}

Replying to myself:
Adding the exit command twice seems to solve this:
commands.add("sudo su - sudouser");
commands.add(command);
commands.add("exit");
commands.add("exit");

Related

how to set password for ssh connection in java

I want to connect my unix server using java code. first it will connect to my server location. inside that it'll connect to my server name. but at that time it'll ask for confirmation (yes/no) and password I don't know how to do?
Here's my code that I have done.please help me out on this
public static void main (String args[]) {
String user = "user";
String password = "password";
String host = "hostName";
int port=22;
//String remoteFile="/home/john/test.txt";
//String yes="yes";
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
System.out.println("Establishing Connection...");
session.connect();
Channel channel = session.openChannel("exec");
// After this it'll ask for confirmation and password
((ChannelExec)channel).setCommand("ssh myServerName");
channel.connect();
InputStream output = channel.getInputStream();
System.out.println("aafter stream");
int readByte = output.read();
StringBuilder outputBuffer = new StringBuilder();
while (readByte != 0xffffffff) {
//System.out.println("read byte" + readByte);
outputBuffer.append((char)readByte);
readByte = output.read();
}
System.out.println(outputBuffer.toString());
channel.disconnect();
} catch (Exception e){
System.err.print("error message" + e);
}
}
You need to get the OutputStream of JSch secured channel and insert the password in it.
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand("sudo -S -p '' " + command);
channel.setInputStream(null);
OutputStream out = channel.getOutputStream();
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
((ChannelExec) channel).setPty(true);
channel.connect();
out.write((password + "\n").getBytes());
out.flush();
Complete source code here: http://codeflex.co/java-run-sudo-command-on-remote-linux-host/
try {
session = jsch.getSession(user, host, port);
}
catch (JSchException e) {
throw new TransferException("Failed to open session - " + params, e);
}
session.setPassword(password);
// Create UserInfo instance in order to support SFTP connection to any machine
// without a key username and password will be given via UserInfo interface.
UserInfo userInfo = new SftpUserInfo();
session.setUserInfo(userInfo);
try {
session.connect(connectTimeout);
}
catch (JSchException e) {
throw new TransferException("Failed to connect to session - " + params, e);
}
boolean isSessionConnected = session.isConnected();
Set the password programmatically like seen above.

Running multiple commands as root with Jsch()

Im having problems running multiple commands as the root user, using the exec channel. I dont get any exceptions, however the second command is not being executed for some reason.
Here is my code
try {
JSch jsch = new JSch();
String command1 = "touch 1.txt; touch 2.txt";
//"sudo chmod 755 script.sh; sudo sh script.sh";
String user = "user";
String host = "10.68.228.140";
String privateKey = "/home/user/.ssh/blabla";
jsch.addIdentity(privateKey);
System.out.println("identity added ");
Session session = null;
while(session == null) {
Thread.sleep(1000);
session = jsch.getSession(user, host);
}
System.out.println("session created ");
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
while(!session.isConnected()) {
Thread.sleep(1000);
session.connect();
}
System.out.println("session connected.....");
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp)channel;
sftpChannel.put("/home/user/script.sh", "/home/user");
sftpChannel.disconnect();
channel.disconnect();
Channel channel1 = session.openChannel("exec");
((ChannelExec) channel1).setCommand(command);
channel1.connect();
channel1.disconnect();
session.disconnect();
} catch(JSchException e){
e.printStackTrace();
} catch(SftpException se){
se.printStackTrace();
}
catch(Exception e) {
}
So if I leave it like this, everything is fine. The two files are created on the remote machine. But if I give as command the commented line, then the script is not executed. (It changes only mode)
Could you give me a help please? I've been stuck with this all day now.

java jsch su- root (how can i?)

I want to connect a Linux server and execute a command, but when I send the command sh and su - it requires password, but my program sends password just before it asks. How can i solve this problem?
public class Stream
{
public void getStream(String fileName)
{
String user = usernametext.getText();
String host = hostiptext.getText();
String password = pass.getText();
String command4 = "sh\nsu -\nmypassword\n";
try
{
System.out.println("preparing the host information for stream.");
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(10 * 1000);
Channel channel = session.openChannel("shell");
InputStream is = new ByteArrayInputStream(command4.getBytes());
channel.setInputStream(is);
channel.setOutputStream(System.out);
channel.connect(15 * 1000);
session.connect(10 * 10);
channel.disconnect();
session.disconnect();
}
catch (Exception ex)
{
System.out.println("Exception found while streaming.");
}
}
}
As you are using a shell channel why do you need to call another sh?
Any how I do the above is to pass individual command and then read the inputStream until you get back to the prompt and then you can set the next input e.g. the password or what ever.
Pseudo-code being
write "su -"
readUntil "password:"
write "******"
readUntil prompt
etc.

Execute commands on GlassFish inside a application in java

I need to flush a pool in GlassFish when my application detect an specific Error. Is it possible to execute commands on GlassFish inside a java aplication? I just need to flush this pool when a get the error.
It can be done with SSH
public class FlushPool {
public static void flushConncetionPool(String nameConnectionPool){
Session session = null;
Channel channel = null;
JSch jsch = new JSch();
try {
session = jsch.getSession("username", "host", port);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.setPassword("password");
session.connect();
channel = session.openChannel("shell");
OutputStream ops = channel.getOutputStream();
PrintStream ps = new PrintStream(ops, true);
channel.connect();
ps.println("sudo su -");
ps.println("/app/glassfish/glassfish/bin/asadmin --user admin --passwordfile password.txt flush-connection-pool " + nameConnectionPool);
session.diconect();
channel.disconect();
}catch(Exception e){
// do something
}
}
}
password.txt must be in server side
AS_ADMIN_PASSWORD = senha
AS_ADMIN_ADMIN_PASSWORD = senha
AS_ADMIN_USERPASSWORD=senha
AS_ADMIN_MASTERPASSWORD= senha

Java SSH Connection: Getting an empty exception

I'm using the following code to make an SSH connection and download a file to the SSH server through curl. It gives me an exception without a message. Not really sure what to do at this point.
try{
JSch jsch=new JSch();
String host=selectedItem.getHost();
String user="down2home";
int port = selectedItem.getPort();
String password = selectedItem.getPass();
String dlurl = dlurlField.getText().toString();
Session session=jsch.getSession(user, host, port);
session.setPassword(password);
UserInfo ui = new MyUserInfo(){
};
ByteArrayOutputStream out = new ByteArrayOutputStream();
String command = "curl -L --create-dirs -o /home/paul/Desktop/geeknights/geeknights.mp3 "+dlurl+"\r\n";
out.write(command.getBytes());
out.flush();
InputStream in = new ByteArrayInputStream(out.toByteArray());
session.setUserInfo(ui);
session.connect(30*1000); // making a connection with timeout.
Channel channel=session.openChannel("shell");
channel.setInputStream(in);
channel.setOutputStream(System.out);
channel.connect(3*1000);
}
catch(Exception e){
String errorMessage = (e.getMessage()==null)?"Message is empty":e.getMessage();
Log.e("Exception:", errorMessage );
}
Traceback:
06-08 00:33:16.561: E/Exception:(9293): Message is empty
Turned out to be a NetworkOnMainThreadException. Not sure why it wouldn't give me that message with e.getMessage()

Categories