I tried some commands such as
echo "Your text here" | ssh hostname 'cat >> output.txt'
but it didnt work.
How can I write in a file inside the server using this exec code or just the ssh command that I will put to String command.
public class TestWrite{
private static final String user = "username here";
private static final String host = "host here";
private static final String password = "pass here";
public static void main(String[] arg){
try{
JSch jsch=new JSch();
Session session=jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
String command = "Command here";
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
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()){
if(in.available()>0) continue;
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);
}
}
}
You can write to a file with
echo "your text here" > file
You don't need ssh because Jsch takes its place.
Try a command like:
ssh hostname 'echo "Your text here" >> output.txt'
Related
I have been working on an application that uses JSCH to scp and transfer a file to another directory in the same server. However, I want to be able to transfer a file from one remote host to another remote host in an automated way. Below is the code I use to make the call. I have tried using other scp commands such as: scp [options] username1#source_host:directory1/filename1 username2#destination_host:directory2/filename2. It works when testing it on the server itself but when I try to incorporate it into the code below, it passes back an error.
CODE:
public static void main(String[] args){
String array [] = {"robert.txt","ops1axv#gaalpltclu00029.linux.us.ams1907.com:/tmp"};
if(array.length!=2){
System.err.println("usage: java ScpTo file1 user#remotehost:file2");
System.exit(-1);
}
FileInputStream fis=null;
try{
String lfile=array[0];
String user=array[1].substring(0, array[1].indexOf('#'));
array[1]=array[1].substring(array[1].indexOf('#')+1);
String host=array[1].substring(0, array[1].indexOf(':'));
String rfile=array[1].substring(array[1].indexOf(':')+1);
System.out.println("RFile: " + rfile );
System.out.println("Lfile: " + lfile);
JSch jsch=new JSch();
Session session=jsch.getSession(user, host, 22);
// username and password will be given via UserInfo interface.
UserInfo ui=new MyUserInfo();
session.setUserInfo(ui);
session.connect();
boolean ptimestamp = true;
// exec 'scp -t rfile' remotely
String command="scp " + (ptimestamp ? "-p" :"") +" -t "+rfile;
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
// get I/O streams for remote scp
OutputStream out=channel.getOutputStream();
InputStream in=channel.getInputStream();
channel.connect();
if(checkAck(in)!=0){
System.exit(0);
}
File _lfile = new File(lfile);
if(ptimestamp){
command="T"+(_lfile.lastModified()/1000)+" 0";
// The access time should be sent here,
// but it is not accessible with JavaAPI ;-<
command+=(" "+(_lfile.lastModified()/1000)+" 0\n");
out.write(command.getBytes()); out.flush();
if(checkAck(in)!=0){
System.exit(0);
}
}
// send "C0644 filesize filename", where filename should not include '/'
long filesize=_lfile.length();
command="C0644 "+filesize+" ";
if(lfile.lastIndexOf('/')>0){
command+=lfile.substring(lfile.lastIndexOf('/')+1);
}
else{
command+=lfile;
}
command+="\n";
out.write(command.getBytes()); out.flush();
if(checkAck(in)!=0){
System.exit(0);
}
// send a content of lfile
fis=new FileInputStream(lfile);
byte[] buf=new byte[1024];
while(true){
int len=fis.read(buf, 0, buf.length);
if(len<=0) break;
out.write(buf, 0, len); //out.flush();
}
fis.close();
fis=null;
// send '\0'
buf[0]=0; out.write(buf, 0, 1); out.flush();
if(checkAck(in)!=0){
System.exit(0);
}
out.close();
channel.disconnect();
session.disconnect();
System.exit(0);
}
catch(Exception e){
System.out.println(e);
try{if(fis!=null)fis.close();}catch(Exception ee){}
}
}
I need run show interfaces status to Cisco/Alcatel switch via java (jsch if possible)
I use SSH to access this swith. after I try
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
channel.setOutputStream(System.out);
InputStream in = channel.getInputStream();
channel.connect();
I try this (OK if I run manually command in console)
Channel channel = session.openChannel("shell");
channel.setInputStream(null);
channel.connect();
I need connect, send command and record the result of command. If I exec this manually the result is OK. I try my code in a virtual machine and the result is different to a physical switch.
You can try this :
Channel channel=null;
String result = null;
try
{
channel = session.openChannel("exec");
String Command = "show interfaces status"; // Command
//System.out.println("Command : "+Command);
((ChannelExec)channel).setCommand(Command);
InputStream in=channel.getInputStream();
byte[] tmp=new byte[1024];
channel.connect();
if(channel.isConnected())
{
//System.out.println("Channel connected");
}
while(true)
{ // geeting the result in this loop
while(in.available()>0)
{
int i=in.read(tmp, 0, 1024);
if(i<0)break;
result += new String(tmp, 0, i); // result
}
if(channel.isClosed())
{
break;
}
else
{
try{ Thread.sleep(1000); }catch(Exception ee){}
}
}
}
catch(JSchException e)
{
// your exception message
}
I need java code that logs into linux box with my credentials, then do a sesu , and then execute a shell script. Permission to execute the shell script if for only sesu user, hence sesu-ing after login is critical. I used te following code which can help me execute a command with my credential scope, however, I need sesu login following my login. Please suggest a way.
I tried adding the sesu command in teh command list, but it prompts for a password. I want a way to pass the password as well and completly automate it.
import java.io.InputStream;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
public class SSHCommandExecutor {
/** * #param args */
public static void main(String[] args) {
String host = "xxxxxxx";
String user = "xxxxxxx";
String password = "xxxxxxx";
String command1 = "cd /test; ./test.sh";
try {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
Channel channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command1);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
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();
System.out.println("DONE");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Variant A: Using JSch all the way
This minimal script (test.sh) requests an input from stdin before putting out one line of data:
#!/bin/bash
echo -n "Is this a good question (y/n)? "
read answer
if echo "$answer" | grep -iq "^y" ;then
echo Yes
else
echo No
fi
So it should be equivalent to your call requesting a password to be given. Now have a look at this code on how to send data into that process
String command1 = "cd /home/jan; ./test.sh";
try {
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
session.setConfig(config);
session.connect();
System.out.println("Connected");
ChannelExec channel = (ChannelExec)session.openChannel("exec");
OutputStream o = channel.getOutputStream();
PrintWriter pw = new PrintWriter(o);
InputStream in = channel.getInputStream();
((ChannelExec) channel).setCommand(command1);
channel.connect();
// 1 - Reading the prompt to input password
byte[] buf = new byte[255];
int len = in.read(buf);
System.out.println(new String(buf,0,len));
// 2 - Send (password) data and flush stream
pw.println("y");
pw.flush();
// 3 - Read result
BufferedReader br = new BufferedReader(new InputStreamReader(in));
System.out.println(br.readLine());
// 4 - Clean up
channel.disconnect();
session.disconnect();
Variant B: Shell magic
String command1 = "cd /test; echo 'password' | ./test.sh";
or
String command1 = "cd /test; ./test.sh <<< 'password'";
(of cause you'd need to specify correct password there)
To run remote script with root privileges even if login user does not have them see here:
https://askubuntu.com/questions/155791/how-do-i-sudo-a-command-in-a-script-without-being-asked-for-a-password
I am executing a rm command via ssh using the jsch library.
The command is being sent and executed correctly.
But when the file I want to delete is not found in the directory, I get an error message as follows:
No such file or directory
I want to store the error message in a variable and use it afterwards.
Currently this message is displayed when the following are executed:
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
after the channel.connect() the message error mesg is displayed.
How can I store it in a variable let's say string and print it after completion?
Below is the main class.
String SSHHOST = "127.0.0.1";
int SSHPPORT = 22;
String SSHPUSER = "user";
String SSHPPASS = "pass";
StringBuilder result = new StringBuilder();
System.out.println("Connecting To Server "+SSHHOST);
JSch jsch = new JSch();
Session session=jsch.getSession(SSHPUSER, SSHHOST, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(SSHPPASS);
session.connect();
Channel channel=session.openChannel("exec");
((ChannelExec)channel).setCommand("find /home/test/DC* -print -exec rm {} \\;|wc -l");
channel.setInputStream(null);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
((ChannelExec)channel).setErrStream(bos) ;
((ChannelExec)channel).setErrStream(System.err);
InputStream in=channel.getInputStream();
channel.connect();
String result2 = bos.toString();
System.out.println(result2);
byte[] tmp=new byte[1024];
while(true)
{
while(in.available()>0)
{
int i=in.read(tmp, 0, 1024);
if(i<0)break;
out=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();
int status = channel.getExitStatus();
System.out.println(out.trim());
if (channel.getExitStatus() == 0)
{
System.out.println("Perso file purging process completed successfully.");
System.out.println("exit-status: "+channel.getExitStatus());
System.out.println("Number of perso files deleted : "+out);
}
else
{
System.out.println("Perso file purging process completed with errors.");
}
I am still unable to get the error message when the files are not found in the directory with the above code.
This is a bit of a guess from me but .....
You seem to be setting the error stream of your channel object to the System.err of your application - unless you have reconfigured the System.err of your application to point to somewhere else, that will be the console.
What arguments does setErrStream take? If it's an OutputStream, could you get it to write to a ByteArrayOutputStream and then build a string from that?
i have been able to store the error in a file by using FileOutputStream
FileOutputStream fos = null;
File file = new File("errors.txt");
try
{
fos = new FileOutputStream(file);
}
catch(IOException ioe)
{
System.err.println("redirection not possible: "+ioe);
System.exit(-1);
}
PrintStream ps = new PrintStream(fos);
((ChannelExec)channel).setErrStream(ps);
My aim is to connect to my linux server using a java application and execute a linux command. I have already achieved this using the JSch API but I can't seem to figure out how to execute more than one command at a time.
It's a problem for me because I need to navigate to a certain directory, then execute another command FROM that directory. My application just exits before the second command can be executed in the correct directory.
Here is my method to execute one linux command as a string when it is passed as a parameter and print any output.
public void connect(String command1){
try {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
System.out.println("Connected");
Channel channel = session.openChannel("exec");
((ChannelExec)channel).setCommand(command1);
channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();
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){
ee.printStackTrace();
}
}
channel.disconnect();
session.disconnect();
System.out.println("DONE");
}
catch(Exception e){
e.printStackTrace();
}
}
Any ideas how to do 2 commands at once?
If a normal shell is started on the remote machine, use ; or && constructs to do more things.
As in
cd /home/foo/banana ; do_things
or
cd /home/foo/banan && do_things #do_things will only be run if the cd command is successfull