Eli*_*Eli 8 bash sftp remote-backup .netrc
我正在尝试编写一个脚本来备份SFTP上的文件.问题是,它需要密码,我看不到手动为SFTP指定密码.我听说过使用公钥不需要密码,但这需要能够ssh到远程服务器并修改一些配置文件,这是我无法做到的.
目前我的解决方案是使用cURL,但这是不安全的(使用普通的FTP).我也查看了该.netrc文件,但这似乎是针对FTP而不是SFTP.如何手动为sftp指定密码?
Lftp允许为ftp和sftp指定密码,并且根本不需要公钥.您的sh同步脚本可能如下所示:
#!/bin/sh
# Define folders
THEFOLDER='/mnt/my/folder'
# List files
THEFILES=`ls -p $THEFOLDER | grep -v "/"`
for file in $THEFILES
do
echo "Processing $file"
lftp -u login,password -e "put $THEFOLDER/$file;quit" theftp/sub/folder
done
Run Code Online (Sandbox Code Playgroud)
cURL 可以支持 sftp,如手册所述:
USING PASSWORDS
FTP
To ftp files using name+passwd, include them in the URL like:
curl ftp://name:passwd@machine.domain:port/full/path/to/file
or specify them with the -u flag like
curl -u name:passwd ftp://machine.domain:port/full/path/to/file
FTPS
It is just like for FTP, but you may also want to specify and use
SSL-specific options for certificates etc.
Note that using FTPS:// as prefix is the "implicit" way as described in the
standards while the recommended "explicit" way is done by using FTP:// and
the --ftp-ssl option.
SFTP / SCP
This is similar to FTP, but you can specify a private key to use instead of
a password. Note that the private key may itself be protected by a password
that is unrelated to the login password of the remote system. If you
provide a private key file you must also provide a public key file.
Run Code Online (Sandbox Code Playgroud)
您可能还想考虑使用 python(paramiko 模块),因为可以从 shell 快速调用它。
pip install paramiko
Run Code Online (Sandbox Code Playgroud)
import paramiko
username = 'my_username'
password = 'my_password'
transport = paramiko.Transport((server, 22))
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
local_filename = '/tmp/filename'
remote_filename = 'MyFiles/temp.txt'
sftp.put( local_filename, remote_filename )
Run Code Online (Sandbox Code Playgroud)
为了使用公钥,您不需要修改任何“配置文件”。您只需将公钥副本留在 ssh 知道查找的位置(通常~/.ssh/authorized_keys)。您可以使用 sftp 来完成此操作。如果您尚未在服务器上建立任何authorized_keys 文件,则只需将id_rsa.pub 文件放在其位置即可。