diff options
| author | Shulhan <ms@kilabit.info> | 2021-07-13 01:22:00 +0700 |
|---|---|---|
| committer | Shulhan <ms@kilabit.info> | 2021-07-13 01:22:00 +0700 |
| commit | 4a7fd734e4e95d8139c8b0bcc5f308953a8e07e4 (patch) | |
| tree | 909e46f96b88663e84172a5754659deab89a182b /command.go | |
| parent | b7b76c1b9e542abd1558f798b87e9f59fadae7fa (diff) | |
| download | awwan-4a7fd734e4e95d8139c8b0bcc5f308953a8e07e4.tar.xz | |
all: use native SFTP to put and get file when possible
Previously, the command to put and get file from remote server depends
on installed scp program on the host computer.
In this changes we add the SFTP client and use it as primary function
to put and get file to/from remote when possible and use the scp as
fallback.
Diffstat (limited to 'command.go')
| -rw-r--r-- | command.go | 27 |
1 files changed, 24 insertions, 3 deletions
@@ -16,6 +16,7 @@ import ( "github.com/shuLhan/share/lib/os/exec" "github.com/shuLhan/share/lib/ssh" "github.com/shuLhan/share/lib/ssh/config" + "github.com/shuLhan/share/lib/ssh/sftp" ) // @@ -31,6 +32,7 @@ type Command struct { script *script env *environment sshClient *ssh.Client + sftpc *sftp.Client tmpDir string } @@ -222,7 +224,10 @@ func (cmd *Command) get(stmt []byte) (err error) { remote := string(paths[0]) local := string(paths[1]) - return cmd.sshClient.ScpGet(remote, local) + if cmd.sftpc == nil { + return cmd.sshClient.ScpGet(remote, local) + } + return cmd.sftpc.Get(remote, local) } // @@ -262,6 +267,9 @@ func (cmd *Command) sudoGet(stmt []byte) (err error) { return fmt.Errorf("%s: %w", logp, err) } + if cmd.sftpc == nil { + return cmd.sshClient.ScpGet(remoteTmp, local) + } return cmd.sshClient.ScpGet(remoteTmp, local) } @@ -288,7 +296,10 @@ func (cmd *Command) put(stmt []byte) (err error) { remote := string(paths[1]) - return cmd.sshClient.ScpPut(local, remote) + if cmd.sftpc == nil { + return cmd.sshClient.ScpPut(local, remote) + } + return cmd.sftpc.Put(local, remote) } // @@ -315,7 +326,11 @@ func (cmd *Command) sudoPut(stmt []byte) (err error) { tmp := filepath.Join(cmd.tmpDir, baseName) remote := string(paths[1]) - err = cmd.sshClient.ScpPut(local, tmp) + if cmd.sftpc == nil { + err = cmd.sshClient.ScpPut(local, tmp) + } else { + err = cmd.sftpc.Put(local, tmp) + } if err != nil { return fmt.Errorf("%s: %w", logp, err) } @@ -504,6 +519,12 @@ func (cmd *Command) initSSHClient() (err error) { return fmt.Errorf("%s: %w", logp, err) } + // Try initialize the sftp client. + cmd.sftpc, err = sftp.NewClient(cmd.sshClient.Client) + if err != nil { + log.Printf("%s: %s\n", logp, err) + } + cmd.env.SSHKey = lastIdentFile cmd.env.SSHUser = sshSection.User cmd.env.SSHHost = sshSection.Hostname |
