3

如何在 Linux 中将密码传递给 scp 命令

 2 years ago
source link: https://os.51cto.com/article/710389.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
4277696254b135da29a83891001f3bf5d3ee58.jpg

将文件和目录从一个系统拷贝到另一个系统是任何系统管理员的常见任务。scp,也称为安全拷贝(secure copy),是一种 Linux 命令行实用程序,用于将文件从一台服务器安全地拷贝或传输到另一台服务器。scp 命令允许你将文件或目录从本地系统拷贝到远程系统,从远程系统拷贝到本地系统,或在本地系统的两个远程系统之间拷贝。

当你使用 scp 命令时,你需要在传输文件之前提供远程用户的密码。在这篇文章中,我们将解释如何在 Linux 中将密码传递给 scp 命令。

  • 运行 Linux 的服务器
  • 在你的服务器上配置的 root 密码

使用 SCP 命令拷贝文件

将文件从本地系统拷贝到远程系统的基本语法如下所示:

scp filename user@remotehost:/directory/path

例如,要将名为file1.txt的文件从本地系统拷贝到 /mnt 目录中 IP 地址为 192.168.1.100 的远程系统,请运行以下命令:

scp file1.txt [email protected]:/mnt/

将文件从远程系统拷贝到本地系统的基本语法如下所示:

scp user@remotehost:/file/path local/path

例如,要将名为 file1.txt 的文件从 IP 地址为192.168.1.100的远程系统拷贝到/opt目录中的本地系统,请运行以下命令:

scp [email protected]:/mnt/file1.txt /opt/

系统将提示你提供远程用户的密码,如下所示:

在 Linux 中安装 sshpass

sshpass 是一个简单轻量级的命令行工具,它允许你为命令提示符本身提供密码。当你想通过 cron 作业进行备份时,它在 shell 脚本中非常有用。默认情况下,sshpass 不包含在任何 Linux 操作系统中,因此你需要在 Linux 系统中安装 sshpass 实用程序以使用 SCP 命令传递密码。对于基于 Ubuntu 和 Debian 的操作系统,使用以下命令安装 sshpass:

linuxmi@linuxmi:~/www.linuxmi.com$ sudo apt install sshpass -y
43a51d9976bdf77432e4488ef8b3fc3da1adc5.jpg

对于 RHEL、Fedora、CentOS 和 Rocky Linux 操作系统,使用以下命令安装 sshpass:

dnf install sshpass -y

安装 sshpass 实用程序后,你可以继续下一步。

如何使用 SCP 命令传递密码

使用 SCP 命令传递密码的基本语法如下所示:

sshpass -p "remote-user-password" scp filename user@remotehost:/dir/path/

例如,如果要将名为file1.txt的文件拷贝到 IP 为192.168.1.100的远程服务器,请使用以下命令:

sshpass -p "password" scp file1.txt [email protected]:/mnt/

如你所见,sshpass + SCP 命令将帮助你使用单行命令将文件和目录从一个系统拷贝到另一个系统。

在这篇文章中,我们解释了如何在 Linux 中使用带有 sshpass 的 SCP 命令来传递密码。sshpass 将帮助你加快文件拷贝过程。你还可以使用它自动从一台服务器备份到另一台服务器。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK