簡體   English   中英

以管理員身份運行python文件

[英]Run python file as admin

我正在嘗試創建一個程序,要求任何網站的用戶鏈接阻止它(在主機中)

import requests
print('Time to block some websites')
ask = input('> Give me the link... ') ; link = {} # Ask user
try:
    r = requests.get(ask) # Try the url 
    print('Protocol : ' , r.url [:r.url.find(":")]) # Check protocol of the url
    url = r.url 
    print('your url : ' , url)
except:
    raise ValueError('Give the url with https/http', ask)

url = url.split('/') ; urlist = list(url) # Split url 
link.update({'linko': urlist[2]}) ; link.update({'host': '127.0.0.1 '}) # Add host and url to link
x = link['linko'] ; y = link['host'] # Transform value of dict in string
z = str(y+x) # Assign host and link

f = open('hosts', 'a') # Open document in append mode
f.write(z) ; f.write('\n') # Write z and newline for future use
f.close() # Always close after use

f = open('hosts' , 'r') # Open document in read mode
print(f.read()) # Read document
f.close() # Always close after use

追溯 :

  File "C:\Windows\System32\drivers\etc\block.py", line 17, in <module>
    f = open('hosts', 'a') # Open document in append mode
PermissionError: [Errno 13] Permission denied: 'hosts'

當我嘗試使用 runas 管理員執行程序時:

RUNAS ERROR: Unable to run - C:\Windows\System32\drivers\etc\block.py
193: C:\Windows\System32\drivers\etc\block.py is not a valid Win32 application. 

如何讓程序獲得向主機添加站點的權限?

感謝您的回答,我找到了一個“手動”解決方案:

以管理員身份運行 cmd.exe 然后移動到 C:\\Windows\\System32\\drivers\\etc 並執行 block.py 命令提示符:


C:\Windows\system32>cd drivers

C:\Windows\System32\drivers>cd etc

C:\Windows\System32\drivers\etc>python block.py
Time to block some websites
> Give me the link... https://stackoverflow.com/questions/64506935/run-python-file-as-admin
Protocol :  https
https://stackoverflow.com/questions/64506935/run-python-file-as-admin
# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#       127.0.0.1       localhost
#       ::1             localhost
127.0.0.1 stackoverflow.com

C:\Windows\System32\drivers\etc>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM