I have a .bat file on a remote machine. I want to invoke it through http call. I dont want to make any changes on the remote machine. Is there a way to do it using java and http?
String command = "cmd /C start C:/Users/abc/Desktop/test.bat";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
The above works good to invoke a .bat file on local machine. I would not mind considering other ways too, but invoking it through http would be the first choice.
EDIT:
I am using paramiko to do this now. However,I am unable to run the remote commands on the command prompt.
ssh = paramiko.SSHClient()
print "Enter the IP address"
ip = raw_input("ip>")
print "Enter the username"
user = raw_input("username>")
print "Enter the password"
pwd = raw_input("password>")
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, username=user, password=pwd, allow_agent = False)
print "connection successfull"
i, o, e = ssh.exec_command("echo test") # example command
s = e.read()
if s: # an error occurred
raise RuntimeError, s
result = o.read()
print result
Somehow it says AllowDesktopAccess failed
You need a service on the remote machine, for example an http server that is configured to run this script on demand (eg via cgi) or an ssh server you can connect to to issue the command.
Since you're using windows (I assume) then PsExec may be the service you need.
http://technet.microsoft.com/en-us/sysinternals/bb897553
Related
I have a JAVA code to create and execute .sh file. The problem is - .sh file is getting created but not getting executed via the JAVA code. When run manually from terminal or cronjob, it gets executed. The big problem is - same code is working fine on all DEV servers but not on client PROD environment with CentOS 6.8. It is also working fine on Client UAT environment with CentOS 6.5.
The code creates executable sh file on the application server and executes it. sh file contained commands sqlldr and sqlplus to upload data via batch upload mechanism. When executed successfully, a log file is created with output of execution. Any errors like are written in the log file. When sh file is not executed, log file is also not created. When executed manually from terminal, sh file is executed and log file is also created. Below are the contents of sh file
sqlldr user/pass#db CONTROL=CTL_1000004453.ctl silent=all
echo -e "UPDATE QT_BATCH_UPLOAD SET UPLOAD_STATUS = 20 WHERE UPLOAD_ID = 1000004453;
commit;
exit;
" > SET_STATUS_1000004453.SQL
sqlplus user/pass#db #SET_STATUS_1000004453.SQL
No error is getting obtained in application and server logs. Application is running on Weblogic server. I have checked and eradicated all permission related issues.
Please help if anyone has encountered such non-replicating issue ever.
Below is the code.
try
{
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(new String[] { "/bin/bash", "-c", "cd " + path + " ;chmod a+x " + exeFile + "; sh " + exeFile + ";" });
BufferedReader br = new BufferedReader(new InputStreamReader(pr.getInputStream()));
FileOutputStream file3 = new FileOutputStream(path + "CONSOLE_" + uploadID + ".LOG");
String line; while ((line = br.readLine()) != null) { String line;
System.out.println(line);
file3.write((line + System.getProperty("line.separator")).getBytes());
file3.flush();
}
file3.close();
}
Issue has been resolved. No change in code was required. Actually the app server (Weblogic) was being run via console. I did some R&D and asked the client to run it via putty/terminal, post which, the code ran fine.
I would still look for solutions to get the same working when weblogic runs via console.
I need to restart the tomcat from Java code.
For eg, if a query is not executed for a certain time Period then it will restart the tomcat automatically.
I have tried the following shutdown and startup code, but when we shutdown the tomcat then the java code will not run and tomcat not started.
Note :- I am running this code from a application and restarting the same tomact which the same application is using.
Following the code
try {
PreparedStatement.setQueryTimeout(10);
rs = PreparedStatement.executeQuery();
} catch (SQLException ex) {
System.out.println("IN CATCH BLOCK FOR THE REFRESH INVOICE");
String shutcommand = "killall java";
Process shutchild = Runtime.getRuntime().exec(shutcommand);
System.out.println("JAVA PROCESS KILLED");
String locationCommand = "cd /root/cluster/tomcat6/bin";
Process locationChild = Runtime.getRuntime().exec(locationCommand);
String strtcommand = "./startup.sh";
Process strtchild = Runtime.getRuntime().exec(strtcommand);
}
Killing tomcat after SQLException this is not good idea to handle this exception. Probably the problem is on database site.
But if you are sure, that it is what you need you can kill this java proces in this section, but to run tomcat you should use for example bash and cron. Why? Beacues after killing your executing code will stop, so you don't achieve the line to start tomcat.
How to check tomcat: Is Tomcat running?
TL;DR
File binaryDir = new File(System.getProperty("catalina.home") + File.separator + "bin");
String restartCommand = "\"shutdown.bat & ping 0.0.0.0 -n 4 & C:\\WINDOWS\\system32\\net start Tomcat8\"";
new ProcessBuilder("cmd", "/c", restartCommand).directory(binaryDir).start();
Survive
Creating new process will survive JVM shutdown. If you combine commands in one line
it should work fine according to my tests and this.
shutdown.bat
You need to use shutdown.bat instead stopping windows service because it often fails on Windows with message Cannot stop service Apache Tomcat...
ping 0.0.0.0 -n 4
You need to wait some time after shutdown otherwise you will get Service is already starting. Try again later error message. Also note I use ping instead timeout because it causes problems on some systems.
C:\WINDOWS\system32\net start Tomcat8
I'm starting windows service because invoking startup.bat won't work for me. Also remember to replace Tomcat8 if you using different tomcat or custom service name for example Tomcat7
Redirect I/O
Don't redirect input or output of process instance or command will shutdown with JVM, and Tomcat won't start.
You can execute this native command using java
String command = "c:\program files\tomcat\bin\startup.bat";//for linux use .sh
Process child = Runtime.getRuntime().exec(command);
You should consider using ProcessBuilder instead of Runtime exec. Also, you should split all the arguments when you want to execute a command.
I suggest this :
ProcessBuilder shutcommand = new ProcessBuilder("killall", "java");
Process shutchild = shutcommand.start();
System.out.println("JAVA PROCESS KILLED");
ProcessBuilder strtcommand = new ProcessBuilder("/root/cluster/tomcat6/bin/startup.sh", "java");
Process strtchild = strtcommand.start();
I have to execute a bat-file within a C# windows service. The bat-file executes a jar-file with some arguments. That works without any problem.
But i noticed a difference between executing the bat-file:
1. via the windows service:
I am able to look up the start-arguments, when i query Win32_Process.
2. not via the windows service (e.g. double click on bat-file):
The start-arguments are not listed in the queries Win32_Process. But the jar-file within the bat was started correctly with the arguments...
How can i execute a bat-file from a c# windows service, so that i can query the details later on?
My current code:
Process p = new Process();
p.StartInfo.FileName = "BAT-PATH";
p.StartInfo.RedirectStandardOutput = false;
p.StartInfo.UseShellExecute = false;
p.Start();
Content of the bat-file:
java -Dspring.profiles.active=postgresql ^
-Xmx1G -Xms1G ^
-jar C:\PATH\TEST.jar
Hi I am currently using the below code line to issue commands to the remote server
ChannelSftp sftp = (ChannelSftp)session.openChannel("sftp");
sftp.connect();
System.out.println("Current Directory: " + sftp.pwd()); <= This Line
But pwd is already be defined as a method in Class ChannelSftp, My Question is what if I want to issue some command or run any .sh file which is not a method in JSch?
Let say if I want to run : sudo /opt/bin/run.sh file.
OR is there any method which I can use to do the job
(Kindly note I have a Jump Server in between localhost and web Server. And web server can only be accessed via the jump server.So that is the reason I am not using exec or shell).
The ChannelSftp class is implementing the SFTP protocol, which is cabable of preforming FTP operations. Executing a random command is clearly not permitted via SFTP. What you need in this case is using a different class of the jsch lib: ChannelExec.
Example is here.
I need to run a batch file on a remote system from a local machine. Using the code below, I am getting the following error:
Path not correct
I have the IP address of the machine, and I have given the batch file as public share and share name is dsc.
The IP address of the machine is 16.181.37.28.
Here is my code. I know that the path is wrong. How can I give the exact path?
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* #author padmaja
*/
import java.io.*;
class Test{
public static void main(String arg[]){
try{
String command = "cmd /C start 16.181.37.28/dsc/StartVisTsDataCenterMySql-log.bat";
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(command);
}catch (IOException e) {
e.printStackTrace();
}
}
}
Are you trying to run the script ON THE REMOTE machine or ON YOUR LOCAL machine? Your approach will read the file from the remote machine but run it on your local.
The usual way to get something running on a remote machine is having a process on the remote machine to run permanently and listen for requests. If a request arrives this process will start your batch file you would like to have run.
You're running on Windows but using Posix paths separators. Try "cmd /C \\\\16.181.37.28\\dsc\\StartVisTsDataCenterMySql-log.bat".
You can test whether it works by creating a service:
sc \\16.181.37.28 create StartVisTsDataCenterMySql-Log binPath= "cmd /c \\16.181.37.28\dsc\StartVisTsDataCenterMySql-log.bat"
Then the command to run it is:
"cmd /c sc \\16.181.37.28 stop StartVisTsDataCenterMySql-Log&sc \\16.181.37.28 start StartVisTsDataCenterMySql-Log"
You'll need to be connected to the share as an administrator (or have the credentials saved). Once you've confirmed that works, change to srvany, as you will get an error in the event log and the batch file will only be allowed to run for 30 seconds otherwise.
If that's not the right answer, perhaps you can elaborate on the real requirement, and give some information on whether reimplementing the batch file in Java is a realistic solution.