Permission denied to access r”C:\Windows\System32\Drivers\etc\hosts” - python

so I have a problem trying to run this python code as administrator so I am not able to access and write on host file. Can anyone help me? I have looked through many of other questions but non of them seem to work.
Host File Directory: C:\Windows\System32\Drivers\etc\hosts
(Such as)
Request UAC elevation from within a Python script?
Some of these answers actually work on prompting to get administrator access, but it still doesn't give permission to my program. The only way I figured out is to run python shell as administrator first and then run the code or run the command prompt as administrator and open python file with command prompt.
WEBSITE
https://boostlog.io/#faisalnad/create-a-website-blocker-with-python-5afe86ff47018500491f4898
This program is made for blocking website.
import time
from datetime import datetime as dt
# change hosts path according to your OS
hosts_path = r”C:\Windows\System32\Drivers\etc\hosts”
# localhost's IP
redirect = "127.0.0.1"
# websites That you want to block
website_list = ["www.facebook.com","facebook.com",
"dub119.mail.live.com","www.dub119.mail.live.com",
"www.gmail.com","gmail.com"]
while True:
# time of your work
if dt(dt.now().year, dt.now().month, dt.now().day,8) < dt.now() < dt(dt.now().year, dt.now().month, dt.now().day,16):
print("Working hours...")
with open(hosts_path, 'r+') as file:
content = file.read()
for website in website_list:
if website in content:
pass
else:
# mapping hostnames to your localhost IP address
file.write(redirect + " " + website + "\n")
else:
with open(hosts_path, 'r+') as file:
content=file.readlines()
file.seek(0)
for line in content:
if not any(website in line for website in website_list):
file.write(line)
# removing hostnmes from host file
file.truncate()
print("Fun hours...")
time.sleep(5)
This is the error:
Working hours...
Traceback (most recent call last):
File "C:\Users\Key\Desktop\random project.py", line 19, in <module>
with open(hosts_path, 'r+') as file:
PermissionError: [Errno 13] Permission denied: 'C:\\Windows\\System32\\Drivers\\etc\\hosts'
FILE DIRECTORY

You can add write permission for the user under which your program runs following this link to add permission to the host file

Related

How to edit text file in server using python

I want to edit a line in a text file in a Linux server using python. The process involves following steps
Telnet to the server (using telnetlib)
Go to the required directory
open the text file in the directory
set or unset the flag (YES or NO) of the variable in the text file based on the requirement
save the file and exit
I'm able to automate until step 2. However, I'm stuck at step 3 through 5.
I tried to mimic the steps I follow manually (using vim editor). But I'm not able to perform the 'ESC', replace and ':wq!' steps. Is there an alternative procedure to edit the file or any ways to improve upon mimicking the manual process
I have added my code here
host = input("Enter the IP address:")
port = input("Enter the port:")
tn = telnetlib.Telnet(host,port)
tn.write(b'\n')
tn.read_until(b"login:")
tn.write(b"admin" + b'\n')
tn.read_until(b"Password:")
tn.write(b"admin" + b'\n')
tn.write(b"version" + b'\n')
tn.write(b"path/to/file/" + b'\n')
# OPEN THE FILE and SET or RESET THE FLAG and CLOSE
with in_place.InPlace('filename.txt') as file:
for line in file:
line = line.replace('line_to_change', 'changed_data')
file.write(line)
print('Task executed')
I tried using the in-place library to set the flag but the programme is looking for the file in my local machine rather in the server. So it throws an error message indicating that the file is not present.
If you are able to connect to your remote server, the rest should work as follows:
with open('path/to/file','r') as fr:
data = fr.readlines() # returns list of lines
changed_data = ["changed_data\n" if line=="line_to_change\n" else line
for line in data]
with open('path/to/file','w') as fw:
for line in changed_data:
fw.write(line) # write the lines back to the back

Python script to tail a log file

I am trying to tail a log file on a remote server using a Python script. The log file rolls over very fast, I am using the python-sshtail module to tail the log file and capture the output of the tail in a file on my local machine. I was able to capture the log file and save it to a file on my local machine but the my script seems to be writing it twice and data is formatted.
The script is working but not the way I want it to, I should be able to run the script, perform some actions on the servers, tail the logs, save the output to a file on my local machine and kill the script using CTRL-C.
I did write some code and it does work but not the way it should. For now I am using time.sleep to wait for the output to be written to the output file on my local machine.
#!/usr/bin/python3
import time
import sshtail.tailers as t
import sys
import datetime
username = "username"
logfile = "/var/log/file.log"
k = t.paramiko.RSAKey.from_private_key_file('keyfile')
conn = t.SSHTailer(username,logfile, k, verbose=True)
try:
conn.connect()
print(f"Connected to {conn.host}")
print("Tailing the file..")
except:
print("Connection unsuccesful...")
conn.tail()
for line in conn.tail():
print(line)
for line in conn.get_new_lines():
print(line)
x = conn.remote_file_size
print(f"The file size is: {x}")
time.sleep(10)
output_file = str(conn.host)+"_"+str(datetime.datetime.now().strftime("%Y-%m-%d_%H:%M:%S"))+".txt"
with open(output_file, "a") as f:
for line in conn.get_new_lines():
print(line)
f.write(line)
conn.disconnect()
I recommend replacing time.sleep with asyncio.sleep

Removing files using python from a server using FTP

I’m having a hard time with this simple script. It’s giving me an error of file or directory not found but the file is there. Script below I’ve masked user and pass plus FTP site
Here is my script
from ftplib import FTP
ftp = FTP('ftp.domain.ca')
pas = str('PASSWORD')
ftp.login(user = 'user', passwd=pas)
ftp.cwd('/public_html/')
filepaths = open('errorstest.csv', 'rb')
for j in filepaths:
    print(j)
    ftp.delete(str(j))
ftp.quit()
The funny thing tho is if I slight change the script to have ftp.delete() it finds the file and deletes it. So modified to be like this:
from ftplib import FTP
ftp = FTP('ftp.domain.ca')
pas = str('PASSWORD')
ftp.login(user = 'user', passwd=pas)
ftp.cwd('/public_html/')
ftp.delete(<file path>)
ftp.quit()
I’m trying to read this from a csv file. What am I doing wrong?
Whatever you have showed seems to be fine. But could you try this?
from ftplib import FTP
ftp = FTP(host)
ftp.login(username, password)
ftp.cwd('/public_html/')
print(ftp.pwd())
print(ftp.nlst())
with open('errorstest.csv') as file:
for line in file:
if line.strip():
ftp.delete(line.strip())
print(ftp.nlst())

Why GeoIP showing error in log analysis?

I have this GeoIP address code and when I run this code, it shows error that there is no module named GeoIP. This is my code :
import sys
import GeoIP
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
with open ('Desktop/trail.txt', 'r') as f:
for line_string in f.readlines():
line = line_string.rstrip()
arr = line.split()
try:
country_code = gi.country_code_by_addr(arr[0])
country_name = "\"" + gi.country_name_by_addr(arr[0]) + "\""
arr.append(country_code)
arr.append(country_name)
except:
arr.append("None")
print ",".join(arr)
This is the error :
line 4, in
gi = GeoIP.new(GeoIP.GEOIP_MEMORY_CACHE)
GeoIP.error: [Errno 2] No such file or directory: '/usr/local/var/GeoIP/GeoIP.dat'
You forgot to add GeoIP.dat database which is your code using to get information
download it from the official release Here
Scroll down to GeoLite Country and choose Download
Move the downloaded file "GeoIP.dat.gz" to /usr/local/var/GeoIP/
Extract it by right click and select Extract HereOr by the following command: gunzip GeoIP.dat.gz
Then will appear a file named GeoIP.dat leave it in this path
Now you have the database file in path /usr/local/var/GeoIP/GeoIP.dat
try to compile again and let me know if still in problem.

Cannot access file on Samba server via Python

I'm trying to access a file on our Samba server using Python. I found out I need to use a Samba client for this, so I started using PySmbClient. Even though there are many examples online of how to do this, mine just does not want to work. See below.
smb = smbclient.SambaClient(server="192.168.0.320", share="DATA", domain="WORKGROUP",username="admin", password="abc123")
f = smb.open('test.json', 'r')
This produces the following error:
OSError: [Errno 2] No such file or directory
with the following trace:
Traceback (most recent call last):
File "create_dataset.py", line 35, in <module>
f = smb.open('serverSaver.txt', 'r')
File "/home/grant/Development/create_dataset/env/local/lib/python2.7/site-packages/smbclient.py", line 408, in open
f = _SambaFile(self, path, mode)
File "/home/grant/Development/create_dataset/env/local/lib/python2.7/site-packages/smbclient.py", line 448, in __init__
connection.download(remote_name, self._tmp_name)
File "/home/grant/Development/create_dataset/env/local/lib/python2.7/site-packages/smbclient.py", line 393, in download
result = self._runcmd('get', remote_path, local_path)
File "/home/grant/Development/create_dataset/env/local/lib/python2.7/site-packages/smbclient.py", line 184, in _runcmd
return self._raw_runcmd(fullcmd)
File "/home/grant/Development/create_dataset/env/local/lib/python2.7/site-packages/smbclient.py", line 168, in _raw_runcmd
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
raise child_exception
I've read and implemented many "solutions", but so far nothing has worked for me. I can access the Samba server with the given credentials through my file manager just fine, so I know those values should be fine. I even spoke to our sys admin and he doesn't know what could be wrong.
It must be more than the simple code I wrote. Do you think there's an issue on the server side of things? Something with the values I input into SambaClient? At this point I'm pretty much open to anything that leads to a solution.
Here's some code that works for me, transferring a file from a Linux Samba share to my Windows laptop. It's also known to work fine in the other direction (Linux client, Windows server).
I'm using the pysmb library version 1.1.19 (the latest) and Python 2.7.1.
See the pysmb site for the pysmb package; I actually downloaded and installed it directly from its tarball and setup.py, as pip was throwing an error.
The pysmb package is less user-friendly but it does work well for Windows clients.
I set up a share called "my_share" on the Linux machine for user "edwards" using the following entry in smb.conf:
[my_share]
path = /home/edwards
valid_users = edwards
read only = no
guest ok = yes
browseable = yes
And then used the following code to list the files on the share, and download a file called "rti_license.dat" to my laptop:
import tempfile
import smb
import shutil
from smb.SMBConnection import SMBConnection
share_name = "my_share"
user_name = "edwards"
password = "######" # secret :-)
local_machine_name = "laptop" # arbitrary
server_machine_name = "edwards-Yocto" # MUST match correctly
server_IP = "192.162.2.1" # as must this
# create and establish connection
conn = SMBConnection(user_name, password, local_machine_name, server_machine_name, use_ntlm_v2 = True)
assert conn.connect(server_IP, 139)
# print list of files at the root of the share
files = conn.listPath(share_name, "/")
for item in files:
print item.filename
# check if the file we want is there
sf = conn.getAttributes(share_name, "rti_license.dat")
print sf.file_size
print sf.filename
# create a temporary file for the transfer
file_obj = tempfile.NamedTemporaryFile(mode='w+t', delete=False)
file_name = file_obj.name
file_attributes, copysize = conn.retrieveFile(share_name, "rti_license.dat", file_obj)
print copysize
file_obj.close()
# copy temporary file
shutil.copy(file_name, "rti_license.dat")
# close connection
conn.close()
Note that the server name must be correct or the connection won't work (from a Linux machine it's the output of the hostname command)
Hope this may be useful.

Categories

Resources