Unable to edit hosts file with python - python

I am trying to write a python script which can block websites based on the time of the day but i am not able to edit the hosts file in windows even running the cmd as an administrator.
Here's the Code:
import time
from datetime import datetime as dt
hosts_location=r"C:\Windows\System32\drivers\etc\hosts"
hosts_temp="hosts"
blocked_websites=['www.facebook.com','facebook.com']
redirect="127.0.0.1"
while True:
if dt(dt.now().year,dt.now().month,dt.now().day,8) < dt.now() <
dt(dt.now().year,dt.now().month,dt.now().day,17):
with open(hosts_location,"r+") as file:
content=file.read()
for website in blocked_websites:
if website in content:
pass
else:
file.write(redirect+"\t"+website+"\n")
print("Working Hours....")
else:
with open(hosts_location,"r+") as file:
content=file.readlines()
file.seek(0)
for line in content:
if not any(website in line for website in blocked_websites):
file.write(line)
file.truncate()
print("Fun Time...")
time.sleep(5)
Update:The code is working fine for a local hosts file but when i try it for the real hosts file even as administrator the script just flashes and with cmd shows message "[Errno 13]:Permission Denied".
Also i am not able to edit hosts even with notepad even as adminstrator my os is windows 10 home edition 64-bit.

First of all,
If you are not an administrator, change permissions of the hosts file by right clicking--> Properties --> Security and allow Read/Write/Execute Permissions for Users.
Then open Command Prompt as administrator and run the script. It will work!

try to save the python file as a .pyw extension
This will work for you.

Go to the hosts file and uncheck "read only" then go to security tab and give the permissions to user to read and write. Hope it'll work.

You should change access to file from users.
Go to C:\Windows\System32\drivers\etc and click right on properties, choose security and edit access to file.

Just change the path to be:
hosts_location = "C:\\Windows\\System32\\drivers\\etc\\hosts"
without r", and it will work

Related

"cannot create temp dir for user data dir" error when not running as admin

I'm just able to run my python selenium code when I run it as admin. If I run it normally I get following error:
C:\startup>Python C:/startup/startupWebDriverScript.py
Traceback (most recent call last):
File "C:/startup/startupWebDriverScript.py", line 26, in connectGuest
driver = webdriver.Chrome(chrome_options=chromeOptions,executable_path="C:/Python36/Chrome Webdriver/chromedriver.exe")
File "C:\Python36\lib\site-packages\selenium\webdriver\chrome\webdriver.py", line 69, in __init__
desired_capabilities=desired_capabilities)
File "C:\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 140, in __init__
self.start_session(desired_capabilities, browser_profile)
File "C:\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 229, in start_session
response = self.execute(Command.NEW_SESSION, parameters)
File "C:\Python36\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 297, in execute
self.error_handler.check_response(response)
File "C:\Python36\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 194, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot create temp dir for user data dir
(Driver info: chromedriver=2.32.498550 (9dec58e66c31bcc53a9ce3c7226f0c1c5810906a),platform=Windows NT 10.0.15063 x86_64)
This is my code:
chromeOptions = Options()
chromeOptions.add_argument("--use-fake-ui-for-media-stream")
chromeOptions.add_argument("--kiosk")
chromeOptions.add_argument("--disable-notifications")
chromeOptions.add_argument("--disable-infobars")
driver = webdriver.Chrome(chrome_options=chromeOptions,executable_path="C:/Python36/Chrome Webdriver/chromedriver.exe")
I'm using python 3.6, Windows 10 and selenium 3.5
I got the same error and nothing described before helped me.
I fixed the problem such a way:
Enter echo %temp% in Windows' command-line
It returned C:\TEMP\2 (Why???)
So I created this folder and after that everything started to work
Based upon my experience, It is possible you have one of following situations.
Either your disk is getting full, thus don't have enough free disks-pace. Try emptying your recycle bin or check for excessively generated temp files and clear those.
Or you have installed packages using admin privileges and hence your script doesn't have proper privileges to execute.
TMP environment variable may need modifications.
right click on computer and then click on properties -> advanced system settings -> environment variables ->
"User variables for " and change the TEMP and TMP vars values to "c:\temp".
Quick solution:
Go to the path C:\Users\Administrator\AppData\Local\Temp, and create a new folder. Rename this new folder to 2
This creates the %temp% folder that was missing.
After trying a lot of different approaches I decided to downgrade the Chrome web driver and it started to work out fine.
Ironically, the same error message can be see on when using on Windows 10 with ChromDriver 2.37 / Chrome 65. My test code was running from within Eclipse instance. To resolve, I had to start Eclipse As an Administrator and everything worked as it should.
I got the same error and I deleted all files in C:\Users\user\AppData\Local\Temp.
After that everything worked.
Move the Temp folder to C:\Windows\Temp\
Update your Temp/TMP in System variables
If you're using a batch file, run it as administrator
The answers above helped a little, but all of them are only temporary solutions. Why echo %tmp% returns C:\Users\ADMINI~1\AppData\Local\Temp\2? It is because for each session Windows creates a separate temp directory.
It is needed to prevent do it by changing 2 keys in Group Policy:
Search/open for 'Edit Group Policy'
Find and enable next keys in the folder
Administrative Templates > Windows Components > Remote Desktop Services > Remote Desktop Session Host > Temporary folders
Do not delete temp folders upon exit
Do not use temporary folders per session
I suppose you can try to change appropriate registry keys instead (not tested):
SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services\DeleteTempDirsOnExit
SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services\PerSessionTempDir
Restart server.
After server is restarted echo %tmp% will always return C:\Users\ADMINI~1\AppData\Local\Temp and the issue will never return for Chrome driver (fixed 10 servers using this way).
The source is here: https://admx.help/?Category=Windows_10_2016&Policy=Microsoft.Policies.TerminalServer::TS_TEMP_PER_SESSION
go to this dir:
C:\Users
open your user name like: "m.rahimi" and then continue to this directory:
\AppData\Local\Temp
create a new folder and name it: "2"
everything got ok
Run as Admin. It solved the problem for me.

os.walk works from console but not from cgi-bin

When I run this os.walk code from my PyScripter IDE, it works just fine. The os.walk was able to traverse the remote unix path and print the directory and file names.
However, when I run this same script from the cgi-bin of my Apache server, I get no os.walk (path, dirs, files) output. I also don't get any error messages recorded in the Apache error.log file.
Note: Python and my cgi-bin are on the same Windows machine, and the remote_path is on Unix.
Why does this same code work from the console but not from the cgi-bin and what can I do to resolve this?
#!C:\Python27\python.exe -u
import os
print "Content-type: text/html\n\n";
print "<html><head>"
print "<font size=+2><B>os.walk test</B></font><br><br>";
# Remote path
remote_path = r'\\unix_server\path\2015\q1\files\na\canada'
i = 0
for (path, dirs, files) in os.walk(remote_path):
print "Path", path
print "<BR><BR>Dirs", dirs
print "<BR><BR>Files", files
i += 1
if i >= 1:
break
Thanks to kindall, I found out the problem was indeed that Apache didn't have the appropriate permissions.
To solve the issue, I did the following (Windows 7 OS):
Opened services.msc. Start -> Run -> "services.msc"
Located my Apache service in the list "Apache2". Double click it.
In the Properties dialog for the Apache2 service, switch to the "Log On" tab. The radio button for "Local System account" was checked. I switched it to "This account" and clicked Browse.
In the "Enter object name to select" text box, I entered the name of my network + backslash + my user name. For example NETWORK\username. Clicked OK.
Then on the Log On tab, I saw that my full network email address was populated. I entered my password and password confirmation and clicked Apply.
The final steps were to stop the Apache2 service and then restart the service. Once that was done, the problem was solved and my script started working from the cgi-bin. :)

How do I write remote machine Path in askopenfilename

I am writing a program in python on Ubuntu, to remove a file from remote machine(raspberrypi) by accessing it, connected with network.
For file selection I am using a command called askopenfilename.
But I am struggling in specifying the Path of RaspberryPi correctly.
Can you please guide me on how do I specify Raspberrypi path correctly?
IP = "192.168.2.34"
Username = "pi"
Password ="raspberry"
Path="/home/pi/python"
Below is my code
from tkFileDialog import askopenfilename
import paramiko
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('192.168.2.34', username='pi', password='raspberry')
checkdir = "/home/pi/python"
name1= askopenfilename(title = "Select File For Removal", initialdir = checkdir)
stdin, stdout, stderr = client.exec_command('ls -l')
for line in stdout:
print '... ' + line.strip('\n')
client.close()
I am fairly sure the tk file dialog is only able to browse the Ubuntu machine (which it seems to run on) filesystem - not the RPi filesystem over SSH, so you will never see RPi directories.
if You can read the RPi directory listing there, so you could create your own file browser component or try to find an existing one that works over SSH.
Then again it looks like you are 'inventing the wheel again' (which of course is ok for learning purposes) - gFTP, FileZilla, many of the Linux desktop file browsers etc. (or WinSCP if you were using a Windows box) are ready made tools for this.

How to get linux screen title from command line

How can I fetch the title of a screen session from the command line?
I came up with a very small and simple python script with pexpect to do it.
It is handy in multiuser environments where some host is reserved and status is written to screen title by user.
It works for me, feel free to make it better.
In order to fetch specific session title, you need to modify the script and call for correct session.
If you run this through remote connection as local script (through SSH for example), remember to set export TERM=xterm before execution.
try:
import pexpect
import sys
child=pexpect.spawn('screen -x')
child.sendcontrol('a');
child.send('A');
i = child.expect('Set window.*')
child.sendcontrol('c');
child.sendcontrol('a');
child.send('d');
TITLE=str(child.after)
TITLE_P=TITLE.split('7m')
if str(TITLE_P[-1]) == '':
print 'Title not found'
else:
print str(TITLE_P[-1])
except:
print 'Could not check screen Title'

Python - How do you run a .py file?

I've looked all around Google and its archives. There are several good articles, but none seem to help me out. So I thought I'd come here for a more specific answer.
The Objective: I want to run this code on a website to get all the picture files at once. It'll save a lot of pointing and clicking.
I've got Python 2.3.5 on a Windows 7 x64 machine. It's installed in C:\Python23.
How do I get this script to "go", so to speak?
=====================================
WOW. 35k views. Seeing as how this is top result on Google, here's a useful link I found over the years:
http://learnpythonthehardway.org/book/ex1.html
For setup, see exercise 0.
=====================================
FYI: I've got zero experience with Python. Any advice would be appreciated.
As requested, here's the code I'm using:
"""
dumpimages.py
Downloads all the images on the supplied URL, and saves them to the
specified output file ("/test/" by default)
Usage:
python dumpimages.py http://example.com/ [output]
"""
from BeautifulSoup import BeautifulSoup as bs
import urlparse
from urllib2 import urlopen
from urllib import urlretrieve
import os
import sys
def main(url, out_folder="C:\asdf\"):
"""Downloads all the images at 'url' to /test/"""
soup = bs(urlopen(url))
parsed = list(urlparse.urlparse(url))
for image in soup.findAll("img"):
print "Image: %(src)s" % image
filename = image["src"].split("/")[-1]
parsed[2] = image["src"]
outpath = os.path.join(out_folder, filename)
if image["src"].lower().startswith("http"):
urlretrieve(image["src"], outpath)
else:
urlretrieve(urlparse.urlunparse(parsed), outpath)
def _usage():
print "usage: python dumpimages.py http://example.com [outpath]"
if __name__ == "__main__":
url = sys.argv[-1]
out_folder = "/test/"
if not url.lower().startswith("http"):
out_folder = sys.argv[-1]
url = sys.argv[-2]
if not url.lower().startswith("http"):
_usage()
sys.exit(-1)
main(url, out_folder)
On windows platform, you have 2 choices:
In a command line terminal, type
c:\python23\python xxxx.py
Open the python editor IDLE from the menu, and open xxxx.py, then press F5 to run it.
For your posted code, the error is at this line:
def main(url, out_folder="C:\asdf\"):
It should be:
def main(url, out_folder="C:\\asdf\\"):
Usually you can double click the .py file in Windows explorer to run it. If this doesn't work, you can create a batch file in the same directory with the following contents:
C:\python23\python YOURSCRIPTNAME.py
Then double click that batch file. Or, you can simply run that line in the command prompt while your working directory is the location of your script.
Since you seem to be on windows you can do this so python <filename.py>. Check that python's bin folder is in your PATH, or you can do c:\python23\bin\python <filename.py>. Python is an interpretive language and so you need the interpretor to run your file, much like you need java runtime to run a jar file.
use IDLE Editor {You may already have it} it has interactive shell for python and it will show you execution and result.
Your command should include the url parameter as stated in the script usage comments.
The main function has 2 parameters, url and out (which is set to a default value)
C:\python23\python "C:\PathToYourScript\SCRIPT.py" http://yoururl.com "C:\OptionalOutput\"
If you want to run .py files in Windows, Try installing Git bash
Then download python(Required Version) from python.org and install in the main c drive folder
For me, its :
"C:\Python38"
then open Git Bash and go to the respective folder where your .py file is stored :
For me, its :
File Location : "Downloads"
File Name : Train.py
So i changed my Current working Directory From "C:/User/(username)/" to "C:/User/(username)/Downloads"
then i will run the below command
" /c/Python38/python Train.py "
and it will run successfully.
But if it give the below error :
from sklearn.model_selection import train_test_split
ModuleNotFoundError: No module named 'sklearn'
Then Do not panic :
and use this command :
" /c/Python38/Scripts/pip install sklearn "
and after it has installed sklearn go back and run the previous command :
" /c/Python38/python Train.py "
and it will run successfully.
!!!!HAPPY LEARNING !!!!

Categories