如何杀掉指定端口的进程

鱼香土豆丝 2016-11-07 09:07:37
小白问问题!
杀掉端口一般方法是:首先是查看端口占用1,netstat -nao吧在里面找到自己想要的进程PID,然后2,tasklist /fi "pid eq 488" 最后打开任务管理器~杀掉就好了


有没有java指令一次就杀掉了?
或者是doc指令?
...全文
870 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
空格键 2016-11-08
  • 打赏
  • 举报
回复
用java 执行这个命令啊
sky_08_06_02 2016-11-08
  • 打赏
  • 举报
回复
小灰狼 2016-11-08
  • 打赏
  • 举报
回复
通过调用 java.lang.Runtime.exec 方法,执行 shell 命令 但是和权限有关
鱼香土豆丝 2016-11-08
  • 打赏
  • 举报
回复
看看这行吗?
鱼香土豆丝 2016-11-08
  • 打赏
  • 举报
回复
package com.hemin.killpro;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class KillPro {

	public static void main(String[] args) {
		String port  = "9999";
		List<String > list = new ArrayList<>();
		String pid=null;
		Runtime run =Runtime.getRuntime();
		Process pro = null;
		//查询端口的pid
		String commend = "cmd /c netstat -ano |findstr "+port;
		try {
			pro = run.exec(commend);
			BufferedReader bf = new BufferedReader(new InputStreamReader(pro.getInputStream()));
			String line = null;
			while((line = bf.readLine())!=null){
				//System.out.println(line);
				list.add(line);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		//判断是否存在指定端口
		if(list.size()==0){
			System.out.println("指定端口没有被使用!");
		}else{
			for (String str : list) {
				String ip = str.split(" +")[2];
				int beg = ip.lastIndexOf(':')+1;
				int end = ip.length();
				String destport = ip.substring(beg, end);
				if(destport.equals(port)){
					System.out.println(str.split(" +")[5]);
					pid = str.split(" +")[5];
					break;
				}
			}
			if(pid ==null){
				System.out.println("没有对应端口没有被使用!");
			}else{
				//kill port
				String  command ="cmd /c taskkill /pid "+port+" /F"; 
				try {
					pro = run.exec(command);
				} catch (IOException e) {
					e.printStackTrace();
				}finally {
					System.out.println("以杀掉占用程序");
				}
			}
		}
			
	}

}
bcsflilong 2016-11-08
  • 打赏
  • 举报
回复
你只能调用java.lang.Runtime.exec 根据返回值做出具体的判断 进而杀掉想杀的进程 但是要根据这个在linux下涉及到权限的问题
鱼香土豆丝 2016-11-08
  • 打赏
  • 举报
回复
没有更好的办法吗?

62,628

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧