如何使用 Bash 脚本中的密码运行 sftp 命令?

发布于 2024-10-25 06:01:32 字数 467 浏览 2 评论 0 原文

我需要使用 sftp 从 Linux 主机将日志文件传输到远程主机。我的运营团队已向我提供了相同的凭据。但是,由于我无法控制其他主机,因此我无法生成 RSA 密钥并与其他主机共享。

那么有没有办法通过 cron 工作?

我发现了一个类似的 Stack Overflow 问题,在 Bash 脚本中指定 sftp 的密码,但没有我的问题的满意答案。

I need to transfer a log file to a remote host using sftp from a Linux host. I have been provided credentials for the same from my operations group. However, since I don't have control over other host, I cannot generate and share RSA keys with the other host.

So is there a way to run the sftp command (with the username/password provided) from inside the Bash script through a cron job?

I found a similar Stack Overflow question, Specify password to sftp in a Bash script, but there was no satisfactory answer to my problem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

神回复 2024-11-01 06:01:33

Bash 程序等待 sftp 要求输入密码,然后将其发送:

#!/bin/bash
expect -c "
spawn sftp username@your_host
expect \"Password\"
send \"your_password_here\r\"
interact "

您可能需要安装 Expect,将“密码”的措辞更改为小写“p”以匹配您的提示符收到的内容。这里的问题是它会在文件和命令历史记录中以纯文本形式公开您的密码。这几乎违背了拥有密码的初衷。

Bash program to wait for sftp to ask for a password then send it along:

#!/bin/bash
expect -c "
spawn sftp username@your_host
expect \"Password\"
send \"your_password_here\r\"
interact "

You may need to install expect, change the wording of 'Password' to lowercase 'p' to match what your prompt receives. The problems here is that it exposes your password in plain text in the file as well as in the command history. Which nearly defeats the purpose of having a password in the first place.

明媚殇 2024-11-01 06:01:33

您可以使用 sshpass 来实现。 步骤

  1. 以下是为 Ubuntu 安装 sshpass 的
  2. - sudo apt-get install sshpass如果是第一次,请将远程 IP 添加到您的已知主机文件中
    对于 Ubuntu -> ssh 用户@IP ->输入 'yes'
  3. 给出 scp 和 sshpass 的组合命令。
    下面是战争应对远程tomcat的示例代码
    sshpass -p '#Password_For_remote_machine' scp /home/ubuntu/latest_build/abc.war #user@#RemoteIP:/var/lib/tomcat7/webapps

You can use sshpass for it. Below are the steps

  1. Install sshpass For Ubuntu - sudo apt-get install sshpass
  2. Add the Remote IP to your known-host file if it is first time
    For Ubuntu -> ssh user@IP -> enter 'yes'
  3. give a combined command of scp and sshpass for it.
    Below is a sample code for war coping to remote tomcat
    sshpass -p '#Password_For_remote_machine' scp /home/ubuntu/latest_build/abc.war #user@#RemoteIP:/var/lib/tomcat7/webapps
一身软味 2024-11-01 06:01:33

有几个人提到了 sshpass,但没有很多清晰的编码示例...

这就是我们使用 bash 脚本进行 rsync 备份的方式:

sshpass -p "${RSYNC_PASSWORD}" sftp "${RSYNC_USER}"@"${RSYNC_REMOTE_HOST}"

请记住,您必须 sudo apt install sshpass 才能正常工作。

A few people have mentioned sshpass but not many clear coding examples...

This is how we are doing it with bash scripts for rsync backups:

sshpass -p "${RSYNC_PASSWORD}" sftp "${RSYNC_USER}"@"${RSYNC_REMOTE_HOST}"

Keep in mind you will have to sudo apt install sshpass before this works properly.

意中人 2024-11-01 06:01:33
curl --netrc-file NETRC --upload-file LOCALPATH sftp://HOST:PORT/REMOTEPATH

对于标准输入,LOCALPATH 可能是 -。 NETRC 文件的行格式如下:(

machine HOST login USERNAME password PASSWORD

也可以使用 --user USER:PASSWORD 代替 --netrc-file 但这会向任何运行 < code>ps 同时在本地,所以不要这样做。)

如果 NETRC 文件不永久存在,您的脚本可以创建一个临时文件(可能借助 mktemp)。

感谢@ASammour 指出curl 使用SFTP。

curl --netrc-file NETRC --upload-file LOCALPATH sftp://HOST:PORT/REMOTEPATH

LOCALPATH may be - for stdin. The NETRC file has lines with format:

machine HOST login USERNAME password PASSWORD

(It's also possible to use --user USER:PASSWORD instead of --netrc-file but that reveals the password to anyone running ps locally at the same time, so don't do that.)

If the NETRC file does not exist permanently, your script can create a temporary file (possibly with the help of mktemp).

Thanks to @ASammour for pointing out that curl speaks SFTP.

久夏青 2024-11-01 06:01:33

您可以使用带有 scp 和 os 库的 Python 脚本来进行系统调用。

  1. ssh-keygen -t rsa -b 2048(本地计算机)
  2. ssh-copy-id user@remote_server_address
  3. 创建一个 Python 脚本,例如:
    import os
    cmd = 'scp user@remote_server_address:remote_file_path local_file_path'
    os.system(cmd)
  1. 脚本
  2. 在 crontab 中创建一条规则来自动完成

You can use a Python script with scp and os library to make a system call.

  1. ssh-keygen -t rsa -b 2048 (local machine)
  2. ssh-copy-id user@remote_server_address
  3. create a Python script like:
    import os
    cmd = 'scp user@remote_server_address:remote_file_path local_file_path'
    os.system(cmd)
  1. create a rule in crontab to automate your script
  2. done
奈何桥上唱咆哮 2024-11-01 06:01:33

@ASamour 启发我将其放入我的 .bashrc 中:

sshpass()
{
        server=$1
        file=$2
        userpass=$3
        outfile=${4:-$file}

        curl \
                --insecure sftp://${server}/${file} \
                --user "${userpass}" \
                --output ${outfile}
}

@ASamour inspired me to put this in my .bashrc:

sshpass()
{
        server=$1
        file=$2
        userpass=$3
        outfile=${4:-$file}

        curl \
                --insecure sftp://${server}/${file} \
                --user "${userpass}" \
                --output ${outfile}
}
爱她像谁 2024-11-01 06:01:33

我来这里只是为了获得身份验证技巧,然后在终端中手动运行命令。该解决方案仅涉及身份验证部分:

我必须安装 sshpass。

sshpass -p thepassword sftp [email protected]

然后您将登录 sftp 手动运行命令,而无需输入密码。

I came here only to get the auth trick, and then run the commands manually in the terminal. This solution is ONLY ABOUT the authentication part:

I had to install sshpass.

sshpass -p thepassword sftp [email protected]

Then you will be logged on sftp to run commands manually, without having to type the password.

萝莉病 2024-11-01 06:01:32

除了使用公钥身份验证之外,您还有其他一些选择:

  1. 使用 keychain
  2. 使用 sshpass (更少安全但可能满足您的要求)
  3. 使用 expect (安全性最低,需要更多编码)

如果您决定给 sshpass 一个机会,这里是一个工作脚本片段:

export SSHPASS=your-password-here
sshpass -e sftp -oBatchMode=no -b - sftp-user@remote-host << !
   cd incoming
   put your-log-file.log
   bye
!

更新:但是请理解,使用环境变量与使用命令行选项 -p 一样不安全用于传递密码。

最好使用 -f 选项从这样的文件中存储和读取密码:

echo 'your-password-here' > ~/.passwd
chmod 0400 ~/.passwd

sshpass -f ~/.passwd -e sftp -oBatchMode=no -b - sftp-user@remote-host << !
   cd incoming
   put your-log-file.log
   bye
!

You have a few options other than using public key authentication:

  1. Use keychain
  2. Use sshpass (less secured but probably that meets your requirement)
  3. Use expect (least secured and more coding needed)

If you decide to give sshpass a chance here is a working script snippet to do so:

export SSHPASS=your-password-here
sshpass -e sftp -oBatchMode=no -b - sftp-user@remote-host << !
   cd incoming
   put your-log-file.log
   bye
!

Update: However do understand that using environment variables is also insecure as using command line option -p for passing password.

It is better to store and read password from a file like this using -f option:

echo 'your-password-here' > ~/.passwd
chmod 0400 ~/.passwd

sshpass -f ~/.passwd -e sftp -oBatchMode=no -b - sftp-user@remote-host << !
   cd incoming
   put your-log-file.log
   bye
!
旧情别恋 2024-11-01 06:01:32

另一种方法是使用 lftp:

lftp sftp://user:password@host  -e "put local-file.name; bye"

此方法的缺点是计算机上的其他用户可以从 ps 等工具读取密码,并且该密码可能成为您的 shell 历史记录的一部分。

自 LFTP 4.5.0 起提供的更安全的替代方案是设置 LFTP_PASSWORD 环境变量并使用 --env-password 执行 lftp。这是一个完整的示例:

export LFTP_PASSWORD="just_an_example"
lftp --env-password sftp://user@host  -e "put local-file.name; bye"

# Destroy password after use
export LFTP_PASSWORD=""

LFTP 还包括一个很酷的镜像功能(可以包括确认传输后删除--Remove-source-files):

lftp -e 'mirror -R /local/log/path/ /remote/path/' --env-password -u user sftp.foo.com

Another way would be to use lftp:

lftp sftp://user:password@host  -e "put local-file.name; bye"

The disadvantage of this method is that other users on the computer can read the password from tools like ps and that the password can become part of your shell history.

A more secure alternative which is available since LFTP 4.5.0 is setting the LFTP_PASSWORD environment variable and executing lftp with --env-password. Here's a full example:

export LFTP_PASSWORD="just_an_example"
lftp --env-password sftp://user@host  -e "put local-file.name; bye"

# Destroy password after use
export LFTP_PASSWORD=""

LFTP also includes a cool mirroring feature (can include delete after confirmed transfer --Remove-source-files):

lftp -e 'mirror -R /local/log/path/ /remote/path/' --env-password -u user sftp.foo.com
咽泪装欢 2024-11-01 06:01:32

EXPECT 是一个很好用的程序。

在 Ubuntu 上安装它:

sudo apt-get install expect

在 CentOS 机器上安装它:

yum install expect

假设您想要连接到 sftp 服务器,然后将本地文件从本地计算机上传到远程 sftp 服务器

#!/usr/bin/expect

spawn sftp [email protected]
expect "password:"
send "yourpasswordhere\n"
expect "sftp>"
send "cd logdirectory\n"
expect "sftp>"
send "put /var/log/file.log\n"
expect "sftp>"
send "exit\n"
interact

这将使用您的密码打开一个 sftp 连接服务器。

然后它会转到您要上传文件的目录,在本例中为“logdirectory”。

这会将日志文件从位于 /var/log/ 的本地目录(文件名为 file.log)上传到上的“logdirectory”远程服务器

EXPECT is a great program to use.

On Ubuntu install it with:

sudo apt-get install expect

On a CentOS Machine install it with:

yum install expect

Lets say you want to make a connection to a sftp server and then upload a local file from your local machine to the remote sftp server

#!/usr/bin/expect

spawn sftp [email protected]
expect "password:"
send "yourpasswordhere\n"
expect "sftp>"
send "cd logdirectory\n"
expect "sftp>"
send "put /var/log/file.log\n"
expect "sftp>"
send "exit\n"
interact

This opens a sftp connection with your password to the server.

Then it goes to the directory where you want to upload your file, in this case "logdirectory"

This uploads a log file from the local directory found at /var/log/ with the files name being file.log to the "logdirectory" on the remote server

难得心□动 2024-11-01 06:01:32

您可以在 shell 脚本中交互使用 lftp,这样密码就不会保存在 .bash_history 或类似文件中,方法如下:

vi test_script.sh

将以下内容添加到您的文件中:

#!/bin/sh
HOST=<yourhostname>
USER=<someusername>
PASSWD=<yourpasswd>

cd <base directory for your put file>

lftp<<END_SCRIPT
open sftp://$HOST
user $USER $PASSWD
put local-file.name
bye
END_SCRIPT

编辑主机、用户、密码和目录后写入/退出 vi 编辑器对于您的放置文件,输入 :wq 。然后使您的脚本可执行 chmod +x test_script.sh 并执行它 ./test_script.sh

You can use lftp interactively in a shell script so the password not saved in .bash_history or similar by doing the following:

vi test_script.sh

Add the following to your file:

#!/bin/sh
HOST=<yourhostname>
USER=<someusername>
PASSWD=<yourpasswd>

cd <base directory for your put file>

lftp<<END_SCRIPT
open sftp://$HOST
user $USER $PASSWD
put local-file.name
bye
END_SCRIPT

And write/quit the vi editor after you edit the host, user, pass, and directory for your put file typing :wq .Then make your script executable chmod +x test_script.sh and execute it ./test_script.sh.

玉环 2024-11-01 06:01:32

最近,我被要求从 ftp 切换到 sftp,以确保服务器之间的文件传输安全。我们使用 Tectia SSH 包,它有一个选项 --password 来在命令行上传递密码。

示例: sftp --password="password" "userid"@"servername"

批处理示例:

(
  echo "
  ascii
  cd pub
  lcd dir_name
  put filename
  close
  quit
    "
) | sftp --password="password" "userid"@"servername"

我认为我应该共享此信息,因为我在运行帮助命令之前正在查看各种网站 (< code>sftp -h),我很惊讶地看到密码选项。

I was recently asked to switch over from ftp to sftp, in order to secure the file transmission between servers. We are using Tectia SSH package, which has an option --password to pass the password on the command line.

example : sftp --password="password" "userid"@"servername"

Batch example :

(
  echo "
  ascii
  cd pub
  lcd dir_name
  put filename
  close
  quit
    "
) | sftp --password="password" "userid"@"servername"

I thought I should share this information, since I was looking at various websites, before running the help command (sftp -h), and was i surprised to see the password option.

心不设防 2024-11-01 06:01:32

我发现实现此目的的最简单方法是使用 CURL< 的组合,而无需安装任何第三方库,例如 ExpectSSHPASS...等/strong> 和 SFTP。这两个几乎存在于每台 Linux 机器中。

这是更改值后应执行的命令。

curl  -k "sftp://SERVER_IP:SERVER_PORT/FULL_PATH_OF_THE_FILE" --user "SERVER_USER:SERVER_PASSOWRD" -o "THE_NAME_OF_THE_FILE_AFTER_DOWNLOADING_IT"

示例:

curl  -k "sftp://10.10.10.10:77/home/admin/test.txt" --user "admin:123456" -o "test.txt"

说明:

我们正在连接到服务器 10.10.10.10:77使用用户名admin和密码123456,将文件/home/admin/test.txt从该服务器移动到您正在使用的服务器当前执行上述命令。

The easiest way I found to accomplish this, without installing any third-party library like Expect, SSHPASS...etc, is by using a combination of CURL, and SFTP. Those two are almost in every Linux machine.

This is the command you should execute, after changing the values.

curl  -k "sftp://SERVER_IP:SERVER_PORT/FULL_PATH_OF_THE_FILE" --user "SERVER_USER:SERVER_PASSOWRD" -o "THE_NAME_OF_THE_FILE_AFTER_DOWNLOADING_IT"

Example:

curl  -k "sftp://10.10.10.10:77/home/admin/test.txt" --user "admin:123456" -o "test.txt"

Explanation:

We are connecting to the server 10.10.10.10:77 using the username admin and password 123456, to move the file /home/admin/test.txt from that server to the server you are using currently to execute the above command.

晨与橙与城 2024-11-01 06:01:32

您可以通过启用无密码身份验证来覆盖。但您应该在执行此操作之前安装密钥(pub、priv)。

在本地服务器上执行以下命令。

Local 
gt; ssh-keygen -t rsa 

按 ENTER 键查看所有提示选项。无需输入任何值。

Local 
gt; cd .ssh
Local 
gt; scp .ssh/id_rsa.pub user@targetmachine:
Prompts for pwd
gt;  ENTERPASSWORD

使用以下命令连接到远程服务器

Local 
gt; ssh user@targetmachine
Prompts for pwd
gt; ENTERPASSWORD

在远程服务器上执行以下命令

Remote 
gt; mkdir .ssh
Remote 
gt; chmod 700 .ssh
Remote 
gt; cat id_rsa.pub >> .ssh/authorized_keys
Remote 
gt; chmod 600 .ssh/authorized_keys
Remote 
gt; exit

在本地服务器上执行以下命令以测试无密码身份验证。
应该无需密码即可连接。

gt; ssh user@targetmachine

You can override by enabling Password less authentication. But you should install keys (pub, priv) before going for that.

Execute the following commands at local server.

Local 
gt; ssh-keygen -t rsa 

Press ENTER for all options prompted. No values need to be typed.

Local 
gt; cd .ssh
Local 
gt; scp .ssh/id_rsa.pub user@targetmachine:
Prompts for pwd
gt;  ENTERPASSWORD

Connect to remote server using the following command

Local 
gt; ssh user@targetmachine
Prompts for pwd
gt; ENTERPASSWORD

Execute the following commands at remote server

Remote 
gt; mkdir .ssh
Remote 
gt; chmod 700 .ssh
Remote 
gt; cat id_rsa.pub >> .ssh/authorized_keys
Remote 
gt; chmod 600 .ssh/authorized_keys
Remote 
gt; exit

Execute the following command at local server to test password-less authentication.
It should be connected without password.

gt; ssh user@targetmachine
怪我入戏太深 2024-11-01 06:01:32

将 sshpass 与锁定的凭据文件结合起来,在实践中,它与任何东西一样安全 - 如果您拥有 root 权限来读取凭据文件,那么无论如何,所有的赌注都会被取消。

Combine sshpass with a locked-down credentials file and, in practice, it's as secure as anything - if you've got root on the box to read the credentials file, all bets are off anyway.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文