端口终结者-Java项目
该PortKiller 项目源代码,是我自己独立开发,现在分享给大家学习和借鉴。
在自动化管理的项目中,有他的应用场景。
废话不多说,直接上代码:
public class KillPort {
public static void main(String[] args) {
try{
System.out.println("输入要杀死的端口号: ");
Scanner scan = new Scanner(System.in) ;
int kill_port = scan.nextInt() ;
String res = execCmdSync("cmd /c netstat -ano | findstr :" + kill_port , null , 5000 ) ;
String pid = findPid( res ) ;
if(pid!=null && !"".equals(pid)){
System.out.println("该端口号的占用者是: ");
res = execCmdSync( "cmd /c tasklist | findstr " + pid , null , 5000 ) ;
System.out.println("请问您是否想杀死它? \n 是 Y , 否 N ");
String if_kill = scan.next() ;
if( if_kill!=null && if_kill.trim().equalsIgnoreCase("y") ){
res = execCmdSync( "cmd /c taskkill -PID " + pid + " -F" , null , 5000 ) ;
System.out.println("执行杀死端口号占用者---完成!");
}
// res = execCmdSync(" netstat " , null , 5000 ) ;
}else{
System.out.println("该端口号没有被占用! ");
}
}catch(Exception e){e.printStackTrace() ; }
}
private static String findPid(String res) {
if(res!=null && res.contains("LISTENING") ){
res = res.substring( res.lastIndexOf("LISTENING") ) ;
res = res.replace( "LISTENING" ,"" ) ;
res = res.trim() ;
}
return res ;
}
static long t_begin = 0 ;
static long t_now = 0 ;
public static String execCmdSync(String cmd, CmdExecResult callback , int timeout_ms ) throws java.io.IOException, InterruptedException {
t_begin = System.currentTimeMillis() ;
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
//String[] commands = {"system.exe","-get t"};
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream(),"UTF-8"));
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream(),"UTF-8"));
StringBuffer stdout = new StringBuffer();
StringBuffer errout = new StringBuffer();
// read the output from the command
System.out.println("执行输出:\n");
String s = null;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
stdout.append(s);
t_now = System.currentTimeMillis() ;
if( t_now - t_begin >= timeout_ms ){
break ;
}
}
// read any errors from the attempted command
// t_begin = System.currentTimeMillis() ;
// System.out.println("Here is the standard error of the command (if any):\n");
// while ((s = stdError.readLine()) != null) {
// System.out.println(s);
// errout.append(s);
//
// t_now = System.currentTimeMillis() ;
// if( t_now - t_begin >= timeout_ms ){
// break ;
// }
// }
try{ stdInput.close() ; }catch(Exception e){}
try{ stdError.close() ; }catch(Exception e){}
if (callback == null) {
// return stdInput.toString();
return stdout.toString();
}
int exitVal = proc.waitFor();
callback.onComplete(exitVal == 0, exitVal, errout.toString(), stdout.toString(), cmd);
// return stdInput.toString();
return stdout.toString();
}
public interface CmdExecResult{
void onComplete(boolean success, int exitVal, String error, String output, String originalCmd);
}
}
总体思路,就是利用windows自带的shell指令,通过java runtime去执行调用执行。传入进程占用的指定的端口号,进行杀死进程的操作。
感觉有用的伙伴点下关注或者赞嘛,谢谢了。有什么不足也欢迎大家指出。