不同的产品设备 在不同时间段落 获取的数据都上传到了服务器,需要将这些数据拉取到本地。
这里需要注意几点
1 将本地的数据拷贝到服务器:
scp [option] /path/to/source/file user@server-ip:/path/to/destination/directory
- 【user@server-IP: 】这是远程系统的用户名和 IP 地址。请注意 IP 地址后面加冒号
- 【 /path/to/destination/directory】 这是文件将复制到的远程系统上的目标目录。
- 【option】常用选项:
-C - 这会在复制过程中压缩文件或目录。
-P - 如果默认 SSH 端口不是 22,则使用此选项指定 SSH 端口。
-r - 此选项递归复制目录及其内容。
-p - 保留文件的访问和修改时间。
举例
- 将当前路径下的logs.tar.gz 复制到远程主机的/root目录下。主机IP为192.168.1.240,用户名为root。
scp logs.tar.gz root@192.168.1.240:/root
- 将当前路径下的目录./test 复制到远程主机的/root目录下,使用-r选项,如下所示
scp -r ./test root@192.168.1.240:/root
类似的,将服务器拷贝到本地的数据:
scp [option] user@server-ip:/path/to/source/file /path/to/local/directory
2 python中运行命令并自动输入密码
在python中调用终端输入命令的常用方式是使用
os.system(command)
,在这里需要调用scp
与服务器之间传输数据,就会弹出输入密码的操作。此时os.system就不够用了。此时可以使用pexpect
的库完成该操作。def do_command(command, password): print(command) child = pexpect.spawn(command, logfile=sys.stdout.buffer) child.expect('password') child.sendline(password) ## 当没有返回数据与expect()匹配时,会跑出超时异常,默认超时时间为30秒。 ## 可以通过设置timeout参数,修改超时时间上限,或者设置timeout=None,忽略超时时间。 child.expect(pexpect.EOF, timeout=None)
3 多进程拉取数据
多进程的相关操作可参考 https://blog.csdn.net/magic_ll/article/details/125613046
4 完整代码示例
这里以设备的sn号 和日期进行划分数据,当然其他场景可以用其他标志划分。
import multiprocessing import math import os import pexpect import shutil import numpy as np import time import sys def makedirs(path): os.makedirs(path) if not os.path.exists(path) else None def do_command(command, password): print("=====") print(command) child = pexpect.spawn(command, logfile=sys.stdout.buffer) child.expect('password') child.sendline(password) ## 当没有返回数据与expect()匹配时,会跑出超时异常,默认超时时间为30秒。 ## 可以通过设置timeout参数,修改超时时间上限,或者设置timeout=None,忽略超时时间。 child.expect(pexpect.EOF, timeout=None) def download_log(SN, DATE, savepath): info = [[sn,date] for sn in SN for date in DATE] for s in range(len(info)): print("=======================================================") sn, date = info[s] copy_path = os.path.join(savepath, f"{date}/{sn}") makedirs(copy_path) password = '123456' key_words = f"{date}*RGB200W*" do_command(f"scp -r root@192.168.1.24:/home/work/private/{sn}/{key_words} {copy_path}", password) if len(os.listdir(copy_path))==0: shutil.rmtree(copy_path) if __name__ == '__main__': sn_list = [ "0002", "0005",] date_list = [ "2022-07-08", "2022-07-08",] savepath = "/home/workfile/DATA/" pool_len = 5 num = math.ceil(len(sn_list)/pool_len) print(len(sn_list), pool_len, num) ## pool = multiprocessing.Pool(pool_len) for i in range(pool_len): pool.apply_async(func=download_log, args=(sn_list[i*num:(i+1)*num], date_list, savepath)) pool.close() pool.join()