Using python how to display dns - python

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()

Related

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)

Python script runs fine from terminal but crashes when run from crontab

I have a simple python script that takes screenshots of a computer that is running Ubuntu. I want it to run automatically on startup, so I put #reboot python3 /bin/program.py in the non-sudo version of crontab.
The program works fine when run from terminal, but gives the error pyscreenshot.err.FailedBackendError. I put it in a try loop, and had it write all exceptions to a file, and that's how I found the error message, "All backends failed."
It has something to do with the program 'pyscreenshot' not working correctly.
import pyscreenshot as screen
import os
from numpy import random
from time import sleep
from os.path import expanduser
TMP_SCREEN_PATH = expanduser('~') + '/.UE/tmp.png'
LOG_FILE_PATH = expanduser('~') + '/.UE/log.txt'
GRAB_DELAY_RANGE = (1, 10)
def screenshot(save_path=TMP_SCREEN_PATH):
img = screen.grab()
img.save(save_path)
def delay(delay_range):
sleep_time = random.randint(delay_range[0], delay_range[1])
print(f"Sleeping for {sleep_time} seconds")
sleep(sleep_time)
def main():
try:
while True:
screenshot()
delay(GRAB_DELAY_RANGE)
except KeyboardInterrupt:
print("Nope")
main()
except Exception as e:
print(e)
with open(LOG_FILE_PATH, 'a') as f:
f.write(str(type(e))+str(e)+'\n')
sleep(5)
main()
f = open(LOG_FILE_PATH, 'w+')
f.write('Startup')
f.close()
main()
I need one of the following solutions:
Simply fix the problem
Another way to run a program at startup
A different module to take screenshots with
Any help is appreciated, thanks
If the user that the cron job runs as is also logged in on the console (you mention a reboot, so I'm guessing that you have enabled autologin), then your cron job might work if you also add:
os.environ["DISPLAY"] = ":0"
This worked for me on Ubuntu in a test using cron and a simplified version of your script:
import os
import pyscreenshot as screen
os.environ["DISPLAY"] = ":0"
img = screen.grab()
img.save("/tmp/test.png")
If it doesn't work for you, then you might also have to try setting the value of the XAUTHORITY environment variable to the value found in the environment of the user's interactive processes, which could be extracted using the psutil package, but let's hope this isn't needed.

how to use netstat -nb in 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!

python - Using a variable as part of a class method/function

I'm sure this is a simple problem, but I'm an amateur so here i am.
Trying to use the obd python library to communicate with my vehicle. I have a bluetooth OBDII adapter and on it's own i can send single commands as outlined in the basic usage section of the readme and get responses.
My problem is that i have a list of commands that i want to send. I'm trying to use a for loop to go through each command and print the responses on screen.
import os
import time
import obd
def clear_Screen():
os.system('cls' if os.name == 'nt' else 'clear')
connection = obd.OBD("COM7")
pids = [ 'RPM' , 'ENGINE_LOAD' , 'COOLANT_TEMP' , 'RUN_TIME' ]
try:
while True:
time.sleep(1)
clear_Screen()
for i in pids:
cmd = "obd.commands." + i
response = connection.query(cmd)
print i , ": " , (response.value)
except KeyboardInterrupt:
exit()
there's a problem with how I'm building the cmd variable because the response i get from each query is that the command isn't supported but i know they are.
if i print cmd instead of trying to use the command.query(cmd) it prints exactly like it would be if i specified it i.e. obd.commands.RPM so I don't understand why this doesn't work.
In your question you stated:
there's a problem with how I'm building the cmd variable
Indeed, in your way, cmd is only a string. So instead if you want the actual evaluated attitude, you should use getattr instead:
cmd = getattr(obd.commands,i)
eval() and exec() are both unsafe so you should never use those.
Try wrapping what you're assigning to cmd in eval():
cmd = eval("obd.commands." + i)

how to provide username and password while checking out the code from SVN using python script without third party module

I am able to write a script to checkout the code from SVN issue using "pysvn" module but just wanted to know is there any way I can do without pysvn also ? Because pysvn is third party library which I have to install separately on linux and windows both which I don't want. Please help me get alternate way in which I don't have to install any third party module code -
import pysvn,os,shutil
def getLogin(realm, username, may_save):
svn_user = '<my-username>'
svn_pass = '<my-password>'
return True, svn_user, svn_pass, False
def ssl_server_trust_prompt( trust_dict ):
return (True # server is trusted
,trust_dict["failures"]
,True) # save the answer so that the callback is not called again
def checkOut(svn_url,dest_dir):
if os.path.isdir(dest_dir):
shutil.rmtree(dest_dir)
os.mkdir(dest_dir)
client = pysvn.Client()
client.callback_ssl_server_trust_prompt = ssl_server_trust_prompt
client.callback_get_login = getLogin
client.checkout(svn_url,dest_dir)
else:
os.mkdir(dest_dir)
client = pysvn.Client()
client.callback_ssl_server_trust_prompt = ssl_server_trust_prompt
client.callback_get_login = getLogin
client.checkout(svn_url,dest_dir)
print "Checking out the code hang on...\n"
checkOut('<svn-repo>','ABC')
print "checked out the code \n"
print "Checking out the code hang on...\n"
checkOut('<svn-repo>','XYZ')
print "checked out the code\n"
print "Checking out the code hang on...\n"
checkOut('<svn-repo>','MNP')
print "checked out the code \n”
You can pass username and password as arguments:
$ svn update --username 'user2' --password 'password'
You can make Executable of ur script which will include the pysvn into binary file, thus wouldn't need to import or pip install any library, n ur code will run on python-less machines too

Categories

Resources