import java.io.BufferedReader
import java.io.File
import java.io.FileWriter
import java.io.InputStreamReader
import java.util.Random
public class GwUtil {
private static Random r = new Random()
/**
* 功能:执行CMD命令,返回命令结果
*/
public static String execByFile(String cmd) throws Exception {
String filename = null
StringBuffer sb = new StringBuffer("")
BufferedReader bufferedReader = null
Process process = null
File file = null
r.setSeed(99999)
if (cmd == null) {
return null
}
try {
String ls_1
// 生成临时文件,文件名随机
filename = "/tmp/gwtemp"局档 + Long.toString(Math.abs(r.nextLong()))
+ ".sh"裂腊橡
file = new File(filename)
while (file.exists()) {
filename = "/tmp/gwtemp"
+ Long.toString(Math.abs(r.nextLong())) + ".sh"
file = new File(filename)
}
String execmd = new String("sh " + filename)// 执行文件的命令
FileWriter filewriter = new FileWriter(file, false)
filewriter.write("#! /bin/sh")
// Log.debug("do cmd:" + cmd + "\n")
filewriter.write("\n" + cmd + "\n")// 将命令写入文件
filewriter.close()
/肆旁/ Log.debug("run cmd\n")
process = Runtime.getRuntime().exec(execmd)// 执行临时的可执行文件
// Log.debug("run cmd over\n")
// 得到结果
bufferedReader = new BufferedReader(new InputStreamReader(process
.getInputStream()))
while ((ls_1 = bufferedReader.readLine()) != null) {
sb.append(ls_1 + "\n")
}
} catch (Exception e) {
throw new Exception("can not exec the cmd:" + cmd)
} finally { // 清理
try {
filename = null
if (file != null) {
file.delete()
file = null
}
if (bufferedReader != null) {
bufferedReader.close()
bufferedReader = null
}
if (process != null) {
process.destroy()
process = null
}
} catch (Exception e) {
e.printStackTrace()
}
}
return sb.toString()
}
public static void main(String args[]){
try {
GwUtil.execByFile("top -bn -1>/tmp/test.txtcat/tmp/test.txt")
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace()
}
}
}
1.putty链接远程郑羡服务器你应该会吧?2.putty主要是命令行 *** 作服务器,如丛笑做文件传输很不方便。
3.如果做java-web部署,肯定要做文件传输,给你推荐个工渣含具叫winSCP
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)