兼容所有系统的局域网传输文件通用方法

既然要通讯,那么必须有服务器和客户端。本文使用sshd做服务器,scp做客户端。
接受文件的一方必须使用sshd启动并绑定本机局域网端口,如0.0.0.0:22
绑定方法就是配置/etc/ssh/sshd_config这个配置文件,如果A(windows/linux/macos)向B(windows/linux/macos)发送文件,那么有两种方式:
假设A的用户名为userA,IP为192.168.1.10,文件路径/1.txt

  1. A运行sshd服务/usr/sbin/sshd,B运行scp :/1.txt 1.txt
  2. B运行sshd服务/usr/sbin/sshd,B运行scp 1.txt :/1.txt

这里有几点注意:

  1. 如何在windows上运行sshd服务器
    linux怎么运行sshd就不必说了吧,很容易搜到。这里只讨论windows的,推荐git for windows自带的sshd.exe,scp.exe,ssh.exe,ssh所用账号密码也用windows自身账号密码即可。最好安装everything这个工具,可以搜到传过来的文件保存在哪里,git自带ssh根目录是git安装目录。注意git自带ssh的配置文件在:git根目录/etc/ssh/sshd_config。另外在登录git自带sshd服务时,使用的也是windows自带的账号密码,这样很方便。同时git自带的passwd命令还可以改登录密码

  2. 如何配置sshd做局域网服务器
    对sshd_config做如下改动:a. ListenAddress 0.0.0.0 这一行取消注释(#号)

    b. GSSAPIAuthentication yes 这一行yes改no并取消注释

  3. 加速传输
    首先是解决每次执行scp需要密码的问题。如果要免密登录,需要用ssh-copy-id命令,如ssh-copy-id 。该命令windows是没有的,如果你要在winows上用scp命令达到免密登录,那么要运行一个python脚本:
import argparse, os
from subprocess import call

def winToPosix(win):
    posix = win.replace('\\', '/')
    return "/" + posix.replace(':', '', 1)

parser = argparse.ArgumentParser()
parser.add_argument("-i", "--identity_file", help="identity file, default to ~\\.ssh\\idrsa.pub", default=os.environ['USERPROFILE']+"\\.ssh\\id_rsa.pub")
parser.add_argument("-d", "--dry", help="run in the dry run mode and display the running commands.", action="store_true")
parser.add_argument("remote", metavar="")
args = parser.parse_args()

local_key = winToPosix(args.identity_file)
remote_key = "~/temp_id_rsa.pub"

scp_command = "scp {} {}:{}".format(local_key, args.remote, remote_key)
print(scp_command)
if not args.dry:
    call(scp_command)

ssh_command = ("ssh {} "
                 "mkdir ~/.ssh;"
                 "touch ~/.ssh/authorized_keys;"
                 "cat {} >> ~/.ssh/authorized_keys;"
                 "rm {};").format(args.remote, remote_key, remote_key)
print(ssh_command)
if not args.dry:
    call(ssh_command)

然后解决scp传输速度越要越慢的问题。我这里局域网是100Mbps的,然而scp传输文件时,最开始能达到3M,最后慢慢降到1M以下,所以单纯用scp也不行的。在使用scp的时候,使用-o "Compression yes"能使速度稳在4M,即:scp -o "Compression yes" 1.txt :/1.txt

相关推荐