Linux系列讲解 —— 【scp】命令行实现两台主机之间传输文件

有时候不方便创建共享文件夹来拷贝文件,这个时候可以通过scp命令实现两台主机之间的文件拷贝操作。

1. 准备工作—安装ssh服务:

scp在拷贝远端电脑的文件时,会通过ssh服务访问远端,所以远端电脑必须要安装ssh服务。下面分别介绍一下linux和windows平台安装ssh服务的方法

1.1 windows平台(Win10)

  1. 安装ssh的客户端和服务端
    在这里插入图片描述
  2. ssh服务的启动和关闭
    调用cmd或powershell终端,然后按情况执行下面命令
    开启服务:net start sshd
    关闭服务:net stop sshd

1.2 Linux平台(Ubuntu18.04)

1.安装openssh-server

sudo apt install openssh-server

2.开启服务和关闭服务

#启动服务
sudo systemctl start ssh

#关闭服务
sudo systemctl stop ssh

3.查看服务状态

sudo systemctl status sshd

开启状态:
在这里插入图片描述

关闭状态:
在这里插入图片描述

2. scp命令使用实例

基本语法:

#文件拷贝
scp 用户名@文件源ip地址:文件源路径 目标路径(本机)

#文件夹拷贝,加-r即可
scp -r 用户名@文件夹源ip地址:文件夹源路径 目标路径(本机)

注:
1.要访问的那个主机必须开启ssh服务
2.上面的本机指的是正在操作的机器,比如通过终端登录机器A,那么此时这个A就是本机。

2.1 远程机是linux系统时

例: 将ip为192.100.10.3的电脑里边的/home/sun/.gitconfig文件拷贝到本地当前工作目录

scp [email protected]:/home/sun/.gitconfig ./

2.2 远程机时windows系统时

例: 将ip为192.100.10.4的电脑里边的D:\1.txt文件拷贝到本地当前工作目录

scp [email protected]:/D:/1.txt ./

注:

  1. 上面的例子都是将其他电脑的文件拷贝到本地,如果想将本地文件拷贝到其他电脑,只需要将源路径和目标路径交换一下即可;
  2. 目的地址和源地址不可以都是远程机,如:scp [email protected]:/xxx [email protected]:/xxx。

3. 遇到的问题

3.1 connect to host 192.32.1.6 port 22: Connection timed out

sun@pc:~/code$ scp -v 1.txt [email protected]:/E:/share
Executing: program /usr/bin/ssh host 192.32.1.6, user administrator, command scp -v -t /E:/share
OpenSSH_7.6p1 Ubuntu-4ubuntu0.7, OpenSSL 1.0.2n  7 Dec 2017
debug1: Reading configuration data /home/sun/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug1: Connecting to 192.32.1.6 [192.32.1.6] port 22.
debug1: connect to address 192.32.1.6 port 22: Connection timed out
ssh: connect to host 192.32.1.6 port 22: Connection timed out
lost connection

这个是由于windows的ssh server没有启动,所以一直连接不上,启动windows ssh服务方法如下
在这里插入图片描述

3.2 Permission denied, please try again.

sun@pc:~/code$ scp [email protected]:/E:/gitcommit_template ~/
[email protected]'s password: 
Permission denied, please try again.
[email protected]'s password: 
Permission denied, please try again.
[email protected]'s password: 
[email protected]: Permission denied (publickey,password,keyboard-interactive).

在你保证ssh服务都开启的情况下,还出现了这个问题,那一定是用户名或者密码写错了,这个里边的administrtor应该是administrator,少写了一个a。不要小看这类问题,往往会困扰很久。

猜你喜欢

转载自blog.csdn.net/In_engineer/article/details/124961097