简体   繁体   English

带有bash的sftp / scp文件

[英]sftp/scp files with bash

I have the need to upload a set of files to an sftp account. 我需要将一组文件上传到sftp帐户。

My first thought was to use php's ssh2_connect() function and I was able to get this working locally no problem. 我的第一个想法是使用php的ssh2_connect()函数,我能够在本地正常工作。 However, once I moved to the dev environment I quickly realized that this wasn't a good solution because there are too many dependencies that wont exist and installing them would require too many approvals from too many people. 但是,一旦我转到开发环境,我很快就意识到这不是一个好的解决方案,因为不存在太多依赖项,安装它们需要太多人的批准。

So, my next thought was to use bash, and this is where I need help. 因此,我的下一个想法是使用bash,这是我需要帮助的地方。 I will be running this bash script every hour through cron, so it needs to be unattended. 我将通过cron每小时运行一次该bash脚本,因此它需要无人看管。 However, when I run sftp/scp it requires a password. 但是,当我运行sftp / scp时,需要输入密码。

The sftp account does not allow ssh connections so I cannot create authorized keys. sftp帐户不允许ssh连接,因此我无法创建授权密钥。 I don't want to rely on the .ssh folder on the remote machine as well. 我也不想依赖远程计算机上的.ssh文件夹。

Any suggestions would be appreciated. 任何建议,将不胜感激。

Keep in mind I cannot install anything, so no keychain, sshpass or expect. 请记住,我无法安装任何东西,因此没有钥匙串,sshpass或期望。 All other answers found in How to run the sftp command with a password from Bash script? 如何使用Bash脚本中的密码运行sftp命令中找到所有其他答案 are not feasible as I cannot install anything on the server. 不可行,因为我无法在服务器上安装任何东西。

Initially I was trying to use php's ssh2_connect() because php creates the file that I need to upload. 最初,我尝试使用php的ssh2_connect(),因为php创建了我需要上传的文件。 It's better to have this sftp transaction in my php script for that reason but since it wasn't working, I moved on to bash. 出于这个原因,最好在我的php脚本中有这个sftp事务,但是由于它不起作用,所以我转向了bash。

My solution is actually using php and curl: 我的解决方案实际上是使用php和curl:

$ch = curl_init();

$fp = fopen($file, "r");

curl_setopt($ch, CURLOPT_URL, "sftp://USER:PASS@HOST/" . basename($file));
curl_setopt($ch, CURLOPT_UPLOAD, 1);
curl_setopt($ch, CURLOPT_PROTOCOLS, CURLPROTO_SFTP);
curl_setopt($ch, CURLOPT_INFILE, $fp);
curl_setopt($ch, CURLOPT_INFILESIZE, filesize($file));

curl_exec($ch);

curl_close($ch);

check lftp, it's very powerful tool in file transfer. 检查lftp,它是文件传输中非常强大的工具。 for example: 例如:

lftp -u "$username","$password" -e "cd /desc/path; put $FILE; bye" sftp://remote.example.com

check also mput, mirror in lftp manual. 请同时检查mput,lftp手册中的镜像。

BTW. BTW。 I don't think you need to install anything on the remote server if you use expect. 如果您使用Expect,我认为您不需要在远程服务器上安装任何东西。 anyway, I am using lftp instead of expect in most similar situations at work. 无论如何,我使用lftp而不是在大多数类似情况下工作。

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

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