javash
1) 在ECLIPSE下面EXPORT成為RUNNABLE JAR FILE。
2)拷貝1)中生成的JAR包,到LINUX中去。
3)隨便搞個什麼名字的.SH文件,岩遲里簡改面輸入粗咐李java -jar XXX.jar
2. 如何在java中執行shell腳本
過CommandHelper.execute方法可以執行命令,該類實現
復制代碼代碼如下:
package javaapplication3;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
*
* @author chenshu
*/
public class CommandHelper {
//default time out, in millseconds
public static int DEFAULT_TIMEOUT;
public static final int DEFAULT_INTERVAL = 1000;
public static long START;
public static CommandResult exec(String command) throws IOException, InterruptedException {
Process process = Runtime.getRuntime().exec(command);
CommandResult commandResult = wait(process);
if (process != null) {
process.destroy();
}
return commandResult;
}
private static boolean isOverTime() {
return System.currentTimeMillis() - START >= DEFAULT_TIMEOUT;
}
private static CommandResult wait(Process process) throws InterruptedException, IOException {
BufferedReader errorStreamReader = null;
BufferedReader inputStreamReader = null;
try {
errorStreamReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
inputStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
//timeout control
START = System.currentTimeMillis();
boolean isFinished = false;
for (;;) {
if (isOverTime()) {
CommandResult result = new CommandResult();
result.setExitValue(CommandResult.EXIT_VALUE_TIMEOUT);
result.setOutput("Command process timeout");
return result;
}
if (isFinished) {
CommandResult result = new CommandResult();
result.setExitValue(process.waitFor());
//parse error info
if (errorStreamReader.ready()) {
StringBuilder buffer = new StringBuilder();
String line;
while ((line = errorStreamReader.readLine()) != null) {
buffer.append(line);
}
result.setError(buffer.toString());
}
//parse info
if (inputStreamReader.ready()) {
StringBuilder buffer = new StringBuilder();
String line;
while ((line = inputStreamReader.readLine()) != null) {
buffer.append(line);
}
result.setOutput(buffer.toString());
}
return result;
}
try {
isFinished = true;
process.exitValue();
} catch (IllegalThreadStateException e) {
// process hasn't finished yet
isFinished = false;
Thread.sleep(DEFAULT_INTERVAL);
}
}
} finally {
if (errorStreamReader != null) {
try {
errorStreamReader.close();
} catch (IOException e) {
}
}
if (inputStreamReader != null) {
try {
inputStreamReader.close();
} catch (IOException e) {
}
}
}
}
}
CommandHelper類使用了CommandResult對象輸出結果錯誤信息。該類實現
復制代碼代碼如下:
package javaapplication3;
/**
*
* @author chenshu
*/
public class CommandResult {
public static final int EXIT_VALUE_TIMEOUT=-1;
private String output;
void setOutput(String error) {
output=error;
}
String getOutput(){
return output;
}
int exitValue;
void setExitValue(int value) {
exitValue=value;
}
int getExitValue(){
return exitValue;
}
private String error;
/**
* @return the error
*/
public String getError() {
return error;
}
/**
* @param error the error to set
*/
public void setError(String error) {
this.error = error;
}
}
3. java在linux上調用sh文件的寫法該怎麼寫
可以用Process 去調用shell腳本,絕枝緩demo如下
並模Stringshellpath="搭肆/home/test/aa.sh";
Processps=Runtime.getRuntime().exec(shellpath);
4. 請教個java調用shell命令操作
近日項目中有這樣一棗扮漏個需求:系統中的外幣資金調度完成以後,要將調度信息生成一個Txt文件,然後將這個Txt文件發送到凳爛另外一個系統(Kondor)中。生成文件自然使用OutputStreamWirter了,發送文件有兩種方式,一種是用寫個一個類似於ftp功能的程序,另外一種就是使用Java來調用Shell,在Shell中完成文件的發送操作。我們選擇後一種,即當完成外幣資金的調度工作後,用Java的OutputStreamWriter來生成一個Txt文件,然後用Java來調用Shell腳本,在Shell腳本中完成FTP文件到Kondor系統的工作。
以下為Java程序JavaShellUtil.java:import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class JavaShellUtil {
//基本路徑
private static final String basePath = "/tmp/";
//記錄Shell執行狀況的日誌文件的位置(絕對路徑)
private static final String executeShellLogFile = basePath + "executeShell.log";
//發送文件到Kondor系統的Shell的文件名(絕對路徑)
private static final String sendKondorShellName = basePath + "sendKondorFile.sh";
public int executeShell(String shellCommand) throws IOException {
int success = 0;
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = null;
//格式化日期時間,記錄日誌缺野時使用
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS ");
try {
stringBuffer.append(dateFormat.format(new Date())).append("准備執行Shell命令 ").append(shellCommand).append(" \r\n");
Process pid = null;
String[] cmd = {"/bin/sh", "-c", shellCommand};
//執行Shell命令
pid = Runtime.getRuntime().exec(cmd);
if (pid != null) {
stringBuffer.append("進程號:").append(pid.toString()).append("\r\n");
//bufferedReader用於讀取Shell的輸出內容 bufferedReader = new BufferedReader(new InputStreamReader(pid.getInputStream()), 1024);
pid.waitFor();
} else {
stringBuffer.append("沒有pid\r\n");
}
stringBuffer.append(dateFormat.format(new Date())).append("Shell命令執行完畢\r\n執行結果為:\r\n");
String line = null;
//讀取Shell的輸出內容,並添加到stringBuffer中
while (bufferedReader != null &
&
(line = bufferedReader.readLine()) != null) {
stringBuffer.append(line).append("\r\n");
}
} catch (Exception ioe) {
stringBuffer.append("執行Shell命令時發生異常:\r\n").append(ioe.getMessage()).append("\r\n");
} finally {
if (bufferedReader != null) {
OutputStreamWriter outputStreamWriter = null;
try {
bufferedReader.close();
//將Shell的執行情況輸出到日誌文件中
OutputStream outputStream = new FileOutputStream(executeShellLogFile);
outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
outputStreamWriter.write(stringBuffer.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
outputStreamWriter.close();
}
}
success = 1;
}
return success;
}
}
以下是Shell腳本sendKondorFile.sh,該Shell腳本的作用是FTP文件到指定的位置:
#!/bin/sh
#日誌文件的位置
logFile="/opt/fms2_kondor/sendKondorFile.log"
#Kondor系統的IP地址,會將生成的文件發送到這個地址
kondor_ip=192.168.1.200
#FTP用戶名
ftp_username=kondor
#FTP密碼
ftp_password=kondor
#要發送的文件的絕對路徑
filePath=""
#要發送的文件的文件名
fileName=""
#如果Shell命令帶有參數,則將第一個參數賦給filePath,將第二個參數賦給fileName
if [ $# -ge "1" ]
then
filePath=$1
else
echo "沒有文件路徑"
echo "沒有文件路徑\n" >
>
$logFile
return
fi
if [ $# -ge "2" ]
then
fileName=$2
else
echo "沒有文件名"
echo "沒有文件名\n" >
>
$logFile
return
fi
echo "要發送的文件是 ${filePath}/${fileName}"
cd ${filePath}
ls $fileName
if (test $? -eq 0)
then
echo "准備發送文件:${filePath}/${fileName}"
else
echo "文件 ${filePath}/${fileName} 不存在"
echo "文件 ${filePath}/${fileName} 不存在\n" >
>
$logFile
return
fi
ftp -n ${kondor_ip} <
<
_end
user ${ftp_username} ${ftp_password}
asc
prompt
put $fileName
bye
_end
echo "`date +%Y-%m-%d' '%H:%M:%S` 發送了文件 ${filePath}/${fileName}"
echo "`date +%Y-%m-%d' '%H:%M:%S` 發送了文件 ${filePath}/${fileName}\n" >
>
$logFile
調用方法為:
JavaShellUtil javaShellUtil = new JavaShellUtil();
//參數為要執行的Shell命令,即通過調用Shell腳本sendKondorFile.sh將/temp目錄下的tmp.pdf文件發送到192.168.1.200上
int success = javaShellUtil.executeShell("sh /tmp/sendKondorFile.sh /temp tmp.pdf");
5. 急~~ 用java生成.sh文件的問題
String lineSeparator = System.getProperty("line.separator");
這個態哪在 Linux 得談閉茄出的是 \n
這個在 Windows 得出的是 \n\r
你注意下這個就可含察以了。
6. java執行sh文件,如何獲取到錯誤信息
package com.cn3158.base.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
public class ProcessExecutor {
private static Logger logger = Logger.getLogger(ProcessExecutor.class);
public static boolean isSubProcessOutput = true;
private static ProcessExecutor instance = new ProcessExecutor();
private ProcessExecutor() {
super();
}
public static ProcessExecutor getInstance()
{
return instance;
}
public Integer executeProcess(List<String> commands) {
Integer result = null;
ProcessBuilder pb = new ProcessBuilder(commands);
// 開啟錯胡返御誤信息的流世銷到標准輸出流,在某種情況下由於錯誤輸出流中的數據沒有被讀取,進程就不會結束
pb.redirectErrorStream(true);
try {
//啟動進程
Process process = pb.start();
//logger.info("begin to start process "+process.hashCode()+" ...");
//System.out.println("begin to start process "+process.hashCode()+" ...");
//開啟子線程褲岩,讀取進程輸出信息
Thread t = new SubprocessReader(process,isSubProcessOutput);
t.start();
//等待進程執行完成
int status = process.waitFor();
//logger.info("finish to execute process "+process.hashCode()+",exit status("+status+") ...");
//System.out.println("finish to execute process "+process.hashCode()+",exit status("+status+") ...");
return status;
} catch (Exception e) {
logger.error(e);
}
return result;
}
/**
* 讀取進程輸出內容
* @author Administrator
*
*/
class SubprocessReader extends Thread {
private Process subprocess;
private boolean isOutput;
SubprocessReader(Process p, boolean isOutput) {
this.subprocess = p;
this.isOutput = isOutput;
}
public void run() {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(
new InputStreamReader(subprocess.getInputStream(),"gbk"));
} catch (Exception e1) {
e1.printStackTrace();
}
String line = null;
try {
while ((line = bufferedReader.readLine()) != null) {
if (isOutput) {
logger.info("process "+subprocess.hashCode()+":"+line);
//System.out.println("process "+subprocess.hashCode()+":"+line);
}
}
} catch (Exception e) {
logger.error("read subProcess error.", e);
} finally {
if (null != subprocess) {
InputStream is = subprocess.getInputStream();
InputStream es = subprocess.getErrorStream();
OutputStream os = subprocess.getOutputStream();
try {
bufferedReader.close();
is.close();
is = null;
es.close();
es = null;
os.close();
os = null;
} catch (IOException e) {
}
subprocess = null;
}
}
}
}
public static void main(String[] args)throws Exception {
List<String> commands = new ArrayList<String>();
//commands.add("convert");
//commands.add("-page");
//commands.add("952x3683");
//commands.add("pattern:gray100");
//commands.add("-page");
//commands.add("+555+316");
//commands.add("d:/wxwtest/common/plot2.png");
//commands.add("-background");
//commands.add("white");
//commands.add("-compose");
//commands.add("multiply");
//commands.add("-flatten");
//commands.add("d:/wxwtest/temp/empty.png");
//commands.add("convert");
//commands.add("d:\\wxwtest\\common\\plot.png");
//commands.add("-fill");
//commands.add("white");
//commands.add("-colorize");
//commands.add("50%");
//commands.add("d:/wxwtest/temp/temp.png");
commands.add("CutyCapt");
commands.add("-–url=http://www.3158.cn");
commands.add("-–out=d:/wxwtest/3158.jpg");
ProcessExecutor pe = ProcessExecutor.getInstance();
pe.executeProcess(commands);
//Runtime.getRuntime().exec("CutyCapt -–url=http://www.3158.cn -–out=d:/wxwtest/3158.jpg");
}
}
這是java執行子進程的實例代碼,希望對你有用
7. java如何執行遠程伺服器上的.sh文件
你可以使用JSch
JSch全稱是「Java Secure Channel」
是SSH2的一個純Java實現。它允許你連接到一個sshd 伺服器,使用埠轉發,X11轉發,文件傳輸等等。同時也是支持執行命令;
以下是大概運行的代碼,只是提供大致思路,可以去查官方API和demo
importcom.jcraft.jsch.ChannelExec;
importcom.jcraft.jsch.ChannelSftp;
importcom.jcraft.jsch.ChannelSftp.LsEntry;
importcom.jcraft.jsch.JSch;
importcom.jcraft.jsch.JSchException;
importcom.jcraft.jsch.Session;
importcom.jcraft.jsch.SftpATTRS;
importcom.jcraft.jsch.SftpException;
.......
try{
Sessionsession=new指培顫JSch().getSession(user,ip,port);
session.setPassword(pwd);
session.setConfig("StrictHostKeyChecking","no");
session.setConfig("userauth.gssapi-with-mic","no");
session.connect();
ChannelExecexec=(ChannelExec)session.openChannel("exec");
exec.setCommand("ifconfig");//這里是你要執唯敗行的命令,部分命令中敏不支持,具體自己執行下
ByteArrayOutputStreambao=newByteArrayOutputStream();
exec.setOutputStream(bao);
ByteArrayOutputStreambaerr=newByteArrayOutputStream();
exec.setErrStream(baerr);
exec.connect();
while(!exec.isEOF())
;
Stringerrmsg=newString(baerr.toByteArray(),"utf-8");
if(StringUtils.notNull(errmsg)){
thrownewRuntimeException(errmsg);
}else{
System.out.println(newString(bao.toByteArray(),"utf-8"));
}
}catch(Exceptione){
e.printStackTrace();
}finally{
//關閉session等操作
}