avatar

RWO.cc

读一次写一次

  • 首页
  • 搭建手册
  • 笔记
  • 短视频
  • 关于
  • 🌈200粉丝🌈
Home python批量kill进程
文章

python批量kill进程

Posted 2024-05-13 Updated 2024-05- 13
By RWO.
10~13 min read

连接到 Linux 系统并执行命令的 Python 程序可以使用 paramiko 库来实现。以下是一个示例程序,用于连接到 Linux 系统,并执行 lsof -i:80 命令来获取进程号并杀死相关进程:

import paramiko

def connect_to_linux_system(hostname, username, password):
    # 创建 SSH 客户端
    client = paramiko.SSHClient()
    
    # 自动添加和保存 SSH 服务器的主机密钥
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    try:
        # 连接到 Linux 系统
        client.connect(hostname, username=username, password=password)
        print("成功连接到 Linux 系统")
        
        # 执行命令
        stdin, stdout, stderr = client.exec_command("lsof -i:80")
        
        # 获取命令输出
        output = stdout.read().decode()
        print(output)
        
        # 关闭 SSH 连接
        client.close()
        
        # 解析输出以获取进程号
        process_id = parse_process_id(output)
        
        if process_id is not None:
            # 杀死进程
            kill_process(process_id)
    except Exception as e:
        print(f"连接失败:{e}")
        client.close()

def parse_process_id(output):
    # 在命令输出中查找进程号
    # 这里你可能需要根据你的 lsof 命令输出的格式进行解析
    # 这只是一个示例实现
    lines = output.split('\n')
    for line in lines:
        if 'LISTEN' in line:
            process_info = line.split()
            return process_info[1]  # 返回第二列的进程号
    return None

def kill_process(process_id):
    # 创建 SSH 客户端
    client = paramiko.SSHClient()
    
    # 自动添加和保存 SSH 服务器的主机密钥
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    try:
        # 连接到 Linux 系统
        client.connect(hostname, username=username, password=password)
        
        # 执行杀死进程的命令
        command = f"kill {process_id}"
        stdin, stdout, stderr = client.exec_command(command)
        
        # 获取命令输出
        output = stdout.read().decode()
        print(output)
        
        # 关闭 SSH 连接
        client.close()
    except Exception as e:
        print(f"连接失败:{e}")
        client.close()

# 输入 Linux 系统的主机名、用户名和密码
hostname = input("请输入 Linux 系统的主机名:")
username = input("请输入用户名:")
password = input("请输入密码:")

# 连接到 Linux 系统并执行相关操作
connect_to_linux_system(hostname, username, password)

把命令也封装成参数,并支持支持多行命令:

import paramiko

def connect_to_linux_system(hostname, username, password, commands):
    # 创建 SSH 客户端
    client = paramiko.SSHClient()
    
    # 自动添加和保存 SSH 服务器的主机密钥
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    
    try:
        # 连接到 Linux 系统
        client.connect(hostname, username=username, password=password)
        print("成功连接到 Linux 系统")
        
        # 执行命令
        for command in commands:
            stdin, stdout, stderr = client.exec_command(command)
            
            # 获取命令输出
            output = stdout.read().decode()
            print(output)
            
        # 关闭 SSH 连接
        client.close()
        
    except Exception as e:
        print(f"连接失败:{e}")
        client.close()

# 输入 Linux 系统的主机名、用户名和密码
hostname = input("请输入 Linux 系统的主机名:")
username = input("请输入用户名:")
password = input("请输入密码:")

# 输入要执行的命令,以空行结束输入
print("请输入要执行的命令,以空行结束输入:")
commands = []
while True:
    command = input()
    if command:
        commands.append(command)
    else:
        break

# 连接到 Linux 系统并执行相关操作
connect_to_linux_system(hostname, username, password, commands)

File is not open for reading:

在运行程序时,你需要按照以下步骤操作:

  1. 输入 Linux 系统的主机名、用户名和密码。
  2. 输入包含命令的文件的路径(例如:/path/to/commands.txt)。
  3. 程序将会尝试打开该文件,并读取其中的命令。
  4. 连接到 Linux 系统并执行读取到的命令。

请确保提供正确的文件路径,并确保程序有权限读取该文件。如果问题仍然存在,请检查文件路径和文件访问权限。

import paramiko

def connect_to_linux_system(hostname, username, password, commands):
    # 创建 SSH 客户端
    client = paramiko.SSHClient()

    # 自动添加和保存 SSH 服务器的主机密钥
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 连接到 Linux 系统
        client.connect(hostname, username=username, password=password)
        print("成功连接到 Linux 系统")

        # 执行命令
        for command in commands:
            stdin, stdout, stderr = client.exec_command(command)

            # 获取命令输出
            output = stdout.read().decode()
            print(output)

        # 关闭 SSH 连接
        client.close()

    except Exception as e:
        print(f"连接失败:{e}")
        client.close()

# 输入 Linux 系统的主机名、用户名和密码
hostname = input("请输入 Linux 系统的主机名:")
username = input("请输入用户名:")
password = input("请输入密码:")

# 输入包含命令的文件路径
file_path = input("请输入包含命令的文件路径:")

try:
    # 从文件中读取命令
    with open(file_path, 'r') as file:
        commands = file.readlines()
        commands = [command.strip() for command in commands if command.strip()]
except Exception as e:
    print(f"读取文件失败:{e}")
    exit()

# 连接到 Linux 系统并执行相关操作
connect_to_linux_system(hostname, username, password, commands)

笔记
学习 服务器 Python
License:  CC BY 4.0
Share

Further Reading

Oct 29, 2024

halo代码注入——实现悬浮展示当前文章二维码 和 自定义主题字体

文章页面悬浮在二维码标志上面,就会把当前页面链接变成二维码并且展示出来,我当前使用的主题没有,所以写此文章记录一下。 效果展示 悬浮二维码效果展示 自定义字体效果展示 代码注入位置 代码一:悬浮二维码 原始<

Aug 26, 2024

Tortoise ORM - values()和value_list()

django: values()与values_list() from django.db import models class Blog(models.Model): name = models.CharField(max_length=100) tagline = model

Aug 25, 2024

tortoise orm 执行原生 SQL 查询

Tortoise ORM 提供了多种方式来执行 SQL 查询。 使用 execute_query_dict 方法执行查询,并以字典的形式返回查询结果: from tortoise.backends.asyncpg import client from typing import List, Opti

OLDER

私有镜像仓库使用教程

NEWER

docker run 参数详解

Recently Updated

  • 什么是 python 的闭包
  • 使用argparse模块解析命令行参数
  • Python中的二维码生成与解析(花里胡哨)
  • Python中的二维码生成与解析(基础使用)
  • 使用platform模块获取系统信息

Trending Tags

学习 Git 工具 SQL docker-compose 每日一点 快捷键 Flink fastapi Windows

Contents

©2025 RWO.cc. Some rights reserved.

Using the Halo theme Chirpy