how to set password for ssh connection in java - 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.

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

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.

SFTP file transfer using Java JSch

Here is my code, which retrieves content of the file, on the remote server and display as output.
package sshexample;
import com.jcraft.jsch.*;
import java.io.*;
public class SSHexample
{
public static void main(String[] args)
{
String user = "user";
String password = "password";
String host = "192.168.100.103";
int port=22;
String remoteFile="sample.txt";
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();
System.out.println("Connection established.");
System.out.println("Creating SFTP Channel.");
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
System.out.println("SFTP Channel created.");
InputStream out= null;
out= sftpChannel.get(remoteFile);
BufferedReader br = new BufferedReader(new InputStreamReader(out));
String line;
while ((line = br.readLine()) != null)
{
System.out.println(line);
}
br.close();
sftpChannel.disconnect();
session.disconnect();
}
catch(JSchException | SftpException | IOException e)
{
System.out.println(e);
}
}
}
Now how to implement this program that the file is copied in the localhost and how to copy a file from localhost to the server.
Here how to make work the transfer of files for any format of files.
The most trivial way to upload a file over SFTP with JSch is:
JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");
Similarly for a download:
sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");
You may need to deal with UnknownHostKey exception.
Usage:
sftp("file:/C:/home/file.txt", "ssh://user:pass#host/home");
sftp("ssh://user:pass#host/home/file.txt", "file:/C:/home");
Implementation
Below code works for me
public static void sftpsript(String filepath) {
try {
String user ="demouser"; // username for remote host
String password ="demo123"; // password of the remote host
String host = "demo.net"; // remote host address
JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
sftpChannel.disconnect();
session.disconnect();
}catch(Exception ex){
ex.printStackTrace();
}
}
OR using StrictHostKeyChecking as "NO" (security consequences)
public static void sftpsript(String filepath) {
try {
String user ="demouser"; // username for remote host
String password ="demo123"; // password of the remote host
String host = "demo.net"; // remote host address
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);;
session.setPassword(password);
System.out.println("user=="+user+"\n host=="+host);
session.connect();
ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();
sftpChannel.put("I:/demo/myOutFile.txt", "/tmp/QA_Auto/myOutFile.zip");
sftpChannel.disconnect();
session.disconnect();
}catch(Exception ex){
ex.printStackTrace();
}
}

Categories