diff --git a/Gossh/Bin/gossh b/Gossh/Bin/gossh index 5730330..716c413 100755 Binary files a/Gossh/Bin/gossh and b/Gossh/Bin/gossh differ diff --git a/Gossh/Bin/gossh.exe b/Gossh/Bin/gossh.exe index c3e0a15..f1d9301 100755 Binary files a/Gossh/Bin/gossh.exe and b/Gossh/Bin/gossh.exe differ diff --git a/Gossh/Gossh.psd1 b/Gossh/Gossh.psd1 index 5773dea..47e1f61 100755 --- a/Gossh/Gossh.psd1 +++ b/Gossh/Gossh.psd1 @@ -12,7 +12,7 @@ RootModule = 'Gossh' # Version number of this module. - ModuleVersion = '2.0.2' + ModuleVersion = '2.1.1' # Supported PSEditions # CompatiblePSEditions = @() diff --git a/Gossh/Public/Invoke-Gossh.ps1 b/Gossh/Public/Invoke-Gossh.ps1 index 7f7208a..6bcd3da 100755 --- a/Gossh/Public/Invoke-Gossh.ps1 +++ b/Gossh/Public/Invoke-Gossh.ps1 @@ -23,7 +23,13 @@ function Invoke-Gossh { $EnableCredential, [Parameter(Mandatory = $false)] - [bool]$ConfigFile = $false + [bool]$ConfigFile = $false, + + [Parameter(Mandatory = $false)] + [string]$ConfigPath, + + [Parameter(Mandatory = $false)] + [bool]$SecondaryLogin = $false ) $VerbosePrefix = "Invoke-Gossh:" @@ -42,6 +48,7 @@ function Invoke-Gossh { if ($IsExecutable -notmatch 'true') { $ExecutableCheckCommand = 'bash -c "chmod +x ' + $NixPath + '"' $MakeExecutable = Invoke-Expression -Command $ExecutableCheckCommand + Write-Verbose $MakeExecutable } } default { @@ -59,7 +66,6 @@ function Invoke-Gossh { ############################################################# # \gossh.exe -h 1.1.1.1 -u admin -p password -P 4001 -C "terminal pager 0/show run interface" -f=false -t 35 - $GosshCommand = $Command -join '||' $GosshUsername = $Credential.UserName $GosshPassword = $Credential.GetNetworkCredential().Password @@ -68,9 +74,10 @@ function Invoke-Gossh { $GosshExpression += ' -u ' + $GosshUsername $GosshExpression += ' -p ' + "'" + $GosshPassword + "'" $GosshExpression += ' -P ' + $Port - $GosshExpression += ' -C "' + $GosshCommand + '"' - $GosshExpression += ' -f=' + $ConfigFile - + if ($ConfigFile) { $GosshExpression += ' -f -d ' + $ConfigPath }else { + $GosshCommand = $Command -join '||' ; $GosshExpression += ' -C "' + $GosshCommand + '"' + } + if ($SecondaryLogin) { $GosshExpression += ' -s' } if ($EnableCredential) { #$EnableCredential = New-Object System.Management.Automation.PSCredential ('test', $EnablePassword) $EnablePassword = $EnableCredential.GetNetworkCredential().Password diff --git a/go/MisFunctions.go b/go/MisFunctions.go.old similarity index 77% rename from go/MisFunctions.go rename to go/MisFunctions.go.old index 18f4fcd..3678bb9 100644 --- a/go/MisFunctions.go +++ b/go/MisFunctions.go.old @@ -17,18 +17,18 @@ func handleError(err error) { fmt.Println(err) } } -func StringToArray1(CLIAurguments string) (CLIReturn []string) { - StringSplit := strings.Split(CLIAurguments, ",") +func StringToArray1(CLIArguments string) (CLIReturn []string) { + StringSplit := strings.Split(CLIArguments, ",") var StringReturn []string for _, stringssplit := range StringSplit { StringReturn = append(StringReturn, stringssplit) } return StringReturn } -func StringToArray(CLIAurguments string) (Commands []string) { - StringSplit := strings.Split(CLIAurguments, "||") +func StringToArray(CLIArguments string) (Commands []string) { + StringSplit := strings.Split(CLIArguments, "||") var Count int - for i, _ := range StringSplit { + for i := range StringSplit { Count = i } var array = make([]string, Count+1) diff --git a/go/MiscFunctions.go b/go/MiscFunctions.go new file mode 100644 index 0000000..0b896f5 --- /dev/null +++ b/go/MiscFunctions.go @@ -0,0 +1,75 @@ +package main + +import ( + "bufio" + "fmt" + "github.com/TwiN/go-color" + "os" + "strings" +) + +func handleError(err error, fatal bool, message string) { + if nil != err { + switch { + case len([]rune(message)) == 0: + fmt.Println(color.Ize(color.Bold + color.Red,"uncategorized error raw error bellow:")) + fmt.Println(err) + case fatal: + fmt.Println(color.Ize(color.Bold + color.Red,"Fatal error encountered terminating execution : "+message)) + fmt.Println(err) + os.Exit(1) + + case len([]rune(message)) >= 1: + fmt.Println(color.Ize(color.Bold + color.Red,message)) + fmt.Println(err) + } + } +} + +func readConfigFile(filepath string) []string { + var ConfigArray []string + ConfigFile, err := os.Open(filepath) + handleError(err, true,"Error encountered opening config file") + defer func(ConfigFile *os.File) { + err := ConfigFile.Close() + handleError(err, true,"Error encountered closing config file") + }(ConfigFile) + FileScanner := bufio.NewScanner(ConfigFile) + for FileScanner.Scan() { + ConfigArray = append(ConfigArray, FileScanner.Text()) + } + return ConfigArray +} + +func writeBuffer2Txt(fileName string, text string, append bool) { + if append { + text += "\n" + } + f, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) + if nil != err { + handleError(err, true,"Error encountered opening log file") + } + if _, err := f.Write([]byte(text)); err != nil { + handleError(err, true, "Error encountered writing to log file") + } + if err := f.Close(); err != nil { + handleError(err, true,"Error encountered closing log file") + } + +} + +func stringToArray(CLIArguments string) (Commands []string) { + StringSplit := strings.Split(CLIArguments, "||") + var Count int + for i := range StringSplit { + Count = i + } + var array = make([]string, Count+1) + for i, stringsSplit := range StringSplit { + if stringsSplit != " " { + array[i] = strings.TrimRight(stringsSplit, " ") + } + } + if verbose {println(color.Ize(color.Yellow,"Commands array:\n" + strings.Join(array,"\n")))} + return array +} \ No newline at end of file diff --git a/go/Run.go b/go/Run.go index 3c08972..a2c3255 100644 --- a/go/Run.go +++ b/go/Run.go @@ -1,48 +1,58 @@ package main import ( - "flag" + "fmt" + "github.com/TwiN/go-color" + "github.com/jessevdk/go-flags" + "os" ) -var Banner = false -var bannerchecked = false -var returnstring = "" +var returnStrings string +var options Options +var verbose bool +var secondaryLogin bool + +type Options struct { + HostName string `short:"h" long:"hostname" description:"device url/ip"` + UserName string `short:"u" long:"username" description:"username used for authentication"` + PassWord string `short:"p" long:"password" description:"password used for authentication"` + EnablePassword string `short:"e" long:"enablepassword" description:"username used for authentication"` + Port int `short:"P" long:"port" description:"tcp port device is listening on" default:"22"` + TimeOut int `short:"t" long:"timeout" description:"timeout value in seconds for each command execution" default:"10"` + CliArguments string `short:"C" long:"cliarguments" description:"array containing cmdS to be run" ` + DirectoryPath string `short:"d" long:"filePath" description:"filePath to document containing cmdS to be run"` + UseFile bool `short:"f" long:"usefile" description:"bool switch for using cmdS file"` + SecondaryLogin bool `short:"s" long:"secondarylogin" description:"bool switch for entering login credentials again as required by some cisco switches"` + Telnet bool `short:"T" long:"telnet" description:"option to use telnet instead of ssh"` + Help bool `short:"H" long:"help" description:"output help"` + Verbose bool `short:"v" long:"verbose" description:"print verbose"` +} func main() { - var HostName string - var UserName string - var Password string - var EnablePassword string - var SSH bool - var File bool - var Port string - var CLIArguments string - var TimeoutValue int - //setting CLI Parameters// - flag.StringVar(&HostName, "h", "", "specify the host you are connecting to with either a hostname or ip address") - flag.StringVar(&UserName, "u", "", "specify device username") - flag.StringVar(&Password, "p", "", "specify device password") - flag.StringVar(&EnablePassword, "e", "", "specify device enable password") - flag.BoolVar(&SSH, "c", true, "specify connection type default is SSH") - flag.StringVar(&Port, "P", "22", "use this to specify port default is 22") - flag.StringVar(&CLIArguments, "C", "", "specify CLI commands to run on host device") - flag.BoolVar(&File, "f", false, "set to true of you are sending a config file") - flag.IntVar(&TimeoutValue, "t", 35, "change default timeout value") - flag.Parse() - switch File { - case false: - switch SSH { - case true: - InvokeSSH(HostName, Port, UserName, Password, StringToArray(CLIArguments), TimeoutValue) - case false: - //InvokeTelnet(HostName, UserName, Password, EnablePassword, Port, StringToArray1(CLIArguments)) - } - case true: - switch SSH { - case true: - InvokeSSH(HostName, Port, UserName, Password, readLines(CLIArguments), TimeoutValue) - case false: - //InvokeTelnet(HostName, UserName, Password, EnablePassword, Port, StringToArray1(CLIArguments)) + parser:= flags.NewParser(&options,flags.Default&^flags.HelpFlag) + _, err := parser.Parse() + if nil != err {handleError(err,true,"Error parsing CLI arguments")} + if options.Help{parser.WriteHelp(os.Stdout);os.Exit(0)} + //bytes := make([]byte, 32) + //if _, err := rand.Read(bytes); err != nil { + // handleError(err, true, "failed to create encryption key") + //} + //key := hex.EncodeToString(bytes) + verbose = options.Verbose + secondaryLogin = options.SecondaryLogin + switch { + case options.UseFile: + commandArguments := readConfigFile(options.DirectoryPath) + switch { + case options.Telnet: + // + default: + sshDial(options.HostName,options.Port,options.UserName,options.PassWord,commandArguments,options.TimeOut,options.EnablePassword) } + case options.Telnet: + println(color.Ize(color.Red,"Telnet functions are not ready yet terminating application")); os.Exit(1) + default: + sshDial(options.HostName, options.Port, options.UserName, options.PassWord,stringToArray(options.CliArguments),options.TimeOut,options.EnablePassword) } + fmt.Println(returnStrings) } diff --git a/go/SSH.go b/go/SSH.go index 456f1ed..190c83b 100644 --- a/go/SSH.go +++ b/go/SSH.go @@ -1,40 +1,124 @@ package main import ( - "fmt" - "time" - + "github.com/TwiN/go-color" "golang.org/x/crypto/ssh" + "io" + "os" + "regexp" + "strconv" + "time" ) -var stopread = false -func InvokeSSH(HostName string, Port string, UserName string, Password string, Commands []string, TimeoutValue int) { - if Password == "blank" { - Password = "" +var cmdEnd = regexp.MustCompile(".*@?.*([#>])\\s?$") +var cmdUserName = regexp.MustCompile(".*(User\\s+Name|username|user\\sname).*$?") + +func sshWriter(cmd string, SshIN io.WriteCloser) { + _, err := SshIN.Write([]byte(cmd + "\r")) + handleError(err,false,"Error writing to ssh buffer") +} + +func sshWriteNewLine(sshIn io.WriteCloser){ + _, err := sshIn.Write([]byte(" \r\n")) + handleError(err,false,"Error writing new line") +} + +func sshReadLogin (sshIn io.WriteCloser,sshOut io.Reader, userName string, password string){ + buf := make([]byte, 2048) + bufferResults, err := sshOut.Read(buf);handleError(err,false,"Error encountered reading ssh buffer") + currentLine := string(buf[:bufferResults]) + ReaderLoop: + for nil == err && cmdEnd.FindStringSubmatch(currentLine) == nil { + switch { + case cmdUserName.FindStringSubmatch(currentLine) != nil: + sshWriter(userName,sshIn);sshWriter(password,sshIn) + n, err := sshOut.Read(buf);if nil != err {handleError(err,true,"error reading login promt");break ReaderLoop} + currentLine += string(buf[:n]) + break ReaderLoop + default: + sshWriteNewLine(sshIn);sshWriteNewLine(sshIn) + n, err := sshOut.Read(buf);if nil != err {handleError(err,true,"error reading login promt");break ReaderLoop} + currentLine += string(buf[:n]) + } + } + returnStrings += currentLine +} + +func sshReadBuffer(sshOut io.Reader, timeOutValue int, cmd string, hostName string) { + buf := make([]byte, 2048) + StartTime := time.Now() + bufferResults, err := sshOut.Read(buf);handleError(err,false,"Error encountered reading ssh buffer") + currentLine := string(buf[:bufferResults]) + if verbose{println(color.Ize(color.Bold + color.Green,currentLine))} + TimeOutValue := time.Duration(timeOutValue) * time.Second +ReaderLoop: + for nil == err && cmdEnd.FindStringSubmatch(currentLine) == nil { + n, err := sshOut.Read(buf) + if verbose{println(color.Ize(color.Bold + color.Green,string(buf[:n])))} + switch { + case nil != err: + handleError(err, false,"Error encountered reading ssh buffer") + break ReaderLoop + case time.Since(StartTime) > TimeOutValue: + directoryPath, err := os.UserHomeDir() + if err != nil { + handleError(err, false,"Error encountered while trying to determine home directory") + break ReaderLoop + } + println(color.Ize(color.Red, "Timeout Value exceeded please check error log for more details "+ + "canceling read operation for cmd:= "+cmd+" | "+directoryPath+"/"+hostName+"-error.txt")) + writeBuffer2Txt(directoryPath+"/"+hostName+"error.txt", returnStrings, true) + break ReaderLoop + default: + currentLine += string(buf[:n]) + } } - conn, err := ssh.Dial("tcp", HostName+":"+Port, &ssh.ClientConfig{ - User: UserName, - Timeout: 5 * time.Second, - Auth: []ssh.AuthMethod{ssh.Password(Password)}, + //println(color.Ize(color.Cyan, currentLine)) //uncomment while troubleshoot to see where the buffer is getting stuck + returnStrings += currentLine +} + +func sshDial(hostname string, port int, username string, password string, cmdS []string, timeOutValue int, enablePassword string) { + var portNumber = strconv.Itoa(port) + conn, err := ssh.Dial("tcp", hostname+":"+portNumber, &ssh.ClientConfig{ + User: username, + Timeout: 5 * time.Second, + Auth: []ssh.AuthMethod{ssh.Password(password)}, HostKeyCallback: ssh.InsecureIgnoreHostKey(), }) - if err != nil { - fmt.Println(err) - } + handleError(err, true, "SSH dial failed check device information and network") session, err := conn.NewSession() - handleError(err) + handleError(err, true, "SSH dial failed check device information and network") sshOut, err := session.StdoutPipe() - handleError(err) - sshIn, err := session.StdinPipe() - - err = session.Shell() - handleError(err) - defer session.Close() - defer conn.Close() - for _, CLICommands := range Commands { - write(CLICommands, sshIn) - readBuff(sshOut, TimeoutValue,HostName) - writeblank(sshIn) - readBuffblank(sshOut, TimeoutValue,HostName) + handleError(err, true, "SSH out pipe creation failed terminating session") + sshIn, err := session.StdinPipe();handleError(err, true, "SSH in pipe creation failed terminating session") + 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 } - fmt.Println(returnstring) -} + // Request pseudo terminal + if err := session.RequestPty("xterm", 40, 80, modes);nil != err {handleError(err,false,"")} + err = session.Shell();handleError(err, true, "SSH in pipe creation failed terminating session") + defer func(conn *ssh.Client) { + err := conn.Close() + handleError(err, false, "Connection failed to close") + }(conn) + defer func(session *ssh.Session) { + err := session.Close() + handleError(err, false, "Session failed to close") + }(session) + switch { //created as a switch to allow the addition of buffer reading for click through prompts + case len([]rune(enablePassword)) >= 1: + sshWriter("en", sshIn) + sshWriter(enablePassword, sshIn) + case secondaryLogin: + sshReadLogin(sshIn,sshOut,username,password) + } + for _, CommandString := range cmdS { + switch { + case verbose: + println(color.Ize(color.Bold + color.Green,"writing command : "+CommandString)) + } + sshWriter(CommandString,sshIn) + sshReadBuffer(sshOut, timeOutValue, CommandString, hostname) + } +} \ No newline at end of file diff --git a/go/SSH.go.old b/go/SSH.go.old new file mode 100644 index 0000000..b57d30f --- /dev/null +++ b/go/SSH.go.old @@ -0,0 +1,44 @@ +package main + +import ( + "fmt" + "time" + + "golang.org/x/crypto/ssh" +) + +func InvokeSSH(HostName string, Port string, UserName string, Password string, Commands []string, TimeoutValue int, EnablePassword string) { + if Password == "blank" { + Password = "" + } + conn, err := ssh.Dial("tcp", HostName+":"+Port, &ssh.ClientConfig{ + User: UserName, + Timeout: 5 * time.Second, + Auth: []ssh.AuthMethod{ssh.Password(Password)}, + HostKeyCallback: ssh.InsecureIgnoreHostKey(), + }) + if err != nil { + fmt.Println(err) + } + session, err := conn.NewSession() + handleError(err) + sshOut, err := session.StdoutPipe() + handleError(err) + sshIn, err := session.StdinPipe() + + err = session.Shell() + handleError(err) + defer session.Close() + defer conn.Close() + if EnablePassword != "" { + writer(sshIn, "en") + writer(sshIn, EnablePassword) + } + for _, CLICommands := range Commands { + write(CLICommands, sshIn) + readBuff(sshOut, TimeoutValue, HostName) + writeblank(sshIn) + readBuffblank(sshOut, TimeoutValue, HostName) + } + fmt.Println(returnstring) +} diff --git a/go/ShhFunctions.go b/go/ShhFunctions.go.old similarity index 62% rename from go/ShhFunctions.go rename to go/ShhFunctions.go.old index 8dae9d5..2db1a48 100644 --- a/go/ShhFunctions.go +++ b/go/ShhFunctions.go.old @@ -9,6 +9,7 @@ import ( "regexp" "time" ) + var prompt = regexp.MustCompile("(%{2})") var prompt2 = regexp.MustCompile(".*@?.*(#|>).*$") @@ -20,10 +21,20 @@ func writeblank(sshIn io.WriteCloser) { _, err := sshIn.Write([]byte("\r")) handleError(err) } -func readBuffForString(sshOut io.Reader, buffRead chan string){ +func writer(sshIn io.WriteCloser, cmd string) { + _, err := sshIn.Write([]byte(cmd + "\r")) + handleError(err) +} +func readBuffForString(sshOut io.Reader, buffRead chan string, timeoutSeconds int) { buf := make([]byte, 1000) waitingString := "" + //StartTime := time.Now() for { + //CurrentTime := time.Now() + //TimeElapsed := CurrentTime.Sub(StartTime) + //TimeOutValue := time.Duration(timeoutSeconds) * time.Second + //fmt.Println(TimeElapsed) + n, err := sshOut.Read(buf) //this reads the ssh terminal if err == io.EOF { fmt.Println(err) @@ -33,19 +44,25 @@ func readBuffForString(sshOut io.Reader, buffRead chan string){ fmt.Println(err) break } + // for every line current := string(buf[:n]) // add current line to result string - returnstring += current waitingString += current + returnstring += current m := prompt.FindStringSubmatch(current) - if m != nil{ + if m != nil { break } - + //if TimeElapsed >= TimeOutValue{ + // l := prompt2.FindStringSubmatch(current) + // if l != nil { + // break + // } + //} } buffRead <- waitingString } -func readBuffForStringblank(sshOut io.Reader, buffRead chan string){ +func readBuffForStringblank(sshOut io.Reader, buffRead chan string) { buf := make([]byte, 1000) waitingString := "" for { @@ -63,36 +80,36 @@ func readBuffForStringblank(sshOut io.Reader, buffRead chan string){ // add current line to result string waitingString += current m := prompt2.FindStringSubmatch(current) - if m != nil{ + if m != nil { break } - } buffRead <- waitingString } -func readBuff(sshOut io.Reader, timeoutSeconds int,HostName string) string { +func readBuff(sshOut io.Reader, timeoutSeconds int, HostName string) string { dirname, err := os.UserHomeDir() if err != nil { - log.Fatal( err ) + log.Fatal(err) } ch := make(chan string) go func(sshOut io.Reader) { buffRead := make(chan string) - go readBuffForString(sshOut, buffRead) + go readBuffForString(sshOut, buffRead, timeoutSeconds) select { case ret := <-buffRead: ch <- ret case <-time.After(time.Duration(timeoutSeconds) * time.Second): - pan.Wlog(dirname+"/"+HostName+"-error.txt", "timeout waiting for command |" +HostName+"\r\n--------" +returnstring+"\r\n--------", true) + pan.Wlog(dirname+"/"+HostName+"-error.txt", "timeout waiting for command |"+HostName+"\r\n--------\r\n"+returnstring+"\r\n--------", true) + fmt.Println("Timeout Value exceeded please check error log for more details exiting gossh| " + dirname + "/" + HostName + "-error.txt") os.Exit(3) } }(sshOut) return <-ch } -func readBuffblank(sshOut io.Reader, timeoutSeconds int,HostName string) string { +func readBuffblank(sshOut io.Reader, timeoutSeconds int, HostName string) string { dirname, err := os.UserHomeDir() if err != nil { - log.Fatal( err ) + log.Fatal(err) } ch := make(chan string) go func(sshOut io.Reader) { @@ -102,9 +119,9 @@ func readBuffblank(sshOut io.Reader, timeoutSeconds int,HostName string) string case ret := <-buffRead: ch <- ret case <-time.After(time.Duration(timeoutSeconds) * time.Second): - pan.Wlog(dirname+"/error.txt", "timeout waiting for command |" +HostName+"\r\n--------" +returnstring+"\r\n--------", true) - os.Exit(3) + pan.Wlog(dirname+"/error.txt", "timeout waiting for blank command read |"+HostName+"\r\n--------"+returnstring+"\r\n--------", true) + //os.Exit(3) } }(sshOut) return <-ch -} \ No newline at end of file +} diff --git a/go/go.mod b/go/go.mod index ff63e63..8bc0d0a 100644 --- a/go/go.mod +++ b/go/go.mod @@ -1,9 +1,13 @@ module gossh go 1.16 + replace golang.org/x/crypto => /Users/nmuragian/go/src/golang.org/x/crypto + require ( + github.com/TwiN/go-color v1.0.1 github.com/beevik/etree v1.1.0 // indirect + github.com/jessevdk/go-flags v1.5.0 github.com/zepryspet/GoPAN v0.0.0-20190604023150-822d8fe77acc golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 golang.org/x/sys v0.0.0-20211004093028-2c5d950f24ef // indirect diff --git a/go/go.sum b/go/go.sum index 2aa28d8..07e713a 100644 --- a/go/go.sum +++ b/go/go.sum @@ -1,18 +1,17 @@ +github.com/TwiN/go-color v1.0.1 h1:kOihQEqDY7oIHUr1clPE2vuDhfTD5Bj45Tvu2jU7iIg= +github.com/TwiN/go-color v1.0.1/go.mod h1:xDwSZwPf9rYRflSPYOehCoROibB4FZDtjo03v0QK6EA= github.com/beevik/etree v1.1.0 h1:T0xke/WvNtMoCqgzPhkX2r4rjY3GDZFi+FjpRZY2Jbs= github.com/beevik/etree v1.1.0/go.mod h1:r8Aw8JqVegEf0w2fDnATrX9VpkMcyFeM0FhwO62wh+A= +github.com/jessevdk/go-flags v1.5.0 h1:1jKYvbxEjfUl0fmqTCOfonvskHHXMjBySTLW4y9LFvc= +github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4= github.com/zepryspet/GoPAN v0.0.0-20190604023150-822d8fe77acc h1:wlZDL97Y833StrbFeAVI4fmLXFd6VoLiWnm43J6sTZ4= github.com/zepryspet/GoPAN v0.0.0-20190604023150-822d8fe77acc/go.mod h1:gp9DPnifOMs61erskyxDxcxJ2+jUEWElx6VnjJwMXyE= -golang.org/x/crypto v0.0.0-20210915214749-c084706c2272 h1:3erb+vDS8lU1sxfDHF4/hhWyaXnhIaO+7RgL4fDZORA= -golang.org/x/crypto v0.0.0-20210915214749-c084706c2272/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg= -golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 h1:SrN+KX8Art/Sf4HNj6Zcz06G7VEz+7w9tdXTPOZ7+l4= +golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20211004093028-2c5d950f24ef h1:fPxZ3Umkct3LZ8gK9nbk+DWDJ9fstZa2grBn+lWVKPs= golang.org/x/sys v0.0.0-20211004093028-2c5d950f24ef/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= diff --git a/go/misctesting.go b/go/misctesting.go new file mode 100644 index 0000000..3549f30 --- /dev/null +++ b/go/misctesting.go @@ -0,0 +1,279 @@ +package main +// +//import ( +// "bufio" +// "crypto/aes" +// "crypto/cipher" +// "crypto/rand" +// "encoding/hex" +// "fmt" +// "github.com/TwiN/go-color" +// "github.com/jessevdk/go-flags" +// "golang.org/x/crypto/ssh" +// "io" +// "os" +// "regexp" +// "strconv" +// "strings" +// "time" +//) +// +////Misc Functions Begin +////Global Variables +// +//var TesterrConnectionTimeout = regexp.MustCompile(".*dial tcp \\d+\\.\\d+\\.\\d+\\.\\d+:?\\d+?: i/o timeout.*") +//var TesterrKeyexchange = regexp.MustCompile(".*no common algorithm for key exchange.*") +// +//func TestsshHandleError(err error, fatal bool) { +// type error interface { +// Error() string +// } +// var errMatched = false +// if nil != err { +// ConnectionTimeout := TesterrConnectionTimeout.FindStringSubmatch(err.Error()) +// if ConnectionTimeout != nil { +// println(color.Red + "Connection failed check Hostname, Port, Credentials, and network access." + color.Reset) +// println(color.Yellow + "Original go err can be found bellow: \r\n\r\n" + color.Reset) +// println(color.Red + err.Error() + color.Reset) +// errMatched = true +// } +// if true != errMatched { +// println(color.Red + "Error message was not matched if you have any information on this error \r\n " + +// "please let the development team know on github \r\n\r\n" + color.Reset) +// println(color.Red + err.Error()) +// } +// } +// if io.EOF == err { +// println(color.Ize(color.Red, "Encountered EOF")) +// println(color.Ize(color.Yellow, "Original go error can be found bellow:\n\n")) +// println(color.Ize(color.Red, err.Error())) +// } +// if fatal { +// os.Exit(1) +// } +//} +// +//func TesthandleError(err error, fatal bool, message string) { +// if nil != err { +// type error interface { +// Error() string +// } +// switch { +// case len([]rune(message)) == 0: +// println(color.Ize(color.Yellow, "uncategorized error raw error bellow:\n\n")) +// println(color.Ize(color.Red, err.Error())) +// case fatal: +// println(color.Ize(color.Yellow, "Fatal error encountered terminating execution : "+message+"\n\n")) +// println(color.Ize(color.Red, err.Error())) +// os.Exit(1) +// +// case len([]rune(message)) >= 1: +// println(color.Ize(color.Yellow, message+"\n\n")) +// println(color.Ize(color.Red, err.Error())) +// } +// } +//} +//func testreadConfigFile(filepath string) []string { +// var ConfigArray []string +// ConfigFile, err := os.Open(filepath) +// TestsshHandleError(err, true) +// defer func(ConfigFile *os.File) { +// err := ConfigFile.Close() +// TestsshHandleError(err, true) +// }(ConfigFile) +// FileScanner := bufio.NewScanner(ConfigFile) +// for FileScanner.Scan() { +// ConfigArray = append(ConfigArray, FileScanner.Text()) +// } +// return ConfigArray +//} +// +//func TestwriteBuffer2Txt(fileName string, text string, append bool) { +// if append { +// text += "\n" +// } +// f, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) +// if nil != err { +// TestsshHandleError(err, true) +// } +// if _, err := f.Write([]byte(text)); err != nil { +// TestsshHandleError(err, true) +// } +// if err := f.Close(); err != nil { +// TestsshHandleError(err, true) +// } +// +//} +// +////Misc Functions end +// +////SSH Function begin +////Global Variables// +// +//var TestcmdEnd = regexp.MustCompile(".*@?.*([#>])\\s?$") +//var TestipRegex = regexp.MustCompile("\\d+\\.\\d+\\.\\d+\\.\\d+") +// +////Functions +//func TestencryptString(string2Encrypt string, keyString string) string { +// key, _ := hex.DecodeString(keyString) +// plaintext := []byte(string2Encrypt) +// block, err := aes.NewCipher(key) +// if nil != err { +// TesthandleError(err, true, "Credential encryption failed terminating execution") +// } +// aesGCM, err := cipher.NewGCM(block) +// if nil != err { +// TesthandleError(err, true, "Credential encryption failed terminating execution") +// } +// nonce := make([]byte, aesGCM.NonceSize()) +// if _, err = io.ReadFull(rand.Reader, nonce); nil != err { +// TesthandleError(err, true, "Credential encryption failed terminating execution") +// } +// ciphertext := aesGCM.Seal(nonce, nonce, plaintext, nil) +// return fmt.Sprintf("%x", ciphertext) +//} +// +//func TestdecryptString(encryptedString string, keyString string) string { +// key, _ := hex.DecodeString(keyString) +// enc, _ := hex.DecodeString(encryptedString) +// block, err := aes.NewCipher(key) +// if err != nil { +// TesthandleError(err, true, "Decryption failed terminating execution") +// } +// aesGCM, err := cipher.NewGCM(block) +// if err != nil { +// TesthandleError(err, true, "Decryption failed terminating execution") +// } +// nonceSize := aesGCM.NonceSize() +// nonce, ciphertext := enc[:nonceSize], enc[nonceSize:] +// plaintext, err := aesGCM.Open(nil, nonce, ciphertext, nil) +// if err != nil { +// TesthandleError(err, true, "Decryption failed terminating execution") +// } +// return fmt.Sprintf("%s", plaintext) +//} +//func TestsshWriter(cmd string, SshIN io.WriteCloser) { +// _, err := SshIN.Write([]byte(cmd + "\r")) +// TestsshHandleError(err, false) +//} +//var returnStrings string +//func TestsshReadBuffer(sshOut io.Reader, timeOutValue int, cmd string, hostName string) { +// buf := make([]byte, 2048) +// StartTime := time.Now() +// bufferResults, err := sshOut.Read(buf);TesthandleError(err,false,"") +// currentLine := "" +// currentLine = string(buf[:bufferResults]) +//ReaderLoop: +// for nil == err && TestcmdEnd.FindStringSubmatch(currentLine) == nil { +// n, err := sshOut.Read(buf) +// CurrentTime := time.Now() +// TimeElapsed := CurrentTime.Sub(StartTime) +// TimeOutValue := time.Duration(timeOutValue) * time.Second +// switch { +// case nil != err: +// TestsshHandleError(err, false) +// break ReaderLoop +// case TimeElapsed >= TimeOutValue: +// directoryPath, err := os.UserHomeDir() +// if err != nil { +// TestsshHandleError(err, false) +// } +// println(color.Ize(color.Red, "Timeout Value exceeded please check error log for more details "+ +// "canceling read operation for cmd:= "+cmd+" | "+directoryPath+"/"+hostName+"-error.txt")) +// TestwriteBuffer2Txt(directoryPath+"/"+hostName+"error.txt", returnStrings, true) +// break ReaderLoop +// default: +// currentLine += string(buf[:n]) +// } +// } +// //println(color.Ize(color.Cyan, currentLine)) //uncomment while troubleshoot to see where the buffer is getting stuck +// +// returnStrings += currentLine +//} +//func TestStringToArray(CLIAurguments string) (Commands []string) { +// StringSplit := strings.Split(CLIAurguments, "||") +// var Count int +// for i := range StringSplit { +// Count = i +// } +// var array = make([]string, Count+1) +// for i, stringssplit := range StringSplit { +// if stringssplit != " " { +// array[i] = strings.TrimRight(stringssplit, " ") +// } +// } +// fmt.Println(array) +// return array +//} +//func TestsshDial(hostname string, port int, username string, password string, cmdS []string, timeOutValue int, enablePassword string) { +// var portNumber = strconv.Itoa(port) +// conn, err := ssh.Dial("tcp", hostname+":"+portNumber, &ssh.ClientConfig{ +// User: username, +// Timeout: 5 * time.Second, +// Auth: []ssh.AuthMethod{ssh.Password(password)}, +// HostKeyCallback: ssh.InsecureIgnoreHostKey(), +// }) +// TesthandleError(err, true, "SSH dial failed check device information and network") +// session, err := conn.NewSession() +// TesthandleError(err, true, "SSH dial failed check device information and network") +// sshOut, err := session.StdoutPipe() +// TesthandleError(err, true, "SSH out pipe creation failed terminating session") +// sshIn, err := session.StdinPipe();TesthandleError(err, true, "SSH in pipe creation failed terminating session") +// 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 +// } +// // Request pseudo terminal +// if err := session.RequestPty("xterm", 40, 80, modes);nil != err {TesthandleError(err,false,"")} +// err = session.Shell();TesthandleError(err, true, "SSH in pipe creation failed terminating session") +// defer func(conn *ssh.Client) { +// err := conn.Close() +// TesthandleError(err, false, "Connection failed to close") +// }(conn) +// defer func(session *ssh.Session) { +// err := session.Close() +// TesthandleError(err, false, "Session failed to close") +// }(session) +// switch { //created as a switch to allow the addition of buffer reading for click through prompts +// case len([]rune(enablePassword)) >= 1: +// TestsshWriter("en", sshIn) +// TestsshWriter(enablePassword, sshIn) +// } +// for _, CommandString := range cmdS { +// TestsshWriter(CommandString,sshIn) +// TestsshReadBuffer(sshOut, timeOutValue, CommandString, hostname) +// } +//} +//type Options struct { +// HostName string `short:"h" long:"hostname" description:"device url/ip"` +// UserName string `short:"u" long:"username" description:"username used for authentication"` +// PassWord string `short:"p" long:"password" description:"password used for authentication"` +// EnablePassword string `short:"e" long:"enablepassword" description:"username used for authentication"` +// Port int `short:"P" long:"port" description:"tcp port device is listening on" default:"22"` +// TimeOut int `short:"t" long:"timeout" description:"timeout value in seconds for each command execution" default:"10"` +// CliArguments string `short:"C" long:"cliarguments" description:"array containing cmdS to be run" ` +// DirectoryPath string `short:"d" long:"filePath" description:"filePath to document containing cmdS to be run"` +// UseFile bool `short:"f" long:"usefile" description:"bool switch for using cmdS file"` +// Telnet bool `short:"T" long:"telnet" description:"option to use telnet instead of ssh" default:"false"` +// Help bool `short:"H" long:"help" description:"output help"` +//} +// var options Options +//func main() { +// parser:= flags.NewParser(&options,flags.Default&^flags.HelpFlag) +// _, err := parser.Parse() +// if nil != err {os.Exit(0)} +// if options.Help{parser.WriteHelp(os.Stdout);os.Exit(0)} +// //bytes := make([]byte, 32) +// //if _, err := rand.Read(bytes); err != nil { +// // TesthandleError(err, true, "failed to create encryption key") +// //} +// //key := hex.EncodeToString(bytes) +// switch { +// case options.Telnet: +// println(color.Ize(color.Red,"Telnet functions are not ready yet terminating application")); os.Exit(1) +// default: +// TestsshDial(options.HostName, options.Port, options.UserName, options.PassWord,TestStringToArray(options.CliArguments),options.TimeOut,options.EnablePassword) +// } +// println(color.Ize(color.Bold + color.Purple,returnStrings)) +//} diff --git a/go/old/Cisco.go b/go/old/Cisco.go deleted file mode 100755 index a7e22d1..0000000 --- a/go/old/Cisco.go +++ /dev/null @@ -1,152 +0,0 @@ -package main - -import ( - "fmt" - "log" - "net" - "strings" - "time" - - cssh "golang.org/x/crypto/ssh" -) - -type NetScan struct { - IPaddress string -} - -func CiscoASA() { - DeviceTypeTrim := strings.TrimSpace(Device) - DeviceType := strings.ToLower(DeviceTypeTrim) - DeviceAddress = strings.TrimSpace(Address) - //fmt.Println(DeviceAddress) - DeviceUser = strings.TrimSpace(UserName) - //fmt.Println(DeviceUser) - DevicePass = strings.TrimSpace(Password) - //fmt.Println(DevicePass) - DeviceConfigSplit := strings.Split(Config, "//") - Deviceport := strings.TrimSpace(Port) - fmt.Println(DeviceType) - conn, err := cssh.Dial("tcp", DeviceAddress+":"+Deviceport, &cssh.ClientConfig{ - User: DeviceUser, - Auth: []cssh.AuthMethod{cssh.Password(DevicePass)}, - HostKeyCallback: cssh.InsecureIgnoreHostKey(), - Timeout: 5 * time.Second, - }) - - if err != nil { - fmt.Println(err) - } - session, err := conn.NewSession() - handleError(err) - sshOut, err := session.StdoutPipe() - handleError(err) - sshIn, err := session.StdinPipe() - - err = session.Shell() - handleError(err) - write("enable", sshIn) - //write(DeviceUser, sshIn) - if EnablePassword != "" { - enablepassword := strings.TrimSpace(EnablePassword) - write(enablepassword, sshIn) - } else { - write(DevicePass, sshIn) - } - write("terminal pager 0", sshIn) - for range DeviceConfigSplit { - fmt.Println(DeviceConfigSplit[ConfigSplitCount]) - // create a new connection - write(DeviceConfigSplit[ConfigSplitCount], sshIn) - ConfigSplitCount++ - } - write("exit", sshIn) - readBuffForString1(sshOut) - session.Close() - conn.Close() -} -func CiscoSwitch() { - DeviceTypeTrim := strings.TrimSpace(Device) - DeviceType := strings.ToLower(DeviceTypeTrim) - DeviceAddress = strings.TrimSpace(Address) - //fmt.Println(DeviceAddress) - DeviceUser = strings.TrimSpace(UserName) - //fmt.Println(DeviceUser) - DevicePass = strings.TrimSpace(Password) - //fmt.Println(DevicePass) - DeviceConfigSplit := strings.Split(Config, "//") - Deviceport := strings.TrimSpace(Port) - fmt.Println(DeviceType) - conn, err := cssh.Dial("tcp", DeviceAddress+":"+Deviceport, &cssh.ClientConfig{ - User: DeviceUser, - Auth: []cssh.AuthMethod{cssh.Password(DevicePass)}, - HostKeyCallback: cssh.InsecureIgnoreHostKey(), - Timeout: 5 * time.Second, - }) - - if err != nil { - fmt.Println(err) - } - session, err := conn.NewSession() - handleError(err) - sshOut, err := session.StdoutPipe() - handleError(err) - sshIn, err := session.StdinPipe() - - err = session.Shell() - handleError(err) - for range DeviceConfigSplit { - fmt.Println(DeviceConfigSplit[ConfigSplitCount]) - // create a new connection - write(DeviceConfigSplit[ConfigSplitCount], sshIn) - ConfigSplitCount++ - } - write("exit", sshIn) - readBuffForString1(sshOut) - session.Close() - conn.Close() -} - -func netscantest() { - DeviceUser = strings.TrimSpace(UserName) - //fmt.Println(DeviceUser) - DevicePass = strings.TrimSpace(Password) - //fmt.Println(DevicePass) - DeviceConfigSplit := strings.Split(Config, "//") - Deviceport := strings.TrimSpace(Port) - DeviceAddress = strings.TrimSpace(Address) - ip, ipnet, err := net.ParseCIDR(DeviceAddress) - if err != nil { - log.Fatal(err) - } - for ip := ip.Mask(ipnet.Mask); ipnet.Contains(ip); inc(ip) { - DeviceIP := fmt.Sprint(ip) - conn, err := cssh.Dial("tcp", DeviceIP+":"+Deviceport, &cssh.ClientConfig{ - User: DeviceUser, - Auth: []cssh.AuthMethod{cssh.Password(DevicePass)}, - HostKeyCallback: cssh.InsecureIgnoreHostKey(), - Timeout: 5 * time.Second, - }) - - if err != nil { - fmt.Println(err) - } - session, err := conn.NewSession() - handleError(err) - sshOut, err := session.StdoutPipe() - handleError(err) - sshIn, err := session.StdinPipe() - - err = session.Shell() - handleError(err) - for range DeviceConfigSplit { - fmt.Println(DeviceConfigSplit[ConfigSplitCount]) - // create a new connection - write(DeviceConfigSplit[ConfigSplitCount], sshIn) - ConfigSplitCount++ - } - write("exit", sshIn) - readBuffForString1(sshOut) - session.Close() - conn.Close() - } -} diff --git a/go/old/Console.go b/go/old/Console.go deleted file mode 100755 index f905772..0000000 --- a/go/old/Console.go +++ /dev/null @@ -1,87 +0,0 @@ -package main - -import ( - "fmt" - "strings" - - pan "github.com/zepryspet/GoPAN/utils" - "golang.org/x/crypto/ssh" -) - -func GetConsole() { - DeviceTypeTrim := strings.TrimSpace(Device) - DeviceType := strings.ToLower(DeviceTypeTrim) - DeviceAddress = strings.TrimSpace(Address) - //fmt.Println(DeviceAddress) - DeviceUser = strings.TrimSpace(UserName) - //fmt.Println(DeviceUser) - DevicePass = strings.TrimSpace(Password) - //fmt.Println(DevicePass) - DeviceConfigSplit := strings.Split(Config, "//") - fmt.Println(DeviceType) - deviceport := strings.TrimSpace(Port) - - // Start up ssh process - //try username pass/first - sshClt, err := ssh.Dial("tcp", DeviceAddress+":"+deviceport, &ssh.ClientConfig{ - User: DeviceUser, - Auth: []ssh.AuthMethod{ - ssh.Password(DevicePass), - //ssh.KeyboardInteractive(Challenge), - }, - HostKeyCallback: ssh.InsecureIgnoreHostKey(), - }) - - //if it fails try interactive keyboard auth type (show the banner and auto ack'd) - if err != nil { - sshClt, err = ssh.Dial("tcp", DeviceAddress+":"+deviceport, &ssh.ClientConfig{ - User: DeviceUser, - Auth: []ssh.AuthMethod{ - //ssh.Password(pass), - ssh.KeyboardInteractive(Challenge(DevicePass)), - }, - HostKeyCallback: ssh.InsecureIgnoreHostKey(), - BannerCallback: ssh.BannerDisplayStderr(), - }) - pan.Logerror(err, true) - } - - session, err := sshClt.NewSession() - pan.Logerror(err, true) - sshOut, err := session.StdoutPipe() - pan.Logerror(err, true) - sshIn, err := session.StdinPipe() - pan.Logerror(err, true) - - // Set up terminal modes - 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 - } - // Request pseudo terminal - if err := session.RequestPty("xterm", 40, 80, modes); err != nil { - pan.Wlog("request for pseudo terminal failed: ", "error.txt", false) - pan.Logerror(err, true) - } - // Start remote shell - if err := session.Shell(); err != nil { - pan.Wlog("request for remote shell failed: ", "error.txt", false) - pan.Logerror(err, true) - } - //wait for banner - // Once a Session is created, you can execute a single command on - // the remote side using the Run method. - //writeBuff("enable", sshIn) - //writeBuff("", sshIn) - //cmdSend(sshOut, sshIn, SplitConfig, false, false, 20) - for range DeviceConfigSplit { - fmt.Println(DeviceConfigSplit[ConfigSplitCount]) - // create a new connection - writeBuff(DeviceConfigSplit[ConfigSplitCount], sshIn) - ConfigSplitCount++ - } - writeBuff("exit", sshIn) - readBuff(">", sshOut, 10) - session.Close() -} diff --git a/go/old/Extreme.go b/go/old/Extreme.go deleted file mode 100755 index fa5a046..0000000 --- a/go/old/Extreme.go +++ /dev/null @@ -1,88 +0,0 @@ -package main - -import ( - "fmt" - "strings" - "time" - - "github.com/sfreiberg/simplessh" - cssh "golang.org/x/crypto/ssh" -) - -func ExtremeEos() { - DeviceTypeTrim := strings.TrimSpace(Device) - DeviceType := strings.ToLower(DeviceTypeTrim) - DeviceAddress = strings.TrimSpace(Address) - //fmt.Println(DeviceAddress) - DeviceUser = strings.TrimSpace(UserName) - //fmt.Println(DeviceUser) - DevicePass = strings.TrimSpace(Password) - //fmt.Println(DevicePass) - DeviceConfigSplit := strings.Split(Config, "//") - Deviceport := strings.TrimSpace(Port) - fmt.Println(DeviceType) - conn, err := cssh.Dial("tcp", DeviceAddress+":"+Deviceport, &cssh.ClientConfig{ - User: DeviceUser, - Auth: []cssh.AuthMethod{cssh.Password(DevicePass)}, - HostKeyCallback: cssh.InsecureIgnoreHostKey(), - Timeout: 5 * time.Second, - }) - - if err != nil { - fmt.Println(err) - } - session, err := conn.NewSession() - handleError(err) - sshOut, err := session.StdoutPipe() - handleError(err) - sshIn, err := session.StdinPipe() - - err = session.Shell() - handleError(err) - for range DeviceConfigSplit { - fmt.Println(DeviceConfigSplit[ConfigSplitCount]) - // create a new connection - write(DeviceConfigSplit[ConfigSplitCount], sshIn) - ConfigSplitCount++ - } - write("exit", sshIn) - readBuffForString1(sshOut) - session.Close() - conn.Close() -} -func ExtremeExos() { - DeviceTypeTrim := strings.TrimSpace(Device) - DeviceType := strings.ToLower(DeviceTypeTrim) - DeviceAddress = strings.TrimSpace(Address) - //fmt.Println(DeviceAddress) - DeviceUser = strings.TrimSpace(UserName) - //fmt.Println(DeviceUser) - DevicePass = strings.TrimSpace(Password) - //fmt.Println(DevicePass) - DeviceConfigSplit := strings.Split(Config, "//") - Deviceport := strings.TrimSpace(Port) - fmt.Println(DeviceType) - fmt.Println(DeviceAddress + ":" + Deviceport) - client, err := simplessh.ConnectWithPassword(DeviceAddress+":"+Deviceport, DeviceUser, DevicePass) - if err != nil { - panic(err) - } - if strings.Contains(Config, "//") { - for range DeviceConfigSplit { - fmt.Println(DeviceConfigSplit[ConfigSplitCount]) - output, err := client.Exec(DeviceConfigSplit[ConfigSplitCount]) - if err != nil { - panic(err) - } - fmt.Printf("%s\n", output) - ConfigSplitCount++ - } - } else { - output, err := client.Exec(Config) - if err != nil { - panic(err) - } - fmt.Printf("%s\n", output) - } - client.Close() -} diff --git a/go/old/HewlettPackard.go b/go/old/HewlettPackard.go deleted file mode 100755 index ad5c0be..0000000 --- a/go/old/HewlettPackard.go +++ /dev/null @@ -1,58 +0,0 @@ -package main - -import ( - "fmt" - "strings" - "time" - - cssh "golang.org/x/crypto/ssh" -) - -func HpSwitch() { - DeviceTypeTrim := strings.TrimSpace(Device) - DeviceType := strings.ToLower(DeviceTypeTrim) - DeviceAddress = strings.TrimSpace(Address) - //fmt.Println(DeviceAddress) - DeviceUser = strings.TrimSpace(UserName) - //fmt.Println(DeviceUser) - DevicePass = strings.TrimSpace(Password) - //fmt.Println(DevicePass) - DeviceConfigSplit := strings.Split(Config, "//") - Deviceport := strings.TrimSpace(Port) - fmt.Println(DeviceType) - conn, err := cssh.Dial("tcp", DeviceAddress+":"+Deviceport, &cssh.ClientConfig{ - User: DeviceUser, - Auth: []cssh.AuthMethod{cssh.Password(DevicePass)}, - HostKeyCallback: cssh.InsecureIgnoreHostKey(), - Timeout: 5 * time.Second, - }) - - if err != nil { - fmt.Println(err) - } - session, err := conn.NewSession() - handleError(err) - sshOut, err := session.StdoutPipe() - handleError(err) - sshIn, err := session.StdinPipe() - - err = session.Shell() - handleError(err) - write("\r\n", sshIn) - write("no page", sshIn) - //write(DeviceUser, sshIn) - //write(DevicePass, sshIn) - //write("terminal pager 0", sshIn) - for range DeviceConfigSplit { - fmt.Println(DeviceConfigSplit[ConfigSplitCount]) - // create a new connection - write(DeviceConfigSplit[ConfigSplitCount], sshIn) - ConfigSplitCount++ - } - write("logout", sshIn) - write("y", sshIn) - test := strings.Replace(readBuffForString2(sshOut), "", "", -1) - fmt.Println(test) - session.Close() - conn.Close() -} diff --git a/go/old/MiscFuncs.go b/go/old/MiscFuncs.go deleted file mode 100755 index 3a79a70..0000000 --- a/go/old/MiscFuncs.go +++ /dev/null @@ -1,261 +0,0 @@ -package main - -import ( - "bufio" - "fmt" - "io" - "net" - "os" - "strings" - "time" - - pan "github.com/zepryspet/GoPAN/utils" -) - -func handleError(err error) { - if err != nil { - panic(err) - } -} -func readBuffForString2(sshOut io.Reader) string { - buf := make([]byte, 1000) - n, err := sshOut.Read(buf) //this reads the ssh terminal - waitingString := "" - if err == nil { - for _, v := range buf[:n] { - fmt.Sprint("%c", v) - } - waitingString = string(buf[:n]) - } - for err == nil { - // this loop will not end!! - n, err = sshOut.Read(buf) - waitingString += string(buf[:n]) - for _, v := range buf[:n] { - fmt.Sprint("%c", v) - } - if err != nil { - fmt.Println(err) - } - } - return waitingString -} -func readBuffForString1(sshOut io.Reader) string { - buf := make([]byte, 1000) - n, err := sshOut.Read(buf) //this reads the ssh terminal - waitingString := "" - if err == nil { - for _, v := range buf[:n] { - fmt.Printf("%c", v) - } - waitingString = string(buf[:n]) - } - for err == nil { - // this loop will not end!! - n, err = sshOut.Read(buf) - waitingString += string(buf[:n]) - for _, v := range buf[:n] { - fmt.Printf("%c", v) - } - if err != nil { - fmt.Println(err) - } - } - return waitingString -} -func write(cmd string, sshIn io.WriteCloser) { - _, err := sshIn.Write([]byte(cmd + "\r")) - handleError(err) -} - -//This is a wrapper function, wraps the original function and passes the password to avoid creating a public variable -func Challenge(pass string) func(string, string, []string, []bool) ([]string, error) { - return func(user, instruction string, questions []string, echos []bool) (answers []string, err error) { - answers = make([]string, len(questions)) - for n, q := range questions { - fmt.Printf("%s\n", q) - if q == "Password: " { - answers[n] = pass - fmt.Printf("Signing In...") - } else if q == "Do you accept and acknowledge the statement above ? (yes/no) : " { - answers[n] = "yes" - fmt.Printf("yes\nauto acknowdleged banner...\n") - } else { - reader := bufio.NewReader(os.Stdin) - r, _ := reader.ReadString('\n') - answers[n] = strings.TrimSpace(r) - } - } - return answers, nil - } -} - -func cmdSend(sshOut io.Reader, sshIn io.WriteCloser, cmd string, isFile bool, isConfig bool, timeout int) { - //setting up the initial prompt - prompt := ">" - readBuff(prompt, sshOut, timeout) - //disabling the CLI pager to avoid having to tab on large outputs - if _, err := writeBuff("set cli pager off", sshIn); err != nil { - pan.Logerror(err, true) - } - readBuff(prompt, sshOut, timeout) - - //verifying if the commands need to be run in config mode - if isConfig { - //changing the prompt to bash as due config mode - prompt = "#" - //Sending configuration - if _, err := writeBuff("configure", sshIn); err != nil { - pan.Logerror(err, true) - } - readBuff(prompt, sshOut, timeout) - } - - //Sending the command (s) to the endpoints - - //checking if it's a file or a single command - if isFile { - file, err := os.Open(cmd) - if err != nil { - pan.Logerror(err, true) - } - defer file.Close() - - scanner := bufio.NewScanner(file) - for scanner.Scan() { - //removing empty spaces - newline := strings.TrimSpace(scanner.Text()) - if _, err := writeBuff(newline, sshIn); err != nil { - pan.Logerror(err, true) - } - readBuff(prompt, sshOut, timeout) - } - if err := scanner.Err(); err != nil { - pan.Logerror(err, true) - } - } else { - if _, err := writeBuff(cmd, sshIn); err != nil { - pan.Logerror(err, true) - } - readBuff(prompt, sshOut, timeout) - } - //Exiting from config mode - if isConfig { - if _, err := writeBuff("exit", sshIn); err != nil { - pan.Logerror(err, true) - } - } - //Exiting from operational mode - if _, err := writeBuff("exit", sshIn); err != nil { - pan.Logerror(err, true) - } -} - -func readBuffForString(whattoexpect string, sshOut io.Reader, buffRead chan<- string) { - buf := make([]byte, 2000) - n, err := sshOut.Read(buf) //this reads the ssh terminal - waitingString := "" - if err == nil { - waitingString = string(buf[:n]) - } - for (err == nil) && (!strings.Contains(waitingString, whattoexpect)) { - n, err = sshOut.Read(buf) - waitingString += string(buf[:n]) - //fmt.Println(waitingString) //uncommenting this might help you debug if you are coming into errors with timeouts when correct details entered - } - fmt.Println(waitingString) - //pan.Wlog("output.txt", waitingString, true) - buffRead <- waitingString -} - -func readBuff(whattoexpect string, sshOut io.Reader, timeoutSeconds int) string { - ch := make(chan string) - go func(whattoexpect string, sshOut io.Reader) { - buffRead := make(chan string) - go readBuffForString(whattoexpect, sshOut, buffRead) - select { - case ret := <-buffRead: - ch <- ret - case <-time.After(time.Duration(timeoutSeconds) * time.Second): - pan.Wlog("error.txt", "timeout waiting for command", true) - break - } - }(whattoexpect, sshOut) - return <-ch -} - -func writeBuff(Config string, sshIn io.WriteCloser) (int, error) { - returnCode, err := sshIn.Write([]byte(Config + "\r")) - return returnCode, err -} - -/////////////////////////////////////////////////// -///////////Test Functions for netscan////////////// -/////////////////////////////////////////////////// -func inc(ip net.IP) { - for j := len(ip) - 1; j >= 0; j-- { - ip[j]++ - if ip[j] > 0 { - break - } - } -} -func cmdSendsonic(sshOut io.Reader, sshIn io.WriteCloser, cmd string, isFile bool, isConfig bool, timeout int) { - //setting up the initial prompt - prompt := ">" - readBuff(prompt, sshOut, timeout) - //disabling the CLI pager to avoid having to tab on large outputs - if _, err := writeBuff("no cli pager session", sshIn); err != nil { - pan.Logerror(err, true) - } - readBuff(prompt, sshOut, timeout) - - //verifying if the commands need to be run in config mode - if isConfig { - //changing the prompt to bash as due config mode - prompt = "#" - //Sending configuration - if _, err := writeBuff("configure", sshIn); err != nil { - pan.Logerror(err, true) - } - readBuff(prompt, sshOut, timeout) - } - //Sending the command (s) to the endpoints - - //checking if it's a file or a single command - if isFile { - file, err := os.Open(cmd) - if err != nil { - pan.Logerror(err, true) - } - defer file.Close() - - scanner := bufio.NewScanner(file) - for scanner.Scan() { - //removing empty spaces - newline := strings.TrimSpace(scanner.Text()) - if _, err := writeBuff(newline, sshIn); err != nil { - pan.Logerror(err, true) - } - readBuff(prompt, sshOut, timeout) - } - if err := scanner.Err(); err != nil { - pan.Logerror(err, true) - } - } else { - if _, err := writeBuff(cmd, sshIn); err != nil { - pan.Logerror(err, true) - } - readBuff(prompt, sshOut, timeout) - } - //Exiting from config mode - if isConfig { - if _, err := writeBuff("exit", sshIn); err != nil { - pan.Logerror(err, true) - } - } - //Exiting from operational mode - if _, err := writeBuff("exit", sshIn); err != nil { - pan.Logerror(err, true) - } -} diff --git a/go/old/PaloAlto.go b/go/old/PaloAlto.go deleted file mode 100755 index 5298e16..0000000 --- a/go/old/PaloAlto.go +++ /dev/null @@ -1,87 +0,0 @@ -package main - -import ( - "fmt" - "strings" - - pan "github.com/zepryspet/GoPAN/utils" - "golang.org/x/crypto/ssh" -) - -func PaloAlto() { - DeviceTypeTrim := strings.TrimSpace(Device) - DeviceType := strings.ToLower(DeviceTypeTrim) - DeviceAddress = strings.TrimSpace(Address) - //fmt.Println(DeviceAddress) - DeviceUser = strings.TrimSpace(UserName) - //fmt.Println(DeviceUser) - DevicePass = strings.TrimSpace(Password) - //fmt.Println(DevicePass) - DeviceConfigSplit := strings.Split(Config, "//") - fmt.Println(DeviceType) - for range DeviceConfigSplit { - SplitConfig = DeviceConfigSplit[ConfigSplitCount] - PanSSHConfig() - ConfigSplitCount++ - //time.Sleep(5 * time.Millisecond) - } -} - -func PanSSHConfig() { - deviceport := strings.TrimSpace(Port) - - // Start up ssh process - //try username pass/first - sshClt, err := ssh.Dial("tcp", DeviceAddress+":"+deviceport, &ssh.ClientConfig{ - User: DeviceUser, - Auth: []ssh.AuthMethod{ - ssh.Password(DevicePass), - //ssh.KeyboardInteractive(Challenge), - }, - HostKeyCallback: ssh.InsecureIgnoreHostKey(), - }) - - //if it fails try interactive keyboard auth type (show the banner and auto ack'd) - if err != nil { - sshClt, err = ssh.Dial("tcp", DeviceAddress+":"+deviceport, &ssh.ClientConfig{ - User: DeviceUser, - Auth: []ssh.AuthMethod{ - //ssh.Password(pass), - ssh.KeyboardInteractive(Challenge(DevicePass)), - }, - HostKeyCallback: ssh.InsecureIgnoreHostKey(), - BannerCallback: ssh.BannerDisplayStderr(), - }) - pan.Logerror(err, true) - } - - session, err := sshClt.NewSession() - pan.Logerror(err, true) - sshOut, err := session.StdoutPipe() - pan.Logerror(err, true) - sshIn, err := session.StdinPipe() - pan.Logerror(err, true) - - // Set up terminal modes - 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 - } - // Request pseudo terminal - if err := session.RequestPty("xterm", 40, 80, modes); err != nil { - pan.Wlog("request for pseudo terminal failed: ", "error.txt", false) - pan.Logerror(err, true) - } - // Start remote shell - if err := session.Shell(); err != nil { - pan.Wlog("request for remote shell failed: ", "error.txt", false) - pan.Logerror(err, true) - } - //wait for banner - // Once a Session is created, you can execute a single command on - // the remote side using the Run method. - - cmdSend(sshOut, sshIn, SplitConfig, false, false, 20) - session.Close() -} diff --git a/go/old/Run.go b/go/old/Run.go deleted file mode 100755 index c82c0d6..0000000 --- a/go/old/Run.go +++ /dev/null @@ -1,67 +0,0 @@ -package main - -import ( - "flag" - "strings" -) - -var DeviceAddress = "" -var DeviceUser = "" -var DevicePass = "" -var DeviceConfig = "" -var ConfigSplitCount = 0 -var HostSplitCount = 0 -var seconds int -var flag1 bool -var flag2 bool -var Config string -var SplitConfig string -var Port string -var Address string -var UserName string -var Password string -var Device string -var EnablePassword string - -func main() { - flag.StringVar(&Address, "host", "", "the hostname or ip address of the devices that you are attempting to connect to") - flag.StringVar(&UserName, "user", "", "username used to connect to the device") - flag.StringVar(&Password, "pass", "", "password used to connect to the device") - flag.StringVar(&Config, "command", "", "commands that you would like to run on the host use a // to seperate diffrent commands") - flag.StringVar(&Device, "device", "", "Current Device Types \"ExtremeExos\",\"ExtremeEos\",\"CiscoASA\",\"PaloAlto\",\"HP\",\"CiscoSwitch\",\"GetConsole\",\"SonicWall\"") - flag.StringVar(&Port, "port", "", "specify the port that the ssh connection will be preformed on") - flag.StringVar(&EnablePassword, "enable", "", "specify the enable password") - flag.Parse() - DeviceTypeTrim := strings.TrimSpace(Device) - DeviceType := strings.ToLower(DeviceTypeTrim) - if strings.Contains(DeviceType, "extremeeos") { - ExtremeEos() - } - if strings.Contains(DeviceType, "extremeexos") { - ExtremeExos() - } - if strings.Contains(DeviceType, "ciscoasa") { - CiscoASA() - } - if strings.Contains(DeviceType, "paloalto") { - PaloAlto() - } - if strings.Contains(DeviceType, "hp") { - HpSwitch() - } - if strings.Contains(DeviceType, "ciscoswitch") { - CiscoSwitch() - } - if strings.Contains(DeviceType, "getconsole") { - GetConsole() - } - if DeviceType == "netscantest" { - netscantest() - } - if DeviceType == "sonicwall" { - SonicWall() - } - if DeviceType == "esxi" { - ESXI() - } -} diff --git a/go/old/esxi.go b/go/old/esxi.go deleted file mode 100755 index c6f47f3..0000000 --- a/go/old/esxi.go +++ /dev/null @@ -1,87 +0,0 @@ -package main - -import ( - "fmt" - "strings" - - pan "github.com/zepryspet/GoPAN/utils" - "golang.org/x/crypto/ssh" -) - -func ESXI() { - DeviceTypeTrim := strings.TrimSpace(Device) - DeviceType := strings.ToLower(DeviceTypeTrim) - DeviceAddress = strings.TrimSpace(Address) - //fmt.Println(DeviceAddress) - DeviceUser = strings.TrimSpace(UserName) - //fmt.Println(DeviceUser) - DevicePass = strings.TrimSpace(Password) - //fmt.Println(DevicePass) - DeviceConfigSplit := strings.Split(Config, "//") - fmt.Println(DeviceType) - deviceport := strings.TrimSpace(Port) - - // Start up ssh process - //try username pass/first - sshClt, err := ssh.Dial("tcp", DeviceAddress+":"+deviceport, &ssh.ClientConfig{ - User: DeviceUser, - Auth: []ssh.AuthMethod{ - ssh.Password(DevicePass), - //ssh.KeyboardInteractive(Challenge), - }, - HostKeyCallback: ssh.InsecureIgnoreHostKey(), - }) - - //if it fails try interactive keyboard auth type (show the banner and auto ack'd) - if err != nil { - sshClt, err = ssh.Dial("tcp", DeviceAddress+":"+deviceport, &ssh.ClientConfig{ - User: DeviceUser, - Auth: []ssh.AuthMethod{ - //ssh.Password(pass), - ssh.KeyboardInteractive(Challenge(DevicePass)), - }, - HostKeyCallback: ssh.InsecureIgnoreHostKey(), - BannerCallback: ssh.BannerDisplayStderr(), - }) - pan.Logerror(err, true) - } - - session, err := sshClt.NewSession() - pan.Logerror(err, true) - sshOut, err := session.StdoutPipe() - pan.Logerror(err, true) - sshIn, err := session.StdinPipe() - pan.Logerror(err, true) - - // Set up terminal modes - 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 - } - // Request pseudo terminal - if err := session.RequestPty("xterm", 40, 80, modes); err != nil { - pan.Wlog("request for pseudo terminal failed: ", "error.txt", false) - pan.Logerror(err, true) - } - // Start remote shell - if err := session.Shell(); err != nil { - pan.Wlog("request for remote shell failed: ", "error.txt", false) - pan.Logerror(err, true) - } - //wait for banner - // Once a Session is created, you can execute a single command on - // the remote side using the Run method. - //writeBuff("enable", sshIn) - //writeBuff("", sshIn) - //cmdSend(sshOut, sshIn, SplitConfig, false, false, 20) - for range DeviceConfigSplit { - fmt.Println(DeviceConfigSplit[ConfigSplitCount]) - // create a new connection - writeBuff(DeviceConfigSplit[ConfigSplitCount], sshIn) - ConfigSplitCount++ - } - writeBuff("exit", sshIn) - readBuff(">", sshOut, 10) - session.Close() -} diff --git a/go/old/sonicwall.go b/go/old/sonicwall.go deleted file mode 100755 index 268a672..0000000 --- a/go/old/sonicwall.go +++ /dev/null @@ -1,87 +0,0 @@ -package main - -import ( - "fmt" - "strings" - - pan "github.com/zepryspet/GoPAN/utils" - "golang.org/x/crypto/ssh" -) - -func SonicWall() { - DeviceTypeTrim := strings.TrimSpace(Device) - DeviceType := strings.ToLower(DeviceTypeTrim) - DeviceAddress = strings.TrimSpace(Address) - //fmt.Println(DeviceAddress) - DeviceUser = strings.TrimSpace(UserName) - //fmt.Println(DeviceUser) - DevicePass = strings.TrimSpace(Password) - //fmt.Println(DevicePass) - DeviceConfigSplit := strings.Split(Config, "//") - fmt.Println(DeviceType) - for range DeviceConfigSplit { - SplitConfig = DeviceConfigSplit[ConfigSplitCount] - SonicSSHConfig() - ConfigSplitCount++ - //time.Sleep(5 * time.Millisecond) - } -} - -func SonicSSHConfig() { - deviceport := strings.TrimSpace(Port) - - // Start up ssh process - //try username pass/first - sshClt, err := ssh.Dial("tcp", DeviceAddress+":"+deviceport, &ssh.ClientConfig{ - User: DeviceUser, - Auth: []ssh.AuthMethod{ - ssh.Password(DevicePass), - //ssh.KeyboardInteractive(Challenge), - }, - HostKeyCallback: ssh.InsecureIgnoreHostKey(), - }) - - //if it fails try interactive keyboard auth type (show the banner and auto ack'd) - if err != nil { - sshClt, err = ssh.Dial("tcp", DeviceAddress+":"+deviceport, &ssh.ClientConfig{ - User: DeviceUser, - Auth: []ssh.AuthMethod{ - //ssh.Password(pass), - ssh.KeyboardInteractive(Challenge(DevicePass)), - }, - HostKeyCallback: ssh.InsecureIgnoreHostKey(), - BannerCallback: ssh.BannerDisplayStderr(), - }) - pan.Logerror(err, true) - } - - session, err := sshClt.NewSession() - pan.Logerror(err, true) - sshOut, err := session.StdoutPipe() - pan.Logerror(err, true) - sshIn, err := session.StdinPipe() - pan.Logerror(err, true) - - // Set up terminal modes - 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 - } - // Request pseudo terminal - if err := session.RequestPty("xterm", 40, 80, modes); err != nil { - pan.Wlog("request for pseudo terminal failed: ", "error.txt", false) - pan.Logerror(err, true) - } - // Start remote shell - if err := session.Shell(); err != nil { - pan.Wlog("request for remote shell failed: ", "error.txt", false) - pan.Logerror(err, true) - } - //wait for banner - // Once a Session is created, you can execute a single command on - // the remote side using the Run method. - - cmdSendsonic(sshOut, sshIn, SplitConfig, false, false, 20) - session.Close() -} diff --git a/go/run.go.old b/go/run.go.old new file mode 100644 index 0000000..29c7388 --- /dev/null +++ b/go/run.go.old @@ -0,0 +1,46 @@ +package main + +import ( + "flag" +) + +var returnstring = "" + +func main() { + var HostName string + var UserName string + var Password string + var EnablePassword string + var SSH bool + var File bool + var Port string + var CLIArguments string + var TimeoutValue int + //setting CLI Parameters// + flag.StringVar(&HostName, "h", "", "specify the host you are connecting to with either a hostname or ip address") + flag.StringVar(&UserName, "u", "", "specify device username") + flag.StringVar(&Password, "p", "", "specify device password") + flag.StringVar(&EnablePassword, "e", "", "specify device enable password") + flag.BoolVar(&SSH, "c", true, "specify connection type default is SSH") + flag.StringVar(&Port, "P", "22", "use this to specify port default is 22") + flag.StringVar(&CLIArguments, "C", "", "specify CLI commands to run on host device") + flag.BoolVar(&File, "f", false, "set to true of you are sending a config file") + flag.IntVar(&TimeoutValue, "t", 35, "change default timeout value") + flag.Parse() + switch File { + case false: + switch SSH { + case true: + InvokeSSH(HostName, Port, UserName, Password, StringToArray(CLIArguments), TimeoutValue, EnablePassword) + case false: + //InvokeTelnet(HostName, UserName, Password, EnablePassword, Port, StringToArray1(CLIArguments)) + } + case true: + switch SSH { + case true: + InvokeSSH(HostName, Port, UserName, Password, readLines(CLIArguments), TimeoutValue, EnablePassword) + case false: + //InvokeTelnet(HostName, UserName, Password, EnablePassword, Port, StringToArray1(CLIArguments)) + } + } +} diff --git a/go/sshfuncold.txt b/go/sshfuncold.txt deleted file mode 100644 index d4fea8d..0000000 --- a/go/sshfuncold.txt +++ /dev/null @@ -1,73 +0,0 @@ -package main - -import ( - "fmt" - "io" - "os" - "regexp" - "time" -) - -var prompt = regexp.MustCompile(".*(#|>)") - -func handleError(err error) { - if err != nil { - fmt.Println(err) - } -} -func check(s string) bool { - m := prompt.FindStringSubmatch(s) - // return true if it is - return m != nil -} -func write(cmd string, sshIn io.WriteCloser, sshOut io.Reader, TimeoutValue int) { - _, err := sshIn.Write([]byte(cmd + "\r")) - handleError(err) -} -func readBuffForString(sshOut io.Reader, buffRead chan string, timeoutSeconds int) { - buf := make([]byte, 1000) - waitingString := "" - for { - n, err := sshOut.Read(buf) //this reads the ssh terminal - if err == io.EOF { - break - } - //if err != nil { - // fmt.Println(err) - // break - //} - // for every line - //fmt.Println(string(buf[:n])) - current := string(buf[:n]) - if check(current) { - // ignore prompt and break - //fmt.Print(current) - break - } - // add current line to result string - waitingString += current - if timeoutSeconds == 5 { - time.Sleep(5 * time.Second) - os.Exit(3) - break - } - - } - fmt.Println(waitingString) - buffRead <- waitingString -} -func readBuff(sshOut io.Reader, timeoutSeconds int) string { - ch := make(chan string) - go func(sshOut io.Reader) { - buffRead := make(chan string) - go readBuffForString(sshOut, buffRead, timeoutSeconds) - select { - case ret := <-buffRead: - ch <- ret - case <-time.After(time.Duration(timeoutSeconds) * time.Second): - //pan.Wlog("error.txt", "timeout waiting for command |"+device+" : "+cmd, true) - break - } - }(sshOut) - return <-ch -} diff --git a/go/sshold.txt b/go/sshold.txt deleted file mode 100644 index d78a5fa..0000000 --- a/go/sshold.txt +++ /dev/null @@ -1,86 +0,0 @@ -package main - -import ( - "fmt" - "strings" - "time" - - "golang.org/x/crypto/ssh" -) - -func InvokeSSH(HostName string, Port string, UserName string, Password string, Commands []string, TimeoutValue int) { - if Password == "blank" { - Password = "" - } - conn, err := ssh.Dial("tcp", HostName+":"+Port, &ssh.ClientConfig{ - User: UserName, - Timeout: 5 * time.Second, - Auth: []ssh.AuthMethod{ - ssh.Password(Password), - //ssh.KeyboardInteractive(Challenge), - }, - HostKeyCallback: ssh.InsecureIgnoreHostKey(), - }) - if err != nil { - defer func() { - if err := recover(); err != nil { - fmt.Print("Connection Failed check HostName and Credentials") - } - }() - } - //if it fails try interactive keyboard auth type (show the banner and auto ack'd) - /* if err != nil { - sshClt, err = ssh.Dial("tcp", HostName+":"+Port, &ssh.ClientConfig{ - User: UserName, - Auth: []ssh.AuthMethod{ - //ssh.Password(pass), - ssh.KeyboardInteractive(Challenge(Password)), - }, - HostKeyCallback: ssh.InsecureIgnoreHostKey(), - BannerCallback: ssh.BannerDisplayStderr(), - }) - }*/ - - session, err := conn.NewSession() - handleError(err) - sshOut, err := session.StdoutPipe() - handleError(err) - sshIn, err := session.StdinPipe() - - err = session.Shell() - handleError(err) - defer session.Close() - defer conn.Close() - - // Set up terminal modes - /* 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 - }*/ - /* // Request pseudo terminal - if err := session.RequestPty("xterm", 40, 80, modes); err != nil { - pan.Wlog("request for pseudo terminal failed: ", "error.txt", false) - handleError(err) - } - // Start remote shell - if err := session.Shell(); err != nil { - pan.Wlog("request for remote shell failed: ", "error.txt", false) - handleError(err) - }*/ - //var outputstring string - for _, CLICommands := range Commands { - if strings.Contains(CLICommands, "boot system ") { - write(CLICommands, sshIn, sshOut,TimeoutValue) - readBuff(sshOut, 5) - write(" ", sshIn, sshOut,TimeoutValue) - } else { - write(CLICommands, sshIn, sshOut,TimeoutValue) - readBuff(sshOut, TimeoutValue) - //write(" ", sshIn, sshOut) - //time.Sleep(5 * time.Millisecond) - //readBuff(sshOut, TimeoutValue, CLICommands, HostName) - } - } - //readBuff(sshOut, TimeoutValue) -}