Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add sudo #33

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion client.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ package goph

import (
"context"
"errors"
"fmt"
"io"
"net"
"os"
"strings"
"time"

"github.com/pkg/sftp"
Expand All @@ -29,11 +31,17 @@ type Config struct {
Port uint
Timeout time.Duration
Callback ssh.HostKeyCallback
Pass string
}

// DefaultTimeout is the timeout of ssh client connection.
var DefaultTimeout = 20 * time.Second

// Set sudo password
func (client *Client) SetPass(pass string) {
client.Config.Pass = pass
}

// New starts a new ssh connection, the host public key must be in known hosts.
func New(user string, addr string, auth Auth) (c *Client, err error) {

Expand Down Expand Up @@ -92,7 +100,15 @@ func Dial(proto string, c *Config) (*ssh.Client, error) {

// Run starts a new SSH session and runs the cmd, it returns CombinedOutput and err if any.
func (c Client) Run(cmd string) ([]byte, error) {

if strings.HasPrefix(cmd, "sudo") {
if c.Config.Pass == "" {
return nil, errors.New("Config.Pass is not set")
}
// if c.Config.Pass {}
/// you have to run sudo commands like this:
/// echo '[password]' | sudo -S [command]
cmd = "echo " + c.Config.Pass + "| sudo -S " + cmd[5:]
}
var (
err error
sess *ssh.Session
Expand Down
3 changes: 2 additions & 1 deletion cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ package goph
import (
"context"
"fmt"
"strings"

"github.com/pkg/errors"
"golang.org/x/crypto/ssh"
"strings"
)

// Cmd it's like os/exec.Cmd but for ssh session.
Expand Down