how to use netstat -nb in python - python

I want to use netstat -nb in python but every code that i write i get the same msg: "The requested operation requires elevation."
The last code that i try is
import os
output_command = os.popen("netstat -nb").readlines()
and i try also
import subprocess
program_list = subprocess.run(["netstat", "-nb"], stdout=subprocess.PIPE).stdout.decode("utf-8")
program_list = program_list.split("\r\n")

import os
a=os.popen('netstat -nb').read()
print("\n Connections ",a )
try this, it's working!

Related

Running cmd command and printing its output with in python

im using an email lookup module, called holehe (more can be found on it here - https://github.com/megadose/holehe) and i want to make it so when you enter an email it will automatically with in your python console output what came out from the new CMD window, makes it easier for my and colleges to use. How can i go about this? My code it bellow
import holehe
import os
from os import system
import subprocess
email = input("Email:")
p = subprocess.Popen(["start", "cmd", "/k", "holehe", email], shell = True)
p.wait()
input()
Thank you for answers

Check if python script running from another python script linux

I have actualy python script running on background, you can see how it's displayed when i use command "ps -aux" :
root 405 0.0 2.6 34052 25328 ? S 09:52 0:04 python3 -u /opt/flask_server/downlink_server/downlink_manager.py
i want to check if this script are running from another python script, so i try to us psutil module, but it just detect that python3 are running but not my script precisely !
there is my python script :
import os
import psutil
import time
import logging
import sys
for process in psutil.process_iter():
if process.cmdline() == ['python3', '/opt/flask_server/downlink_server/downlink_manager.py']:
print('Process found: exiting.')
It's look like simple, but trust me, i already try other function proposed on another topic, like this :
def find_procs_by_name(name):
"Return a list of processes matching 'name'."
ls = []
for p in psutil.process_iter(attrs=["name", "exe", "cmdline"]):
if name == p.info['name'] or \
p.info['exe'] and os.path.basename(p.info['exe']) == name or \
p.info['cmdline'] and p.info['cmdline'][0] == name:
ls.append(p)
return ls
ls = find_procs_by_name("downlink_manager.py")
But this function didn't fin my script, it's work, when i search python3 but not the name of the script.
Of course i try to put all the path of the script but nothing, can you please hepl me ?
I resolve the issue with this modification :
import psutil
proc_iter = psutil.process_iter(attrs=["pid", "name", "cmdline"])
process = any("/opt/flask_server/downlink_server/downlink_manager.py" in p.info["cmdline"] for p in proc_iter)
print(process)

Using python how to display dns

Using Python, is there a way using psutil or something else to return the output of "ipconfig /displaydns" or something similar?
Spawning a cmd process and running the command is not an option.
To execute a command, you can use the os library. Executing the command you've shown above is as simple as:
import os
os.system('ipconfig /displaydns')
If you want to store the output of a command in a variable, you can use:
x = os.popen('ipconfig /displaydns')
You can try using dnspython's resolver class, which has a nameservers list attached to it.
import dns.resolver
resolver = dns.resolver.Resolver()
resolver.nameservers
# Returns ['8.8.8.8', '8.8.4.4', '8.8.8.8'] on my pc
This python script I made creates a directory in widows user profile and copies windows dns information into a log.txt,So if directory does not exist it will create it. Hope it works for you.
#!/usr/bin/env python3
import time
import os
def dns():
path = os.system("ipconfig /displaydns >> %USERPROFILE%\DNS\logdns.txt")
if path == False:
os.system("ipconfig /displaydns >> %USERPROFILE%\DNS\logdns.txt")
print("Please wait copying information........")
time.sleep(5 )
os.system("cls")
print("Information copy complete.")
time.sleep(3)
else:
print("Making directory please wait a second....")
time.sleep(5)
os.system("cls")
os.system("mkdir %USERPROFILE%\DNS")
time.sleep(1)
dns()
dns()

python os.system from input nor working

#!/usr/bin/env python
import os
import subprocess
mail=raw_input("")
os.system("mail" + mail + "<<<test")
When I run this program I`ve got error :sh: 1: Syntax error: redirection unexpected.
The script must send mail using mailutilis
Don't use os.system. Replace it with subprocess.Popen:
address = raw_input()
with open('test') as text:
subprocess.Popen(["mail", address], stdin=text).wait()

Python - How to find UUID of computer and set as variable

I have been looking all over the internet for a way to find a way to get UUID for a computer and set it as a variable in python.
Some of the ways I tried doing didn't work.
Original idea:
import os
x = os.system("wmic diskdrive get serialnumber")
print(x)
However this does not work, and only returns 0.
I am wondering if their is a way i can find a unique Harddrive ID or any other type of identifier in python.
The os.system function returns the exit code of the executed command, not the standard output of it.
According to Python official documentation:
On Unix, the return value is the exit status of the process encoded in the format specified for wait().
On Windows, the return value is that returned by the system shell
after running command.
To get the output as you want, the recommended approach is to use some of the functions defined in the subprocess module. Your scenario is pretty simple, so subprocess.check_output works just fine for it.
You just need to replace the code you posted code with this instead:
import subprocess
x = subprocess.check_output('wmic csproduct get UUID')
print(x)
If the aim is to get the serial number of the HDD, then one can do:
In Linux (replace /dev/sda with the block disk identifier for which you want the info):
>>> import os
>>> os.popen("hdparm -I /dev/sda | grep 'Serial Number'").read().split()[-1]
In Windows:
>>> import os
>>> os.popen("wmic diskdrive get serialnumber").read().split()[-1]
for windows i do work with this one and it works perfectly:
import subprocess
UUID = str(subprocess.check_output('wmic csproduct get UUID'),'utf-8').split('\n')[1].strip()
print(UUID)
For windows:
import wmi
import os
def get_serial_number_of_system_physical_disk():
c = wmi.WMI()
logical_disk = c.Win32_LogicalDisk(Caption=os.getenv("SystemDrive"))[0]
partition = logical_disk.associators()[1]
physical_disc = partition.associators()[0]
return physical_disc.SerialNumber
For Linux try this:
def get_uuid():
dmidecode = subprocess.Popen(['dmidecode'],
stdout=subprocess.PIPE,
bufsize=1,
universal_newlines=True
)
while True:
line = dmidecode.stdout.readline()
if "UUID:" in str(line):
uuid = str(line).split("UUID:", 1)[1].split()[0]
return uuid
if not line:
break
my_uuid = get_uuid()
print("My ID:", my_uuid)

Categories

Resources