如何自动定时传文件到window系统

  • ~1.58K 字
  • 0 次阅读 次阅读
  • 0 评论 条评论
  1. 1. window系统准备
    1. 1.1. 开启openssl服务
    2. 1.2. 防火墙放通22端口
    3. 1.3. 其他
  2. 2. linux系统准备
    1. 2.1. 安装scp
    2. 2.2. 安装expect
  3. 3. 传输初始化(scp命令)
  4. 4. 脚本
  5. 5. 定时执行

简单记录下折腾从linux系统自动定时传输文件到window系统的过程

window系统准备

开启openssl服务

window搜索功能搜索可选功能-添加可选功能选择OpenSSH服务器然后添加,等待添加完成即可

防火墙放通22端口

打开CMDpowershell执行以下命令即可

1
New-NetFirewallRule -Name "OpenSSH Server (sshd)" -DisplayName "OpenSSH Server (sshd)" -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22

其他

重启sshd

1
Restart-Service sshd

开机启动

1
Set-Service -Name sshd -StartupType 'Automatic' 

日志位置

1
C:\ProgramData\ssh\logs\

linux系统准备

安装scp

默认系统自带,如果没有请执行

1
2
3
4
# ubuntu/debian
apt-get install openssh-client
# Centos/AlmaLinux/Rocky Linux
yum install openssh-clients

安装expect

1
2
3
4
# ubuntu/debian
apt-get install expect
# Centos/AlmaLinux/Rocky Linux
yum install expect

传输初始化(scp命令)

1
2
3
scp -P 接收服务器的SSH端口 -r 发送文件目录路径 登录账号(如root)@接收服务器ip或域名:接收服务器存储路径
例子,把ssl证书发送到windows服务器上,实现证书同步:
scp -P 22 -r /etc/nginx/cert [email protected]:D:/nginx

按提示输入yes和接收服务器密码信息

脚本

该脚本能实现自动填充密码然后发送文件功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// scp_expect.sh
#!/usr/bin/expect -f
set local_folder "/etc/nginx/cert"
set remote_host "example.com"
set remote_user "administrator"
set remote_path "D:/nginx"
set password "接收服务器密码"
set remote_port "22"

spawn scp -P $remote_port -r $local_folder $remote_user@$remote_host:$remote_path
expect {
"*assword:*" {
send "$password\r"
exp_continue
}
eof
}

保存后执行chmod +x scp_expect.sh,然后执行一次是否正常,连接新机子需手动跑一遍scp跳过验证才可正确执行脚本

定时执行

执行crontab -e后填入

1
0 2 1 * * /root/scp_expect.sh >> /root/scp_cert_expect.sh.log 2>&1

每周一2点会执行该脚本,脚本路径和日志路径自行修改

打赏
打赏提示信息
分享
分享提示信息