golang expect包的使用
最近和业务的相关人员对接某一需求时,其提出希望能在业务服务器上不给业务人员密码信息,而能通过执行某个命令后由usera变成userb。这个需求其实用expect 就可以实现,不过使用tcl 语言编写的脚本里密码还是以明文出现的,业务是想通过安装pexpect (python)包,通过生成pyc的文件,略微增加下安全性。不过想了下,可以通过使用golang下的expect实现同样的效果,而且安全性更强。
经搜索引擎检索,发现 可以实现该效果,而且在该包的examples里提供了ftp、ping、python、screen相关的使用示例。这里如果使用su切换用户,代码比较简单,如下:
 1//code from www.361way.com
 2package main
 3import gexpect "github.com/ThomasRooney/gexpect"
 4func main() {
 5        child, err := gexpect.Spawn("su - zabbix")
 6        if err != nil {
 7                panic(err)
 8        }
 9        child.Expect("Password")
10        child.SendLine("123456")
11  child.Interact()
12  child.Close()
13}
不过这个包在使用后,可以正常切换用户,不过缺点也比较多:
- 无法tab补全
 - 无法正常按pty Terminal size大小输出(只能输出一部分,有点类似于虚拟化virsh console连接后的情况)
 - 无法使用ctrl +D 快捷键退出,只能使用ctrl + c退出
 - 执行过的命令会再输入一遍
 
在项目的issues 上已经有人提出该问题。项目近两年来并没有更新。
更多expect项目(各种语言版本的)可以参考维基百科 ,不过维基百科上提到的goexpect、go-expect 两个模块经测试并不能成功。
捐赠本站(Donate)
如您感觉文章有用,可扫码捐赠本站!(If the article useful, you can scan the QR code to donate))
- Author: shisekong
 - Link: https://blog.361way.com/go-expect/5899.html
 - License: This work is under a 知识共享署名-非商业性使用-禁止演绎 4.0 国际许可协议. Kindly fulfill the requirements of the aforementioned License when adapting or creating a derivative of this work.