I am trying to get only the PID by running this python script.
My current error:
Select string is not recognized as an internal or external command
To deal with this error, I thought that I needed to escape | by adding ^ --> But apparently it doesn't work
I added in some \ to escape ", hopefully it's correct?
cmd = "netstat -ano | findstr " + str(o)
print (cmd)
cmd += " | Select-String \"TCP\s+(.+)\:(.+)\s+(.+)\:(\d+)\s+(\w+)\s+(\d+)\" | ForEach-Object { Write-Output $_.matches[0].Groups[6].value }"
print (cmd)
pid = run_command(cmd)
The run_command method does this:
def run_command(cmd_array,os_name='posix'):
p = subprocess.Popen(cmd_array,shell=True,cwd=os.getcwd())
output,err = p.communicate()
print('output=%s'%output)
print('err=%s'%err)
return output
Expected Result
When I run solely the command in command prompt, it gives me the PID --> which is 7556 in this case.
Not too sure why it is not working for the script but working in command prompt by itself.
This question is specific to windows OS
Answer to my own question
With help from the comments, i did not use my run_command method since it was using shell = True.
shell = True refers to cmd.exe on Windows, not powershell.
The commands i have written are powershell commands.
Directly use subprocess.call to run powershell commands
Python scripts
cmd = "netstat -ano | findstr 8080"
cmd += " | Select-String \"TCP\s+(.+)\:(.+)\s+(.+)\:(\d+)\s+(\w+)\s+(\d+)\" | ForEach-Object { Write-Output $_.matches[0].Groups[6].value }"
subprocess.call(["powershell.exe", cmd])
#this does the job but the code will print extra zeros along with PID. It was not what i was looking for.
Result:
6492 (Prints out the PID Along with some additional zeros)
What worked for me - For those who are trying to get only PID and kill port using PID in python script
cmd = "for /f \"tokens=5\" %a in ('netstat -aon ^| find \":8080"
cmd += "\" ^| find \"LISTENING\"\') do taskkill /f /pid %a"
#I added in some \ to escape the "
run_command(cmd)
Result:
SUCCESS: The process with PID 2072 has been terminated
Related
I'm having an issue running a simple python script that reads a helm command from a .sh script and outputs it.
When I run the command directly in the terminal, it runs fine:
helm list | grep prod- | cut -f5
# OUTPUT: prod-L2.0.3.258
But when I run python test.py (see below for whole source code of test.py), I get an error as if the command I'm running is helm list -f5 and not helm list | grep prod- | cut -f5:
user#node1:$ python test.py
# OUTPUT:
# Opening file 'helm_chart_version.sh' for reading...
# Running command 'helm list | grep prod- | cut -f5'...
# Error: unknown shorthand flag: 'f' in -f5
The test.py script:
import subprocess
# Open file for reading
file = "helm_chart_version.sh"
print("Opening file '" + file + "' for reading...")
bashCommand = ""
with open (file) as fh:
next(fh)
bashCommand = next(fh)
print("Running command '" + bashCommand + "'...")
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
if error is None:
print output
else:
print error
Contents of helm_chart_version.sh:
cat helm_chart_version.sh
# OUTPUT:
## !/bin/bash
## helm list | grep prod- | cut -f5
Try to avoid running complex shell pipelines from higher-level languages. Given the command you show, you can run helm list as a subprocess, and then do the post-processing on it in Python.
process = subprocess.run(["helm", "list"], capture_output=True, text=True, check=True)
for line in process.stdout.splitlines():
if 'prod-' not in line:
continue
words = line.split()
print(words[4])
The actual Python script you show doesn't seem to be semantically different from just directly running the shell script. You can use the sh -x option or the shell set -x command to cause it to print out each line as it executes.
I am trying to run the following awk command inside python but I get a syntax error related to the quotes:
import subprocess
COMMAND = "df /dev/sda1 | awk /'NR==2 {sub("%","",$5); if ($5 >= 80) {printf "Warning! Space usage is %d%%", $5}}"
subprocess.call(COMMAND, shell=True)
I tried to escape the quotes but I am still getting the same error.
You may want to put ''' or """ around the string since you have both ' and ".
import subprocess
COMMAND = '''"df /dev/sda1 | awk /'NR==2 {sub("%","",$5); if ($5 >= 80) {printf "Warning! Space usage is %d%%", $5}}"'''
subprocess.call(COMMAND, shell=True)
There also seems to be a relevant answer already for this as well: awk commands within python script
Try this:
import subprocess
COMMAND="df /dev/sda1 | awk 'NR==2 {sub(\"%\",\"\",$5); if ($5 >= 80) {printf \"Warning! Space usage is %d%%\", $5}}'"
subprocess.Popen(COMMAND,stdin=subprocess.PIPE,stdout=subprocess.PIPE, shell=True).stdout.read()
I was writing a python script for my deployment purpose and one part of the script was to explicitely kill the process if its not stopped successfully.
Below is the python code which actually performs
Find the processId of the process named myApplication
ps -ef | grep myApplication | grep -v grep | awk {'print $2'}
and then perform
kill -9 PID //where PID is output of earlier command
import subprocess
import signal
def killApplicationProcessIfStillRunning(app_name):
p1 = subprocess.Popen(['ps', '-ef'], stdout=subprocess.PIPE)
p2 = subprocess.Popen(['grep', app_name],stdin=p1.stdout, stdout=subprocess.PIPE)
p3 = subprocess.Popen(['grep', '-v' , 'grep'],stdin=p2.stdout, stdout=subprocess.PIPE)
p4 = subprocess.Popen(['awk', '{print $2}'],stdin=p3.stdout, stdout=subprocess.PIPE)
out, err = p4.communicate()
if out:
print 'Attempting to kill '+app_name +' process with PID ' +out.splitlines()[0]
os.kill(int(out.splitlines()[0]),signal.SIGKILL)
Now invoke the above method as
killApplicationProcessIfStillRunning(myApplication)
Hope it helps someone.
I'm trying to run Python file with root access with php index
in php there is :
passthru('python /home/register/register.py '. $_POST['username'] . ' example.com ' . $_POST['password'] . ' ' . $_POST['email'] . ' ' . $ip . ' 1 2>&1');
and in Python file there is:
os.popen("sudo -u root -p password /sbin/ejabberdctl register %s %s %s" % (user,domain,password)).read()
is there any command with Python to login with root user then do command like : ls or mkdir
thnx.
from subprocess import PIPE,Popen
p = Popen(["sudo", "-s", "-S"], stdin=PIPE, stdout=PIPE, universal_newlines=True)
p.stdin.write("password\n")
p.stdin.write("mkdir foo\n")
p.stdin.write("id -u")
To see output use communicate:
from subprocess import PIPE,Popen
p = Popen(["sudo", "-s", "-S"], stdin=PIPE, stdout=PIPE, universal_newlines=True)
p.stdin.write("password\n")
p.stdin.write("ls -la\n")
p.stdin.write("/usr/bin/pip list\n")
p.stdin.write("id -u")
print(p.communicate()[0])
But be very sure you know what commands you are running.
I recently published a project that allows PHP to obtain and interact with a real Bash shell (as user: apache/www-data or root if needed). Get it here: https://github.com/merlinthemagic/MTS
After downloading you would simply use the following code:
//Setting the second argument in getShell():
//true will return a shell with root
//false will return a shell with the php execution user
$shell = \MTS\Factories::getDevices()->getLocalHost()->getShell('bash', true);
$return1 = $shell->exeCmd("mkdir -p /some/path");
$return2 = $shell->exeCmd("ls --color=none /some/path");
notice the ls command has a switch called --color=none, that is needed because the bash shell will return color information as odd chars, the switch prevents it.
This question already has answers here:
AppleScript: how to get the current directory of the topmost Terminal
(3 answers)
Closed 8 years ago.
Is there a way in Python, subprocessing Bash and/or AppleScript, for me to get the current working directory of the frontmost Terminal.app tab and window in OSX?
I've tried the solution in AppleScript: how to get the current directory of the topmost Terminal. It doesn't work in my script.
I use Python to run AppleScript through the following function:
def run(script):
"Returns the result of running string in osascript (Applescript)"
if hasattr(script, "encode"): #Assumes Python 3
script = script.encode("utf-8")
osa = Popen(["osascript", "-"], stdout=PIPE, stdin=PIPE, stderr=PIPE)
results, err = osa.communicate(script)
if err:
raise Exception(err)
return results.decode("utf-8")
I have tried using the suggested answer through the following call:
def getTerminalDir():
script = '''
tell application "Terminal"
do shell script "lsof -a -p `lsof -a -c bash -u $USER -d 0 -n | tail -n +2 | awk '{if($NF==\"" & (tty of front tab of front window) & "\"){print $2}}'` -d cwd -n | tail -n +2 | awk '{print $NF}'"
end tell
'''
result = run(script)
return result
When I do that, I get the following error:
Exception: 126:127: syntax error: Expected end of line but found “"”. (-2741)
You can try something like:
tell application "Terminal"
if not (exists window 1) then reopen
activate
do script "pwd" in selected tab of window 1
set tabContents to contents of selected tab of window 1
end tell
set myPath to paragraph -2 of (do shell script "grep . <<< " & quoted form of tabContents)
Got it. Thanks for the useful AppleScript insights that helped lead to this solution, Zero.
from subprocess import Popen, PIPE, check_output, STDOUT
def runAppleScript(script):
"Returns the result of running string in osascript (Applescript)"
if hasattr(script, "encode"): #Assumes Python 3
script = script.encode("utf-8")
osa = Popen(["osascript", "-"], stdout=PIPE, stdin=PIPE, stderr=PIPE)
results, err = osa.communicate(script)
if err:
raise Exception(err)
return results.decode("utf-8")
def runBash(command):
output = check_output(command, stderr=STDOUT, shell=True)
return output
def getCurrentTerminalTTYS():
script = '''
tell application "Terminal"
return (tty of selected tab of front window)
end tell
'''
result = runAppleScript(script)
return result.strip()
def getPathForTTYS(ttys):
lsof = runBash('lsof').split('\n')
process = None
for line in lsof:
if ttys in line:
process = line.split()[1]
break
path = None
for line in lsof:
if 'cwd' in line and process in line:
path = ' '.join(line.split()[8:])
break
return path
def getCurrentTerminalPath():
ttys = getCurrentTerminalTTYS()
return getPathForTTYS(ttys)
This can be stored as a string using
path = getCurrentTerminalPath()
I'm having an issue with subprocess.Popen and what I believe to be pipes. I have the following block of code which works without issue 100% of the time when running from the cli:
p = subprocess.Popen("psexec \\\\" + serverName.get() + " cmd /c \
ver & \
echo %USERDOMAIN% & \
dir /a C:\pagefile.sys | find \"pagefile.sys\" & \
dir C:\ | find \"bytes free\" & \
dir D:\ | find \"bytes free\" ", \
stdin=None, stdout=subprocess.PIPE, stderr=None)
### Assign the results from the Popen
results = p.communicate()[0]
rc = p.returncode
print 'results: ' + str(results)
sys.exit()
Output:
PsExec v1.90 - Execute processes remotely
Copyright (C) 2001-2007 Mark Russinovich
Sysinternals - www.sysinternals.com
The device is not ready.
cmd exited on XXXXXXX with error code 1.
Microsoft Windows XP [Version 5.1.2600]
PROD
02/23/2011 09:37 AM 1,610,612,736 pagefile.sys
49 Dir(s) 17,104,437,248 bytes free
I had this program complete, but once I compiled it with py2exe, it would just hang or crash. I tracked that issue down to py2exe not liking undefined stdin, out, or err in subprocess. I then modified my code as follows:
p = subprocess.Popen("psexec \\\\" + serverName.get() + " cmd /c \
ver & \
echo %USERDOMAIN% & \
dir /a C:\pagefile.sys | find \"pagefile.sys\" & \
dir C:\ | find \"bytes free\" & \
dir D:\ | find \"bytes free\" ", \
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
p.stdin.close()
### Assign the results from the Popen
results = p.communicate()[0]
rc = p.returncode
print 'results: ' + str(results)
sys.exit()
This code works 100% of the time as well, but when I print results, it only shows me the standard psexec messages, not the output of the commands executed.
Output:
results:
PsExec v1.90 - Execute processes remotely
Copyright (C) 2001-2007 Mark Russinovich
Sysinternals - www.sysinternals.com
cmd exited on XXXXXXX with error code 1.
I tried to combat this by adding shell=true to the subprocess options, but when I do that the program just hangs 99% of the time. It will actually run 1% of the time . I noticed that while the program is hanging, if I go into task manager and manually kill the psexec process, the desired output is shown. This is driving me crazy and I've been searching forever without finding anything. The code is running on WinXP python v2.7. Please let me know if you have any questions or need any additional information.
Hanging Code:
p = subprocess.Popen("psexec \\\\" + serverName.get() + " cmd /c \
ver & \
echo %USERDOMAIN% & \
dir /a C:\pagefile.sys | find \"pagefile.sys\" & \
dir C:\ | find \"bytes free\" & \
dir D:\ | find \"bytes free\" ", \
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True)
p.stdin.close()
### Assign the results from the Popen
results = p.communicate()[0]
rc = p.returncode
print 'results:' + str(results)
sys.exit()
Desired output after killing psexec.exe from task manager:
results:
PsExec v1.90 - Execute processes remotely
Copyright (C) 2001-2007 Mark Russinovich
Sysinternals - www.sysinternals.com
PROD
02/23/2011 09:37 AM 1,610,612,736 pagefile.sys
49 Dir(s) 17,102,487,552 bytes free
The device is not ready.
[This should be a comment, but I don't have the rep to leave comments]
I've heard of a lot of problems with subprocess.PIPE. Try making stdin, stdout, and stderr all point to temporary files. Then you can use p.wait() instead of communicate(). Does that seem to work correctly?
I've seen this problem a once:
Redirecting traffic to temporary files seems a working solution - the problem is the additional code needed to access the process output - but it is a stable solution. The problem is the additional code needed to get to the process output (if you want to display it while it is running - if not, it's just dumping a file)
You could also check fabric's local implementations - I haven't run psexec with it, but all other processes worked fine (except for the fact it does not provide a timeout mechanism)
try running the psexec with -i
it works for me
p = subprocess.Popen("psexec " "-i " . . .