我正在尝试编写一个脚本通过SFTP备份文件。问题在于,它需要密码,但我找不到手动指定SFTP密码的方法。我听说过可以使用公钥而不需要密码,但这需要能够ssh到远程服务器并修改一些配置文件,而我无法这样做。
目前我的解决方案是使用cURL,但这是不安全的(使用普通FTP)。我也看了.netrc
文件,但它似乎是用于FTP而不是SFTP。我该如何手动为sftp指定密码?
我正在尝试编写一个脚本通过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
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.
pip install paramiko
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 )
Bash程序等待sftp要求密码,然后发送密码:
#!/bin/bash
expect -c "
spawn sftp username@your_host
expect \"assword\"
send \"your_password_here\r\"
interact "
将其放入名为sftp_autologin.sh
的文件中。 \r
发送到sftp以执行命令。 我不包括密码中的“p”,因为在某些系统上它是大写字母,而在其他系统上则是小写字母。 expect生成sftp命令。 等待看到字符串“assword”并发送命令。 然后结束。
要使其正常工作:
然后运行它:
chmod +x sftp_autologin.sh
./sftp_autologin.sh
它应该将您直接带入sftp命令行,而不会提示您输入密码。
这是最不安全的命令之一。它会将密码暴露给命令历史记录和任何能够读取“ps”输出的其他人,从根本上打败了密码的全部意义。
但嘿,对于欺诈活动,再多一条日志也无关紧要,每年的受害者损失约为250亿美元,让我们争取500亿。
此命令会自动在sftp shell中运行一些命令,并在完成后自动退出:
#!/bin/bash
expect -c "
spawn sftp myuser@myserver.com
expect \"assword\"
send \"yourpassword\r\"
expect \"sftp\"
send \"get your_directory/yourfilename.txt\r\"
expect \"sftp\"
send \"exit\r\"
interact "
~/.ssh/authorized_keys
)。您可以使用sftp完成此操作。如果您尚未在服务器上建立任何authorized_keys文件,则可以将id_rsa.pub文件放置在其位置。
您无法在命令行中指定ssh / scp或sftp的密码。连接而不提示输入密码的唯一方法是使用公钥身份验证。
您说您无法通过ssh访问服务器以修改配置文件,但如果您可以通过sftp访问服务器,则可能可以上传您的公钥。
您的公钥只需放在主目录下的.ssh目录中即可。