简体   繁体   English

Linux:通过ssh连接自动执行sftp文件传输

[英]Linux: automated sftp file transference by an ssh connection

I need to make a crontab script (executed automatically and periodically) that should find the latest changed file of a folder and then transfer it to another machine, using an sftp connection. 我需要创建一个crontab脚本(自动和定期执行),该脚本应该找到文件夹的最新更改文件,然后使用sftp连接将其传输到另一台机器。 The first part of the problem is solved by extracting the name of the desired file: 通过提取所需文件的名称来解决问题的第一部分:

cd $myFolder
output=$(find . -type f -printf "%C@ %p\n" | sort -rn | head -n 1)
filename=$(echo $output | cut -d'/' -f 2)

But the second part is difficult, because I cannot find the way to type the value of $filename variable in a Linux sftp connection and also the user/password in a non-interactive way. 但第二部分很难,因为我无法找到在Linux sftp连接中键入$filename变量值的方法,也无法以非交互方式键入用户/密码。 Saving it into a temporary file may be a good solution. 将其保存到临时文件中可能是一个很好的解决方案。

Is there any better alternative? 还有更好的选择吗?

Thanks 谢谢

You could use inotify to monitor the directory and trigger on modify . 您可以使用inotify来监视目录并在修改时触发。 The file name can be fed to rsync or scp . 文件名可以提供给rsyncscp Example: 例:

inotifywait      \
  --quiet        \
  --event modify \
  --format '%f'  \
  --monitor watch_directory |
  while read FILE; do \
  scp watch_directory/$FILE host:/destination;
  done

You could use scp instead of sftp - it uses the same protocol but is more suitable for non-interactive use. 您可以使用scp而不是sftp - 它使用相同的协议,但更适合非交互式使用。

You can find the last modified file in a directory with only ls , if the directory only contains files (no subdirectories): 如果目录只包含文件(没有子目录),您可以在只有ls的目录中找到最后修改的文件:

output=$(ls -t "$myFolder" | head -1)

您可以使用curl通过sftp将文件上传到远程服务器,并在命令中传递登录信用(用户名和密码),如下所示:

curl -T uploadfilename -u username:password sftp://sitename.com/myfile

My solution: 我的解决方案

To obtain the filename: 要获取文件名:

filename=$(ls -t . | head -1)

To transfer the data to the remote server: 要将数据传输到远程服务器:

#!/usr/bin/expect -f

# A copy of the $sourceFile is sent to the $targetPath by using the scp command (secure copy)

set timeout 20

set sourceFile [lindex $argv 0]
set targetPath [lindex $argv 1]
set user [lindex $argv 2]
set password [lindex $argv 3]

# connect via scp
spawn scp $sourceFile "$user@$targetPath"
#######################
expect {
  -re ".*es.*o.*" {
    exp_send "yes\r"
    exp_continue
  }
  -re ".*sword.*" {
    exp_send "$password\r"
  }
}
interact

The user authentication is delegated to the script that uses this script, and can be made by the generation of a public/private rsa key pair in the remote server, and then using it: Read next link: SSH login without password . 用户身份验证委派给使用此脚本的脚本,可以通过在远程服务器中生成公钥/私钥rsa密钥对,然后使用它来进行:读取下一个链接: 无需密码的SSH登录

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM