1

I tried using date command to change the system time in debian linux:

os.system("echo passwd | "sudo date -s \"Thu Aug 9 21:31:26 UTC 2012\")

and I set the python file permission to 777 and also chown as root. But it does not work and says date: cannot set date: Operation not permitted. Any Ideas?

Thanks

Saeed Vrz
  • 147
  • 1
  • 3
  • 10
  • It did not give me any problems (I executed it normally). Try running .py with sudo. In my case, permissions are == -rw-r--r-- – pnv Mar 30 '15 at 14:11
  • Your quoting is wrong, try: os.system("echo passwd | 'sudo date -s \"Thu Aug 9 21:31:26 UTC 2012\"'") – cdarke Mar 30 '15 at 14:12
  • @cdarke, when I use sudo it works. But I want to run it without writing sudo. – Saeed Vrz Mar 30 '15 at 14:15
  • That isn't what your question asks, and that is nothing to do with Python. – cdarke Mar 30 '15 at 14:34

2 Answers2

3

Sudo doesn't take password from stdin, but from the terminal device.

Add your date to the sudoers file so you can run it as root without a password. man sudoers.

bob     ALL = NOPASSWD: /bin/date

Next, use subprocess instead of os.system.

sudodate = subprocess.Popen(["sudo", "date", "-s", "Thu Aug  9 21:31:26 UTC 2012"])
sudodate.communicate()
Chad Miller
  • 1,435
  • 8
  • 11
  • You can [pass the password to `sudo` via stdin if you must](http://stackoverflow.com/a/23692520/4279) but updating `sudoers` (creating `/etc/sudoers.d/date`) is a better option in most cases. Don't use `.communicate()` unless some of the standard streams are redirected (using `PIPE`). Use `subprocess.check_call()` instead. To hide the output of a subprocess, see [this question](http://stackoverflow.com/q/11269575/4279) – jfs Mar 31 '15 at 08:35
  • @ChadMiller, Thanks for your comment. I learned a lot ;), However before I see your comment, I tried making another python file and I addressed `os.system("echo passwd | sudo -S python file.py")` and run without `sudo`. It worked 0_o . Isn't it a little bit strange?! – Saeed Vrz Mar 31 '15 at 16:05
  • Note: even with **NOPASSWD**, you still must use **SUDO** in front of command – Timothy L.J. Stewart Jul 07 '22 at 14:15
1

You did a lower case -s it is meant to be -S so that is why it isn't working.