python操作服务器,迷你库ssh-lite发布(支持shell交互/文件上传下载,封装自paramiko)

在做后台测试/自动化运维的时候,使用python操作ssh服务器是很常见的情况。常规是使用paramiko库,但他比较复杂,主要是读取的请求是阻塞的(需要自己多线程管理)。甚至好多自动化测试教学培训,都不涉及paramiko这个库。
但操作linux确实是作为测试,尤其自动化测试来讲,算是四大基础设施之一(其他的如操作数据库,操作文件和操作网络[发请求的客户端,和收请求的服务端])。

网上并没有找到专门目的是为了简化封装ssh操作的库,所以以前就封装了一个用。对我来讲,控制自动编译、部署、启停服务,管理docker容器、推送文件、日志断言都要依靠它。

功能:

  • shell交互
  • 文件上传下载
  • expect和grep
  • 预置组合键

github仓库地址,欢迎issue PR和star
https://github.com/rainydew/ssh-lite

自己也想写一个库,上传到pypi上给大家用? 参考我的另一篇博文https://blog.csdn.net/qq_27884799/article/details/96664812

这个库目前已上传至pypi,可以快速安装(兼容python 3.5+)

pip install ssh-lite

注意ssh-lite是数学上的减号

简单使用(注意import的时候,ssh_lite是下划线,因为不允许用-号)

from ssh_lite import Server

ci = Server("127.0.0.1", "123456", "root")
ci.send_and_read("")    # 先消化掉登录后屏幕上的输出,比如Last Login之类的信息
print(ci.send_and_read("ls -l"))   # 这样,再打印的时候,就此时只剩下了ls -l后的输出
del ci

效果

ls -l
total 1736
-rw-r--r-- 1 root  root  1775417 Aug 25  2019 get-pip.py
-rwxrwxrwx 1 root  root      289 Feb 20 12:00 temp.py
-rwxrwxrwx 1 root  root      136 Nov 22 21:18 upload

提供一个更复杂的示例,使用了上下文管理器来自动关闭连接

from ssh_lite import Server, KeyAbbr

remote = "/docker_binding_path"
file = "test.file"

with Server("127.0.0.1", "123456", "root", port=22, key_path=None) as ci:  # type: Server  # 这个库也支持使用RSA密钥文件
    ci.debug = True     # 将其改成True以后,所有的服务端输出就会在控制台也打印出来
    ci.get_file("/a_log_file_to_get", ".")      # 下载文件,目标路径不需要文件名 
    ci.send_and_read("mkdir -p " + remote, timeout=1)
    ci.send_and_read("rm -f {}*".format(remote), timeout=1)
    ci.put_file("prepare/" + file, remote + file)      # 上传文件则严格要求目标路径也包含文件名(否则报错)
    ci.send_and_read("", timeout=1)    # 在执行expect命令前,先清除缓冲区的其他信息文本
    cmd = 'docker exec -i container_name curl -v "http://127.0.0.1:9990/upload?file=/reference_path/{}&uri=me"'.format(
        file)
    print("inner cmd is: {}".format(cmd))
    ci.send(cmd)    # 发送docker内的指令
    ci.expect("< HTTP/1.1 200 OK", timeout=30)      # 在30s内如果看不到期待的输出,则会报错
    ci.send(KeyAbbr.CTRL_C, end="")      # 发送ctrl+C退出转化的HTTP2长连接。默认换行符是\n,但发送ctrl+C不需要换行,所以指定end为空
    ci.send('exit')       # 推出容器以便释放连接
发布了25 篇原创文章 · 获赞 22 · 访问量 9322

猜你喜欢

转载自blog.csdn.net/qq_27884799/article/details/105269929
今日推荐