定期从linux服务器下拷贝资料至本地电脑,免去输入密码等操作

有时候我们需要定期从云服务器上更新资料到本地,可以写一个python脚本,在本机运行,达到这样的效果:

#!/usr/bin/python  
# -*- coding: utf-8 -*- 

import os
import subprocess
import time
import pexpect
import psutil


# 杀进程函数
while True:
    child = pexpect.spawn('scp [email protected]:/home/test.txt /home/')  # 远程拷贝
    child.expect('password:')
    child.sendline('xxxx')  # 自动输入密码
    print("start sleep....")
    time.sleep(20)

其中睡觉的时间为更新的周期。

这个可以用来检测服务器上某个文件的状态变化,例如,这是一个使用场景,当服务器上某个文件发生了变化,则在本地执行其他的操作:

#!/usr/bin/python  
# -*- coding: utf-8 -*- 

import os
import subprocess
import time
import pexpect
import psutil

# 杀进程函数
def kill_process(name):
    for proc in psutil.process_iter():
        print("pid-%d,name:%s" % (proc.pid, proc.name()))
        if (proc.name() == name):
            os.system("kill -9 {}".format(proc.pid))
            print("杀死{}进程".format(name))


KMS_listen_port = 10000  # 初始化KMS监听端口
while True:
    child = pexpect.spawn('scp [email protected]:/home/test.txt /home/')  # 远程拷贝
    child.expect('password:')
    child.sendline('xxxxxx')  # 自动输入密码
    print("start sleep....")
    time.sleep(20)
    with open('/home/test.txt') as f:  # 读取文件,判断监听端口是否发生了变化,如果变换,杀死原来的fmpeg,重新开启ffmpeg
        new_port = int(f.read())
        print("new_port: ", new_port)
        if new_port != KMS_listen_port:
            KMS_listen_port = new_port
            kill_process("docker")  # 杀死正在运行的docker
            os.system("sudo sesrvice c start")

猜你喜欢

转载自blog.csdn.net/hongge_smile/article/details/108256624