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

我需要制作一个crontab脚本(自动执行和定期执行),find文件夹的最新更改文件,然后使用sftp连接将其传输到另一台计算机。 问题的第一部分是通过提取所需文件的名称来解决的:

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

但是第二部分是困难的,因为我找不到在Linux sftp连接中键入$filenamevariables的值并且以非交互方式键入用户/密码的方式。 将其保存到临时文件可能是一个很好的解决scheme。

有没有更好的select?

谢谢

您可以使用inotify来监视目录并在修改时触发。 文件名可以被送到rsyncscp 。 例:

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

您可以使用scp而不是sftp – 它使用相同的协议,但更适合非交互式使用。

如果目录只包含文件(无子目录),则可以在只有ls的目录中找到最后一个修改过的文件:

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

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

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

我的解决方案

要获取文件名:

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

将数据传输到远程服务器:

 #!/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 

用户身份验证委托给使用此脚本的脚本,可以通过在远程服务器中生成公钥/私钥rsa密钥对,然后使用它来执行:读取下一个链接: 不使用密码的SSH登录 。