Saeed Vrz Saeed Vrz - 6 months ago 104
Linux Question

change date/time using python in linux

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

Answer

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()
Comments