利用Python脚本调用ssh scp命令批量拷贝文件
By:Roy.LiuLast updated:2021-08-18
在linux环境下利用python脚本,ssh scp 命令批量拷贝文件到其他机器。
#coding:utf-8
import sys,re
import os
import subprocess
import redis
log_redis_name = "log:scp"
log_path = "/data/files"
conn = redis.Redis(host="127.0.0.1", port=6379, password="xxxxxxxxx",db=2)
remote_user = "username"
remote_password = "user_password"
remote_path = "/data/dest/files"
remote_ip = "192.168.222.33"
def hset(key):
conn.hset(log_redis_name, key, "Y")
def hget(key):
return conn.hget(log_redis_name, key)
def cp(f):
cmd = "sshpass -p {password} scp {localsource} {username}@{host}:{remotedest}".format(password=remote_password, username=remote_user, host=remote_ip, localsource=f, remotedest=remote_path)
val = os.popen(cmd).read()
print(val)
def walk_folder():
for f in os.listdir(log_path):
exist_flag = hget(f)
print("processing file: " + f + ", is existed: " + str(exist_flag))
if not exist_flag:
print("begin to scp file: " + f)
cp(log_path + "/" + f)
hset(f)
if __name__ == "__main__":
walk_folder()里面用到了redis,可以自己安装,利用redis的目的是因为可以记录成功的文件,如果已经传输成功之后,就不需要传输了。然后可以对这个python脚本做成一个cron 定时任务。
From:一号门
Previous:Redis与lua脚本配合操作zset的简单例子

COMMENTS