我想远程取得另一个电脑系统时间 并与我本地系统时间比较 怎样写呢
可以取得本地系统时间 但其它电脑时间怎样取得 已经有其它电脑ip
sytiem = time.strftime("%Y-%m-%d %I:%M:%S %p", localtime)
怎样通过ip 进入远程电脑并执行下面
subprocess.Popen('echo %date:6,4%%date:3,2%%date:~0,2% %time%',)
可以试试ntplib
import ntplib
def get_remote_time(ip):
try:
client = ntplib.NTPClient()
response = client.request(ip, version=3)
remote_time = response.tx_time
return remote_time
except ntplib.NTPException as e:
print("Failed to retrieve remote time:", str(e))
return None
要远程获取另一台计算机的系统时间,你可以使用 Python 的 socket 模块建立一个网络连接,并向目标计算机发送一个获取系统时间的请求。
以下是一个简单的示例代码:
import socket
import struct
# 目标计算机的 IP 地址和端口号
target_host = '192.168.1.100'
target_port = 12345
# 创建一个 TCP 套接字并连接到目标计算机
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((target_host, target_port))
# 发送一个请求消息,表示要获取系统时间
request_msg = b'get_time'
client_socket.sendall(request_msg)
# 接收目标计算机返回的系统时间数据
response_data = client_socket.recv(1024)
# 解析系统时间数据
system_time = struct.unpack('!Q', response_data)[0]
# 将系统时间转换为本地时间格式并打印出来
print('System time:', datetime.datetime.fromtimestamp(system_time))
在这个示例中,我们使用了 Python 的 struct 模块来解析从目标计算机返回的二进制数据。我们将接收到的数据视为一个 8 字节的无符号整数,并使用 !Q
格式指令进行解析,其中 !
表示网络字节序,Q
表示 unsigned long long 类型。
可采用Python中的paramiko库来实现远程获取另一台电脑的系统时间并对比本地系统时间的功能,具体步骤如下: 1. 安装paramiko库,命令为:pip install paramiko 2. 导入paramiko库和datetime库,以获取当前系统时间 3. 创建ssh对象,以通过IP地址远程连接另一台电脑 4. 调用ssh对象的命令执行方法来执行获取系统时间的命令 5. 解析命令执行结果,提取远程系统时间 6. 将本地系统时间与远程系统时间进行比较
示例代码如下:
import paramiko
import datetime
# IP地址及用户名、密码
ip = "xxx.xxx.xxx.xxx"
username = "username"
password = "password"
# 获取当前本地系统时间
local_time = datetime.datetime.now()
# 连接远程服务器
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, username=username, password=password)
# 执行命令获取远程系统时间
stdin, stdout, stderr = ssh.exec_command("date")
remote_time_str = stdout.read()
remote_time_str = remote_time_str.strip().decode('utf-8')
# 解析命令执行结果,提取远程系统时间
remote_time = datetime.datetime.strptime(remote_time_str, '%a %b %d %H:%M:%S %Z %Y')
# 比较本地系统时间和远程系统时间
time_diff = local_time - remote_time
print("本地系统时间为:", local_time)
print("远程系统时间为:", remote_time)
print("时间差为:", time_diff)
需要注意的是,在使用paramiko库进行远程连接时,需要确保目标主机开放了SSH端口并且允许SSH连接。另外,由于不同操作系统下获取系统时间的命令格式可能存在差异,可能需要对命令进行适当修改。
对方电脑必须有一个服务器端程序报告时间
最简单的,对方电脑安装一个mysql
你连接上那个电脑,就可以用 select now() 得到那个电脑的时间了。
不过要考虑网络延迟,你得到的是执行那刻的时间,之后的延迟如果很大,就不一定准了。