下面由golang教程栏目给大家详解golang ssh连接服务器(模拟交互terminal),希望对需要的朋友有所帮助!
用到的库:golang.org/x/crypto/ssh(隔墙有代理https://goproxy.cn)
1. 发送指令执行 session.Run()
package main import ( "bytes" "fmt" "golang.org/x/crypto/ssh" "log") func main() { // 建立SSH客户端连接 client, err := ssh.Dial("tcp", "127.0.0.1:2222", &ssh.ClientConfig{ User: "root", Auth: []ssh.AuthMethod{ssh.Password("123456")}, HostKeyCallback: ssh.InsecureIgnoreHostKey(), }) if err != nil { log.Fatalf("SSH dial error: %s", err.Error()) } // 建立新会话 session, err := client.NewSession() if err != nil { log.Fatalf("new session error: %s", err.Error()) } defer session.Close() var b bytes.Buffer session.Stdout = &b if err := session.Run("ls"); err != nil { panic("Failed to run: " + err.Error()) } fmt.Println(b.String()) }
2. 发送指令执行 session.Output()
session.run(command)是直接在host执行命令,不关心执行结果。session.Output是将执行命令之后的Stdout返回
package main import ( "fmt" "golang.org/x/crypto/ssh" "log" "os") func test() { // 建立SSH客户端连接 client, err := ssh.Dial("tcp", "127.0.0.1:2222", &ssh.ClientConfig{ User: "root", Auth: []ssh.AuthMethod{ssh.Password("123456")}, HostKeyCallback: ssh.InsecureIgnoreHostKey(), }) if err != nil { log.Fatalf("SSH dial error: %s", err.Error()) } // 建立新会话 session, err := client.NewSession() defer session.Close() if err != nil { log.Fatalf("new session error: %s", err.Error()) } result, err := session.Output("ls -al") if err != nil { fmt.Fprintf(os.Stdout, "Failed to run command, Err:%s", err.Error()) os.Exit(0) } fmt.Println(string(result)) }
3. 模拟交互terminal
package main import ( "golang.org/x/crypto/ssh" "log" "os") func main() { // 建立SSH客户端连接 client, err := ssh.Dial("tcp", "127.0.0.1:2222", &ssh.ClientConfig{ User: "root", Auth: []ssh.AuthMethod{ssh.Password("123456")}, HostKeyCallback: ssh.InsecureIgnoreHostKey(), }) if err != nil { log.Fatalf("SSH dial error: %s", err.Error()) } // 建立新会话 session, err := client.NewSession() defer session.Close() if err != nil { log.Fatalf("new session error: %s", err.Error()) } session.Stdout = os.Stdout // 会话输出关联到系统标准输出设备 session.Stderr = os.Stderr // 会话错误输出关联到系统标准错误输出设备 session.Stdin = os.Stdin // 会话输入关联到系统标准输入设备 modes := ssh.TerminalModes{ ssh.ECHO: 0, // 禁用回显(0禁用,1启动) ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud ssh.TTY_OP_OSPEED: 14400, //output speed = 14.4kbaud } if err = session.RequestPty("linux", 32, 160, modes); err != nil { log.Fatalf("request pty error: %s", err.Error()) } if err = session.Shell(); err != nil { log.Fatalf("start shell error: %s", err.Error()) } if err = session.Wait(); err != nil { log.Fatalf("return error: %s", err.Error()) } }
禁用回显:
//如果不禁用回显 [root@65a9c031a770 ~]# ls ls anaconda-ks.cfg //禁用回显 [root@65a9c031a770 ~]# ls anaconda-ks.cfg
注意:
这里的ssh.InsecureIgnoreHostKey是不检查host key,需要检查的话得参考client源码重写函数
使用GO语言灵活批量ssh登录服务器执行操作: https://www.cnblogs.com/findumars/p/5930584.html
github一个非常好的web ssh项目: https://github.com/libragen/felix
以上是详解golang ssh连接服务器(模拟交互terminal)的详细内容。更多信息请关注PHP中文网其他相关文章!

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建筑物内currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用辅助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

CustomInterfacesingoarecrucialforwritingFlexible,可维护,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增强ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

使用接口进行模拟和测试的原因是:接口允许定义合同而不指定实现方式,使得测试更加隔离和易于维护。1)接口的隐式实现使创建模拟对象变得简单,这些对象在测试中可以替代真实实现。2)使用接口可以轻松地在单元测试中替换服务的真实实现,降低测试复杂性和时间。3)接口提供的灵活性使得可以为不同测试用例更改模拟行为。4)接口有助于从一开始就设计可测试的代码,提高代码的模块化和可维护性。

在Go中,init函数用于包初始化。1)init函数在包初始化时自动调用,适用于初始化全局变量、设置连接和加载配置文件。2)可以有多个init函数,按文件顺序执行。3)使用时需考虑执行顺序、测试难度和性能影响。4)建议减少副作用、使用依赖注入和延迟初始化以优化init函数的使用。

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,执行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,确保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,确保Allimizegoroutines,确保AllizeNizeGoROutines,确保AllimizeGoroutines


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具

Atom编辑器mac版下载
最流行的的开源编辑器

WebStorm Mac版
好用的JavaScript开发工具

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能