如何获取远程Linux服务器datetime以对比InfluxDB时间戳?
获取远程Linux服务器时间的几种方法
因为两台都是Linux服务器,你可以通过以下几种方式获取远程服务器的系统时间:
1. 通过SSH远程执行命令(最直接)
利用Linux的date命令输出标准格式的时间,再在本地Python中解析为datetime对象:
方法一:用subprocess调用系统ssh命令
import subprocess from datetime import datetime # 替换为你的远程服务器信息 remote_user = "your_user" remote_host = "remote_server_ip_or_hostname" # 执行远程date命令,输出带微秒的ISO格式时间 cmd = f"ssh {remote_user}@{remote_host} 'date +%Y-%m-%dT%H:%M:%S.%6N'" result = subprocess.run(cmd, shell=True, capture_output=True, text=True) remote_time_str = result.stdout.strip() # 转换为Python datetime对象 remote_datetime = datetime.fromisoformat(remote_time_str) local_datetime = datetime.now() # 对比时间 print(f"本地时间: {local_datetime}") print(f"远程服务器时间: {remote_datetime}")
方法二:用paramiko库(纯Python实现,无需依赖系统ssh配置)
先安装依赖:pip install paramiko
import paramiko from datetime import datetime # 远程服务器信息 remote_host = "remote_server_ip_or_hostname" remote_port = 22 remote_user = "your_user" remote_password = "your_password" # 也可使用密钥认证替代密码 # 建立SSH连接 ssh_client = paramiko.SSHClient() ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_client.connect(remote_host, port=remote_port, username=remote_user, password=remote_password) # 执行date命令获取时间 stdin, stdout, stderr = ssh_client.exec_command("date +%Y-%m-%dT%H:%M:%S.%6N") remote_time_str = stdout.read().decode().strip() # 转换为datetime对象 remote_datetime = datetime.fromisoformat(remote_time_str) # 关闭连接 ssh_client.close() # 时间对比逻辑 local_datetime = datetime.now() print(f"本地与远程时间差: {local_datetime - remote_datetime}")
2. 通过InfluxDB查询间接获取
如果有权限操作InfluxDB,可以写入一条测试数据,通过查询该数据的时间戳间接获取远程服务器时间(前提是InfluxDB使用所在服务器的系统时间):
from influxdb_client import InfluxDBClient, Point from influxdb_client.client.write_api import SYNCHRONOUS from datetime import datetime # InfluxDB配置信息 url = "http://remote_server_ip:8086" token = "your_influxdb_token" org = "your_org" bucket = "test_bucket" # 写入测试数据,时间由InfluxDB服务器自动生成 with InfluxDBClient(url=url, token=token, org=org) as client: write_api = client.write_api(write_options=SYNCHRONOUS) point = Point("test_time").field("value", 1) write_api.write(bucket=bucket, org=org, record=point) # 查询最新写入数据的时间戳 query_api = client.query_api() query = f''' from(bucket: "{bucket}") |> range(start: -1m) |> filter(fn: (r) => r._measurement == "test_time") |> last() ''' result = query_api.query(query=query, org=org) for table in result: for record in table.records: remote_influx_time = record.get_time() print(f"InfluxDB服务器时间: {remote_influx_time}") # 对比本地时间 local_datetime = datetime.now() print(f"本地时间: {local_datetime}")
内容的提问来源于stack exchange,提问作者ivolemm
相关产品推荐
相关产品推荐

