美文网首页
Python:paramiko+shell交互式处理sudo等交

Python:paramiko+shell交互式处理sudo等交

作者: 玩转测试开发 | 来源:发表于2022-09-01 00:39 被阅读0次

    简介:普通用户执行sudo时需要输入对应密码才能运行成功。所以仅使用常规的shell命令不足以完成任务,这里推荐使用paramiko+交互式shell进行处理。

    历史攻略:
    Python:paramiko获取top实时数据

    案例源码:ssh_client.py

    # -*- coding: utf-8 -*-
    # time: 2022/8/9 17:42
    # file: ssh_client.py
    # 公众号: 玩转测试开发
    
    import time
    import paramiko
    
    
    def chanel_exe_cmd(ChanelSSHOb, cmd, t=0.1):
        ChanelSSHOb.send(cmd)
        ChanelSSHOb.send("\n")
        time.sleep(t)
        resp = ChanelSSHOb.recv(9999).decode("utf8")
        print("<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<")
        print("Exec sshCmd: %s" % (cmd))
        print("--------------------")
        print("Exec Result: %s" % (resp))
        print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n")
        return resp
    
    
    def creatSShConnectOb(ip_remote, port_remote, username, password):
        print('---------- start to create SSH object')
        print('Remote SSH Info:\n\'ip:%s  port:%d  username:%s  password:%s\'\n' % (
            ip_remote, port_remote, username, password))
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            ssh.connect(ip_remote, port_remote, username=username, password=password, timeout=60)  # timeout protection
            return ssh
        except:
            print('Warning:\nFist connect the ABC failed, now will retry!')
            ssh.connect(ip_remote, port_remote, username=username, password=password, timeout=60)  # timeout re-try
            print('Error:\nAttempt to connect ABC failed!!! Please check the IP / port/ account / password.')
    

    主程序源码:

    # -*- coding: utf-8 -*-
    # time: 2022/8/9 19:14
    # file: old.py
    # 公众号: 玩转测试开发
    
    from ssh_client import chanel_exe_cmd, creatSShConnectOb
    
    
    def run():
        ssh = creatSShConnectOb("11.12.13.14", 22, "ken", "123456")
        chanelSSHOb = ssh.invoke_shell()  # 建立交互式的shell
    
        cmd = 'sudo -s'
        if "password for ken" in chanel_exe_cmd(chanelSSHOb, cmd):
            cmd = "123456"
            chanel_exe_cmd(chanelSSHOb, cmd)
    
        cmd = 'pwd'
        chanel_exe_cmd(chanelSSHOb, cmd)
    
        cmd = 'whoami'
        chanel_exe_cmd(chanelSSHOb, cmd)
    
    
    if __name__ == '__main__':
        run()
    

    执行结果:切换sudo后,whoami = root

    image.png

    微信公众号:玩转测试开发
    欢迎关注,共同进步,谢谢!

    相关文章

      网友评论

          本文标题:Python:paramiko+shell交互式处理sudo等交

          本文链接:https://www.haomeiwen.com/subject/zirenrtx.html