Repository: appleboy/easyssh-proxy
Branch: master
Commit: 2f6609f5fe93
Files: 42
Total size: 89.0 KB
Directory structure:
gitextract_unycxq1o/
├── .github/
│ ├── FUNDING.yml
│ ├── dependabot.yml
│ └── workflows/
│ ├── codeql.yml
│ ├── goreleaser.yml
│ ├── testing.yml
│ └── trivy.yml
├── .gitignore
├── .goreleaser.yaml
├── CLAUDE.md
├── LICENSE
├── Makefile
├── README.md
├── README.zh-tw.md
├── _examples/
│ ├── proxy/
│ │ ├── go.mod
│ │ ├── go.sum
│ │ └── proxy.go
│ ├── scp/
│ │ ├── go.mod
│ │ ├── go.sum
│ │ └── scp.go
│ ├── ssh/
│ │ ├── go.mod
│ │ ├── go.sum
│ │ └── ssh.go
│ ├── stream/
│ │ ├── go.mod
│ │ ├── go.sum
│ │ └── stream.go
│ └── writeFile/
│ ├── go.mod
│ ├── go.sum
│ └── writeFile.go
├── easyssh.go
├── easyssh_test.go
├── go.mod
├── go.sum
└── tests/
├── .ssh/
│ ├── id_rsa
│ ├── id_rsa.pub
│ ├── test
│ └── test.pub
├── a.txt
├── b.txt
├── entrypoint.sh
├── global/
│ ├── c.txt
│ └── d.txt
└── sudoers
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
custom: ['https://www.paypal.me/appleboy46']
================================================
FILE: .github/dependabot.yml
================================================
version: 2
updates:
- package-ecosystem: github-actions
directory: /
schedule:
interval: weekly
- package-ecosystem: gomod
directory: /
schedule:
interval: weekly
================================================
FILE: .github/workflows/codeql.yml
================================================
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL"
on:
push:
branches: [master]
pull_request:
# The branches below must be a subset of the branches above
branches: [master]
schedule:
- cron: "41 23 * * 6"
jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: ["go"]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
# Learn more about CodeQL language support at https://git.io/codeql-language-support
steps:
- name: Checkout repository
uses: actions/checkout@v6
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v4
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v4
================================================
FILE: .github/workflows/goreleaser.yml
================================================
name: Goreleaser
on:
push:
tags:
- "*"
permissions:
contents: write
jobs:
goreleaser:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0 # all history for all branches and tags
- name: Setup go
uses: actions/setup-go@v6
with:
go-version-file: go.mod
check-latest: true
- name: Run GoReleaser
uses: goreleaser/goreleaser-action@v7
with:
# either 'goreleaser' (default) or 'goreleaser-pro'
distribution: goreleaser
# 'latest', 'nightly', or a semver
version: '~> v2'
args: release --clean
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
================================================
FILE: .github/workflows/testing.yml
================================================
name: Lint and Testing
on:
push:
pull_request:
jobs:
lint:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0 # all history for all branches and tags
- name: Setup go
uses: actions/setup-go@v6
with:
go-version-file: go.mod
check-latest: true
- name: Setup golangci-lint
uses: golangci/golangci-lint-action@v9
with:
version: latest
args: --verbose
testing:
runs-on: ubuntu-latest
strategy:
matrix:
go-version: ['1.25', '1.26']
container: golang:${{ matrix.go-version }}-alpine
steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0 # all history for all branches and tags
- name: setup sshd server
run: |
apk add git make curl perl bash build-base zlib-dev ucl-dev sudo
make ssh-server
- name: testing
run: |
make test
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v6
================================================
FILE: .github/workflows/trivy.yml
================================================
name: Trivy Security Scan
on:
pull_request:
branches:
- master
push:
branches:
- master
schedule:
- cron: "0 1 * * *" # Run daily at 1:00 AM UTC
jobs:
trivy-scan:
name: Trivy Vulnerability Scan
runs-on: ubuntu-latest
permissions:
contents: read
security-events: write
actions: read
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Run Trivy vulnerability scanner in fs mode
uses: aquasecurity/trivy-action@0.35.0
with:
scan-type: "fs"
scan-ref: "."
format: "sarif"
output: "trivy-results.sarif"
severity: "CRITICAL,HIGH,MEDIUM"
exit-code: "0" # Don't fail on vulnerabilities, only record them
- name: Upload Trivy results to GitHub Security tab
uses: github/codeql-action/upload-sarif@v4
if: always()
with:
sarif_file: "trivy-results.sarif"
- name: Run Trivy vulnerability scanner in table format
uses: aquasecurity/trivy-action@0.35.0
with:
scan-type: "fs"
scan-ref: "."
format: "table"
severity: "CRITICAL,HIGH"
exit-code: "1" # Fail only if CRITICAL/HIGH vulnerabilities found
================================================
FILE: .gitignore
================================================
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof
coverage.txt
================================================
FILE: .goreleaser.yaml
================================================
builds:
- # If true, skip the build.
# Useful for library projects.
# Default is false
skip: true
changelog:
# Set it to true if you wish to skip the changelog generation.
# This may result in an empty release notes on GitHub/GitLab/Gitea.
disable: false
# Changelog generation implementation to use.
#
# Valid options are:
# - `git`: uses `git log`;
# - `github`: uses the compare GitHub API, appending the author login to the changelog.
# - `gitlab`: uses the compare GitLab API, appending the author name and email to the changelog.
# - `github-native`: uses the GitHub release notes generation API, disables the groups feature.
#
# Defaults to `git`.
use: github
# Sorts the changelog by the commit's messages.
# Could either be asc, desc or empty
# Default is empty
sort: asc
# Group commits messages by given regex and title.
# Order value defines the order of the groups.
# Proving no regex means all commits will be grouped under the default group.
# Groups are disabled when using github-native, as it already groups things by itself.
#
# Default is no groups.
groups:
- title: Features
regexp: "^.*feat[(\\w)]*:+.*$"
order: 0
- title: "Bug fixes"
regexp: "^.*fix[(\\w)]*:+.*$"
order: 1
- title: "Enhancements"
regexp: "^.*chore[(\\w)]*:+.*$"
order: 2
- title: "Refactor"
regexp: "^.*refactor[(\\w)]*:+.*$"
order: 3
- title: "Build process updates"
regexp: ^.*?(build|ci)(\(.+\))??!?:.+$
order: 4
- title: "Documentation updates"
regexp: ^.*?docs?(\(.+\))??!?:.+$
order: 4
- title: Others
order: 999
================================================
FILE: CLAUDE.md
================================================
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
easyssh-proxy is a Go library that provides a simple SSH client implementation with support for SSH tunneling/proxy connections. It's forked from the original easyssh project with additional features for proxy connections, timeout handling, and secure key management.
## Core Architecture
### Main Types
- **MakeConfig**: Primary configuration struct containing SSH connection parameters (user, server, keys, timeouts, proxy settings)
- **DefaultConfig**: Configuration struct used for SSH proxy/jumphost connections
- Both structs share similar fields but MakeConfig includes additional proxy capabilities
### Key Methods
- `Connect()`: Establishes SSH session and client connection
- `Run()`: Executes single command and returns output
- `Stream()`: Executes command with real-time streaming output via channels
- `Scp()`: Copies files to remote server
- `WriteFile()`: Writes content from io.Reader to remote file
### Authentication Support
- Password authentication
- Private key files (with optional passphrase)
- Raw private key content (embedded in code)
- SSH agent integration
- Custom cipher and key exchange algorithms
### Proxy/Jumphost Architecture
The library supports SSH proxy connections where traffic is tunneled through an intermediate server:
```text
Client -> Jumphost -> Target Server
```
The `Proxy` field in MakeConfig uses DefaultConfig to define the jumphost connection parameters.
## Development Commands
### Testing
```bash
make test # Run all tests with coverage
go test -v ./... # Run tests verbose
```
### Code Quality
```bash
make fmt # Format code using gofumpt
make vet # Run go vet
```
### SSH Test Server Setup
```bash
make ssh-server # Setup local SSH test server (Alpine Linux)
```
### Linting
The project uses golangci-lint via GitHub Actions. No local lint command is defined in the Makefile.
## Testing Infrastructure
### Test Environment
- Uses Alpine Linux container with SSH server setup
- Creates test users: `drone-scp` and `root`
- SSH keys located in `tests/.ssh/` directory
- Test files in `tests/` include sample data and configuration
### CI/CD
- GitHub Actions workflow in `.github/workflows/testing.yml`
- Runs tests in Go 1.25 and 1.26 Alpine containers
- Includes golangci-lint for code quality
- Codecov integration for coverage reporting
## Code Patterns
### Configuration Pattern
```go
ssh := &easyssh.MakeConfig{
User: "username",
Server: "hostname",
KeyPath: "/path/to/key",
Port: "22",
Timeout: 60 * time.Second,
}
```
### Proxy Configuration
```go
ssh := &easyssh.MakeConfig{
// ... main server config
Proxy: easyssh.DefaultConfig{
// ... jumphost config
},
}
```
### Error Handling
Functions return multiple values following Go conventions:
- `Run()`: (stdout, stderr, isTimeout, error)
- `Stream()`: (stdoutChan, stderrChan, doneChan, errChan, error)
## Example Usage
Comprehensive examples are available in `_examples/` directory:
- `ssh/`: Basic command execution
- `scp/`: File copying
- `proxy/`: SSH tunneling through jumphost
- `stream/`: Real-time command output streaming
- `writeFile/`: Writing content to remote files
## Dependencies
- `golang.org/x/crypto/ssh`: Core SSH protocol implementation
- `github.com/ScaleFT/sshkeys`: Enhanced private key parsing with passphrase support
- `github.com/stretchr/testify`: Testing framework
## Security Considerations
- Supports both secure and insecure cipher configurations
- `UseInsecureCipher` flag enables legacy/weak ciphers when needed
- Fingerprint verification available for enhanced security
- Private keys can be embedded as strings or loaded from files
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2017 Bo-Yi Wu
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: Makefile
================================================
GOFMT ?= gofumpt -l -s
GO ?= go
PACKAGES ?= $(shell $(GO) list ./...)
SOURCES ?= $(shell find . -name "*.go" -type f)
all: lint
fmt:
@hash gofumpt > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
$(GO) install mvdan.cc/gofumpt; \
fi
$(GOFMT) -w $(SOURCES)
vet:
$(GO) vet $(PACKAGES)
test:
@$(GO) test -v -cover -coverprofile coverage.txt $(PACKAGES) && echo "\n==>\033[32m Ok\033[m\n" || exit 1
clean:
go clean -x -i ./...
rm -rf coverage.txt $(EXECUTABLE) $(DIST) vendor
ssh-server:
adduser -h /home/drone-scp -s /bin/sh -D -S drone-scp
echo drone-scp:1234 | chpasswd
mkdir -p /home/drone-scp/.ssh
chmod 700 /home/drone-scp/.ssh
cat tests/.ssh/id_rsa.pub >> /home/drone-scp/.ssh/authorized_keys
cat tests/.ssh/test.pub >> /home/drone-scp/.ssh/authorized_keys
chmod 600 /home/drone-scp/.ssh/authorized_keys
chown -R drone-scp /home/drone-scp/.ssh
# add public key to root user
mkdir -p /root/.ssh
chmod 700 /root/.ssh
cat tests/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
cat tests/.ssh/test.pub >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
# Append the following entry to run ALL command without a password for a user named drone-scp:
cat tests/sudoers >> /etc/sudoers.d/sudoers
# install ssh and start server
apk add --update openssh openrc
rm -rf /etc/ssh/ssh_host_rsa_key /etc/ssh/ssh_host_dsa_key
sed -i 's/^#PubkeyAuthentication yes/PubkeyAuthentication yes/g' /etc/ssh/sshd_config
sed -i 's/AllowTcpForwarding no/AllowTcpForwarding yes/g' /etc/ssh/sshd_config
./tests/entrypoint.sh /usr/sbin/sshd -D &
================================================
FILE: README.md
================================================
# easyssh-proxy
[](https://pkg.go.dev/github.com/appleboy/easyssh-proxy)
[](https://github.com/appleboy/easyssh-proxy/actions/workflows/testing.yml)
[](https://github.com/appleboy/easyssh-proxy/actions/workflows/trivy.yml)
[](https://codecov.io/gh/appleboy/easyssh-proxy)
[](https://goreportcard.com/report/github.com/appleboy/easyssh-proxy)
[](https://sourcegraph.com/github.com/appleboy/easyssh-proxy?badge)
[繁體中文](./README.zh-tw.md)
easyssh-proxy provides a simple implementation of some SSH protocol features in Go.
## Feature
This project is forked from [easyssh](https://github.com/hypersleep/easyssh) but add some features as the following.
- [x] Support plain text of user private key.
- [x] Support key path of user private key.
- [x] Support Timeout for the TCP connection to establish.
- [x] Support SSH ProxyCommand.
```bash
+--------+ +----------+ +-----------+
| Laptop | <--> | Jumphost | <--> | FooServer |
+--------+ +----------+ +-----------+
OR
+--------+ +----------+ +-----------+
| Laptop | <--> | Firewall | <--> | FooServer |
+--------+ +----------+ +-----------+
192.168.1.5 121.1.2.3 10.10.29.68
```
## Installation
```bash
go get github.com/appleboy/easyssh-proxy
```
**Requirements:** Go 1.24 or higher
## Usage
You can see detailed examples of the `ssh`, `scp`, `Proxy`, and `stream` commands inside the [`examples`](./_examples/) folder.
### MakeConfig
All functionality provided by this package is accessed via methods of the MakeConfig struct.
```go
ssh := &easyssh.MakeConfig{
User: "drone-scp",
Server: "localhost",
KeyPath: "./tests/.ssh/id_rsa",
Port: "22",
Timeout: 60 * time.Second,
}
stdout, stderr, done, err := ssh.Run("ls -al", 60*time.Second)
err = ssh.Scp("/root/source.csv", "/tmp/target.csv")
stdoutChan, stderrChan, doneChan, errChan, err = ssh.Stream("for i in {1..5}; do echo ${i}; sleep 1; done; exit 2;", 60*time.Second)
```
MakeConfig takes in the following properties:
| property | description |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| user | The SSH user to be logged in with |
| Server | The IP or hostname pointing of the server |
| Key | A string containing the private key to be used when making the connection |
| KeyPath | The path pointing to the SSH key file to be used when making the connection |
| Port | The port to use when connecting to the SSH daemon of the server |
| Protocol | The tcp protocol to be used: `"tcp", "tcp4" "tcp6"` |
| Passphrase | The Passphrase to unlock the provided SSH key (leave blank if no Passphrase is required) |
| Password | The Password to use to login the specified user |
| Timeout | The length of time to wait before timing out the request |
| Proxy | An additional set of configuration params that will be used to SSH into an additional server via the server configured in this top-level block |
| Ciphers | An array of ciphers (e.g. aes256-ctr) to enable for the SSH connection |
| KeyExchanges | An array of key exchanges (e.g. ecdh-sha2-nistp384) to enable for the SSH connection |
| Fingerprint | The expected fingerprint to be returned by the SSH server, results in a fingerprint error if they do not match |
| UseInsecureCipher | Enables the use of insecure ciphers and key exchanges that are insecure and can lead to compromise, [see ssh](#ssh) |
NOTE: Please view the reference documentation for the most up to date properties of [MakeConfig](https://pkg.go.dev/github.com/appleboy/easyssh-proxy#MakeConfig) and [DefaultConfig](https://pkg.go.dev/github.com/appleboy/easyssh-proxy#DefaultConfig)
### ssh
See [examples/ssh/ssh.go](./_examples/ssh/ssh.go)
```go
package main
import (
"fmt"
"time"
"github.com/appleboy/easyssh-proxy"
)
func main() {
// Create MakeConfig instance with remote username, server address and path to private key.
ssh := &easyssh.MakeConfig{
User: "appleboy",
Server: "example.com",
// Optional key or Password without either we try to contact your agent SOCKET
// Password: "password",
// Paste your source content of private key
// Key: `-----BEGIN RSA PRIVATE KEY-----
// MIIEpAIBAAKCAQEA4e2D/qPN08pzTac+a8ZmlP1ziJOXk45CynMPtva0rtK/RB26
// 7XC9wlRna4b3Ln8ew3q1ZcBjXwD4ppbTlmwAfQIaZTGJUgQbdsO9YA==
// -----END RSA PRIVATE KEY-----
// `,
KeyPath: "/Users/username/.ssh/id_rsa",
Port: "22",
Timeout: 60 * time.Second,
// Parse PrivateKey With Passphrase
Passphrase: "1234",
// Optional fingerprint SHA256 verification
// Get Fingerprint: ssh.FingerprintSHA256(key)
// Fingerprint: "SHA256:mVPwvezndPv/ARoIadVY98vAC0g+P/5633yTC4d/wXE"
// Enable the use of insecure ciphers and key exchange methods.
// This enables the use of the the following insecure ciphers and key exchange methods:
// - aes128-cbc
// - aes192-cbc
// - aes256-cbc
// - 3des-cbc
// - diffie-hellman-group-exchange-sha256
// - diffie-hellman-group-exchange-sha1
// Those algorithms are insecure and may allow plaintext data to be recovered by an attacker.
// UseInsecureCipher: true,
}
// Call Run method with command you want to run on remote server.
stdout, stderr, done, err := ssh.Run("ls -al", 60*time.Second)
// Handle errors
if err != nil {
panic("Can't run remote command: " + err.Error())
} else {
fmt.Println("don is :", done, "stdout is :", stdout, "; stderr is :", stderr)
}
}
```
### scp
See [examples/scp/scp.go](./_examples/scp/scp.go)
```go
package main
import (
"fmt"
"github.com/appleboy/easyssh-proxy"
)
func main() {
// Create MakeConfig instance with remote username, server address and path to private key.
ssh := &easyssh.MakeConfig{
User: "appleboy",
Server: "example.com",
Password: "123qwe",
Port: "22",
}
// Call Scp method with file you want to upload to remote server.
// Please make sure the `tmp` floder exists.
err := ssh.Scp("/root/source.csv", "/tmp/target.csv")
// Handle errors
if err != nil {
panic("Can't run remote command: " + err.Error())
} else {
fmt.Println("success")
}
}
```
### SSH ProxyCommand
See [examples/proxy/proxy.go](./_examples/proxy/proxy.go)
```go
ssh := &easyssh.MakeConfig{
User: "drone-scp",
Server: "localhost",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Timeout: 60 * time.Second,
Proxy: easyssh.DefaultConfig{
User: "drone-scp",
Server: "localhost",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Timeout: 60 * time.Second,
},
}
```
NOTE: Properties for the Proxy connection are not inherited from the Jumphost. You must explicitly specify them in the DefaultConfig struct.
e.g. A custom `Timeout` length must be specified for both the Jumphost (intermediary server) and the destination server.
### SSH Stream Log
See [examples/stream/stream.go](./_examples/stream/stream.go)
```go
func main() {
// Create MakeConfig instance with remote username, server address and path to private key.
ssh := &easyssh.MakeConfig{
Server: "localhost",
User: "drone-scp",
KeyPath: "./tests/.ssh/id_rsa",
Port: "22",
Timeout: 60 * time.Second,
}
// Call Run method with command you want to run on remote server.
stdoutChan, stderrChan, doneChan, errChan, err := ssh.Stream("for i in {1..5}; do echo ${i}; sleep 1; done; exit 2;", 60*time.Second)
// Handle errors
if err != nil {
panic("Can't run remote command: " + err.Error())
} else {
// read from the output channel until the done signal is passed
isTimeout := true
loop:
for {
select {
case isTimeout = <-doneChan:
break loop
case outline := <-stdoutChan:
fmt.Println("out:", outline)
case errline := <-stderrChan:
fmt.Println("err:", errline)
case err = <-errChan:
}
}
// get exit code or command error.
if err != nil {
fmt.Println("err: " + err.Error())
}
// command time out
if !isTimeout {
fmt.Println("Error: command timeout")
}
}
}
```
### WriteFile
See [examples/writeFile/writeFile.go](./_examples/writeFile/writeFile.go)
```go
func (ssh_conf *MakeConfig) WriteFile(reader io.Reader, size int64, etargetFile string) error
```
```go
func main() {
// Create MakeConfig instance with remote username, server address and path to private key.
ssh := &easyssh.MakeConfig{
Server: "localhost",
User: "drone-scp",
KeyPath: "./tests/.ssh/id_rsa",
Port: "22",
Timeout: 60 * time.Second,
}
fileContents := "Example Text..."
reader := strings.NewReader(fileContents)
// Write a file to the remote server using the writeFile command.
// Second argument specifies the number of bytes to write to the server from the reader.
if err := ssh.WriteFile(reader, int64(len(fileContents)), "/home/user/foo.txt"); err != nil {
return fmt.Errorf("Error: failed to write file to client. error: %w", err)
}
}
```
| property | description |
| ----------- | ------------------------------------------------------------------- |
| reader | The `io.reader` who's contents will be read and saved to the server |
| size | The number of bytes to be read from the `io.reader` |
| etargetFile | The location on the server that the file will be written to |
================================================
FILE: README.zh-tw.md
================================================
# easyssh-proxy
[](https://pkg.go.dev/github.com/appleboy/easyssh-proxy)
[](https://github.com/appleboy/easyssh-proxy/actions/workflows/testing.yml)
[](https://github.com/appleboy/easyssh-proxy/actions/workflows/trivy.yml)
[](https://codecov.io/gh/appleboy/easyssh-proxy)
[](https://goreportcard.com/report/github.com/appleboy/easyssh-proxy)
[](https://sourcegraph.com/github.com/appleboy/easyssh-proxy?badge)
easyssh-proxy 提供了一個用 Go 語言實現的一些 SSH 協議功能的簡單實現。
## 功能
這個項目是從 [easyssh](https://github.com/hypersleep/easyssh) 分叉而來,但添加了一些如下所示的功能。
- [x] 支援用戶私鑰的純文字。
- [x] 支援用戶私鑰的路徑。
- [x] 支援 TCP 連接建立的超時設定。
- [x] 支援 SSH ProxyCommand。
```bash
+--------+ +----------+ +-----------+
| Laptop | <--> | Jumphost | <--> | FooServer |
+--------+ +----------+ +-----------+
OR
+--------+ +----------+ +-----------+
| Laptop | <--> | Firewall | <--> | FooServer |
+--------+ +----------+ +-----------+
192.168.1.5 121.1.2.3 10.10.29.68
```
## 安裝
```bash
go get github.com/appleboy/easyssh-proxy
```
**需求:** Go 1.24 或更高版本
## 使用方法
你可以在 [`examples`](./_examples/) 資料夾中看到 `ssh`、`scp`、`Proxy` 和 `stream` 命令的詳細範例。
### MakeConfig
這個套件提供的所有功能都是通過 MakeConfig 結構體的方法來訪問的。
```go
ssh := &easyssh.MakeConfig{
User: "drone-scp",
Server: "localhost",
KeyPath: "./tests/.ssh/id_rsa",
Port: "22",
Timeout: 60 * time.Second,
}
stdout, stderr, done, err := ssh.Run("ls -al", 60*time.Second)
err = ssh.Scp("/root/source.csv", "/tmp/target.csv")
stdoutChan, stderrChan, doneChan, errChan, err = ssh.Stream("for i in {1..5}; do echo ${i}; sleep 1; done; exit 2;", 60*time.Second)
```
MakeConfig 接受以下屬性:
| 屬性 | 描述 |
| ----------------- | ---------------------------------------------------------------------------- |
| user | 要登入的 SSH 用戶 |
| Server | 伺服器的 IP 或主機名稱 |
| Key | 包含用於建立連接的私鑰的字串 |
| KeyPath | 指向用於建立連接的 SSH 密鑰文件的路徑 |
| Port | 連接到伺服器的 SSH 守護程序時使用的端口 |
| Protocol | 要使用的 TCP 協議:"tcp", "tcp4", "tcp6" |
| Passphrase | 用於解鎖提供的 SSH 密鑰的密碼(如果不需要密碼,則留空) |
| Password | 用於登入指定用戶的密碼 |
| Timeout | 請求超時前等待的時間長度 |
| Proxy | 一組額外的配置參數,將通過此頂層塊中配置的伺服器 SSH 到另一個伺服器 |
| Ciphers | 用於 SSH 連接的密碼陣列(例如 aes256-ctr) |
| KeyExchanges | 用於 SSH 連接的密鑰交換陣列(例如 ecdh-sha2-nistp384) |
| Fingerprint | SSH 伺服器返回的預期指紋,如果不匹配則會導致指紋錯誤 |
| UseInsecureCipher | 啟用不安全的密碼和密鑰交換,這些是不安全的,可能會導致妥協,[參見 ssh](#ssh) |
注意:請查看參考文件以獲取 [MakeConfig](https://pkg.go.dev/github.com/appleboy/easyssh-proxy#MakeConfig) 和 [DefaultConfig](https://pkg.go.dev/github.com/appleboy/easyssh-proxy#DefaultConfig) 的最新屬性。
### ssh
See [examples/ssh/ssh.go](./_examples/ssh/ssh.go)
```go
package main
import (
"fmt"
"time"
"github.com/appleboy/easyssh-proxy"
)
func main() {
// Create MakeConfig instance with remote username, server address and path to private key.
ssh := &easyssh.MakeConfig{
User: "appleboy",
Server: "example.com",
// Optional key or Password without either we try to contact your agent SOCKET
// Password: "password",
// Paste your source content of private key
// Key: `-----BEGIN RSA PRIVATE KEY-----
// MIIEpAIBAAKCAQEA4e2D/qPN08pzTac+a8ZmlP1ziJOXk45CynMPtva0rtK/RB26
// 7XC9wlRna4b3Ln8ew3q1ZcBjXwD4ppbTlmwAfQIaZTGJUgQbdsO9YA==
// -----END RSA PRIVATE KEY-----
// `,
KeyPath: "/Users/username/.ssh/id_rsa",
Port: "22",
Timeout: 60 * time.Second,
// Parse PrivateKey With Passphrase
Passphrase: "1234",
// Optional fingerprint SHA256 verification
// Get Fingerprint: ssh.FingerprintSHA256(key)
// Fingerprint: "SHA256:mVPwvezndPv/ARoIadVY98vAC0g+P/5633yTC4d/wXE"
// Enable the use of insecure ciphers and key exchange methods.
// This enables the use of the the following insecure ciphers and key exchange methods:
// - aes128-cbc
// - aes192-cbc
// - aes256-cbc
// - 3des-cbc
// - diffie-hellman-group-exchange-sha256
// - diffie-hellman-group-exchange-sha1
// Those algorithms are insecure and may allow plaintext data to be recovered by an attacker.
// UseInsecureCipher: true,
}
// Call Run method with command you want to run on remote server.
stdout, stderr, done, err := ssh.Run("ls -al", 60*time.Second)
// Handle errors
if err != nil {
panic("Can't run remote command: " + err.Error())
} else {
fmt.Println("don is :", done, "stdout is :", stdout, "; stderr is :", stderr)
}
}
```
### scp
See [examples/scp/scp.go](./_examples/scp/scp.go)
```go
package main
import (
"fmt"
"github.com/appleboy/easyssh-proxy"
)
func main() {
// Create MakeConfig instance with remote username, server address and path to private key.
ssh := &easyssh.MakeConfig{
User: "appleboy",
Server: "example.com",
Password: "123qwe",
Port: "22",
}
// Call Scp method with file you want to upload to remote server.
// Please make sure the `tmp` folder exists.
err := ssh.Scp("/root/source.csv", "/tmp/target.csv")
// Handle errors
if err != nil {
panic("Can't run remote command: " + err.Error())
} else {
fmt.Println("success")
}
}
```
### SSH ProxyCommand
See [examples/proxy/proxy.go](./_examples/proxy/proxy.go)
```go
ssh := &easyssh.MakeConfig{
User: "drone-scp",
Server: "localhost",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Timeout: 60 * time.Second,
Proxy: easyssh.DefaultConfig{
User: "drone-scp",
Server: "localhost",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Timeout: 60 * time.Second,
},
}
```
注意:代理連接的屬性不會從跳板機繼承。您必須在 DefaultConfig 結構體中明確指定它們。
例如,必須為跳板機(中介伺服器)和目標伺服器分別指定自定義的 `Timeout` 長度。
### SSH Stream Log
See [examples/stream/stream.go](./_examples/stream/stream.go)
```go
func main() {
// Create MakeConfig instance with remote username, server address and path to private key.
ssh := &easyssh.MakeConfig{
Server: "localhost",
User: "drone-scp",
KeyPath: "./tests/.ssh/id_rsa",
Port: "22",
Timeout: 60 * time.Second,
}
// Call Run method with command you want to run on remote server.
stdoutChan, stderrChan, doneChan, errChan, err := ssh.Stream("for i in {1..5}; do echo ${i}; sleep 1; done; exit 2;", 60*time.Second)
// Handle errors
if err != nil {
panic("Can't run remote command: " + err.Error())
} else {
// read from the output channel until the done signal is passed
isTimeout := true
loop:
for {
select {
case isTimeout = <-doneChan:
break loop
case outline := <-stdoutChan:
fmt.Println("out:", outline)
case errline := <-stderrChan:
fmt.Println("err:", errline)
case err = <-errChan:
}
}
// get exit code or command error.
if err != nil {
fmt.Println("err: " + err.Error())
}
// command time out
if !isTimeout {
fmt.Println("Error: command timeout")
}
}
}
```
### WriteFile
參見 [examples/writeFile/writeFile.go](./_examples/writeFile/writeFile.go)
```go
func (ssh_conf *MakeConfig) WriteFile(reader io.Reader, size int64, etargetFile string) error
```
```go
func main() {
// 使用遠程用戶名、伺服器地址和私鑰路徑創建 MakeConfig 實例。
ssh := &easyssh.MakeConfig{
Server: "localhost",
User: "drone-scp",
KeyPath: "./tests/.ssh/id_rsa",
Port: "22",
Timeout: 60 * time.Second,
}
fileContents := "Example Text..."
reader := strings.NewReader(fileContents)
// 使用 writeFile 命令將文件寫入到遠程伺服器。
// 第二個參數指定從 reader 中寫入到伺服器的字節數。
if err := ssh.WriteFile(reader, int64(len(fileContents)), "/home/user/foo.txt"); err != nil {
return fmt.Errorf("錯誤:無法將文件寫入到客戶端。錯誤:%w", err)
}
}
```
| 屬性 | 描述 |
| ----------- | --------------------------------------------- |
| reader | 將讀取其內容並保存到伺服器的 `io.reader` |
| size | 要從 `io.reader` 中讀取的字節數 |
| etargetFile | 文件將被寫入到伺服器上的位置 |
================================================
FILE: _examples/proxy/go.mod
================================================
module example
go 1.24.0
require github.com/appleboy/easyssh-proxy v1.5.0
require (
github.com/ScaleFT/sshkeys v1.4.0 // indirect
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a // indirect
golang.org/x/crypto v0.43.0 // indirect
golang.org/x/sys v0.37.0 // indirect
)
replace github.com/appleboy/easyssh-proxy v1.5.0 => ../../
================================================
FILE: _examples/proxy/go.sum
================================================
github.com/ScaleFT/sshkeys v1.4.0 h1:Yqd0cKA5PUvwV0dgRI67BDHGTsMHtGQBZbLXh1dthmE=
github.com/ScaleFT/sshkeys v1.4.0/go.mod h1:GineMkS8SEiELq8q5DzA2Wnrw65SqdD9a+hm8JOU1I4=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a h1:saTgr5tMLFnmy/yg3qDTft4rE5DY2uJ/cCxCe3q0XTU=
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a/go.mod h1:Bw9BbhOJVNR+t0jCqx2GC6zv0TGBsShs56Y3gfSCvl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04=
golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0=
golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.36.0 h1:zMPR+aF8gfksFprF/Nc/rd1wRS1EI6nDBGyWAvDzx2Q=
golang.org/x/term v0.36.0/go.mod h1:Qu394IJq6V6dCBRgwqshf3mPF85AqzYEzofzRdZkWss=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
================================================
FILE: _examples/proxy/proxy.go
================================================
package main
import (
"fmt"
"github.com/appleboy/easyssh-proxy"
)
func main() {
// Create MakeConfig instance with remote username, server address and path to private key.
ssh := &easyssh.MakeConfig{
User: "drone-scp",
Server: "localhost",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Proxy: easyssh.DefaultConfig{
User: "drone-scp",
Server: "localhost",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
},
}
// Call Scp method with file you want to upload to remote server.
// Please make sure the `tmp` floder exists.
err := ssh.Scp("/root/source.csv", "/tmp/target.csv")
if err != nil {
panic("Can't run remote command: " + err.Error())
}
fmt.Println("success")
}
================================================
FILE: _examples/scp/go.mod
================================================
module example
go 1.24.0
require github.com/appleboy/easyssh-proxy v1.5.0
require (
github.com/ScaleFT/sshkeys v1.4.0 // indirect
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a // indirect
golang.org/x/crypto v0.43.0 // indirect
golang.org/x/sys v0.37.0 // indirect
)
replace github.com/appleboy/easyssh-proxy v1.5.0 => ../../
================================================
FILE: _examples/scp/go.sum
================================================
github.com/ScaleFT/sshkeys v1.4.0 h1:Yqd0cKA5PUvwV0dgRI67BDHGTsMHtGQBZbLXh1dthmE=
github.com/ScaleFT/sshkeys v1.4.0/go.mod h1:GineMkS8SEiELq8q5DzA2Wnrw65SqdD9a+hm8JOU1I4=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a h1:saTgr5tMLFnmy/yg3qDTft4rE5DY2uJ/cCxCe3q0XTU=
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a/go.mod h1:Bw9BbhOJVNR+t0jCqx2GC6zv0TGBsShs56Y3gfSCvl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04=
golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0=
golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.36.0 h1:zMPR+aF8gfksFprF/Nc/rd1wRS1EI6nDBGyWAvDzx2Q=
golang.org/x/term v0.36.0/go.mod h1:Qu394IJq6V6dCBRgwqshf3mPF85AqzYEzofzRdZkWss=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
================================================
FILE: _examples/scp/scp.go
================================================
package main
import (
"fmt"
"github.com/appleboy/easyssh-proxy"
)
func main() {
// Create MakeConfig instance with remote username, server address and path to private key.
ssh := &easyssh.MakeConfig{
User: "appleboy",
Server: "example.com",
Password: "123qwe",
Port: "22",
}
// Call Scp method with file you want to upload to remote server.
// Please make sure the `tmp` floder exists.
err := ssh.Scp("/root/source.csv", "/tmp/target.csv")
// Handle errors
if err != nil {
panic("Can't run remote command: " + err.Error())
}
fmt.Println("success")
}
================================================
FILE: _examples/ssh/go.mod
================================================
module example
go 1.24.0
require github.com/appleboy/easyssh-proxy v1.5.0
require (
github.com/ScaleFT/sshkeys v1.4.0 // indirect
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a // indirect
golang.org/x/crypto v0.43.0 // indirect
golang.org/x/sys v0.37.0 // indirect
)
replace github.com/appleboy/easyssh-proxy v1.5.0 => ../../
================================================
FILE: _examples/ssh/go.sum
================================================
github.com/ScaleFT/sshkeys v1.4.0 h1:Yqd0cKA5PUvwV0dgRI67BDHGTsMHtGQBZbLXh1dthmE=
github.com/ScaleFT/sshkeys v1.4.0/go.mod h1:GineMkS8SEiELq8q5DzA2Wnrw65SqdD9a+hm8JOU1I4=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a h1:saTgr5tMLFnmy/yg3qDTft4rE5DY2uJ/cCxCe3q0XTU=
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a/go.mod h1:Bw9BbhOJVNR+t0jCqx2GC6zv0TGBsShs56Y3gfSCvl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04=
golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0=
golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.36.0 h1:zMPR+aF8gfksFprF/Nc/rd1wRS1EI6nDBGyWAvDzx2Q=
golang.org/x/term v0.36.0/go.mod h1:Qu394IJq6V6dCBRgwqshf3mPF85AqzYEzofzRdZkWss=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
================================================
FILE: _examples/ssh/ssh.go
================================================
package main
import (
"fmt"
"time"
"github.com/appleboy/easyssh-proxy"
)
func main() {
// Create MakeConfig instance with remote username, server address and path to private key.
ssh := &easyssh.MakeConfig{
User: "appleboy",
Server: "example.com",
// Optional key or Password without either we try to contact your agent SOCKET
// Password: "password",
// Paste your source content of private key
// Key: `-----BEGIN RSA PRIVATE KEY-----
// MIIEpAIBAAKCAQEA4e2D/qPN08pzTac+a8ZmlP1ziJOXk45CynMPtva0rtK/RB26
// 7XC9wlRna4b3Ln8ew3q1ZcBjXwD4ppbTlmwAfQIaZTGJUgQbdsO9YA==
// -----END RSA PRIVATE KEY-----
// `,
KeyPath: "/Users/username/.ssh/id_rsa",
Port: "22",
Timeout: 60 * time.Second,
// Parse PrivateKey With Passphrase
Passphrase: "1234",
// Optional fingerprint SHA256 verification
// Get Fingerprint: ssh.FingerprintSHA256(key)
// Fingerprint: "SHA256:mVPwvezndPv/ARoIadVY98vAC0g+P/5633yTC4d/wXE"
// Enable the use of insecure ciphers and key exchange methods.
// This enables the use of the the following insecure ciphers and key exchange methods:
// - aes128-cbc
// - aes192-cbc
// - aes256-cbc
// - 3des-cbc
// - diffie-hellman-group-exchange-sha256
// - diffie-hellman-group-exchange-sha1
// Those algorithms are insecure and may allow plaintext data to be recovered by an attacker.
// UseInsecureCipher: true,
}
// Call Run method with command you want to run on remote server.
stdout, stderr, done, err := ssh.Run("ls -al", 60*time.Second)
// Handle errors
if err != nil {
panic("Can't run remote command: " + err.Error())
}
fmt.Println("don is :", done, "stdout is :", stdout, "; stderr is :", stderr)
}
================================================
FILE: _examples/stream/go.mod
================================================
module example
go 1.24.0
require github.com/appleboy/easyssh-proxy v1.5.0
require (
github.com/ScaleFT/sshkeys v1.4.0 // indirect
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a // indirect
golang.org/x/crypto v0.43.0 // indirect
golang.org/x/sys v0.37.0 // indirect
)
replace github.com/appleboy/easyssh-proxy v1.5.0 => ../../
================================================
FILE: _examples/stream/go.sum
================================================
github.com/ScaleFT/sshkeys v1.4.0 h1:Yqd0cKA5PUvwV0dgRI67BDHGTsMHtGQBZbLXh1dthmE=
github.com/ScaleFT/sshkeys v1.4.0/go.mod h1:GineMkS8SEiELq8q5DzA2Wnrw65SqdD9a+hm8JOU1I4=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a h1:saTgr5tMLFnmy/yg3qDTft4rE5DY2uJ/cCxCe3q0XTU=
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a/go.mod h1:Bw9BbhOJVNR+t0jCqx2GC6zv0TGBsShs56Y3gfSCvl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04=
golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0=
golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.36.0 h1:zMPR+aF8gfksFprF/Nc/rd1wRS1EI6nDBGyWAvDzx2Q=
golang.org/x/term v0.36.0/go.mod h1:Qu394IJq6V6dCBRgwqshf3mPF85AqzYEzofzRdZkWss=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
================================================
FILE: _examples/stream/stream.go
================================================
package main
import (
"fmt"
"time"
"github.com/appleboy/easyssh-proxy"
)
func main() {
// Create MakeConfig instance with remote username, server address and path to private key.
ssh := &easyssh.MakeConfig{
Server: "localhost",
User: "drone-scp",
KeyPath: "./tests/.ssh/id_rsa",
Port: "22",
Timeout: 60 * time.Second,
}
// Call Run method with command you want to run on remote server.
stdoutChan, stderrChan, doneChan, errChan, err := ssh.Stream("for i in {1..5}; do echo ${i}; sleep 1; done; exit 2;", 60*time.Second)
// Handle errors
if err != nil {
panic("Can't run remote command: " + err.Error())
}
// read from the output channel until the done signal is passed
isTimeout := true
loop:
for {
select {
case isTimeout = <-doneChan:
break loop
case outline := <-stdoutChan:
fmt.Println("out:", outline)
case errline := <-stderrChan:
fmt.Println("err:", errline)
case err = <-errChan:
}
}
// get exit code or command error.
if err != nil {
panic("err: " + err.Error())
}
// command time out
if !isTimeout {
fmt.Println("Error: command timeout")
}
}
================================================
FILE: _examples/writeFile/go.mod
================================================
module example
go 1.24.0
require github.com/appleboy/easyssh-proxy v1.5.0
require (
github.com/ScaleFT/sshkeys v1.4.0 // indirect
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a // indirect
golang.org/x/crypto v0.43.0 // indirect
golang.org/x/sys v0.37.0 // indirect
)
replace github.com/appleboy/easyssh-proxy v1.5.0 => ../../
================================================
FILE: _examples/writeFile/go.sum
================================================
github.com/ScaleFT/sshkeys v1.4.0 h1:Yqd0cKA5PUvwV0dgRI67BDHGTsMHtGQBZbLXh1dthmE=
github.com/ScaleFT/sshkeys v1.4.0/go.mod h1:GineMkS8SEiELq8q5DzA2Wnrw65SqdD9a+hm8JOU1I4=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a h1:saTgr5tMLFnmy/yg3qDTft4rE5DY2uJ/cCxCe3q0XTU=
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a/go.mod h1:Bw9BbhOJVNR+t0jCqx2GC6zv0TGBsShs56Y3gfSCvl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04=
golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0=
golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.36.0 h1:zMPR+aF8gfksFprF/Nc/rd1wRS1EI6nDBGyWAvDzx2Q=
golang.org/x/term v0.36.0/go.mod h1:Qu394IJq6V6dCBRgwqshf3mPF85AqzYEzofzRdZkWss=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
================================================
FILE: _examples/writeFile/writeFile.go
================================================
package main
import (
"strings"
"time"
"github.com/appleboy/easyssh-proxy"
)
func main() {
// Create MakeConfig instance with remote username, server address and path to private key.
ssh := &easyssh.MakeConfig{
User: "appleboy",
Server: "example.com",
KeyPath: "/Users/username/.ssh/id_rsa",
Port: "22",
Timeout: 60 * time.Second,
}
fileContents := "Example Text..."
reader := strings.NewReader(fileContents)
// Write a file to the remote server using the writeFile command.
// Second arguement specifies the number of bytes to write to the server from the reader.
if err := ssh.WriteFile(reader, int64(len(fileContents)), "/home/user/foo.txt"); err != nil {
panic("Error: failed to write file to client")
}
}
================================================
FILE: easyssh.go
================================================
// Package easyssh provides a simple implementation of some SSH protocol
// features in Go. You can simply run a command on a remote server or get a file
// even simpler than native console SSH client. You don't need to think about
// Dials, sessions, defers, or public keys... Let easyssh think about it!
package easyssh
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"log"
"net"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/ScaleFT/sshkeys"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
)
var (
defaultTimeout = 60 * time.Second
defaultBufferSize = 4096
)
var (
// ErrProxyDialTimeout is returned when proxy dial connection times out
ErrProxyDialTimeout = errors.New("proxy dial timeout")
)
type Protocol string
const (
PROTOCOL_TCP Protocol = "tcp"
PROTOCOL_TCP4 Protocol = "tcp4"
PROTOCOL_TCP6 Protocol = "tcp6"
)
type (
// MakeConfig Contains main authority information.
// User field should be a name of user on remote server (ex. john in ssh john@example.com).
// Server field should be a remote machine address (ex. example.com in ssh john@example.com)
// Key is a path to private key on your local machine.
// Port is SSH server port on remote machine.
// Note: easyssh looking for private key in user's home directory (ex. /home/john + Key).
// Then ensure your Key begins from '/' (ex. /.ssh/id_rsa)
MakeConfig struct {
User string
Server string
Key string
KeyPath string
Port string
Protocol Protocol
Passphrase string
Password string
Timeout time.Duration
Proxy DefaultConfig
ReadBuffSize int
Ciphers []string
KeyExchanges []string
Fingerprint string
// Enable the use of insecure ciphers and key exchange methods.
// This enables the use of the the following insecure ciphers and key exchange methods:
// - aes128-cbc
// - aes192-cbc
// - aes256-cbc
// - 3des-cbc
// - diffie-hellman-group-exchange-sha256
// - diffie-hellman-group-exchange-sha1
// Those algorithms are insecure and may allow plaintext data to be recovered by an attacker.
UseInsecureCipher bool
// RequestPty requests a pseudo-terminal from the server.
RequestPty bool
}
// DefaultConfig for ssh proxy config
DefaultConfig struct {
User string
Server string
Key string
KeyPath string
Port string
Protocol Protocol
Passphrase string
Password string
Timeout time.Duration
Ciphers []string
KeyExchanges []string
Fingerprint string
// Enable the use of insecure ciphers and key exchange methods.
// This enables the use of the the following insecure ciphers and key exchange methods:
// - aes128-cbc
// - aes192-cbc
// - aes256-cbc
// - 3des-cbc
// - diffie-hellman-group-exchange-sha256
// - diffie-hellman-group-exchange-sha1
// Those algorithms are insecure and may allow plaintext data to be recovered by an attacker.
UseInsecureCipher bool
}
)
// returns ssh.Signer from user you running app home path + cutted key path.
// (ex. pubkey,err := getKeyFile("/.ssh/id_rsa") )
func getKeyFile(keypath, passphrase string) (ssh.Signer, error) {
var pubkey ssh.Signer
var err error
buf, err := os.ReadFile(keypath)
if err != nil {
return nil, err
}
if passphrase != "" {
pubkey, err = sshkeys.ParseEncryptedPrivateKey(buf, []byte(passphrase))
} else {
pubkey, err = ssh.ParsePrivateKey(buf)
}
if err != nil {
return nil, err
}
return pubkey, nil
}
// returns *ssh.ClientConfig and io.Closer.
// if io.Closer is not nil, io.Closer.Close() should be called when
// *ssh.ClientConfig is no longer used.
func getSSHConfig(config DefaultConfig) (*ssh.ClientConfig, io.Closer) {
var sshAgent io.Closer
// auths holds the detected ssh auth methods
auths := []ssh.AuthMethod{}
// figure out what auths are requested, what is supported
if config.Password != "" {
auths = append(auths, ssh.Password(config.Password))
}
if config.KeyPath != "" {
if pubkey, err := getKeyFile(config.KeyPath, config.Passphrase); err != nil {
log.Printf("getKeyFile error: %v\n", err)
} else {
auths = append(auths, ssh.PublicKeys(pubkey))
}
}
if config.Key != "" {
var signer ssh.Signer
var err error
if config.Passphrase != "" {
signer, err = sshkeys.ParseEncryptedPrivateKey([]byte(config.Key), []byte(config.Passphrase))
} else {
signer, err = ssh.ParsePrivateKey([]byte(config.Key))
}
if err != nil {
log.Printf("ssh.ParsePrivateKey: %v\n", err)
} else {
auths = append(auths, ssh.PublicKeys(signer))
}
}
if sshAgent, err := net.Dial("unix", os.Getenv("SSH_AUTH_SOCK")); err == nil {
auths = append(auths, ssh.PublicKeysCallback(agent.NewClient(sshAgent).Signers))
}
c := ssh.Config{}
if config.UseInsecureCipher {
c.SetDefaults()
c.Ciphers = append(c.Ciphers, "aes128-cbc", "aes192-cbc", "aes256-cbc", "3des-cbc")
c.KeyExchanges = append(c.KeyExchanges, "diffie-hellman-group-exchange-sha1", "diffie-hellman-group-exchange-sha256")
}
if len(config.Ciphers) > 0 {
c.Ciphers = append(c.Ciphers, config.Ciphers...)
}
if len(config.KeyExchanges) > 0 {
c.KeyExchanges = append(c.KeyExchanges, config.KeyExchanges...)
}
hostKeyCallback := ssh.InsecureIgnoreHostKey()
if config.Fingerprint != "" {
hostKeyCallback = func(hostname string, remote net.Addr, publicKey ssh.PublicKey) error {
if ssh.FingerprintSHA256(publicKey) != config.Fingerprint {
return fmt.Errorf("ssh: host key fingerprint mismatch")
}
return nil
}
}
return &ssh.ClientConfig{
Config: c,
Timeout: config.Timeout,
User: config.User,
Auth: auths,
HostKeyCallback: hostKeyCallback,
}, sshAgent
}
// Connect to remote server using MakeConfig struct and returns *ssh.Session
func (ssh_conf *MakeConfig) Connect() (*ssh.Session, *ssh.Client, error) {
var client *ssh.Client
var err error
// Default protocol is: tcp.
if ssh_conf.Protocol == "" {
ssh_conf.Protocol = PROTOCOL_TCP
}
if ssh_conf.Proxy.Protocol == "" {
ssh_conf.Proxy.Protocol = PROTOCOL_TCP
}
targetConfig, closer := getSSHConfig(DefaultConfig{
User: ssh_conf.User,
Key: ssh_conf.Key,
KeyPath: ssh_conf.KeyPath,
Passphrase: ssh_conf.Passphrase,
Password: ssh_conf.Password,
Timeout: ssh_conf.Timeout,
Ciphers: ssh_conf.Ciphers,
KeyExchanges: ssh_conf.KeyExchanges,
Fingerprint: ssh_conf.Fingerprint,
UseInsecureCipher: ssh_conf.UseInsecureCipher,
})
if closer != nil {
defer closer.Close()
}
// Enable proxy command
if ssh_conf.Proxy.Server != "" {
proxyConfig, closer := getSSHConfig(DefaultConfig{
User: ssh_conf.Proxy.User,
Key: ssh_conf.Proxy.Key,
KeyPath: ssh_conf.Proxy.KeyPath,
Passphrase: ssh_conf.Proxy.Passphrase,
Password: ssh_conf.Proxy.Password,
Timeout: ssh_conf.Proxy.Timeout,
Ciphers: ssh_conf.Proxy.Ciphers,
KeyExchanges: ssh_conf.Proxy.KeyExchanges,
Fingerprint: ssh_conf.Proxy.Fingerprint,
UseInsecureCipher: ssh_conf.Proxy.UseInsecureCipher,
})
if closer != nil {
defer closer.Close()
}
proxyClient, err := ssh.Dial(string(ssh_conf.Proxy.Protocol), net.JoinHostPort(ssh_conf.Proxy.Server, ssh_conf.Proxy.Port), proxyConfig)
if err != nil {
return nil, nil, err
}
// Apply timeout to the connection from proxy to target server
timeout := ssh_conf.Timeout
if timeout == 0 {
timeout = defaultTimeout
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
type connResult struct {
conn net.Conn
err error
}
connCh := make(chan connResult, 1)
go func() {
conn, err := proxyClient.Dial(string(ssh_conf.Protocol), net.JoinHostPort(ssh_conf.Server, ssh_conf.Port))
select {
case connCh <- connResult{conn: conn, err: err}:
// Successfully sent result
case <-ctx.Done():
// Context was cancelled, clean up the connection if it was established
if conn != nil {
conn.Close()
}
}
}()
var conn net.Conn
select {
case result := <-connCh:
conn = result.conn
err = result.err
case <-ctx.Done():
return nil, nil, fmt.Errorf("%w: %v", ErrProxyDialTimeout, ctx.Err())
}
if err != nil {
return nil, nil, err
}
ncc, chans, reqs, err := ssh.NewClientConn(conn, net.JoinHostPort(ssh_conf.Server, ssh_conf.Port), targetConfig)
if err != nil {
return nil, nil, err
}
client = ssh.NewClient(ncc, chans, reqs)
} else {
client, err = ssh.Dial(string(ssh_conf.Protocol), net.JoinHostPort(ssh_conf.Server, ssh_conf.Port), targetConfig)
if err != nil {
return nil, nil, err
}
}
session, err := client.NewSession()
if err != nil {
return nil, nil, err
}
// Request a pseudo-terminal if this option is set
if ssh_conf.RequestPty {
modes := ssh.TerminalModes{
ssh.ECHO: 0, // disable echoing
ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
}
if err := session.RequestPty("xterm", 80, 40, modes); err != nil {
session.Close()
return nil, nil, err
}
}
return session, client, nil
}
// Stream returns one channel that combines the stdout and stderr of the command
// as it is run on the remote machine, and another that sends true when the
// command is done. The sessions and channels will then be closed.
func (ssh_conf *MakeConfig) Stream(command string, timeout ...time.Duration) (<-chan string, <-chan string, <-chan bool, <-chan error, error) {
// continuously send the command's output over the channel
stdoutChan := make(chan string)
stderrChan := make(chan string)
doneChan := make(chan bool)
errChan := make(chan error)
// connect to remote host
session, client, err := ssh_conf.Connect()
if err != nil {
return stdoutChan, stderrChan, doneChan, errChan, err
}
// defer session.Close()
// connect to both outputs (they are of type io.Reader)
outReader, err := session.StdoutPipe()
if err != nil {
client.Close()
session.Close()
return stdoutChan, stderrChan, doneChan, errChan, err
}
errReader, err := session.StderrPipe()
if err != nil {
client.Close()
session.Close()
return stdoutChan, stderrChan, doneChan, errChan, err
}
err = session.Start(command)
if err != nil {
client.Close()
session.Close()
return stdoutChan, stderrChan, doneChan, errChan, err
}
// combine outputs, create a line-by-line scanner
stdoutReader := io.MultiReader(outReader)
stderrReader := io.MultiReader(errReader)
var stdoutScanner *bufio.Reader
var stderrScanner *bufio.Reader
if ssh_conf.ReadBuffSize > 0 {
stdoutScanner = bufio.NewReaderSize(stdoutReader, ssh_conf.ReadBuffSize)
} else {
stdoutScanner = bufio.NewReaderSize(stdoutReader, defaultBufferSize)
}
if ssh_conf.ReadBuffSize > 0 {
stderrScanner = bufio.NewReaderSize(stderrReader, ssh_conf.ReadBuffSize)
} else {
stderrScanner = bufio.NewReaderSize(stderrReader, defaultBufferSize)
}
go func(stdoutScanner, stderrScanner *bufio.Reader, stdoutChan, stderrChan chan string, doneChan chan bool, errChan chan error) {
defer close(doneChan)
defer close(errChan)
defer client.Close()
defer session.Close()
// default timeout value
executeTimeout := defaultTimeout
if len(timeout) > 0 {
executeTimeout = timeout[0]
}
ctxTimeout, cancel := context.WithTimeout(context.Background(), executeTimeout)
defer cancel()
res := make(chan struct{}, 1)
var resWg sync.WaitGroup
resWg.Add(2)
go func() {
defer close(stdoutChan)
for {
var text string
text, err = stdoutScanner.ReadString('\n')
if errors.Is(err, io.EOF) {
break
}
stdoutChan <- strings.TrimRight(text, "\n")
}
resWg.Done()
}()
go func() {
defer close(stderrChan)
for {
var text string
text, err = stderrScanner.ReadString('\n')
if errors.Is(err, io.EOF) {
break
}
stderrChan <- strings.TrimRight(text, "\n")
}
resWg.Done()
}()
go func() {
resWg.Wait()
// close all of our open resources
res <- struct{}{}
}()
select {
case <-res:
errChan <- session.Wait()
doneChan <- true
case <-ctxTimeout.Done():
errChan <- fmt.Errorf("Run Command Timeout: %v", ctxTimeout.Err())
doneChan <- false
}
}(stdoutScanner, stderrScanner, stdoutChan, stderrChan, doneChan, errChan)
return stdoutChan, stderrChan, doneChan, errChan, err
}
// Run command on remote machine and returns its stdout as a string
func (ssh_conf *MakeConfig) Run(command string, timeout ...time.Duration) (outStr string, errStr string, isTimeout bool, err error) {
stdoutChan, stderrChan, doneChan, errChan, err := ssh_conf.Stream(command, timeout...)
if err != nil {
// Check if the error is from a proxy dial timeout
if errors.Is(err, ErrProxyDialTimeout) {
isTimeout = true
}
return outStr, errStr, isTimeout, err
}
// read from the output channel until the done signal is passed
loop:
for {
select {
case isTimeout = <-doneChan:
break loop
case outline, ok := <-stdoutChan:
if !ok {
stdoutChan = nil
}
if outline != "" {
outStr += outline + "\n"
}
case errline, ok := <-stderrChan:
if !ok {
stderrChan = nil
}
if errline != "" {
errStr += errline + "\n"
}
case err = <-errChan:
}
}
// return the concatenation of all signals from the output channel
return outStr, errStr, isTimeout, err
}
// WriteFile reads size bytes from the reader and writes them to a file on the remote machine
func (ssh_conf *MakeConfig) WriteFile(reader io.Reader, size int64, etargetFile string) error {
session, client, err := ssh_conf.Connect()
if err != nil {
return err
}
defer client.Close()
defer session.Close()
targetFile := filepath.Base(etargetFile)
w, err := session.StdinPipe()
if err != nil {
return err
}
copyF := func() error {
_, err := fmt.Fprintln(w, "C0644", size, targetFile)
if err != nil {
return err
}
if size > 0 {
_, err = io.Copy(w, reader)
if err != nil {
return err
}
}
_, err = fmt.Fprint(w, "\x00")
if err != nil {
return err
}
return nil
}
copyErrC := make(chan error, 1)
go func() {
defer w.Close()
copyErrC <- copyF()
}()
err = session.Run(fmt.Sprintf("scp -tr %s", etargetFile))
if err != nil {
return err
}
err = <-copyErrC
return err
}
// Scp uploads sourceFile to remote machine like native scp console app.
func (ssh_conf *MakeConfig) Scp(sourceFile string, etargetFile string) error {
session, client, err := ssh_conf.Connect()
if err != nil {
return err
}
defer client.Close()
defer session.Close()
src, srcErr := os.Open(sourceFile)
if srcErr != nil {
return srcErr
}
defer src.Close()
srcStat, statErr := src.Stat()
if statErr != nil {
return statErr
}
return ssh_conf.WriteFile(src, srcStat.Size(), etargetFile)
}
================================================
FILE: easyssh_test.go
================================================
package easyssh
import (
"context"
"errors"
"os"
"os/user"
"path"
"runtime"
"testing"
"time"
"github.com/stretchr/testify/assert"
"golang.org/x/crypto/ssh"
)
func getHostPublicKeyFile(keypath string) (ssh.PublicKey, error) {
var pubkey ssh.PublicKey
var err error
buf, err := os.ReadFile(keypath)
if err != nil {
return nil, err
}
pubkey, _, _, _, err = ssh.ParseAuthorizedKey(buf)
if err != nil {
return nil, err
}
return pubkey, nil
}
func TestGetKeyFile(t *testing.T) {
// missing file
_, err := getKeyFile("abc", "")
assert.Error(t, err)
assert.Equal(t, "open abc: no such file or directory", err.Error())
// wrong format
_, err = getKeyFile("./tests/.ssh/id_rsa.pub", "")
assert.Error(t, err)
assert.Equal(t, "ssh: no key found", err.Error())
_, err = getKeyFile("./tests/.ssh/id_rsa", "")
assert.NoError(t, err)
_, err = getKeyFile("./tests/.ssh/test", "1234")
assert.NoError(t, err)
}
func TestRunCommandWithFingerprint(t *testing.T) {
// wrong fingerprint
sshConf := &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Fingerprint: "wrong",
}
outStr, errStr, isTimeout, err := sshConf.Run("whoami", 10)
assert.Equal(t, "", outStr)
assert.Equal(t, "", errStr)
assert.False(t, isTimeout)
assert.Error(t, err)
hostKey, err := getHostPublicKeyFile("/etc/ssh/ssh_host_rsa_key.pub")
assert.NoError(t, err)
sshConf = &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Fingerprint: ssh.FingerprintSHA256(hostKey),
}
outStr, errStr, isTimeout, err = sshConf.Run("whoami")
assert.Equal(t, "drone-scp\n", outStr)
assert.Equal(t, "", errStr)
assert.True(t, isTimeout)
assert.NoError(t, err)
}
func TestPrivateKeyAndPassword(t *testing.T) {
// provide password and ssh private key
ssh := &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
Password: "1234",
KeyPath: "./tests/.ssh/id_rsa",
}
outStr, errStr, isTimeout, err := ssh.Run("whoami")
assert.Equal(t, "drone-scp\n", outStr)
assert.Equal(t, "", errStr)
assert.True(t, isTimeout)
assert.NoError(t, err)
// provide correct password and wrong private key
ssh = &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
Password: "1234",
KeyPath: "./tests/.ssh/id_rsa.pub",
}
outStr, errStr, isTimeout, err = ssh.Run("whoami")
assert.Equal(t, "drone-scp\n", outStr)
assert.Equal(t, "", errStr)
assert.True(t, isTimeout)
assert.NoError(t, err)
// provide wrong password and correct private key
ssh = &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
Password: "123456",
KeyPath: "./tests/.ssh/id_rsa",
}
outStr, errStr, isTimeout, err = ssh.Run("whoami")
assert.Equal(t, "drone-scp\n", outStr)
assert.Equal(t, "", errStr)
assert.True(t, isTimeout)
assert.NoError(t, err)
}
func TestRunCommand(t *testing.T) {
// wrong key
ssh := &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa.pub",
}
outStr, errStr, isTimeout, err := ssh.Run("whoami", 10)
assert.Equal(t, "", outStr)
assert.Equal(t, "", errStr)
assert.False(t, isTimeout)
assert.Error(t, err)
ssh = &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
}
outStr, errStr, isTimeout, err = ssh.Run("whoami")
assert.Equal(t, "drone-scp\n", outStr)
assert.Equal(t, "", errStr)
assert.True(t, isTimeout)
assert.NoError(t, err)
// error message: not found
outStr, errStr, isTimeout, err = ssh.Run("whoami1234")
assert.Equal(t, "", outStr)
assert.Equal(t, "sh: whoami1234: not found\n", errStr)
assert.True(t, isTimeout)
// Process exited with status 127
assert.Error(t, err)
// error message: Run Command Timeout
outStr, errStr, isTimeout, err = ssh.Run("sleep 2", 1*time.Second)
assert.Equal(t, "", outStr)
assert.Equal(t, "", errStr)
assert.False(t, isTimeout)
assert.Error(t, err)
assert.Equal(t, "Run Command Timeout: "+context.DeadlineExceeded.Error(), err.Error())
// test exit code
outStr, errStr, isTimeout, err = ssh.Run("exit 1")
assert.Equal(t, "", outStr)
assert.Equal(t, "", errStr)
assert.True(t, isTimeout)
// Process exited with status 1
assert.Error(t, err)
}
func TestSCPCommand(t *testing.T) {
// wrong key
ssh := &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa.pub",
}
err := ssh.Scp("./tests/a.txt", "a.txt")
assert.Error(t, err)
ssh = &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
}
err = ssh.Scp("./tests/a.txt", "a.txt")
assert.NoError(t, err)
u, err := user.Lookup("drone-scp")
if err != nil {
t.Fatalf("Lookup: %v", err)
}
// check file exist
if _, err := os.Stat(path.Join(u.HomeDir, "a.txt")); os.IsNotExist(err) {
t.Fatalf("SCP-error: %v", err)
}
}
func TestSCPCommandWithKey(t *testing.T) {
ssh := &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
Key: `-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA4e2D/qPN08pzTac+a8ZmlP1ziJOXk45CynMPtva0rtK/RB26
VbfAF0hIJji7ltvnYnqCU9oFfvEM33cTn7T96+od8ib/Vz25YU8ZbstqtIskPuwC
bv3K0mAHgsviJyRD7yM+QKTbBQEgbGuW6gtbMKhiYfiIB4Dyj7AdS/fk3v26wDgz
7SHI5OBqu9bv1KhxQYdFEnU3PAtAqeccgzNpbH3eYLyGzuUxEIJlhpZ/uU2G9ppj
/cSrONVPiI8Ahi4RrlZjmP5l57/sq1ClGulyLpFcMw68kP5FikyqHpHJHRBNgU57
1y0Ph33SjBbs0haCIAcmreWEhGe+/OXnJe6VUQIDAQABAoIBAH97emORIm9DaVSD
7mD6DqA7c5m5Tmpgd6eszU08YC/Vkz9oVuBPUwDQNIX8tT0m0KVs42VVPIyoj874
bgZMJoucC1G8V5Bur9AMxhkShx9g9A7dNXJTmsKilRpk2TOk7wBdLp9jZoKoZBdJ
jlp6FfaazQjjKD6zsCsMATwAoRCBpBNsmT6QDN0n0bIgY0tE6YGQaDdka0dAv68G
R0VZrcJ9voT6+f+rgJLoojn2DAu6iXaM99Gv8FK91YCymbQlXXgrk6CyS0IHexN7
V7a3k767KnRbrkqd3o6JyNun/CrUjQwHs1IQH34tvkWScbseRaFehcAm6mLT93RP
muauvMECgYEA9AXGtfDMse0FhvDPZx4mx8x+vcfsLvDHcDLkf/lbyPpu97C27b/z
ia07bu5TAXesUZrWZtKA5KeRE5doQSdTOv1N28BEr8ZwzDJwfn0DPUYUOxsN2iIy
MheO5A45Ko7bjKJVkZ61Mb1UxtqCTF9mqu9R3PBdJGthWOd+HUvF460CgYEA7QRf
Z8+vpGA+eSuu29e0xgRKnRzed5zXYpcI4aERc3JzBgO4Z0er9G8l66OWVGdMfpe6
CBajC5ToIiT8zqoYxXwqJgN+glir4gJe3mm8J703QfArZiQrdk0NTi5bY7+vLLG/
knTrtpdsKih6r3kjhuPPaAsIwmMxIydFvATKjLUCgYEAh/y4EihRSk5WKC8GxeZt
oiZ58vT4z+fqnMIfyJmD5up48JuQNcokw/LADj/ODiFM7GUnWkGxBrvDA3H67WQm
49bJjs8E+BfUQFdTjYnJRlpJZ+7Zt1gbNQMf5ENw5CCchTDqEq6pN0DVf8PBnSIF
KvkXW9KvdV5J76uCAn15mDkCgYA1y8dHzbjlCz9Cy2pt1aDfTPwOew33gi7U3skS
RTerx29aDyAcuQTLfyrROBkX4TZYiWGdEl5Bc7PYhCKpWawzrsH2TNa7CRtCOh2E
R+V/84+GNNf04ALJYCXD9/ugQVKmR1XfDRCvKeFQFE38Y/dvV2etCswbKt5tRy2p
xkCe/QKBgQCkLqafD4S20YHf6WTp3jp/4H/qEy2X2a8gdVVBi1uKkGDXr0n+AoVU
ib4KbP5ovZlrjL++akMQ7V2fHzuQIFWnCkDA5c2ZAqzlM+ZN+HRG7gWur7Bt4XH1
7XC9wlRna4b3Ln8ew3q1ZcBjXwD4ppbTlmwAfQIaZTGJUgQbdsO9YA==
-----END RSA PRIVATE KEY-----
`,
}
// source file not found
err := ssh.Scp("./tests/test.txt", "a.txt")
assert.Error(t, err)
// target file not found ex: appleboy folder not found
err = ssh.Scp("./tests/a.txt", "/appleboy/a.txt")
assert.Error(t, err)
err = ssh.Scp("./tests/a.txt", "a.txt")
assert.NoError(t, err)
u, err := user.Lookup("drone-scp")
if err != nil {
t.Fatalf("Lookup: %v", err)
}
// check file exist
if _, err := os.Stat(path.Join(u.HomeDir, "a.txt")); os.IsNotExist(err) {
t.Fatalf("SCP-error: %v", err)
}
}
func TestProxyClient(t *testing.T) {
ssh := &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
Password: "1234",
Proxy: DefaultConfig{
User: "drone-scp",
Server: "localhost",
Port: "22",
Password: "123456",
},
}
// password of proxy client is incorrect.
// can't connect proxy server
session, client, err := ssh.Connect()
assert.Nil(t, session)
assert.Nil(t, client)
assert.Error(t, err)
ssh = &MakeConfig{
Server: "www.che.ccu.edu.tw",
User: "drone-scp",
Port: "228",
Password: "123456",
Proxy: DefaultConfig{
User: "drone-scp",
Server: "localhost",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
},
}
// proxy client can't dial to target server
session, client, err = ssh.Connect()
assert.Nil(t, session)
assert.Nil(t, client)
assert.Error(t, err)
ssh = &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
Password: "123456",
Proxy: DefaultConfig{
User: "drone-scp",
Server: "localhost",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
},
}
// proxy client can't create new client connection of target
session, client, err = ssh.Connect()
assert.Nil(t, session)
assert.Nil(t, client)
assert.Error(t, err)
ssh = &MakeConfig{
User: "drone-scp",
Server: "localhost",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Proxy: DefaultConfig{
User: "drone-scp",
Server: "localhost",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
},
}
session, client, err = ssh.Connect()
assert.NotNil(t, session)
assert.NotNil(t, client)
assert.NoError(t, err)
}
func TestProxyClientSSHCommand(t *testing.T) {
ssh := &MakeConfig{
User: "drone-scp",
Server: "localhost",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Proxy: DefaultConfig{
User: "drone-scp",
Server: "localhost",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
},
}
outStr, errStr, isTimeout, err := ssh.Run("whoami")
assert.Equal(t, "drone-scp\n", outStr)
assert.Equal(t, "", errStr)
assert.True(t, isTimeout)
assert.NoError(t, err)
}
func TestSCPCommandWithPassword(t *testing.T) {
ssh := &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
Password: "1234",
Timeout: 60 * time.Second,
}
err := ssh.Scp("./tests/b.txt", "b.txt")
assert.NoError(t, err)
u, err := user.Lookup("drone-scp")
if err != nil {
t.Fatalf("Lookup: %v", err)
}
// check file exist
if _, err := os.Stat(path.Join(u.HomeDir, "b.txt")); os.IsNotExist(err) {
t.Fatalf("SCP-error: %v", err)
}
}
func TestWrongRawKey(t *testing.T) {
// wrong key
ssh := &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
Key: "appleboy",
}
outStr, errStr, isTimeout, err := ssh.Run("whoami")
assert.Equal(t, "", outStr)
assert.Equal(t, "", errStr)
assert.False(t, isTimeout)
assert.Error(t, err)
}
func TestExitCode(t *testing.T) {
ssh := &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Timeout: 60 * time.Second,
}
outStr, errStr, isTimeout, err := ssh.Run("set -e;echo 1; mkdir a;mkdir a;echo 2")
assert.Equal(t, "1\n", outStr)
assert.Equal(t, "mkdir: can't create directory 'a': File exists\n", errStr)
assert.True(t, isTimeout)
assert.Error(t, err)
}
func TestSSHWithPassphrase(t *testing.T) {
ssh := &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
KeyPath: "./tests/.ssh/test",
Passphrase: "1234",
Timeout: 60 * time.Second,
}
outStr, errStr, isTimeout, err := ssh.Run("set -e;echo 1; mkdir test1234;mkdir test1234;echo 2")
assert.Equal(t, "1\n", outStr)
assert.Equal(t, "mkdir: can't create directory 'test1234': File exists\n", errStr)
assert.True(t, isTimeout)
assert.Error(t, err)
}
func TestSCPCommandUseInsecureCipher(t *testing.T) {
ssh := &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
UseInsecureCipher: true,
}
err := ssh.Scp("./tests/a.txt", "a.txt")
assert.NoError(t, err)
u, err := user.Lookup("drone-scp")
if err != nil {
t.Fatalf("Lookup: %v", err)
}
// check file exist
if _, err := os.Stat(path.Join(u.HomeDir, "a.txt")); os.IsNotExist(err) {
t.Fatalf("SCP-error: %v", err)
}
}
// TestRootAccount test root account
func TestRootAccount(t *testing.T) {
ssh := &MakeConfig{
Server: "localhost",
User: "root",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
}
outStr, errStr, isTimeout, err := ssh.Run("whoami")
assert.Equal(t, "root\n", outStr)
assert.Equal(t, "", errStr)
assert.True(t, isTimeout)
assert.NoError(t, err)
}
// TestSudoCommand
func TestSudoCommand(t *testing.T) {
ssh := &MakeConfig{
Server: "localhost",
User: "drone-scp",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
RequestPty: true,
}
outStr, errStr, isTimeout, err := ssh.Run(`sudo su - -c "whoami"`)
assert.Equal(t, "root\r\n", outStr)
assert.Equal(t, "", errStr)
assert.True(t, isTimeout)
assert.NoError(t, err)
}
func TestCommandTimeout(t *testing.T) {
ssh := &MakeConfig{
Server: "localhost",
User: "root",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
}
outStr, errStr, isTimeout, err := ssh.Run("whoami; sleep 2", 1*time.Second)
assert.Equal(t, "root\n", outStr)
assert.Equal(t, "", errStr)
assert.False(t, isTimeout)
assert.NotNil(t, err)
assert.Equal(t, "Run Command Timeout: "+context.DeadlineExceeded.Error(), err.Error())
}
// TestProxyTimeoutHandling tests that timeout is properly respected when using proxy connections
// This test uses a non-existent proxy server to force a timeout during proxy connection
func TestProxyTimeoutHandling(t *testing.T) {
ssh := &MakeConfig{
Server: "example.com",
User: "testuser",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Timeout: 1 * time.Second, // Short timeout for testing
Proxy: DefaultConfig{
User: "testuser",
Server: "10.255.255.1", // Non-routable IP that should timeout
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Timeout: 1 * time.Second,
},
}
// Test Connect() method directly to test proxy connection timeout
start := time.Now()
session, client, err := ssh.Connect()
elapsed := time.Since(start)
// Should timeout within reasonable bounds
assert.True(t, elapsed < 3*time.Second, "Connection should timeout within 3 seconds, took %v", elapsed)
assert.True(t, elapsed >= 1*time.Second, "Connection should take at least 1 second (timeout value), took %v", elapsed)
// Should return nil session and client
assert.Nil(t, session)
assert.Nil(t, client)
// Should have error
assert.NotNil(t, err)
}
// TestProxyDialTimeout tests the specific scenario described in issue #93
// where proxy dial timeout should be respected and properly detected
func TestProxyDialTimeout(t *testing.T) {
ssh := &MakeConfig{
Server: "10.255.255.1", // Non-routable IP that should timeout
User: "testuser",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Timeout: 2 * time.Second, // Short timeout for testing
Proxy: DefaultConfig{
User: "testuser",
Server: "10.255.255.2", // Another non-routable IP for proxy
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Timeout: 2 * time.Second,
},
}
// Test Connect() method directly to avoid SSH server dependency
start := time.Now()
session, client, err := ssh.Connect()
elapsed := time.Since(start)
// Should timeout within reasonable bounds
assert.True(t, elapsed < 5*time.Second, "Connection should timeout within 5 seconds, took %v", elapsed)
assert.True(t, elapsed >= 2*time.Second, "Connection should take at least 2 seconds (timeout value), took %v", elapsed)
// Should return nil session and client
assert.Nil(t, session)
assert.Nil(t, client)
// Should have error
assert.NotNil(t, err)
// Note: This will timeout at the proxy connection level, not at proxy dial level
// so it won't be ErrProxyDialTimeout, but we can still verify the timeout behavior
}
// TestProxyDialTimeoutInRun tests timeout detection in Run method
func TestProxyDialTimeoutInRun(t *testing.T) {
ssh := &MakeConfig{
Server: "example.com",
User: "testuser",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Timeout: 2 * time.Second,
Proxy: DefaultConfig{
User: "testuser",
Server: "127.0.0.1", // Assume localhost SSH exists
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Timeout: 2 * time.Second,
},
}
// Mock a scenario where Connect() returns ErrProxyDialTimeout
// by temporarily changing the target to a non-routable address
ssh.Server = "10.255.255.1"
start := time.Now()
outStr, errStr, isTimeout, err := ssh.Run("whoami")
elapsed := time.Since(start)
// Should timeout within reasonable bounds
assert.True(t, elapsed < 5*time.Second, "Should timeout within 5 seconds, took %v", elapsed)
// Should return empty output
assert.Equal(t, "", outStr)
assert.Equal(t, "", errStr)
// Should have error
assert.NotNil(t, err)
// If it's specifically a proxy dial timeout, isTimeout should be true
if errors.Is(err, ErrProxyDialTimeout) {
assert.True(t, isTimeout, "isTimeout should be true for proxy dial timeout")
}
}
// TestProxyGoroutineLeak tests that no goroutines are leaked when proxy dial times out
func TestProxyGoroutineLeak(t *testing.T) {
// Get initial goroutine count
initialGoroutines := runtime.NumGoroutine()
ssh := &MakeConfig{
Server: "10.255.255.1", // Non-routable IP that should timeout
User: "testuser",
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Timeout: 1 * time.Second, // Short timeout
Proxy: DefaultConfig{
User: "testuser",
Server: "10.255.255.2", // Another non-routable IP for proxy
Port: "22",
KeyPath: "./tests/.ssh/id_rsa",
Timeout: 1 * time.Second,
},
}
// Run multiple timeout operations
for i := 0; i < 5; i++ {
_, _, err := ssh.Connect()
assert.NotNil(t, err) // Should have error due to timeout
}
// Give some time for goroutines to cleanup
time.Sleep(100 * time.Millisecond)
runtime.GC() // Force garbage collection
// Check final goroutine count - should not have grown significantly
finalGoroutines := runtime.NumGoroutine()
// Allow for some variance due to test framework overhead, but shouldn't grow by more than 2-3 goroutines
assert.True(t, finalGoroutines <= initialGoroutines+3,
"Goroutine leak detected: initial=%d, final=%d", initialGoroutines, finalGoroutines)
}
================================================
FILE: go.mod
================================================
module github.com/appleboy/easyssh-proxy
go 1.25.9
require (
github.com/ScaleFT/sshkeys v1.4.0
github.com/stretchr/testify v1.8.4
golang.org/x/crypto v0.43.0
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
golang.org/x/sys v0.37.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
================================================
FILE: go.sum
================================================
github.com/ScaleFT/sshkeys v1.4.0 h1:Yqd0cKA5PUvwV0dgRI67BDHGTsMHtGQBZbLXh1dthmE=
github.com/ScaleFT/sshkeys v1.4.0/go.mod h1:GineMkS8SEiELq8q5DzA2Wnrw65SqdD9a+hm8JOU1I4=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a h1:saTgr5tMLFnmy/yg3qDTft4rE5DY2uJ/cCxCe3q0XTU=
github.com/dchest/bcrypt_pbkdf v0.0.0-20150205184540-83f37f9c154a/go.mod h1:Bw9BbhOJVNR+t0jCqx2GC6zv0TGBsShs56Y3gfSCvl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
golang.org/x/crypto v0.43.0 h1:dduJYIi3A3KOfdGOHX8AVZ/jGiyPa3IbBozJ5kNuE04=
golang.org/x/crypto v0.43.0/go.mod h1:BFbav4mRNlXJL4wNeejLpWxB7wMbc79PdRGhWKncxR0=
golang.org/x/sys v0.37.0 h1:fdNQudmxPjkdUTPnLn5mdQv7Zwvbvpaxqs831goi9kQ=
golang.org/x/sys v0.37.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.36.0 h1:zMPR+aF8gfksFprF/Nc/rd1wRS1EI6nDBGyWAvDzx2Q=
golang.org/x/term v0.36.0/go.mod h1:Qu394IJq6V6dCBRgwqshf3mPF85AqzYEzofzRdZkWss=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
================================================
FILE: tests/.ssh/id_rsa
================================================
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA4e2D/qPN08pzTac+a8ZmlP1ziJOXk45CynMPtva0rtK/RB26
VbfAF0hIJji7ltvnYnqCU9oFfvEM33cTn7T96+od8ib/Vz25YU8ZbstqtIskPuwC
bv3K0mAHgsviJyRD7yM+QKTbBQEgbGuW6gtbMKhiYfiIB4Dyj7AdS/fk3v26wDgz
7SHI5OBqu9bv1KhxQYdFEnU3PAtAqeccgzNpbH3eYLyGzuUxEIJlhpZ/uU2G9ppj
/cSrONVPiI8Ahi4RrlZjmP5l57/sq1ClGulyLpFcMw68kP5FikyqHpHJHRBNgU57
1y0Ph33SjBbs0haCIAcmreWEhGe+/OXnJe6VUQIDAQABAoIBAH97emORIm9DaVSD
7mD6DqA7c5m5Tmpgd6eszU08YC/Vkz9oVuBPUwDQNIX8tT0m0KVs42VVPIyoj874
bgZMJoucC1G8V5Bur9AMxhkShx9g9A7dNXJTmsKilRpk2TOk7wBdLp9jZoKoZBdJ
jlp6FfaazQjjKD6zsCsMATwAoRCBpBNsmT6QDN0n0bIgY0tE6YGQaDdka0dAv68G
R0VZrcJ9voT6+f+rgJLoojn2DAu6iXaM99Gv8FK91YCymbQlXXgrk6CyS0IHexN7
V7a3k767KnRbrkqd3o6JyNun/CrUjQwHs1IQH34tvkWScbseRaFehcAm6mLT93RP
muauvMECgYEA9AXGtfDMse0FhvDPZx4mx8x+vcfsLvDHcDLkf/lbyPpu97C27b/z
ia07bu5TAXesUZrWZtKA5KeRE5doQSdTOv1N28BEr8ZwzDJwfn0DPUYUOxsN2iIy
MheO5A45Ko7bjKJVkZ61Mb1UxtqCTF9mqu9R3PBdJGthWOd+HUvF460CgYEA7QRf
Z8+vpGA+eSuu29e0xgRKnRzed5zXYpcI4aERc3JzBgO4Z0er9G8l66OWVGdMfpe6
CBajC5ToIiT8zqoYxXwqJgN+glir4gJe3mm8J703QfArZiQrdk0NTi5bY7+vLLG/
knTrtpdsKih6r3kjhuPPaAsIwmMxIydFvATKjLUCgYEAh/y4EihRSk5WKC8GxeZt
oiZ58vT4z+fqnMIfyJmD5up48JuQNcokw/LADj/ODiFM7GUnWkGxBrvDA3H67WQm
49bJjs8E+BfUQFdTjYnJRlpJZ+7Zt1gbNQMf5ENw5CCchTDqEq6pN0DVf8PBnSIF
KvkXW9KvdV5J76uCAn15mDkCgYA1y8dHzbjlCz9Cy2pt1aDfTPwOew33gi7U3skS
RTerx29aDyAcuQTLfyrROBkX4TZYiWGdEl5Bc7PYhCKpWawzrsH2TNa7CRtCOh2E
R+V/84+GNNf04ALJYCXD9/ugQVKmR1XfDRCvKeFQFE38Y/dvV2etCswbKt5tRy2p
xkCe/QKBgQCkLqafD4S20YHf6WTp3jp/4H/qEy2X2a8gdVVBi1uKkGDXr0n+AoVU
ib4KbP5ovZlrjL++akMQ7V2fHzuQIFWnCkDA5c2ZAqzlM+ZN+HRG7gWur7Bt4XH1
7XC9wlRna4b3Ln8ew3q1ZcBjXwD4ppbTlmwAfQIaZTGJUgQbdsO9YA==
-----END RSA PRIVATE KEY-----
================================================
FILE: tests/.ssh/id_rsa.pub
================================================
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDh7YP+o83TynNNpz5rxmaU/XOIk5eTjkLKcw+29rSu0r9EHbpVt8AXSEgmOLuW2+dieoJT2gV+8QzfdxOftP3r6h3yJv9XPblhTxluy2q0iyQ+7AJu/crSYAeCy+InJEPvIz5ApNsFASBsa5bqC1swqGJh+IgHgPKPsB1L9+Te/brAODPtIcjk4Gq71u/UqHFBh0USdTc8C0Cp5xyDM2lsfd5gvIbO5TEQgmWGln+5TYb2mmP9xKs41U+IjwCGLhGuVmOY/mXnv+yrUKUa6XIukVwzDryQ/kWKTKoekckdEE2BTnvXLQ+HfdKMFuzSFoIgByat5YSEZ7785ecl7pVR drone-scp@localhost
================================================
FILE: tests/.ssh/test
================================================
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABAgX0UT5U
dbd5qk/WLiRyDeAAAAEAAAAAEAAAIXAAAAB3NzaC1yc2EAAAADAQABAAACAQDojzlRtxSq
AaOGaPHwCSRlsw870qwpc55W5AxlcOsbFZdtSwZ/dESBu5ql3dLsTB7WcqXoaA7Qp3w5GV
RcFxn+5r2dL17MPe3zZrLNZulbnkXiaVgYLjWa0cAv9zD+0nR8/mtz2DbkpKCD8R3oLJ2B
z5oscT2XLcPvIKZlw2eBErpSopLxfpPyhU8WNK9E38mUl2tjtiBVIoIJmtgYWY8XmIpEUR
iiRjPidBJUVmLq9kKdUV62V/pMB2UDzqPJUiuABgzh8/9/qM81uMCwyqULzaVhPE+S9P7L
dv1Npj5nqwOmUcGj0dhofi+F+qZ8WqGkQJ5JPam0LkGuMKGNJywrxo8XTXSpYCUvbKrTWo
0/1GNLCcHpIcjhUUJGObOMk1YI0Tu52PGpzDf1kI+zzAgPqWxxzegQdLcPIgm4I6x6S48E
V13THoAoU5T+rLrhE0i6FokGIwKv4SycDtFCvIdOr1jxJpw0CrKHqMG/kzeljtM1HOojD5
gHwESwwsZL5P5/IWvnZlGZD0fAp/SPWpZIeMTeH12QANxX69RoQfKLRMYWSabDUvGKkIxQ
CBaoVOmyVQIqyT5wTZ3msfGVLb729TlZcNo+8snG0k2W9skdlahx1TugzE096P+RzjUfov
6g1NZKHCN8VSeu4+gmPIEiuN3tt99dKDNBMx/QYLfPpwAAB1DxxEspVRHEF4mTxw4+hFhe
855+u3ffHmjgrK7IWZqrrze8bayRAVKPK7UMux4ZCOccc1ydtJFGUrZw8Q5gMe+Y+TusXE
WB7LWZK5an/WrEVe1jNgxwrQKjXauKtTY33CFnnTvdE8dUixHr3AddYq1gQ4WcB7v08sj6
f8V4yf80u294H5pjYxFMmTu4QldphV/mZcPQCyuzZKmkPLK2TzZWqGk615zJDd/W8Inm1c
IJTQPH4tIA3X3daThxOMLC3eQXC2rvl7qaSz2k8ok7LnND8GrTU0CnE6XUMNjRjlxXO+6n
XGVILifwk+bdLlE6aPIqhSuwx/TnbzHwj8DYnd5/Da/KdXpbc4T+925w6til98lyfRICol
So6gXace2IK33LKEAaEIr3im+ZFgSIvWZdPu/ZPV7nlNcb/rbMsRF6fKAMFA/kpPr4z5tQ
0pMJYfUmPCMdP7ahZ3km/Cpmee/VQ07s11myA2XeaEPov6yNrHJJtnAp5wsZ5s6ifLmoyl
WEPKt8YoIIDib44ANoyhgf6+PA2i+367p5U55ynI6HTXOdB/xWqJ7k4Rah4BSbd1t73wyU
kh04/9+YGDabwup7WzT07S7b+T5tGKAwMwK0cE/y5RyVI5JwT2b7fvbO6YH9ZFaNOMT+e0
jBpsrEDkdqnVaFU5b6yWO4Gw6I4Myw+ByATlPM6rmAQoOgfmQmoI47UiTYPr4bLvB7w02B
yQb2AxWDFdCJadZDTpFp5E5mXudt3JnfnKpR+9zDud4AahEU63ggJn0gpd51zRtqrTViob
qnZ9UtMl9dzGReZFInS6Uq6ge4JJlsxhEVREr/RPUa4NldT7nRMnfxlnwiVcgrdNdeL2Ho
5azXYMsDsACBR9rmz6h7JOpM/oyupbyitGtJMiBrR20UD264L4zZIBU4d6MXQADdOo+oKE
OofB9Zj9ovIAGzb9SNAh7vEXE0X6C/EdRNI/DOlca15bd33r+HgKTIONqTws2wThLnSx1r
W0voqE6SnhUhQ1FovxtBFYE1Ve8HR7BGyO6AJGQOpqivLry7W1BJyOiwSJ+DDUmcrnCyqJ
IoDc9pHQ/9hBlJz2qeBNaSdwMZWKkTCnIYq1f8FAKdRqujFx81toUZw7Lb03JmKZBlALvU
PvXcfxCDqSVy66SHVEtGvegFCeo0gQJS0BywQkushDVSoqGQppVoICNtyuzaMzpzkWj5tP
iYJzm5VBDucWkCmmqzFVVVdeX4Vd5crQ08ZeuHHOAL61bKde7ji1XnvlmllpByeHA5uPef
mGmgf/A1fM3MqioWW/C/Beffe5tJDKxoG7lavIg7F83c48wk+SeJ+2twNMySu1PDYmlRvb
VUdy1LtjutFtvySYBDHTFUOkvTOCX01gMTaB8HhaZAA+cjt91jrdKkKBh8spQHg1En/oaR
rmuqMWuMadxKIlzUBWLkAme78ce0SbpnGmBG1jz6kbjF3ZWWFJVj+3DHwE9dydfX4gCKT8
iV3IuifJLGtmaQO5AgpquMWYKsdOI+HCsWN2+YngqScmfokMSR4bn8DmcLNVYzzNkfo2/o
Oc/ZHtSJlXsY/5el+Bg4FBsvX3akyz32KJ9azsexjMFQl6dt5e6qAeV7kGKic8uaqXhWYW
l/sKzuqXVqVP8QwfipH+SZB3b71canc2mnC3+eXroSgG9yYneGzxfP4ppABGRu/hSyLaaq
tGyqgelrCXKSiWQs/Vgj46zEAoeIvLW9/NwnPkV3r499Ieh7kqMl2iZzpBXqab2ip6yt0+
9GQuBwb3YNj7HO/a2YU0aMJrs6YofOa6/0h4ZvLYe6ndzDAAFIlUmqGiHUnjnDtChaUZLX
E+9a8GkASVSizvMEpo/71uzOhn3Ta9ixDBqDQgA1DD0p3ko4bq7nYTNIfqghpJW2yTb8Sq
Fw9yuZ7WRcS/SNmsVxCN8UsimixI4uugKgiU+YWLdZrlaQk7yCRUZ4Drris4FBW55AjVJ8
nz3suOA+nh8JK0DN99hE9EAtgtMc1oKb76te1VCtd5tUfjN13qq5SvHMQp/dn+y+aVSIEg
KrvhXVwxyncL7AC04yK0TJHVk83vXCK6hyFnPeFBPhY0yUtq1smWLrjotaW8ZRLMKG6Kz/
cD69lsCnhFATfbBmKh6mRrBUaZV3nvZKKojJGnTguOQZodg0EEx/XR+aXFmJfKzyo4wdfK
OQR/HeDLS+X1tAzEkZl3QtAgeNWwngXlov3wJgg0R5X4scJZlG9ns7UNrJG2D9E4LTLMvZ
W1d9tnqAJprUdR9vvqUXGgbndzV+MuV/gY52jt2p7gvscBFVwLLuH7eTarrvqfBPAx+I33
V79GEkDdc9rCpA6BGDEJGr/Xcpx2tDiSqLc8vELfpruROx4T4PuPZvKqqcvHNNUYUQi1+y
7quwL7RgZj+i5hXGTRQ5Y+YfVYY+7sNgUxQpS5pC64s7bvwB0pHjgjn1KTXuyroPkV6pWA
FfFEk1ETJhXcl7plxpmcLROyI=
-----END OPENSSH PRIVATE KEY-----
================================================
FILE: tests/.ssh/test.pub
================================================
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDojzlRtxSqAaOGaPHwCSRlsw870qwpc55W5AxlcOsbFZdtSwZ/dESBu5ql3dLsTB7WcqXoaA7Qp3w5GVRcFxn+5r2dL17MPe3zZrLNZulbnkXiaVgYLjWa0cAv9zD+0nR8/mtz2DbkpKCD8R3oLJ2Bz5oscT2XLcPvIKZlw2eBErpSopLxfpPyhU8WNK9E38mUl2tjtiBVIoIJmtgYWY8XmIpEURiiRjPidBJUVmLq9kKdUV62V/pMB2UDzqPJUiuABgzh8/9/qM81uMCwyqULzaVhPE+S9P7Ldv1Npj5nqwOmUcGj0dhofi+F+qZ8WqGkQJ5JPam0LkGuMKGNJywrxo8XTXSpYCUvbKrTWo0/1GNLCcHpIcjhUUJGObOMk1YI0Tu52PGpzDf1kI+zzAgPqWxxzegQdLcPIgm4I6x6S48EV13THoAoU5T+rLrhE0i6FokGIwKv4SycDtFCvIdOr1jxJpw0CrKHqMG/kzeljtM1HOojD5gHwESwwsZL5P5/IWvnZlGZD0fAp/SPWpZIeMTeH12QANxX69RoQfKLRMYWSabDUvGKkIxQCBaoVOmyVQIqyT5wTZ3msfGVLb729TlZcNo+8snG0k2W9skdlahx1TugzE096P+RzjUfov6g1NZKHCN8VSeu4+gmPIEiuN3tt99dKDNBMx/QYLfPpw== deploy@easyssh
================================================
FILE: tests/a.txt
================================================
appleboy
================================================
FILE: tests/b.txt
================================================
================================================
FILE: tests/entrypoint.sh
================================================
#!/bin/sh
if [ ! -f "/etc/ssh/ssh_host_rsa_key" ]; then
# generate fresh rsa key
ssh-keygen -f /etc/ssh/ssh_host_rsa_key -N '' -t rsa
fi
if [ ! -f "/etc/ssh/ssh_host_dsa_key" ]; then
# generate fresh dsa key
ssh-keygen -f /etc/ssh/ssh_host_dsa_key -N '' -t dsa
fi
exec "$@"
================================================
FILE: tests/global/c.txt
================================================
================================================
FILE: tests/global/d.txt
================================================
================================================
FILE: tests/sudoers
================================================
Defaults requiretty
drone-scp ALL=(ALL) NOPASSWD:ALL
gitextract_unycxq1o/
├── .github/
│ ├── FUNDING.yml
│ ├── dependabot.yml
│ └── workflows/
│ ├── codeql.yml
│ ├── goreleaser.yml
│ ├── testing.yml
│ └── trivy.yml
├── .gitignore
├── .goreleaser.yaml
├── CLAUDE.md
├── LICENSE
├── Makefile
├── README.md
├── README.zh-tw.md
├── _examples/
│ ├── proxy/
│ │ ├── go.mod
│ │ ├── go.sum
│ │ └── proxy.go
│ ├── scp/
│ │ ├── go.mod
│ │ ├── go.sum
│ │ └── scp.go
│ ├── ssh/
│ │ ├── go.mod
│ │ ├── go.sum
│ │ └── ssh.go
│ ├── stream/
│ │ ├── go.mod
│ │ ├── go.sum
│ │ └── stream.go
│ └── writeFile/
│ ├── go.mod
│ ├── go.sum
│ └── writeFile.go
├── easyssh.go
├── easyssh_test.go
├── go.mod
├── go.sum
└── tests/
├── .ssh/
│ ├── id_rsa
│ ├── id_rsa.pub
│ ├── test
│ └── test.pub
├── a.txt
├── b.txt
├── entrypoint.sh
├── global/
│ ├── c.txt
│ └── d.txt
└── sudoers
SYMBOL INDEX (39 symbols across 7 files)
FILE: _examples/proxy/proxy.go
function main (line 9) | func main() {
FILE: _examples/scp/scp.go
function main (line 9) | func main() {
FILE: _examples/ssh/ssh.go
function main (line 10) | func main() {
FILE: _examples/stream/stream.go
function main (line 10) | func main() {
FILE: _examples/writeFile/writeFile.go
function main (line 10) | func main() {
FILE: easyssh.go
type Protocol (line 36) | type Protocol
constant PROTOCOL_TCP (line 39) | PROTOCOL_TCP Protocol = "tcp"
constant PROTOCOL_TCP4 (line 40) | PROTOCOL_TCP4 Protocol = "tcp4"
constant PROTOCOL_TCP6 (line 41) | PROTOCOL_TCP6 Protocol = "tcp6"
type MakeConfig (line 52) | type MakeConfig struct
method Connect (line 210) | func (ssh_conf *MakeConfig) Connect() (*ssh.Session, *ssh.Client, erro...
method Stream (line 339) | func (ssh_conf *MakeConfig) Stream(command string, timeout ...time.Dur...
method Run (line 454) | func (ssh_conf *MakeConfig) Run(command string, timeout ...time.Durati...
method WriteFile (line 491) | func (ssh_conf *MakeConfig) WriteFile(reader io.Reader, size int64, et...
method Scp (line 543) | func (ssh_conf *MakeConfig) Scp(sourceFile string, etargetFile string)...
type DefaultConfig (line 84) | type DefaultConfig struct
function getKeyFile (line 113) | func getKeyFile(keypath, passphrase string) (ssh.Signer, error) {
function getSSHConfig (line 137) | func getSSHConfig(config DefaultConfig) (*ssh.ClientConfig, io.Closer) {
FILE: easyssh_test.go
function getHostPublicKeyFile (line 17) | func getHostPublicKeyFile(keypath string) (ssh.PublicKey, error) {
function TestGetKeyFile (line 33) | func TestGetKeyFile(t *testing.T) {
function TestRunCommandWithFingerprint (line 51) | func TestRunCommandWithFingerprint(t *testing.T) {
function TestPrivateKeyAndPassword (line 85) | func TestPrivateKeyAndPassword(t *testing.T) {
function TestRunCommand (line 132) | func TestRunCommand(t *testing.T) {
function TestSCPCommand (line 185) | func TestSCPCommand(t *testing.T) {
function TestSCPCommandWithKey (line 218) | func TestSCPCommandWithKey(t *testing.T) {
function TestProxyClient (line 275) | func TestProxyClient(t *testing.T) {
function TestProxyClientSSHCommand (line 353) | func TestProxyClientSSHCommand(t *testing.T) {
function TestSCPCommandWithPassword (line 374) | func TestSCPCommandWithPassword(t *testing.T) {
function TestWrongRawKey (line 397) | func TestWrongRawKey(t *testing.T) {
function TestExitCode (line 413) | func TestExitCode(t *testing.T) {
function TestSSHWithPassphrase (line 429) | func TestSSHWithPassphrase(t *testing.T) {
function TestSCPCommandUseInsecureCipher (line 446) | func TestSCPCommandUseInsecureCipher(t *testing.T) {
function TestRootAccount (line 470) | func TestRootAccount(t *testing.T) {
function TestSudoCommand (line 486) | func TestSudoCommand(t *testing.T) {
function TestCommandTimeout (line 502) | func TestCommandTimeout(t *testing.T) {
function TestProxyTimeoutHandling (line 520) | func TestProxyTimeoutHandling(t *testing.T) {
function TestProxyDialTimeout (line 555) | func TestProxyDialTimeout(t *testing.T) {
function TestProxyDialTimeoutInRun (line 591) | func TestProxyDialTimeoutInRun(t *testing.T) {
function TestProxyGoroutineLeak (line 632) | func TestProxyGoroutineLeak(t *testing.T) {
Condensed preview — 42 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (100K chars).
[
{
"path": ".github/FUNDING.yml",
"chars": 768,
"preview": "# These are supported funding model platforms\n\ngithub: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [u"
},
{
"path": ".github/dependabot.yml",
"chars": 195,
"preview": "version: 2\nupdates:\n - package-ecosystem: github-actions\n directory: /\n schedule:\n interval: weekly\n - pack"
},
{
"path": ".github/workflows/codeql.yml",
"chars": 1758,
"preview": "# For most projects, this workflow file will not need changing; you simply need\n# to commit it to your repository.\n#\n# Y"
},
{
"path": ".github/workflows/goreleaser.yml",
"chars": 770,
"preview": "name: Goreleaser\n\non:\n push:\n tags:\n - \"*\"\n\npermissions:\n contents: write\n\njobs:\n goreleaser:\n runs-on: ub"
},
{
"path": ".github/workflows/testing.yml",
"chars": 1117,
"preview": "name: Lint and Testing\n\non:\n push:\n pull_request:\n\njobs:\n lint:\n runs-on: ubuntu-latest\n steps:\n - name: C"
},
{
"path": ".github/workflows/trivy.yml",
"chars": 1274,
"preview": "name: Trivy Security Scan\n\non:\n pull_request:\n branches:\n - master\n push:\n branches:\n - master\n sched"
},
{
"path": ".gitignore",
"chars": 280,
"preview": "# Compiled Object files, Static and Dynamic libs (Shared Objects)\n*.o\n*.a\n*.so\n\n# Folders\n_obj\n_test\n\n# Architecture spe"
},
{
"path": ".goreleaser.yaml",
"chars": 1681,
"preview": "builds:\n - # If true, skip the build.\n # Useful for library projects.\n # Default is false\n skip: true\n\nchangel"
},
{
"path": "CLAUDE.md",
"chars": 3887,
"preview": "# CLAUDE.md\n\nThis file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.\n\n## "
},
{
"path": "LICENSE",
"chars": 1065,
"preview": "MIT License\n\nCopyright (c) 2017 Bo-Yi Wu\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\no"
},
{
"path": "Makefile",
"chars": 1564,
"preview": "GOFMT ?= gofumpt -l -s\nGO ?= go\nPACKAGES ?= $(shell $(GO) list ./...)\nSOURCES ?= $(shell find . -name \"*.go\" -type f)\n\na"
},
{
"path": "README.md",
"chars": 11407,
"preview": "# easyssh-proxy\n\n[](https://pkg.go.dev/github.co"
},
{
"path": "README.zh-tw.md",
"chars": 9199,
"preview": "# easyssh-proxy\n\n[](https://pkg.go.dev/github.co"
},
{
"path": "_examples/proxy/go.mod",
"chars": 354,
"preview": "module example\n\ngo 1.24.0\n\nrequire github.com/appleboy/easyssh-proxy v1.5.0\n\nrequire (\n\tgithub.com/ScaleFT/sshkeys v1.4."
},
{
"path": "_examples/proxy/go.sum",
"chars": 1545,
"preview": "github.com/ScaleFT/sshkeys v1.4.0 h1:Yqd0cKA5PUvwV0dgRI67BDHGTsMHtGQBZbLXh1dthmE=\ngithub.com/ScaleFT/sshkeys v1.4.0/go.m"
},
{
"path": "_examples/proxy/proxy.go",
"chars": 716,
"preview": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/appleboy/easyssh-proxy\"\n)\n\nfunc main() {\n\t// Create MakeConfig instance with"
},
{
"path": "_examples/scp/go.mod",
"chars": 354,
"preview": "module example\n\ngo 1.24.0\n\nrequire github.com/appleboy/easyssh-proxy v1.5.0\n\nrequire (\n\tgithub.com/ScaleFT/sshkeys v1.4."
},
{
"path": "_examples/scp/go.sum",
"chars": 1545,
"preview": "github.com/ScaleFT/sshkeys v1.4.0 h1:Yqd0cKA5PUvwV0dgRI67BDHGTsMHtGQBZbLXh1dthmE=\ngithub.com/ScaleFT/sshkeys v1.4.0/go.m"
},
{
"path": "_examples/scp/scp.go",
"chars": 586,
"preview": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/appleboy/easyssh-proxy\"\n)\n\nfunc main() {\n\t// Create MakeConfig instance with"
},
{
"path": "_examples/ssh/go.mod",
"chars": 354,
"preview": "module example\n\ngo 1.24.0\n\nrequire github.com/appleboy/easyssh-proxy v1.5.0\n\nrequire (\n\tgithub.com/ScaleFT/sshkeys v1.4."
},
{
"path": "_examples/ssh/go.sum",
"chars": 1545,
"preview": "github.com/ScaleFT/sshkeys v1.4.0 h1:Yqd0cKA5PUvwV0dgRI67BDHGTsMHtGQBZbLXh1dthmE=\ngithub.com/ScaleFT/sshkeys v1.4.0/go.m"
},
{
"path": "_examples/ssh/ssh.go",
"chars": 1697,
"preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/appleboy/easyssh-proxy\"\n)\n\nfunc main() {\n\t// Create MakeConfig insta"
},
{
"path": "_examples/stream/go.mod",
"chars": 354,
"preview": "module example\n\ngo 1.24.0\n\nrequire github.com/appleboy/easyssh-proxy v1.5.0\n\nrequire (\n\tgithub.com/ScaleFT/sshkeys v1.4."
},
{
"path": "_examples/stream/go.sum",
"chars": 1545,
"preview": "github.com/ScaleFT/sshkeys v1.4.0 h1:Yqd0cKA5PUvwV0dgRI67BDHGTsMHtGQBZbLXh1dthmE=\ngithub.com/ScaleFT/sshkeys v1.4.0/go.m"
},
{
"path": "_examples/stream/stream.go",
"chars": 1123,
"preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/appleboy/easyssh-proxy\"\n)\n\nfunc main() {\n\t// Create MakeConfig insta"
},
{
"path": "_examples/writeFile/go.mod",
"chars": 354,
"preview": "module example\n\ngo 1.24.0\n\nrequire github.com/appleboy/easyssh-proxy v1.5.0\n\nrequire (\n\tgithub.com/ScaleFT/sshkeys v1.4."
},
{
"path": "_examples/writeFile/go.sum",
"chars": 1545,
"preview": "github.com/ScaleFT/sshkeys v1.4.0 h1:Yqd0cKA5PUvwV0dgRI67BDHGTsMHtGQBZbLXh1dthmE=\ngithub.com/ScaleFT/sshkeys v1.4.0/go.m"
},
{
"path": "_examples/writeFile/writeFile.go",
"chars": 746,
"preview": "package main\n\nimport (\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/appleboy/easyssh-proxy\"\n)\n\nfunc main() {\n\t// Create MakeConfig i"
},
{
"path": "easyssh.go",
"chars": 15024,
"preview": "// Package easyssh provides a simple implementation of some SSH protocol\n// features in Go. You can simply run a command"
},
{
"path": "easyssh_test.go",
"chars": 17964,
"preview": "package easyssh\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"os\"\n\t\"os/user\"\n\t\"path\"\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stre"
},
{
"path": "go.mod",
"chars": 429,
"preview": "module github.com/appleboy/easyssh-proxy\n\ngo 1.25.9\n\nrequire (\n\tgithub.com/ScaleFT/sshkeys v1.4.0\n\tgithub.com/stretchr/t"
},
{
"path": "go.sum",
"chars": 1754,
"preview": "github.com/ScaleFT/sshkeys v1.4.0 h1:Yqd0cKA5PUvwV0dgRI67BDHGTsMHtGQBZbLXh1dthmE=\ngithub.com/ScaleFT/sshkeys v1.4.0/go.m"
},
{
"path": "tests/.ssh/id_rsa",
"chars": 1679,
"preview": "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA4e2D/qPN08pzTac+a8ZmlP1ziJOXk45CynMPtva0rtK/RB26\nVbfAF0hIJji7ltvnYnqCU9o"
},
{
"path": "tests/.ssh/id_rsa.pub",
"chars": 401,
"preview": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDh7YP+o83TynNNpz5rxmaU/XOIk5eTjkLKcw+29rSu0r9EHbpVt8AXSEgmOLuW2+dieoJT2gV+8QzfdxOf"
},
{
"path": "tests/.ssh/test",
"chars": 3434,
"preview": "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAACmFlczI1Ni1jdHIAAAAGYmNyeXB0AAAAGAAAABAgX0UT5U\ndbd5qk/WLiRyD"
},
{
"path": "tests/.ssh/test.pub",
"chars": 740,
"preview": "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDojzlRtxSqAaOGaPHwCSRlsw870qwpc55W5AxlcOsbFZdtSwZ/dESBu5ql3dLsTB7WcqXoaA7Qp3w5GVRc"
},
{
"path": "tests/a.txt",
"chars": 9,
"preview": "appleboy\n"
},
{
"path": "tests/b.txt",
"chars": 0,
"preview": ""
},
{
"path": "tests/entrypoint.sh",
"chars": 285,
"preview": "#!/bin/sh\n\nif [ ! -f \"/etc/ssh/ssh_host_rsa_key\" ]; then\n # generate fresh rsa key\n ssh-keygen -f /etc/ssh/ssh_host_rs"
},
{
"path": "tests/global/c.txt",
"chars": 0,
"preview": ""
},
{
"path": "tests/global/d.txt",
"chars": 0,
"preview": ""
},
{
"path": "tests/sudoers",
"chars": 60,
"preview": "Defaults requiretty\ndrone-scp ALL=(ALL) NOPASSWD:ALL\n"
}
]
About this extraction
This page contains the full source code of the appleboy/easyssh-proxy GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 42 files (89.0 KB), approximately 32.5k tokens, and a symbol index with 39 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.