之前文章有提到过做一个定时长时间运行服务,这个服务就是实现远程获取电脑时间。
2种思路,
1) 远端Macos开一个TCP服务,做一个获取当前时间接口
tcp通信实现,在NPI电脑运行一个服务器,实现一个接口返回当前电脑时间,准备一台电脑一个客户端,多线程去触发所有NPI电脑获取时间 。因产线限制tcp通信,放弃
#中心控制Macos端:运行多个线程程去启动tcp
import datetime
import time
import csv
import threading
import socket
exitFlag = 0
class myThread(threading.Thread):
def __init__(self, threadID, name, delay, hostname, portvalue):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.delay = delay
self.hostname = hostname
self.port = portvalue
def run(self):
print("Start run")
print_time(self.name, self.delay, 1, self.hostname, self.port)
def print_time(threadName, delay, counter, hostname, port):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
s = socket.socket()
s.connect((hostname, port))
s.sendall("RTC".encode())
remote = s.recv(1024)
s.close()
remote=remote.decode().rstrip()
print(remote)
print(" Get from "+hostname+", "+str(port)+" value is :"+remote)
remoteTime.append(remote)
counter -= 1
if __name__ == '__main__':
threads = []
thread1 = myThread(1, "Thread-1", 0.01, "127.0.0.1", 8500)
thread2 = myThread(2, "Thread-2", 0.01, "127.0.0.1", 8501)
threads.append(thread1)
threads.append(thread2)
headers = ['Local', 'remote1', 'remote2']
localtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
remoteTime = [localtime]
for td in threads:
td.start()
for td in threads:
td.join()
print("remote times :", remoteTime)
with open('timeCheck.csv', 'a') as f:
f_csv = csv.writer(f)
f_csv.writerow(remoteTime)
print(localtime)
#服务端
#!/user/bin/env python
# coding=utf-8
"""
@project : rtcproject
@author : Lani.wang
#@file : rpcservice.py
#@ide : PyCharm
#@time : 2022-02-16 14:24:12
"""
# coding: utf-8
# server
import socket
import time
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("127.0.0.1", 8500)) # 根据需要修改端口
sock.listen(1) # 监听客户端连接
print("Start")
while True:
conn, addr = sock.accept() # 接收一个客户端连接
print(conn.recv(1024)) # 从接收缓冲读消息 recv buffer
timevalue=time.time()
conn.sendall(str(timevalue).encode()) # 将响应发送到发送缓冲 send buffer
conn.close() # 关闭连接...
break
2)因为是局域网,设置免密登录,然后远程打印电脑时间?
?免密SSH,py运行一个脚本,脚本实现远程免密登录并运行远端脚本。远端脚本运行一个python来获取时间。 下面是远端放的py脚本,远程ssh不能直接执行,需要写一个shell脚本放在这个脚本目录。然后中心电脑也写一个shell脚本完成远程ssh登录并执行这个远程电脑shell脚本。
#远端电脑,timeCheck.csv手动创建
import datetime
import time
import csv
import os
import threading
import socket
if __name__ == '__main__':
localtime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
remoteTime = ["106",localtime,time.time()]
print("remote times :", remoteTime)
try:
with open('timeCheck.csv', 'a') as f:
f_csv = csv.writer(f)
f_csv.writerow(remoteTime)
print ("finish")
except Exception as e:
print(e)
print(localtime)
#中控电脑
...
shell脚本:clientcmmd.command
#!/bin/bash
cd "$(dirname "$0")"
python timeCheckClient.py
中心控制端:
#!/bin/bash
echo "Run ssh 107"
ssh gdlocal@10.100.73.107 "/Users/xxx/Documents/sshgettimeForNPI/clientcmmd.command"
exit
echo "Stop"
最后写个python, 运行个for循环去遍历所有需要远程获取时间的电脑。
|