使用Python(Paramiko模块)在Unix服务器上设置日期/时间

2 投票
2 回答
1473 浏览
提问于 2025-04-17 05:22

好的,有人能告诉我我在这个简单的时间更改请求中做错了什么吗?我在一台Windows 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()

2 个回答

1

你应该对用户输入进行验证。特别是当这些输入可能未经处理就传递给系统命令行的时候。

#!/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: ''
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()

撰写回答