javash,java实训报告总结

发布时间:2023-01-09

本文目录一览:

  1. 请教个java调用shell命令操作
  2. java如何执行远程服务器上的.sh文件
  3. [急~~ 用java生成.sh文件的问题](#急~~ 用java生成.sh文件的问题)

请教个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 ((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 {
                    if (outputStreamWriter != null) {
                        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");

java如何执行远程服务器上的.sh文件

你可以使用JSch。 JSch全称是“Java Secure Channel”,是SSH2的一个纯Java实现。它允许你连接到一个sshd服务器,使用端口转发、X11转发、文件传输等等,同时也支持执行命令。 以下是大概运行的代码,只是提供大致思路,可以去查官方API和demo:

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelS;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
...
try {
    Session session = new JSch().getSession(user, ip, port);
    session.setPassword(pwd);
    session.setConfig("StrictHostKeyChecking", "no");
    session.setConfig("userauth.gssapi-with-mic", "no");
    session.connect();
    ChannelExec exec = (ChannelExec) session.openChannel("exec");
    exec.setCommand("ifconfig"); // 这里是你执行的命令,部分命令不支持,具体自己执行下
    ByteArrayOutputStream bao = new ByteArrayOutputStream();
    exec.setOutputStream(bao);
    ByteArrayOutputStream baerr = new ByteArrayOutputStream();
    exec.setErrStream(baerr);
    exec.connect();
    while (!exec.isEOF());
    String errmsg = new String(baerr.toByteArray(), "utf-8");
    if (StringUtils.notNull(errmsg)) {
        throw new RuntimeException(errmsg);
    } else {
        System.out.println(new String(bao.toByteArray(), "utf-8"));
    }
} catch (Exception e) {
    e.printStackTrace();
} finally {
    // 关闭session等操作
}

急~~ 用java生成.sh文件的问题

String lineSeparator = System.getProperty("line.separator");

这个在 Linux 得出的是 \n
这个在 Windows 得出的是 \r\n
你注意下这个就可以了。