好的,有人能告诉我这个改变时间的简单请求我做错了吗?我正在使用win 7机器,试图改变linux机器上的时间。我可以登录,搜索日志和运行其他命令,当然也可以在下面调整我的代码。但是这个简单的命令并没有改变日期/时间。我一定是在忽视什么?
datetime_string = raw_input("Enter date and time in format 11/1/2011 1600")
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(iP_address, username='root', password='******')
apath = '/'
apattern = datetime_string
rawcommand = 'date -s' + datetime_string
command1 = rawcommand.format(pattern=apattern)
stdin, stdout, stderr = ssh.exec_command(command1)
dateresult = stdout.read().splitlines()
答案 0 :(得分:1)
尝试更改此内容:
rawcommand = 'date -s' + datetime_string
对此:
rawcommand = 'date -s "%s"' % datetime_string
我不是肯定的,但我不认为rawcommand.format(pattern=apattern)
是必要的:
datetime_string = raw_input("Enter date and time in format 11/1/2011 1600")
command1 = 'date -s "%s"' % datetime_string
stdin, stdout, stderr = ssh.exec_command(command1)
dateresult = stdout.read().splitlines()
答案 1 :(得分:1)
您应验证用户输入。特别是如果它可能会被转移到shell中。
#!/usr/bin/env python
from datetime import datetime
import paramiko
# read new date from stdin
datetime_format = "%m/%d/%Y %H%M"
newdate_string = raw_input("Enter date and time in format 11/1/2011 1600")
# validate that newdate string is in datetime_format
newdate = datetime.strptime(newdate_string, datetime_format)
# print date (change it to `-s` to set the date)
command = "date -d '%s'" % newdate.strftime(datetime_format)
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect("localhost") # use ssh keys to authenticate
# run it
stdin, stdout, stderr = ssh.exec_command(command)
stdin.close()
# get output of the command
print
print "stdout: %r" % (stdout.read(),)
print '*'*79
print "stderr: %r" % (stderr.read(),)
$ echo 1/11/2011 1600 | python set-date.py
Enter date and time in format 11/1/2011 1600
stdout: 'Tue Jan 11 16:00:00 EST 2011\n'
*******************************************************************************
stderr: ''