Grzegorz Zych
Grzegorz Zych

Reputation: 31

How to kill script run by another script

I'm working on following script to automate enumeration phase.

I use subprocess to run nmap like this:

subprocess.run(["nmap", "192.168.1.1"])

I want to achive possibility to kill this subprocess and execute rest of code, but when i pick ctrl + c whole script run down.

Upvotes: 1

Views: 77

Answers (3)

David Vu
David Vu

Reputation: 29

this is where you should use subprocess.Popen or subprocess.call rather than subprocess.run

subprocess.call will be a blocking call, which mean it wait until the command finish and then it will move on with your code.

or another way is to put your subprocess.run in an async function and execute it separately

example

import asyncio
async def run_nmap(ip:str):
    subprocess.run(["nmap", ip])

def run_the_thing():
    ...
    loop = asyncio.get_event_loop()
    loop.create_task(run_nmap("192.168.1.1"))
    ...

Upvotes: 0

Mehran Seifalinia
Mehran Seifalinia

Reputation: 92

You can make subprocess in try / except:

try:
    subprocess.run(["nmap", "192.168.1.1"])
except:
    print("Nmap Stopped.")
    pass

When you press CTRL+C an error will be occur and you handle it with except section.

Upvotes: 0

MyTricker
MyTricker

Reputation: 11

Background it by doing :

ctrl+z

Upvotes: 1

Related Questions