Using powershell as Admin in python - python

So I have a project I'm working on, and one thing I need to do is to run in the background the "netstat -nb" command at the PowerShell as admin and recive the results to the python program.
I've been searching the web for a solution but never found one efficient out there. I'd be glad for some help.
"netstat -nb"

If you want to execute the netstat command you can do so from Python directly.But you need to be running Python script as a Admin:
import subprocess
subprocess.call("netstat -nb")
If you need to access the powershell netstat values inside the Python script then you can set variable in powershell and pass it to Python script.
Following is the powershell command:
$con=netstat -nb
& python.exe "FullPath of Python script file"-p $con
Python script:
import sys
print(sys.argv[5])
for conn in sys.argv:
print(conn)
Here we are looping the parameters passed (netstat output) and displaying.So you are passing powershell command result to Python script and displaying it there.
Following columns would be displayed:

You can use subprocess library. About subprocess module you can check this documentation for more detail and features. It helps you to solve your problem. You can use subprocess.Popen or subprocess.call or to get output from another script you can use subprocess.check_output.
You can use it like this piece of code:
import subprocess
import sys
output = subprocess.Popen(['python','sample.py','Hello'],stdout=subprocess.PIPE).communicate()
print(output)
Inside of the sample.py script is:
import sys
my_message = "This is desired output. " + sys.argv[1]
print(my_message)
In your case you can use Popen as:
subprocess.Popen(['netstat','-nb'],stdout=subprocess.PIPE).communicate()

Related

Pip3 gives me error message `import: command not found` [duplicate]

I am running a (bio)python script which results in the following error:
from: can't read /var/mail/Bio
seeing as my script doesn't have anything to with mail, I don't understand why my script is looking in /var/mail.
What seems to be the problem here? i doubt it will help as the script doesn't seem to be the problem, but here's my script anyway:
from Bio import SeqIO
from Bio.SeqUtils import ProtParam
handle = open("examplefasta.fasta")
for record in SeqIO.parse(handle, "fasta"):
seq = str(record.seq)
X = ProtParam.ProteinAnalysis(seq)
print X.count_amino_acids()
print X.get_amino_acids_percent()
print X.molecular_weight()
print X.aromaticity()
print X.instability_index()
print X.flexibility()
print X.isoelectric_point()
print X.secondary_structure_fraction()
what is the problem here? bad python setup? I really don't think it's the script.
No, it's not the script, it's the fact that your script is not executed by Python at all. If your script is stored in a file named script.py, you have to execute it as python script.py, otherwise the default shell will execute it and it will bail out at the from keyword. (Incidentally, from is the name of a command line utility which prints names of those who have sent mail to the given username, so that's why it tries to access the mailboxes).
Another possibility is to add the following line to the top of the script:
#!/usr/bin/env python
This will instruct your shell to execute the script via python instead of trying to interpret it on its own.
I ran into a similar error when trying to run a command.
After reading the answer by Tamás,
I realized I was not trying this command in Python but in the shell (this can happen to those new to Linux).
Solution was to first enter in the Python shell with the command python
and when you get these >>>
then run any Python commands.
Same here. I had this error when running an import command from terminal without activating python3 shell through manage.py in a django project (yes, I am a newbie yet). As one must expect, activating shell allowed the command to be interpreted correctly.
./manage.py shell
and only then
>>> from django.contrib.sites.models import Site
Put this at the top of your .py file (for Python 2.x)
#!/usr/bin/env python
or for Python 3.x
#!/usr/bin/env python3
This should look up the Python environment. Without it, it will execute the code as if it were not Python code, but shell code. If you need to specify a manual location of the Python environment, put
#!/#path/#to/#python
for Mac OS just go to applications and just run these Scripts Install Certificates.command and Update Shell Profile.command, now it will work.
For Flask users, before writing the commands, first make sure you enter the Flask shell using:
flask shell

automated python script via vm

I'm new in a company for IT and very few people here know Python so I can't ask then for help.
The problem: I need to create a script in Python that connects via ssh from my VM to my client server, after I access with my script I need to find a log file and search for a few data.
I tested my script within my Windows with a copy of that file and it searched everything that I need. However, I don't know how to do that connection via SSH.
I tried like this but I don't know where to start:
from subprocess import Popen, PIPE
import sys
ssh = subprocess.check_output(['ssh', 'my_server', 'password'], shell = True)
ssh.stdin.write("cd /path/")
ssh.stdin.write("cat file | grep err|error")
This generates a error "name 'subprocess' is not defined".
I don't understand how to use the subprocess nor how to begin to develop the solution.
Note: I can't use Paramiko because I don't have permission to install packages via pip or download the package manually.
You didn't import subprocess itself so you can't refer to it.
check_output simply runs a process and waits for it to finish, so you can't use that to run a process you want to interact with. But there is nothing interactive here, so let's use that actually.
The first argument to subprocess.Popen() and friends is either a string for the shell to parse, with shell=True; or a list of token passed directly to exec with no shell involved. (On some platforms, passing a list of tokens with shell=True actually happens to work, but this is coincidental, and could change in a future version of Python.)
ssh myhost password will try to run the command password on myhost so that's not what you want. Probably you should simply set things up for passwordless SSH in the first place.
... But you can use this syntax to run the commands in one go; just pass the shell commands to ssh as a string.
from subprocess import check_output
#import sys # Remove unused import
result = check_output(['ssh', 'my_server',
# Fix quoting and Useless Use of Cat, and pointless cd
"grep 'err|error' /path/file"])

Getting the current shell type from python script

My script sets some environment varrible, to be used by the Makefiles, so since every shell, bash(export to set varriable) and tcsh(setenv), I need to get the correct shell type, from where we have run the python, I have tried using $SHELL varrriable, but it always given me sh as my shell.
Is there a way, I can get the right shell type from a python script or will it always output "SH" as the $SHELL variable.
Sorry to bring this back from the dead but I just did this myself.
The following should give you the path to your current shell:
from os import environ
print(environ['SHELL'])
You should be able to replace shell with any environment variable you're looking for.
For the case that a user has launched a shell of a different type from their login shell, and then invoked your Python script in that shell, you need to look at the executable used to run your script's parent process:
import os
os.path.realpath(f'/proc/{os.getppid()}/exe')
use shellingham like below
import shellingham
try:
shell = shellingham.detect_shell()
except shellingham.ShellDetectionFailure:
shell = provide_default()
the shell will return you a tuple with two params and you can read your shell name with shell[0]

Getting Python error "from: can't read /var/mail/Bio"

I am running a (bio)python script which results in the following error:
from: can't read /var/mail/Bio
seeing as my script doesn't have anything to with mail, I don't understand why my script is looking in /var/mail.
What seems to be the problem here? i doubt it will help as the script doesn't seem to be the problem, but here's my script anyway:
from Bio import SeqIO
from Bio.SeqUtils import ProtParam
handle = open("examplefasta.fasta")
for record in SeqIO.parse(handle, "fasta"):
seq = str(record.seq)
X = ProtParam.ProteinAnalysis(seq)
print X.count_amino_acids()
print X.get_amino_acids_percent()
print X.molecular_weight()
print X.aromaticity()
print X.instability_index()
print X.flexibility()
print X.isoelectric_point()
print X.secondary_structure_fraction()
what is the problem here? bad python setup? I really don't think it's the script.
No, it's not the script, it's the fact that your script is not executed by Python at all. If your script is stored in a file named script.py, you have to execute it as python script.py, otherwise the default shell will execute it and it will bail out at the from keyword. (Incidentally, from is the name of a command line utility which prints names of those who have sent mail to the given username, so that's why it tries to access the mailboxes).
Another possibility is to add the following line to the top of the script:
#!/usr/bin/env python
This will instruct your shell to execute the script via python instead of trying to interpret it on its own.
I ran into a similar error when trying to run a command.
After reading the answer by Tamás,
I realized I was not trying this command in Python but in the shell (this can happen to those new to Linux).
Solution was to first enter in the Python shell with the command python
and when you get these >>>
then run any Python commands.
Same here. I had this error when running an import command from terminal without activating python3 shell through manage.py in a django project (yes, I am a newbie yet). As one must expect, activating shell allowed the command to be interpreted correctly.
./manage.py shell
and only then
>>> from django.contrib.sites.models import Site
Put this at the top of your .py file (for Python 2.x)
#!/usr/bin/env python
or for Python 3.x
#!/usr/bin/env python3
This should look up the Python environment. Without it, it will execute the code as if it were not Python code, but shell code. If you need to specify a manual location of the Python environment, put
#!/#path/#to/#python
for Mac OS just go to applications and just run these Scripts Install Certificates.command and Update Shell Profile.command, now it will work.
For Flask users, before writing the commands, first make sure you enter the Flask shell using:
flask shell

Is there a possibility to execute a Python script while being in interactive mode

Normally you can execute a Python script for example: python myscript.py, but if you are in the interactive mode, how is it possible to execute a Python script on the filesystem?
>>> exec(File) ???
It should be possible to execute the script more than one time.
Use execfile('script.py') but it only work on python 2.x, if you are using 3.0 try exec(open('script.py').read())
import file without the .py extension will do it, however __name__ will not be "__main__" so if the script does any checks to see if it's being run interactively you'll need to bypass them.
Alternately, if you're wanting to have a look at the environment after the script runs try python -i script.py
EDIT: To load it again
file = reload(file)
You might want to look into IPython, a more powerful interactive shell. It has various "magic" commands including %run script.py (which, of course, runs the script and leaves any variables it defined for you to examine).
You can also use the subprocess module. Something like:
>>> import subprocess
>>> proc = subprocess.Popen(['./script.py'])
>>> proc.communicate()
You can run any system command using python:
>>>from subprocess import Popen
>>>Popen("python myscript.py", shell=True)
The easiest way to do it is to use the os module:
import os
os.system('python script.py')
In fact os.system('cmd') to run shell commands. Hope it will be enough.

Categories

Resources