Java SSH Connection: Getting an empty exception - java

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()

Related

How to use JSch with ProxyJump in .ssh/confg [duplicate]

This question already has an answer here:
"reject HostKey" when connecting to remote host through jumphost with JSch
(1 answer)
Closed 3 years ago.
I have config file under ~/.ssh/config contains :
Host jumbHost
HostName x.domain.com
Host host1
HostName y1.domain.com
ProxyJump jumbHost
How could I use JSch to tunnel to x.domain.com server by host1 in order to execute commands ?
Note: y1.domain.com doesn't have public IP
I tried to use jsch.setConfigRepository(config_file_path) but it seems there are more config I need to set or methods to use.
It will be very useful if described using example.
EDIT:
So I can ssh to x.domain.com server when I get session using jsch.getSession(user,"host1"); or something like that
Thanks in advance
Thanks KevinO and Martin Prikryl for your value tips and help
Based on your descriptions and links I was able to apply needed config to enable access to x.domain.com using host1 name and then execute commands on y1.domain.com
For record, this is how I end up with
public class Main {
public static void main(String args[]) throws Exception {
try {
String user = "user_name";
String host = "host1";
String command = "hostname";
JSch jsch = new JSch();
ConfigRepository configRepository = OpenSSHConfig.parseFile(System.getProperty("user.home") + "/.ssh/config");
jsch.setConfigRepository(configRepository);
jsch.addIdentity(new File(System.getProperty("user.home") + "/.ssh/id_rsa").getAbsolutePath());
Session sessionProxy = jsch.getSession(user,configRepository.getConfig(host).getValue("ProxyJump"),22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
sessionProxy.setConfig(config);
sessionProxy.connect();
int assignedPort = sessionProxy.setPortForwardingL(0, configRepository.getConfig(host).getHostname(), 22);
Session sessionTunnel = jsch.getSession(user, "127.0.0.1", assignedPort);
sessionTunnel.connect();
Channel channel = sessionTunnel.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream input = channel.getInputStream();
channel.connect();
try {
InputStreamReader inputReader = new InputStreamReader(input);
BufferedReader bufferedReader = new BufferedReader(inputReader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(">>> output: " + line);
}
bufferedReader.close();
inputReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
channel.disconnect();
sessionTunnel.disconnect();
sessionProxy.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

JSch shell channel - Won't close after disconnecting

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");

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.

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

Categories