如何在不使用Shell命令的情况下通过SSH以编程方式修改文件?

如何在不使用Shell命令的情况下通过SSH以编程方式修改文件?

问题描述:

I'm writing a tool which, among other things, needs to be able to modify files over an SSH connection. However, I don't want to have to invoke CLI tools on the remote server due to security concerns (TL;DR: string escaping is really hard). How can I do this with either (a) the ssh command-line tool (invoked locally) or, (b), the golang.org/x/crypto/ssh/* packages?

EDIT: Sorry, I forgot to mention. I need to be able to do this all within a single session. On some clients, the server being connected to is behind a load balancer, so if I make multiple invocations, I might end up connecting to different servers.

我正在编写一个工具,该工具除其他外,需要能够通过SSH连接修改文件。 但是,由于安全方面的考虑,我不想在远程服务器上调用CLI工具(TL; DR:字符串转义确实很难)。 我该如何使用(a)ssh命令行工具(在本地调用)或(b) golang.org/x/crypto/ssh / * code>软件包来做到这一点? p >

编辑: strong>:抱歉,我忘了提。 我需要能够在一个会话中完成所有这些操作。 在某些客户端上,连接到的服务器位于负载均衡器的后面,因此,如果我多次调用,最终可能会连接到其他服务器。 p> div>

Establish a master connection with ssh that you keep alive. Then you can download the file to your localhost, modify it and upload it again using scp while tunneling through the master connection.

See https://unix.stackexchange.com/a/2869

I am not sure how you plan on doing that. SSH is a very strict protocol which allows you to do specific things: file transfer and terminal connection.

You can see here the features different ssh servers have: https://en.wikipedia.org/wiki/Comparison_of_SSH_servers#Features

But SSH is just a protocol: a set of commands the SSH server (as opposed to the SSH client, which would be your go program) will understand.

If you want to do specific actions, I recommend you to build your own server, that you secure using encryption technologies such as SSL or TLS, to which your client will connect.

PS: This question is not really Go-related, but more SSH related, as it works the same for any language.

The most portable way to manipulate files through SSH is to use the SFTP protocol. SFTP is mostly used to transfer files, but it's really a remote filesystem protocol. It has operations to do all of the following on the remote system:

  • Create, delete, and rename files
  • Open files for reading or writing; read and write blocks of data within a file.
  • List directory contents
  • Read and change file attributes

SFTP exposes a POSIX (unix-like) naming scheme. The file separator is a "/" and absolute paths start with "/". File attributes also follow the POSIX model.