12 Replies - 7161 Views - Last Post: 22 December 2010 - 01:40 PM Rate Topic: -----

#1 LinuxFan  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 26
  • View blog
  • Posts: 82
  • Joined: 19-December 10

Python and administrative/superuser rights

Posted 20 December 2010 - 09:05 PM

Hey everyone, I'm writing a script to manage the 'hosts' file on windows/linux, and I need to determine a way to platform-independently detect whether or not the user is running the python script as administrator/superuser.

The hosts file (search wikipedia if you aren't familiar with it) is only able to be written to by the system administrator/superuser(s).

At the moment I'm using a try/except block and just catching the IOError (Permission Denied, iirc) the write throws when you try to write to the hosts file, but it'd be great to be able to tell the user that s/he needs to run the script as administrator/superuser before the script prompts for domains to add.

I searched bing for a solution, but kept ending up with results for VB.NET, Ruby, and a few other languages :angry:

As it is, it runs fine - no crashes or bugs that I'm aware of, but it'd be neat to tell the user to run the script as administrtor/superuser *before* prompting for input :unsure:

Thanks!

Is This A Good Question/Topic? 1
  • +

Replies To: Python and administrative/superuser rights

#2 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: Python and administrative/superuser rights

Posted 20 December 2010 - 09:26 PM

That's a new one on me. This resource discusses how to do it using the pywin32 library. However, you want it to be platform independent. One approach is to code it for Mac, Windows, Linux (and coming soon, CHROMEOS!!), and then do an os check at the beginning to determine which of the three styles to use... perhaps not the most elegant solution.

Another potential approach (AND PROBABLY FAR MORE ELEGANT) is to try to append some whitespace to the end of the HOSTS file. If you can, you're good to go, right? Then you can just read the data from the hosts file into a string, trim it, and you have the whitespace removed. I'm extremely tired as I'm writing this, so I can't guarantee my ideas are any good right now!

P.S. Oh the hosts file... I remember learning about it in college... and playing the meanest joke ever on my roommate when I knew he was going home to visit his parents...

This post has been edited by atraub: 20 December 2010 - 09:27 PM

Was This Post Helpful? 1
  • +
  • -

#3 LinuxFan  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 26
  • View blog
  • Posts: 82
  • Joined: 19-December 10

Re: Python and administrative/superuser rights

Posted 20 December 2010 - 09:53 PM

That is a great idea, I have no idea how I missed it! Probably because I was looking for something like a function to return a True/False value whether the script was ran as administrator/superuser, but your idea would work.

Still, if anyone happens to know of any platform-independent APIs that detect administrator/superuser rights, I'm open to more ideas! In the meantime, I'll use atraub's idea of writing whitespace to the hosts file.

Thanks, atraub!
Was This Post Helpful? 0
  • +
  • -

#4 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5901
  • View blog
  • Posts: 12,805
  • Joined: 16-October 07

Re: Python and administrative/superuser rights

Posted 21 December 2010 - 05:31 AM

I'll expand on the above.

Make a class for the system specific operations. Then you can just do something like:
import platform

hostParser = None

if platform.system()=='Windows':
	hostParser = HostParserWin()
else:
	hostParser = HostParserNix()



A slightly more elegant solution would be to import the one you need and alias it:
if platform.system()=='Windows':
	import HostWin as host
else:
	import HostNix as host

# ...
hostParser = host.parser()



Making a separate file for each OS makes things much easier to organize.
Was This Post Helpful? 2
  • +
  • -

#5 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: Python and administrative/superuser rights

Posted 21 December 2010 - 07:07 AM

With fresh eyes and baavgai's support, I feel more confident about both approaches. The first approach is good if you can foresee other times where you'll need to check admin rights. After all, once you code it, it's yours forever. The whitespace approach is a nice 'quick and dirty' way to get past the problem so you can move forward with your software.

Glad I could help ya out!
Was This Post Helpful? 0
  • +
  • -

#6 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1253
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Re: Python and administrative/superuser rights

Posted 22 December 2010 - 09:13 AM

The best approach would be to code specifically for each OS, then use aliases like baavgai suggested. Cleaner code and you set it and forget it.
Was This Post Helpful? 0
  • +
  • -

#7 LinuxFan  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 26
  • View blog
  • Posts: 82
  • Joined: 19-December 10

Re: Python and administrative/superuser rights

Posted 22 December 2010 - 12:46 PM

Thank you atraub, I ended up using this as a solution:

def isAdmin():
    hostsFileBackup = file(HostsFile).read()
    try:
        file = open(HostsFile, 'w')
        file.write(hostsFileBackup)
        file.close()
        return True
    except IOError, e:
        return False



It accomplishes what atraub said, but without needing to trim extra whitespace (which could wind up screwing the hosts file if I'm not careful).

Thanks also to baavgai, I've been having trouble figuring out how to reliably detect the OS, and when I finally get back here to ask about it, it's solved! :D

I'm not sure I should waste the time writing two classes for each operating system, as the format of the hosts file is the same on both Windows and linux, the only difference would be the path to the hosts file... ('C:\Windows\System32\drivers\etc\hosts' on windows, '/etc/hosts' on linux)

I'll probably end up setting the hosts file variable on the init method of the HostsManager class based on platform.system(), something along the lines of:

import platform
class HostsManager(object):
    def __init__(self):
        if platform.system() == "Windows":
            self.hostsFile = "C:\Windows\System32\drivers\etc\hosts"
        else:
            self.hostsFile = "/etc/hosts"
#....



Anyway, thanks many times over to atraub and baavgai :D

P.S.:
I don't think I mentioned this, but I intend to use this as a library.
I want to add a GUI to it after I perfect the actual adding of hosts so that when (and if) I distribute it, people aren't puzzling at how to use it at the command-line...
I haven't yet added any GUI libraries to my Python installation yet, any recommendations on Tkinter vs wxPython vs PyQt4? I'm thinking about Tkinter, as it comes standard with windows, but seems to be complicated to install on linux (need to compile it myself :unsure:)
Was This Post Helpful? 0
  • +
  • -

#8 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: Python and administrative/superuser rights

Posted 22 December 2010 - 12:54 PM

In the long run baag's approach is better than the first one I suggested. One benefit is that it'll be easier to extend the module to add additional functionality if you ever need to.

Your idea to have the hosts file overwrite itself is clever, I like it. It's better than the whitespace idea I had and probably a little safer too.

As for the the GUI aspect, I'd like to quote my man Dogstopper when he said:

Quote

For most applications, Tkinter should be just fine. However, wxWidgets is nice for its extendibility.

Was This Post Helpful? 1
  • +
  • -

#9 LinuxFan  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 26
  • View blog
  • Posts: 82
  • Joined: 19-December 10

Re: Python and administrative/superuser rights

Posted 22 December 2010 - 01:08 PM

Quote

In the long run baag's approach is better than the first one I suggested. One benefit is that it'll be easier to extend the module to add additional functionality if you ever need to.

Alright then, that's what I'll do.

Quote

Your idea to have the hosts file overwrite itself is clever, I like it. It's better than the whitespace idea I had and probably a little safer too.

Thanks! :)

Anyway, one last question: What's the most graceful way of basically saying, 'You don't have admin rights' when you create the HostsManager object? Raise a custom error like NotAdminError?
Was This Post Helpful? 0
  • +
  • -

#10 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: Python and administrative/superuser rights

Posted 22 December 2010 - 01:17 PM

I'll give you my personal opinion. Surely someone will disagree with me though :)

If your script is meant to be a stand-alone command line program, I'd do something like:
#Assuming we're using py3
input("Must be Admin/Super User to continue.  Please re-run application with higher permissions.  Press enter to escape")
sys.exit(x) #where x would be a non 0 value which would represent a user-permission error



If it's meant to be a module used by other programs, then I'd raise an exception. That way, the program utilizing your module can decide how to handle it. By making each part only handle specific roles, you're enforcing modular design.

If you're building a GUI, you could keep the GUI and your module seperate. In that case, I'd have it raise an exception and make your GUI handle the exception appropriately. Perhaps by making a little popup window say, "Must be admin to continue. Please restart application as admin".

This post has been edited by atraub: 22 December 2010 - 01:22 PM

Was This Post Helpful? 1
  • +
  • -

#11 LinuxFan  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 26
  • View blog
  • Posts: 82
  • Joined: 19-December 10

Re: Python and administrative/superuser rights

Posted 22 December 2010 - 01:26 PM

Quote

If it's meant to be a module used by other programs, ...

It is.

Quote

...then I'd raise an exception. That way, the program utilizing your module can decide how to handle it.

If you're building a GUI, you could keep the GUI and your module seperate. *snip*

That's actually what I was thinking, I just wanted to be sure I wasn't out of my mind when I had that thought :)

Thanks a lot!

P.S.:
When I finish it, I plan to paste the code on something like paste.pocoo.org and link to it here so that I can show off the hosts manager :D (and possibly get suggestions for improvements)

This post has been edited by LinuxFan: 22 December 2010 - 01:30 PM

Was This Post Helpful? 0
  • +
  • -

#12 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: Python and administrative/superuser rights

Posted 22 December 2010 - 01:30 PM

It's good that you're practicing modularity. I've seen some people build some horrendously long programs that are a pain to debug.
Was This Post Helpful? 0
  • +
  • -

#13 LinuxFan  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 26
  • View blog
  • Posts: 82
  • Joined: 19-December 10

Re: Python and administrative/superuser rights

Posted 22 December 2010 - 01:40 PM

Well, I started with programming Java... It teaches modularity out the wazoo :P

And as for the 'horrendously long programs that are a pain to debug', that's how I write my programs! :eek: After they begin to work though, I piece them into functions, then continue writing the script.

Anyway, thanks!

This post has been edited by LinuxFan: 22 December 2010 - 01:47 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1