golang ssh 串連交換器

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
/* switch sshusername cisco password ciscoip domain name hupucrypto key generate rsaip ssh time-out 30line vty 0 4transport input alllogin local*/package mainimport ("fmt""io""log""os""strings""sync")import ("golang.org/x/crypto/ssh")func main() {config := &ssh.ClientConfig{User: "cisco",Auth: []ssh.AuthMethod{ssh.Password("cisco"),},Config: ssh.Config{Ciphers: []string{"aes128-cbc"},},}// config.Config.Ciphers = append(config.Config.Ciphers, "aes128-cbc")clinet, err := ssh.Dial("tcp", "192.168.1.253:22", config)checkError(err, "串連交換器")session, err := clinet.NewSession()defer session.Close()checkError(err, "建立shell")modes := ssh.TerminalModes{ssh.ECHO:          1,     // disable echoingssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaudssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud}if err := session.RequestPty("vt100", 80, 40, modes); err != nil {log.Fatal(err)}w, err := session.StdinPipe()if err != nil {panic(err)}r, err := session.StdoutPipe()if err != nil {panic(err)}e, err := session.StderrPipe()if err != nil {panic(err)}in, out := MuxShell(w, r, e)if err := session.Shell(); err != nil {log.Fatal(err)}<-out //ignore the shell outputin <- "show arp"in <- "show int status"in <- "exit"in <- "exit"fmt.Printf("%s\n%s\n", <-out, <-out)_, _ = <-out, <-outsession.Wait()}func checkError(err error, info string) {if err != nil {fmt.Printf("%s. error: %s\n", info, err)os.Exit(1)}}func MuxShell(w io.Writer, r, e io.Reader) (chan<- string, <-chan string) {in := make(chan string, 3)out := make(chan string, 5)var wg sync.WaitGroupwg.Add(1) //for the shell itselfgo func() {for cmd := range in {wg.Add(1)w.Write([]byte(cmd + "\n"))wg.Wait()}}()go func() {var (buf [65 * 1024]bytet   int)for {n, err := r.Read(buf[t:])if err != nil {fmt.Println(err.Error())close(in)close(out)return}t += nresult := string(buf[:t])if strings.Contains(result, "Username:") ||strings.Contains(result, "Password:") ||strings.Contains(result, "#") {out <- string(buf[:t])t = 0wg.Done()}}}()return in, out}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.